WebSockets - why is the handshake HTTP? Sharing port 80

Question: I'm not clear why the handshake for WebSocket is HTTP. Wiki says "The handshake resembles HTTP so that servers can handle HTTP connections as well as WebSocket connections on the same port." What is the benefit of this? Once you start communicating over WebSocket you are using port 80 also...so why can't the initial handshake be in WebSocket format?
Also, how do you have both WebSocket and HTTP servers listening on port 80? Or is it typically the same application functioning as HTTP and WebSocket servers?
Thanks y'all :)
Answer: WebSockets are designed to work almost flawlessly with existing web infrastructures. That is the reason why WS connections starts as HTTP and then switches to a persistent binary connection.
This way the deployment is simplified. You don't need to modify your router's port forwarding and server listen ports... Also, because it starts as HTTP it can be load balanced in the same way that a normal HTTP request, firewalls are more lean to let the connection through, etc.. etc... Last but not the least, the HTTP handshake also carry cookies, which it is great to integrate with the rest of the app in the same way that AJAX does.
Both, traditional HTTP request-response and WS, can operate in the same port. Basiclally the WS client sends a HTTP request asking for "Upgrade:websocket", then if the server accepts the WS connections, replies with a HTTP response indicating "101 Switching Protocols", from that point the connection remains open and both ends consider it as a binary connection.
Comment: Thanks for your response.

So if I understand correctly, while typically it's one application per port, that's not a hard-and-fast rule...it's more due to the way OS APIs are designed? As in this answer: http://stackoverflow.com/a/1694271/1628347. So it's possible to have both HTTP and WS servers running on one machine listening on one port.

Why doesn't HTTPS also use port 80 for the same reasons you describe?
Comment: It is ok to have both in the same port as long it is the same process whom is processing both, because both are somehow HTTP. HTTPS is HTTP over SSL/TLS, meaning that the beginning of the connection is totally different, it will be the SSL/TLS handshake, and then the HTTP matter afterwards, that is why runs in a different port, because the process is not (immediately) expecting a HTTP request at that port. The same happens with ws:// and wss://, they must run in different ports because the same reason.
Comment: Don't applications run in different processes? So it has to be the same web server application that handles HTTP and WS, such that it is the same process.
Comment: "application" is a high level concept, that usually maps to a single process, but it may be several process working together. In Microsoft world, you can run your application with several application domains that are actually different processes, but they are managed in a special way that allows them hang from http.sys, that is the responsible of listening at the IIS configured ports.


Newly-built replica WSUS server's clients can't find updates or report status

Question: WSUS 3.0 SP2 on Windows Server 2008 R2.
I built a new box to replace my old WSUS box which was still on Server 2003.
All clients using the WSUS server can't find updates and don't report status.
C:\Windows\WindowsUpdate.log on one of the clients:
2013-05-09  10:04:48:629     764    494 AU  Triggering AU detection through DetectNow API
2013-05-09  10:04:48:629     764    494 AU  Triggering Online detection (non-interactive)
2013-05-09  10:04:48:630     764    7b0 AU  #############
2013-05-09  10:04:48:630     764    7b0 AU  ## START ##  AU: Search for updates
2013-05-09  10:04:48:630     764    7b0 AU  #########
2013-05-09  10:04:48:630     764    7b0 AU  <<## SUBMITTED ## AU: Search for updates [CallId = {E7AC5D1F-612A-4879-9B77-83C692868D11}]
2013-05-09  10:04:48:630     764    64c Agent   *************
2013-05-09  10:04:48:630     764    64c Agent   ** START **  Agent: Finding updates [CallerId = AutomaticUpdates]
2013-05-09  10:04:48:630     764    64c Agent   *********
2013-05-09  10:04:48:630     764    64c Agent     * Online = Yes; Ignore download priority = No
2013-05-09  10:04:48:630     764    64c Agent     * Criteria = "IsInstalled=0 and DeploymentAction='Installation' or IsPresent=1 and DeploymentAction='Uninstallation' or IsInstalled=1 and DeploymentAction='Installation' and RebootRequired=1 or IsInstalled=0 and DeploymentAction='Uninstallation' and RebootRequired=1"
2013-05-09  10:04:48:630     764    64c Agent     * ServiceID = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7} Managed
2013-05-09  10:04:48:630     764    64c Agent     * Search Scope = {Machine}
2013-05-09  10:04:48:630     764    64c Setup   Checking for agent SelfUpdate
2013-05-09  10:04:48:630     764    64c Setup   Client version: Core: 7.6.7600.256  Aux: 7.6.7600.256
2013-05-09  10:04:48:630     764    64c Misc    Validating signature for C:\Windows\SoftwareDistribution\SelfUpdate\wuident.cab:
2013-05-09  10:04:48:637     764    64c Misc     Microsoft signed: Yes
2013-05-09  10:04:50:897     764    64c Misc    Validating signature for C:\Windows\SoftwareDistribution\SelfUpdate\wuident.cab:
2013-05-09  10:04:50:901     764    64c Misc     Microsoft signed: Yes
2013-05-09  10:04:50:902     764    64c Misc    Validating signature for C:\Windows\SoftwareDistribution\SelfUpdate\wsus3setup.cab:
2013-05-09  10:04:50:907     764    64c Misc     Microsoft signed: Yes
2013-05-09  10:04:50:909     764    64c Misc    Validating signature for C:\Windows\SoftwareDistribution\SelfUpdate\wsus3setup.cab:
2013-05-09  10:04:50:913     764    64c Misc     Microsoft signed: Yes
2013-05-09  10:04:50:927     764    64c Setup   Determining whether a new setup handler needs to be downloaded
2013-05-09  10:04:50:927     764    64c Setup   SelfUpdate handler is not found.  It will be downloaded
2013-05-09  10:04:50:928     764    64c Setup   Evaluating applicability of setup package "WUClient-SelfUpdate-ActiveX~31bf3856ad364e35~amd64~~7.6.7600.256"
2013-05-09  10:04:50:931     764    64c Setup   Setup package "WUClient-SelfUpdate-ActiveX~31bf3856ad364e35~amd64~~7.6.7600.256" is already installed.
2013-05-09  10:04:50:931     764    64c Setup   Evaluating applicability of setup package "WUClient-SelfUpdate-Aux-TopLevel~31bf3856ad364e35~amd64~~7.6.7600.256"
2013-05-09  10:04:50:955     764    64c Setup   Setup package "WUClient-SelfUpdate-Aux-TopLevel~31bf3856ad364e35~amd64~~7.6.7600.256" is already installed.
2013-05-09  10:04:50:955     764    64c Setup   Evaluating applicability of setup package "WUClient-SelfUpdate-Core-TopLevel~31bf3856ad364e35~amd64~~7.6.7600.256"
2013-05-09  10:04:50:990     764    64c Setup   Setup package "WUClient-SelfUpdate-Core-TopLevel~31bf3856ad364e35~amd64~~7.6.7600.256" is already installed.
2013-05-09  10:04:50:990     764    64c Setup   SelfUpdate check completed.  SelfUpdate is NOT required.
2013-05-09  10:04:51:205     764    64c PT  +++++++++++  PT: Synchronizing server updates  +++++++++++
2013-05-09  10:04:51:205     764    64c PT    + ServiceId = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7}, Server URL = http://wsus-server.company.local/ClientWebService/client.asmx
2013-05-09  10:04:51:266     764    64c PT  WARNING: Cached cookie has expired or new PID is available
2013-05-09  10:04:51:266     764    64c PT  Initializing simple targeting cookie, clientId = 9f4df40d-f61e-41d5-9fd2-3cdce1823f45, target group = Servers, DNS name = wsus-server.company.local
2013-05-09  10:04:51:266     764    64c PT    Server URL = http://wsus-server.company.local/SimpleAuthWebService/SimpleAuth.asmx
2013-05-09  10:04:51:286     764    64c PT  WARNING: GetCookie failure, error = 0x8024400D, soap client error = 7, soap error code = 300, HTTP status code = 200
2013-05-09  10:04:51:286     764    64c PT  WARNING: SOAP Fault: 0x00012c
2013-05-09  10:04:51:286     764    64c PT  WARNING:     faultstring:System.Web.Services.Protocols.SoapException: Fault occurred
   at Microsoft.UpdateServices.Internal.SoapUtilities.ThrowException(ErrorCode errorCode, String message, String[] clientIds)
   at Microsoft.UpdateServices.Internal.ClientImplementation.GetCookie(AuthorizationCookie[] authCookies, Cookie oldCookie, DateTime lastChange, DateTime currentClientTime, String protocolVersion)
2013-05-09  10:04:51:286     764    64c PT  WARNING:     ErrorCode:ConfigChanged(2)
2013-05-09  10:04:51:286     764    64c PT  WARNING:     Message:(null)
2013-05-09  10:04:51:286     764    64c PT  WARNING:     Method:"http://www.microsoft.com/SoftwareDistribution/Server/ClientWebService/GetCookie"
2013-05-09  10:04:51:286     764    64c PT  WARNING:     ID:f50afcf7-2117-495c-9123-9aa4bf683520
2013-05-09  10:04:51:296     764    64c PT  WARNING: Cached cookie has expired or new PID is available
2013-05-09  10:04:51:296     764    64c PT  Initializing simple targeting cookie, clientId = 9f4df40d-f61e-41d5-9fd2-3cdce1823f45, target group = Servers, DNS name = wsus-server.company.local
2013-05-09  10:04:51:296     764    64c PT    Server URL = http://wsus-server.company.local/SimpleAuthWebService/SimpleAuth.asmx
2013-05-09  10:04:55:116     764    64c PT  +++++++++++  PT: Synchronizing extended update info  +++++++++++
2013-05-09  10:04:55:116     764    64c PT    + ServiceId = {3DA21691-E39D-4DA6-8A4B-B43877BCB1B7}, Server URL = http://wsus-server.company.local/ClientWebService/client.asmx
2013-05-09  10:04:55:170     764    64c PT  WARNING: GetExtendedUpdateInfo failure, error = 0x8024400E, soap client error = 7, soap error code = 400, HTTP status code = 200
2013-05-09  10:04:55:170     764    64c PT  WARNING: SOAP Fault: 0x000190
2013-05-09  10:04:55:170     764    64c PT  WARNING:     faultstring:System.Web.Services.Protocols.SoapException: Fault occurred
   at Microsoft.UpdateServices.Internal.SoapUtilities.ThrowException(ErrorCode errorCode, Exception e, Int32 eventLogEntryId, String[] clientIds, Boolean logToEventLog)
   at Microsoft.UpdateServices.Internal.ClientImplementation.GetExtendedUpdateInfo(Cookie cookie, Int32[] revisionIds, XmlUpdateFragmentType[] fragmentTypes, String[] locales)
2013-05-09  10:04:55:170     764    64c PT  WARNING:     ErrorCode:InternalServerError(5)
2013-05-09  10:04:55:170     764    64c PT  WARNING:     Message:(null)
2013-05-09  10:04:55:170     764    64c PT  WARNING:     Method:"http://www.microsoft.com/SoftwareDistribution/Server/ClientWebService/GetExtendedUpdateInfo"
2013-05-09  10:04:55:170     764    64c PT  WARNING:     ID:37740867-4b9f-4394-b58b-12aad48d7b97
2013-05-09  10:04:55:170     764    64c PT  WARNING: PTError: 0x8024400e
2013-05-09  10:04:55:170     764    64c PT  WARNING: GetExtendedUpdateInfo_WithRecovery: 0x8024400e
2013-05-09  10:04:55:170     764    64c PT  WARNING: Sync of Extended Info: 0x8024400e
2013-05-09  10:04:55:170     764    64c PT  WARNING: SyncServerUpdatesInternal failed : 0x8024400e
2013-05-09  10:04:55:171     764    64c Agent     * WARNING: Exit code = 0x8024400E
2013-05-09  10:04:55:171     764    64c Agent   *********
2013-05-09  10:04:55:171     764    64c Agent   **  END  **  Agent: Finding updates [CallerId = AutomaticUpdates]
2013-05-09  10:04:55:171     764    64c Agent   *************
2013-05-09  10:04:55:171     764    64c Agent   WARNING: WU client failed Searching for update with error 0x8024400e
2013-05-09  10:04:55:180     764    bf4 AU  >>##  RESUMED  ## AU: Search for updates [CallId = {E7AC5D1F-612A-4879-9B77-83C692868D11}]
2013-05-09  10:04:55:180     764    bf4 AU    # WARNING: Search callback failed, result = 0x8024400E
2013-05-09  10:04:55:180     764    bf4 AU    # WARNING: Failed to find updates with error code 8024400E
2013-05-09  10:04:55:180     764    bf4 AU  #########
2013-05-09  10:04:55:180     764    bf4 AU  ##  END  ##  AU: Search for updates [CallId = {E7AC5D1F-612A-4879-9B77-83C692868D11}]
2013-05-09  10:04:55:180     764    bf4 AU  #############
2013-05-09  10:04:55:180     764    bf4 AU  Successfully wrote event for AU health state:0
2013-05-09  10:04:55:180     764    bf4 AU  AU setting next detection timeout to 2013-05-09 13:04:55
2013-05-09  10:04:55:181     764    bf4 AU  Successfully wrote event for AU health state:0
2013-05-09  10:04:55:181     764    bf4 AU  Successfully wrote event for AU health state:0
2013-05-09  10:05:00:171     764    64c Report  REPORT EVENT: {1C2D6590-41BD-464D-AE18-289CB7D6E254}    2013-05-09 10:04:55:171+0200    1   148 101 {00000000-0000-0000-0000-000000000000}  0   8024400e    AutomaticUpdates    Failure Software Synchronization    Windows Update Client failed to detect with error 0x8024400e.
2013-05-09  10:05:00:191     764    64c Report  CWERReporter::HandleEvents - WER report upload completed with status 0x8
2013-05-09  10:05:00:191     764    64c Report  WER Report sent: 7.6.7600.256 0x8024400e 00000000-0000-0000-0000-000000000000 Scan 101 Managed
2013-05-09  10:05:00:191     764    64c Report  CWERReporter finishing event handling. (00000000)

I found several old blogs and forum entries that link this to a fault in Office 2003 SP1, with the fix being to decline/approve/decline that update, but this hasn't fixed it for me.
The Microsoft WSUS client & server diagnostic tools don't run on x64 systems.
Anybody had any luck with this before?
update: I find this in C:\Program Files\UpdateServices\LogFiles\SoftwareDistribution.log:
2013-05-13 14:02:46.437 UTC Warning w3wp.6  SoapUtilities.CreateException   ThrowException: actor = http://wsus-server.company.local/ClientWebService/client.asmx, ID=4db89865-40da-4520-a126-d196e3db07b6, ErrorCode=ConfigChanged, Message=, Client=d9ce7281-379b-49b8-8944-7f593c32397b
2013-05-13 14:02:50.867 UTC Error   w3wp.6  ClientImplementation.GetExtendedUpdateInfo  System.ArgumentException: The database does not contain a URL for the file 3F7E7915F44A6133B990A22A87604854C34BDF4E.

Google fails me completely if I search for "3F7E7915F44A6133B990A22A87604854C34BDF4E", so I'm not sure exactly what that is, but it seems that its DB entry is somehow incomplete. Sync logs with the upstream WSUS show no errors.
update 2: So it seems as if there's something weird with my upstream. I've found that if I install a new WSUS instance & sync it from Microsoft, all works perfectly well. If I make it a downstream replica of my existing WSUS server, either during the configuration, or afterwards, it breaks. Even more strange, my upstream itself and another existing replica appear to be functioning just fine. It looks as if I'm just going to build new WSUS instances in all 3 sites and start fresh, ignoring the existing upstream.
update 3: I built a new WSUS upstream server, started clean so as to not bring over whatever weirdness was going on in the original upstream's DB. Pointed my 2 replicas at my new upstream. Everything was fine for several days. 5 days ago the replicas stopped getting status updates from clients again. WTF?!?!
update 4: I have logged a support request with Microsoft on this, hopefully some good will come out of it.
update 5: After Microsoft product support spent countless hours checking and re-checking all the same stuff I'd already checked, I suspect I have stumbled upon the cause. Our Junior sysadmin recently discovered Local Update Publisher and started using it to push Adobe & Java updates to workstations. The time of Local Update Publisher's installation coincides perfectly with the time the downstream clients last reported status. I am going through the product documentation to determine what I need to do to fix this.
Comment: What about this? http://support.microsoft.com/kb/954960
Comment: @duenni: not applicable, as the WSUS installation is running SP2 as soon as its installed.
Answer: I had a similar issue not to long ago when migrating to WSUS 3.0 SP2 on Windows Server 2008 R2. After quite a few frustrating hours I finally resolved it with KB2720211. I'm not sure why it worked since it doesn't seem to directly address the error code I was receiving from clients at the time (800b0001), however it seemed logical to make sure the WSUS version was fully patched before getting further into diagnostics.
You can use the instructions from http://support.microsoft.com/kb/2720211
Since my setup only involved one WSUS server I only had to use the following instructions from the site after downloading the patch.
1.Set up WSUS. To do this, at a command prompt, type one of the following commands, as applicable to your system:
WSUS-KB2720211-x64.exe /q C:\MySetup.log
WSUS-KB2720211-x86.exe /q C:\MySetup.log
The update will install immediately, without any prompts.
2.Review the setup log to verify the upgrade was successful. To do this, at a command prompt, type C:\MySetup.log.
3.Make sure that IIS and the WSUS service are stopped. To do this, at a command prompt, type the following commands:
iisreset/stop
net stop wsusservice
Comment: It's quite odd, I could've sworn I tried that KB already, but this time it does seem to have worked. I have tinkered so much with this install now though that its kind of in a messy state. I'm going to wipe and re-install it and try this KB again if the issue persists.
Comment: I am glad it helped, let me know if you run into any other issues.
Comment: Strange, when I install as a downstream of my existing WSUS, even this KB doesn't resolve my issue.
Answer: The 0x8024400D/SOAP 0x12c errors are almost always (these days) a manifestation of clients with duplicate SusClientIDs. See Microsoft KB903262 for remediation instructions.
The 0x8024400E/SOAP 0x190 errors are typically manifestations of bad updates in the WSUS database. Make sure you have declined all expired updates (the ones typically that are "bad), as well as decline all superseded/not-needed updates.
Comment: The Server Cleanup Wizard takes care of declining expired/superseded updates, so that's covered. I'll try KB903262, although I can't see how it can be that as the clients all used to update just fine and weren't deployed from images/cloned.
Comment: KB903262 didn't help either I'm afraid.
Answer: So nearly 3 months later and after dozens of hours spent by Microsoft PSS on this, I finally stumbled on the answer.
It turns out that the root cause was an incomplete implementation of Local Update Publisher.
When you implement Local Update Publisher, you are supposed to distribute the WSUS SSL certificate to all WSUS clients as a Trusted Publisher and Trusted Root Certificate Authority. It turns out that my colleague who implemented it only distributed it to workstations, not servers.
I'm not clear on the exact details under the hood, but as soon as I distributed the SSL certificate to all WSUS clients, they started receiving their updates and reporting status as per normal.


What is the purpose of entity_keys in ContentEntityBase?

Question: I'm trying to figure out what is the purpose of entity_keys in ContentEntityBase entities and what fields should be set as entity_keys.
For example in \Drupal\node\Entity\Node we have such entity_keys:
entity_keys = {
 "id" = "nid",
 "revision" = "vid",
 "bundle" = "type",
 "label" = "title",
 "langcode" = "langcode",
 "uuid" = "uuid",
 "status" = "status",
 "uid" = "uid",
}

Why exactly these fields are selected to be entity_keys? And, for example, why in \Drupal\comment\Entity\Comment status isn't in entity_keys?
Answer: entity_keys are basically an alias for fields. It allows generic code, like the storage backends, to access common fields that have different names, for example the ID. They need write the saved value, so the can't just use id() as most places.
Internally, those keys are also used by generic methods like id(), label(), getRevisionId() and so on, so they work out of the box.
There isn't really a reason that comment doesn't define status. Nothing really uses status, if you search for getKey('status'), there are no matches, while getKey('id') finds a lot.
Node only uses it internally for the isPublished().
Comment: Maybe important to point out: The annotation has "entity_keys" with entries like "id" = "nid". The entity has a property $entity->entityKeys with entries like ['id' => 5]. So this property holds the values of those keys, not the keys themselves.
Comment: So If I guess correctly If we dont add them for some fields they can be just accessed/used as defaults?


Explicit loading of grandchild collections in EF 4.1

Question: Given the following model ...
public class Parent
{
    public int Id { get; set; }
    public ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }
    public ICollection<Grandchild> Grandchildren { get; set; }
}

public class Grandchild
{
    public int Id { get; set; }
}

... we can eager load with Include a Parent with all Children and Grandchildren in one step like so:
context.Parents.Include(p => p.Children.Select(c => c.Grandchildren))

Is something similar possible for explicit loading?
The child collection can be explicitely loaded this way:
Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();

But trying to load the children in a similar way as with Include ...
context.Entry(parent)
    .Collection(p => p.Children.Select(c => c.Grandchildren)).Load();

... doesn't compile und the string overload of Collection ...
context.Entry(parent).Collection("Children.Grandchildren").Load();

... throws an exception ("...no dotted paths allowed...").
The only thing which I found working is to explicitely load the Grandchildren in a loop:
Parent parent = context.Parents.Find(parentId);
context.Entry(parent).Collection(p => p.Children).Load();
foreach (var child in parent.Children)
    context.Entry(child).Collection(c => c.GrandChildren).Load();

I am wondering if I missed something and if there is some other way to explicitely load the GrandChildren in one roundtrip.
Thanks for feedback in advance!
Comment: Did you try `Collection(...).Query().Include(...).Load()`? If it doesn't work as well I'm afraid that it is not supported. Generally `Load` is equivalent of handling `RelatedEnd.Load` from ObjectContext API.
Comment: @Ladislav: Please put this in an answer :) It works!
Answer: As I pointed in the comment you can try to get query for relation first, then add includes and execute loading. Something like:
context.Entry(parent)
       .Collection(p => p.Children)
       .Query()
       .Include(c => c.Grandchildren) // I'm not sure if you can include grandchild directly
       .Load();

Comment: Yes, that's exactly what I tried after your comment, and it works. It opens the question, if you could then also load "GrandGrandChildren" with `Include(...Select(...))` and so on. But I'd guess it will work too. Thanks for this solution!
Comment: I've just tested the code with your `IncludeMultiple` (instead of simple Include) from here (http://stackoverflow.com/questions/5376421/ef-including-other-entities-generic-repository-pattern/5376637#5376637) with "GrandGrandChildren" and "SomeReferenceInGrandChild" and it works too!
Comment: It should work because `Query()` returns `ObjectQuery` implementing `IQueryable` so it is EF query as any other only with some predefined condition.
Comment: Late to this thread, I know, but the `Load()` only covers entities specified _after_ the `Query()` (Grandchildren). But then a second SQL call is made to load the missing entity layer (Children). So you get 2 SQL calls, but everything ends up loaded.

To be fully explicit, use two calls, the first being:
`context.Entry(parent).Collection(p => p.Children).Load();`
Comment: I am super late to this party, but this still works in EF6


Fundamental assumption about number theory: divisibility

Question: Some interesting questions arose in my mind. The Mathematics we have built to date depend on the fundamental assumptions we make in the very beginning. For example, if we consider Number Theory - more precisely divisibility (see [1], page 24) - we come upon the following statement:

An integer $d$ is said to divide $n$ or be a divisor of $n$ if there exists an integer $e$ such that $n=de$.

I am wondering:

Is this an axiom?
Is this a fact of life arising from nature, or was this invented?
Can a different Mathematics be built if we change this statement?

Bonus points for anyone who can point me to literature that covers topics such as:

Fundamental nature of Number Theory (or in general, Mathematics)
Possibility of other variants of Number Theory (or in general, Mathematics)

[1] Kenneth S. Williams, 2010. Number Theory in the Spirit of Liouville. Cambridge University Press.
Comment: It's a definition.
Comment: As regards q3, I'd be interested to see an example of what you think this statement might look like after we "change' it
Comment: @AakashM Well, the simplest modification I can think of: allow $d=0$, so that $0|n$.
Comment: The statement you've shown doesn't explicitly exclude zero. What is the *whole statement* you want to change it to?
Comment: @AakashM Of course it does! If we look closely at the statement (definition) **"An integer $d$ is said to divide $n$ or be a divisor of $n$ if there exists an integer $e$ such that $n=de$."** we can see that $d$ can't be $0$ because there is no such integer $e$ that could meet the requirement $0 \cdot e=n$.
Comment: "Explicitly". So what's your proposed changed statement?
Answer:
It is a definition.
It is not a fact of life. It's just a definition. It's the meaning of the word divisor.
There is no answer to this question since it is not a statement. It is just a definition.
Comment: @DietrichBurde I've edited my answer. Thank you.
Answer: It is just a definition of a concept, a notion that mathematicians stumbled across. So, they just gave it a name (divisor). They could also have called the concept "Peter" or "Flabber" or whatever. The concept was not invented but found/discovered. This is also true for many other mathematical concepts such as groups, for example. Even though groups do not appear in there pure form in nature, their concept can be transferred to many instances in reality (for example, in quantum mechanics).
By simply assigning a different name to the word divisor we do not get some "different Mathematics" since we are only dealing with a definition and not with an axiom. If your statement was indeed an axiom, we could very well end up with some different mathematics if we changed it. A good example for this is the parallel postulate in geometry. If you replace the parallel postulate of Euclidean Geometry with

For any given line $R$ and point $P$ not on $R$, in the plane containing both line $R$ and point $P$ there are at least two distinct lines through $P$ that do not intersect $R$. (taken from: Wikipedia),

then you will come to Hyperbolic geometry which is indeed very different from Euclidean geometry.
Concerning your last question about possible variants of number theory, you might find analytic number theory interesting, which brings together methods from number theory and mathematical analysis such as complex analysis.


Compare 2 different hexadecimal

Question: I have a hexadecimal in unsigned char *hex_1 that contains:
hex_1[0] = 0x5b
hex_1[1] = 0x83
hex_1[2] = 0xb6
hex_1[3] = 0xe9

and I want to compare it with a hex value: 1ca0aaf9.
What should I do? Should I create a new character array, split 1ca0aaf9 into 1c ca 0a, then do memcpy()?
EDIT: I actually want them to either tell me whether "THEY ARE THE SAME!" or "THEY ARE NOT THE SAME!".
EDIT 2: I want it to be like hex[0] to be compared with 1c, etc...
Comment: What order do you want?  Does `f9` of  `0x1ca0aaf9`  compare against `hex_1[0]`, `hex_1[3]` or something else?  C does not specify this order.  Your choice.
Answer: Your probably want this:
uint32_t val = *(uint32_t*)(hex_1);  // uint32_t is available by #include <stdint.h>

if (val == 0x1ca0aaf9)
{

}

On a big-endian architecture, you are done.  On Intel and other little endian architectures you need to decide if that byte array is logicialy meant to be interpreted as in network byte order as 0x5b83b6e9 (decimal 1535358697).  Or if it's meant to be in host byte order (0xe9b6835b) (decimal 3921052507).  If the byte array is in network byte order, then you'll need to swap the bytes.  That's what the ntohl function does.
uint32_t val = *(uint32_t*)(hex_1);
val = ntohl(val);    // <arpa/inet.h> or <winsock2.h>

if (val == 0x1ca0aaf9)
{

}

Comment: @ThomasWest : You don't need a for-loop.
Comment: so I dont need a `for loop`?
Comment: So I wonder how to check whether my `hex_1` has the same value with `1ca0aaf9`? I actually want it to check for similarity. Sorry if I didn't explain it clear-er.
Comment: Nice that you brought the architecture into this. :)  Most probably, @ThomasWest will need `val = ntohl(val); `

Compare 2 different hexadecimal


Why won't my custom content field update on save/edit?

Question: I am building a custom content type programmatically within my module. Everything appears as I thought it would on the "Add Content" page, but whenever I create a new piece of content or edit the created content the data from the field is not being saved. When I go back into the content nothing is there.
What am I missing? Is there a better approach? I wanted to keep the scope of this module inside of the related "Add Content" page because it needs to be able to follow the Drupal Workbench workflow.
On .install:
function header_maker_enable(){
  $contentType = "brand_header";
  $readableType = "Brand Header";
  $type = node_type_load($contentType);

  //Verify that the content type has not already been created once for this module
  if(!$type){
    $type = array(
      'type' => $contentType,
      'name' => t($readableType),
      'base' => 'node_content',
      'description' => t("Test"),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    );

   $type = node_type_set_defaults($type);

   //Creating Custom Test Field
   $field = array(
    'field_name' => 'brand_header_config',
    'type' => 'text',
    'entity_types' => array('node'),
  );
  $field = field_create_field($field);
  $instance = array(
    'field_name' => 'brand_header_config',
    'entity_type' => 'node',
    'bundle' => 'brand_header',
    'label' => t('Test Field'),
    'widget' => array('type' => 'text_textfield'),
  );
  $instance = field_create_instance($instance);

  node_type_save($type);
}

}

Here is my .module file. Something a bit more tricky is going on here with some JS. Basically I am rendering a UI to create some JSON. That JSON is then being added to the input field that was created on install in real time.
function header_maker_form_brand_header_node_form_alter(&$form, $form_state, $form_id){
  if ($form_id == 'brand_header_node_form') {
  $form['header_maker_ui'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['header_maker_render'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

$order = array(
'header_maker_render',
'brand_header_node_form',
'brand_header_config'
  );

  foreach ($order as $key => $field) {
// Set/Reset the field's
// weight to the array key value
// from our order array.
$form[$field]['#weight'] = $key;
  }
  }
  return $form;
  }

function header_maker_preprocess_page(&$vars, $hook){
  if(isset($vars['page']['content']['system_main']['#form_id'])){
$formid = $vars['page']['content']['system_main']['#form_id'];
if($formid == "brand_header_node_form"){
  drupal_add_css(drupal_get_path('module', 'header_maker'). '/css/brand-header-form.css', array('group' => CSS_THEME, 'every_page' => FALSE));
  drupal_add_js(drupal_get_path('module', 'header_maker') . '/js/header_maker.js');
}
}
}

Comment: If the issue is not in the construction of the field instance, then you can try adding a custom validator or submit handler to your form and see if the field retains its value that far.  Add a watchdog line in the node_save section of core to see what is being passed, etc.
Comment: Why are you adding a field through code instead of through the admin interface?  That is an important detail to knowing how I can suggest something to you.  The admin interface also creates the database table that stores the value for your field, which it looks like your code does not.
Comment: @DeveloperWeeks A content type and it's relevant fields are being added on module install to make the UX as simple as possible. I wanted to have the users be able to add the module to their site and have everything ready to go for content creation, since most of the people who will be working with it will not be actual developers. After looking in the DB I can confirm that this code does create the table in my DB.
Comment: [Features module](https://www.drupal.org/project/features) was made specifically for the feat you are attempting.
Comment: I actually ended up dpm'ing the values through node_save. Thanks!
Answer: I figured out what my issue was. In order to force users to use the UI I set the input field as being disabled from my JS file.
 document.getElementById('edit-brand-header-config-und-0-value').disabled = true;

Apparently setting it to disabled prevents it from being stored even though I could add a value to it programmatically through JS.
Removing "disabled = true"


Confusion over RAID controllers for Dell R620 - what will work?

Question: I have a (remotely located) R620 server with an H310 PERC controller (Described as "405-1110 : H310 Adapter, low profile", part R1DNH -  What I've got is definitely a PCIE card.
First question - What SAS connector interface is this?  (According to the specs it should be an SFF8078  - but this is relevant to the next part of my question -)
Second Question - When I look at the specs for the H710 it talks about an internal SFF8088 connector - but am I misunderstanding something?  I understood the SFF8088 to be EXTERNAL connectors?   Is this an error on the spec sheet?
Third question: When I search on EBAY and the like for PERC H710 R620, most of the listings are not for the PCI form factor card.   Do I need to use the PCI form factor card in my unit, or can I use the other type shown?
Fourth Question: The Dell Distributor quoted me on an H810 card as a replacement for the H310.   Dells website describes the H810 as an EXTERNAL card - and a more expensive one at that.  Is this card appropriate to replace my H310 ?  Does it give me any benefit over the H710 card - if the H710 card will work ?
Answer:
The connectors in your picture are SFF-8087
You're correct, SFF-8088 is an external connection. That is a documentation typo. The H710 does in fact have the same SFF-8087 internal connections as the H310.
I don't believe those other form factors will work, they appear to have a different connector type - I would play it safe and go with the one that matches the form factor of your existing card though. e.g. Dell part number 0GJKT
H810 is an external card, and is not a replacement for the H310. You need an H710.


Modelo ARIMA com lag em 1 e 25 no R

Question: Por favor, ao aplicar a modelagem ARIMA(p,d,q) em uma série , na função de autocorrelação parcial aparece um pico em lag 1 e outro em 25 e nenhum outro estatisticamente significativo.
Existe algum comando no R para tratar desses dois lags apenas, sem incluir 25 coeficientes regressivos?
Comment: Henrique, tu chegou a ver se não é um comportamento sazonal? Se o lag 50 também não é significativo?
Answer: Sim existe.
Considerando a série lh do R:
> lh
Time Series:
Start = 1
End = 48
Frequency = 1
 [1] 2.4 2.4 2.4 2.2 2.1 1.5 2.3 2.3 2.5 2.0 1.9 1.7 2.2 1.8 3.2 3.2 2.7 2.2 2.2 1.9 1.9
[22] 1.8 2.7 3.0 2.3 2.0 2.0 2.9 2.9 2.7 2.7 2.3 2.6 2.4 1.8 1.7 1.5 1.4 2.1 3.3 3.5 3.5
[43] 3.1 2.6 2.1 3.4 3.0 2.9

Ajuste o modelo assim:
> arima(lh, order = c(1,1,1), fixed = c(NA, 0))

Call:
arima(x = lh, order = c(1, 1, 1), fixed = c(NA, 0))

Coefficients:
          ar1  ma1
      -0.0404    0
s.e.   0.1443    0

sigma^2 estimated as 0.2525:  log likelihood = -34.35,  aic = 72.7

Neste caso, estou dizendo que o parâmetro AR1 é livre (estimado pelo modelo) e que o MA1 é igual a zero por meio do argumento fixed.
No seu caso, se você quisesse ajustar um arima(25,1,0) com apenas os coeficientes 1 e 25 do AR, poderia fazer assim:
> arima(lh, order = c(25,1,0), fixed = c(NA, rep(0,23), NA))

Call:
arima(x = lh, order = c(25, 1, 0), fixed = c(NA, rep(0, 23), NA))

Coefficients:
          ar1  ar2  ar3  ar4  ar5  ar6  ar7  ar8  ar9  ar10  ar11  ar12  ar13  ar14
      -0.0539    0    0    0    0    0    0    0    0     0     0     0     0     0
s.e.   0.1343    0    0    0    0    0    0    0    0     0     0     0     0     0
      ar15  ar16  ar17  ar18  ar19  ar20  ar21  ar22  ar23  ar24    ar25
         0     0     0     0     0     0     0     0     0     0  0.2994
s.e.     0     0     0     0     0     0     0     0     0     0  0.1918

sigma^2 estimated as 0.2297:  log likelihood = -33.3,  aic = 72.6

O argumento fixed é sempre um vetor com o número de elementos igual ao número de parâmetros que o seu modelo possui. Você pode pré-especificar qualquer valor para os parâmetros, mas normalmente usamos apenas 0 (quando não queremos aquele termo) e NA (quando queremos que o parâmetros seja estimado pelo modelo).
Comment: Veja se isso funciona: `arima(lh, order = c(25,1,1), fixed = c(rep(0,24), NA, NA))`

Modelo ARIMA com lag em 1 e 25 no R


Need help making site available externally

Question: I'm trying to open a hole in the firewall (ASA 5505, v8.2) to allow external access to a Web application.  Via ASDM (6.3?), I've added the server as a Public Server, which creates a static NAT entry [I'm using the public IP that is assigned to 'dynamic NAT--outgoing' for the LAN, after confirming on the Cisco forums that it wouldn't bring everyone's access crashing down] and an incoming rule "any... public_ip... https... allow" but traffic is still not getting through.  When I look at the log viewer, it says it's denied by access-group outside_access_in, implicit rule, which is "any any ip deny"
I haven't had much experience with Cisco management.  I can't see what I'm missing to allow this connection through, and I'm wondering if there's anything else special I have to add.  I tried adding a rule (several variations) within that access-group to allow https to the server, but it never made a difference.  Maybe I haven't found the right combination? :P
I also made sure the Windows firewall is open on port 443, although I'm pretty sure the current problem is Cisco, because of the logs. :)
Any ideas?  If you need more information, please let me know.
Thanks
Edit:
First of all, I had this backward.  (Sorry)  Traffic is being blocked by access-group "inside_access_out" which is what confused me in the first place.  I guess I confused myself again in the midst of typing the question.
Here, I believe, is the pertinent information.  Please let me know what you see wrong.
access-list acl_in extended permit tcp any host PUBLIC_IP eq https
access-list acl_in extended permit icmp CS_WAN_IPs 255.255.255.240 any
access-list acl_in remark Allow Vendor connections to LAN
access-list acl_in extended permit tcp host Vendor any object-group RemoteDesktop
access-list acl_in remark NetworkScanner scan-to-email incoming (from smtp.mail.microsoftonline.com to PCs)
access-list acl_in extended permit object-group TCPUDP any object-group Scan-to-email host NetworkScanner object-group Scan-to-email
access-list acl_out extended permit icmp any any
access-list acl_out extended permit tcp any any
access-list acl_out extended permit udp any any
access-list SSLVPNSplitTunnel standard permit LAN_Subnet 255.255.255.0
access-list nonat extended permit ip VPN_Subnet 255.255.255.0 LAN_Subnet 255.255.255.0
access-list nonat extended permit ip LAN_Subnet 255.255.255.0 VPN_Subnet 255.255.255.0
access-list inside_access_out remark NetworkScanner Scan-to-email outgoing (from scanner to Internet)
access-list inside_access_out extended permit object-group TCPUDP host NetworkScanner object-group Scan-to-email any object-group Scan-to-email
access-list inside_access_out extended permit tcp any interface outside eq https

static (inside,outside) PUBLIC_IP LOCAL_IP[server object] netmask 255.255.255.255

access-group inside_access_out out interface inside
access-group acl_in in interface outside
access-group acl_out out interface outside

I wasn't sure if I needed to reverse that "static" entry, since I got my question mixed up... and also with that last access-list entry, I tried interface inside and outside - neither proved successful... and I wasn't sure about whether it should be www, since the site is running on https.  I assumed it should only be https.
Comment: The inbound ACL on the outside interface is missing a rule to allow the traffic.
Comment: Could you post a "sanitized" config file with IP addresses using internal space and passwords blanked out?
Answer: Uh yearh probably it's CISCO fault. Honestly for me ASDM it's a bit confusing so I will pass you the command lines directive:
ssh pix@INTERNAL_IP
[type cisco password]
enable
[retype password]
show conf <- retrieve the config plain text

Now you should have lines like that
access-group outside_access_in in interface outside
access-list outside_access_in extended permit tcp any interface outside eq www

Maybe the access-list name is different, but doesn't matter. Also in my case the outside interface it's an alias for the VLan2 on which is the internet connected. This allows traffic for www connection to be accepted.
Now for the port forwarding you need a line like that:
static (inside,outside) tcp interface www LOCAL_IP www netmask 255.255.255.255

Again the inside it's an name for my local interface, which act as an gateway for the network. If you con't have lines like that just add them with configure terminal. Add the magic lines and should work. If you need any help in the console just use the magic ?:)
Comment: I was told on the Cisco forums to remove the inside_access_out group.  I was nervous about doing that (not sure about any other ramifications), so I resolved this by adding 'any any https allow' on that access group.  There is probably a better way of doing this, but I tried all combinations I could think of (server_ip as source, destination, etc... even if it didn't necessarily make sense - thought I might get lucky :P) with no success.  With the 'any any' it's working.  Thanks for the help!
Comment: I'm sorry, I got my question backwards (apparently, inside_access_out is blocked).  I've posted an update, as I was unable to convert your answer to my scenario. :P


Custom module .install does not create table in database

Question: I want to create database table for my custom module.
Inside mymodule.install I have:
function mymodule_schema(){
    $schema['a_visits'] = array(

    'description' => 'visits table',
    'fields' => array(
        'id' => array(
            'description' => 'make id primary key auto increment',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'oferta' => array(
            'description' => 'nazwa oferty',
            'type' => 'varchar',
            'length' => '255',
            'not null' => TRUE,
        )
    ),
    'primary key' => array('id'),
    );
    return $schema;
}

function mymodule_install() {
   drupal_install_schema('a_visits');
}

function mymodule_uninstall() {
   drupal_uninstall_schema('a_visits');
}

Then I've moved the module's file to server under sites/all/modules/custom/mymodule and enabled it via admin panel. Unfortunately no table in database has been created (the module is listed as active now).
Comment: You don't have to explicitly install the schema anymore: https://api.drupal.org/comment/3073#comment-3073 . However, i ran your code and the table was created in my database. Can you disable, uninstall and then enable the module? Also, any notices/warnings in the dblog?
Answer: hook_schema alone is sufficient to create database tables. I assume you are just disabling and then enabling the module which will not help you to create tables in the database.
To get it working, admin/modules' locate your module and disable it. Then navigate to 'admin/modules/uninstall' and again locate your module and uninstall it.
After this, go toadmin/modules', and enable your module.
Now you can find the respective tables in your database.
You can also use drush for the same.
drush dis module_name, then
drush pm-uninstall module_name and finally
drush en module_name.
Also, as per @OPTASY Canada, do check your dblog for any warning or error.
Comment: `drush dre module_name` also disables, uninstalls and renables it with one command.
Answer: Only this much will work. make sure you first uninstall and reinstall this module again.
function mymodule_schema(){
    $schema['a_visits'] = array(

    'description' => 'visits table',
    'fields' => array(
        'id' => array(
            'description' => 'make id primary key auto increment',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'oferta' => array(
            'description' => 'nazwa oferty',
            'type' => 'varchar',
            'length' => '255',
            'not null' => TRUE,
        )
    ),
    'primary key' => array('id'),
    );
    return $schema;
}


It is possible to resume execution from the point where an exception was raised?

Question: There is an example which illustrates my question:
procedure Test;
begin
  try
    ShowMessage('1');
    raise EWarning.Create(12345, 'Warning: something is happens!');
    ShowMessage('2');
  except
    on E: EWarning do
      if IWantToContinue(E.ErrorCode) then
        E.SkipThisWarning // shows '1' then '2'
      else
        E.StopExecution;  // shows '1'
  end;
end;

function IWantToContinue(const ErrorCode: Integer): Boolean;
begin
  //...
end;

I tried to use something like this:
asm
  jmp ExceptAddr
end;

but it's wont' work...
Any ideas?
Thanks.
Comment: Don't raise the exception in the first place. Or learn all about Windows SEH and start hacking. The former solution is the tractable one.
Comment: something similar to VB `On Error Resume Next`? (one of main reasons I hate VB is that you don't have normal `try-catch` blocks).
Comment: if your running in IDE then hitting f9 will do the trick i gues
Comment: @kobik: I had the same association (guess we are "[mentally mutilated](http://www.brainyquote.com/quotes/quotes/e/edsgerdijk201164.html)" :-)). Unfortunately googling for `delphi "On Error Resume Next"` doesn't bring up anything useful.
Comment: @kobik: You're only talking about vb6 and before, right?  `On Error Result Next` was truly monstrous, especially in its handling of errors in subroutines, though `On Error...(do stuff)...Resume` was worse.  On the other hand, vb.net has try-catch blocks which are better than those in C# since they support exception filters.
Comment: @supercat, Indeed. however, I'll always take C# over VB.Net :)
Comment: @kobik: Both languages have annoying limitations.  I mainly use vb.net, but have tried to learn C# well enough to understand it.  If C# would add exception filters, the ability to implement interfaces with protected methods, allow the direct writing of Finalize methods (deprecate the silly "destructor" wrappers), add some better event handling, and allow a choice between early field initialization, late field initialization, constructor-parameter-based field initialization, and const-param pseudo-fields, then I'd likely say it was better than vb.
Answer: No, it is not possible:
There are two kinds of exceptions: logic exceptions that are raised by the programmer using the raise command, and external exceptions that are initiated by the CPU for various conditions: division by zero, stack overflow, access violation. For the first kind, the logic exceptions, there's nothing you can do because they're part of the application "flow". You can't mess with the flow of 3rd party code, you can't even mess with the flow of your own code.
External exceptions
Those are normally raised as a consequence of running a single CPU instruction, when that instruction fails. In Delphi those are made available as EExternal descendants. The list includes access violations, division by zero, stack overflow, privileged instruction and not-so-many others. Theoretically, for some of those exceptions, the causing condition of the exception could be removed and the single CPU instruction retried, allowing the original code to continue as if no error happened. For example SOME access violations might be "fixed" by actually mapping a page of RAM at the address where the error occurred.
There are provisions in the SEH (Structured Exception Handling) mechanism provided by Windows for dealing with such retry-able errors, and Delphi is using SEH under the hood. Unfortunately Delphi doesn't expose the required elements to make this easily accessible, so using them would be very difficult if not impossible. None the less, for particular types of EExternal errors, smart Delphinians might attempt writing custom SEH code and get things working. If that's the case, please ask a new question mentioning the particular type of error you're getting plus the steps you'd like to take to remove the error condition: you'll either get some working code or a customized explanation of why your idea would not work.
Logic exceptions initiated through the use of raise
Most exceptions fall into this category, because most code will check it's inputs before doing potentially dangerous low level stuff. For example, when trying to access an invalid index in a TList, the index would be checked and an invalid index exception raised before attempting to access the requested index. Without the check, accessing the invalid index would either return invalid data or raise an Access Violation. Both of those conditions would be very hard to track errors, so the invalid index exception is a very good thing. For the sake of this question, even if code were allowed to access an invalid index, causing an Access Violation, it would be impossible to "fix" the code and continue, because there's no way to guess what the correct index should be.
In other words, fixing "logic" exceptions doesn't work, shouldn't work, and it's insanely dangerous. If the code that raises the error is yours then you can simply restructure it to NOT raise exceptions for warnings. If that's not your code, then continuing the exception falls into the "insanely dangerous" category (not to mention it's technically not possible). When looking at already written code, ask yourself: would the code behave properly if the raise Exeption were replaced with ShowMessage? The answer should mostly be "NO, the code would fail anyway". For the very rare, very wrong case of 3rd party code that raises an exception for no good reason, you may ask for specific help on patching the code at run-time to NEVER raise the exception.
Here's what could be in some 3rd party code:
function ThirdPartyCode(A, B: Integer): Integer;
begin
  if B = 0 then raise Exception.Create('Division by zero is not possible, you called ThirdPartyCode with B=0!');
  Result := A div B;
end;

It should be obvious that continuing that code after the exception is not going to allow stuff to "self heal".
Third party code might also look like this:
procedure DoSomeStuff;
begin
  if SomeCondition then
    begin
      // do useful stuff
    end
  else
    raise Exception.Create('Ooops.');
end;

Where would that code "continue"? Quite obviously not the "do usefull stuff" part, unless the code is specifically designed that way.
Those were, of course, simple examples only scratching the surface. From a technical perspective, "continuing" after an exception as you're suggesting is a lot more difficult then jumping to the address of the error. Method calls use stack space to set up local variables. That space was released in the process of "rolling back" after the error, on the way to your exception handler. finally blocks were executed, possibly de-allocating resources where needed. Jumping back to the originating address would be very wrong, because the calling code no longer has what it expects on stack, it's local variables are no longer what they're ment to be.
If it's your code that's raising the exception
Your code can easily be fixed. Use something like this:
procedure Warning(const ErrorText:string);
begin
  if not UserWantsToContinue(ErrorText) then
    raise Exception.Create(ErrorText);
end;

// in your raising code, replace:
raise Exception.Create('Some Text');

// with:
Warning('Some Text');

Comment: As I wrote in my previous comments to Ulrich Gerhardt - I can't restructure my code in other way. If its technically not possible to "rolling back" (because stack is released after exception throwing), so there is an answer for my question (see the top): "not, it is not possible".
Comment: I edited the answer to incorporate the blunt answer you apparently expect. My intention was to give you not only the plain fact but explain why that's not going to work and why that's dangerous. You can't mess with the flow of code, and "resuming at the next line" does precisely that, messes with the flow. Again, that's beside the fact that technically the stack is unrolled to reach your exception handler. I'm ignoring that aspect in my explanation because it could be considered an implementation detail: if continuing after an exception would make some sense, an alternative implementation...
Comment: ... of the exception mechanism could be devised where the stack would not actually unroll, allowing the application to "continue". But that's not the case, because exceptions are supposed to stop the execution of current code because continuing is impossible or meaningless.
Comment: Thank you for your detailed answer. I know that it can be dangerous, but using exceptions as something that must stop the flow it's just a kind of using them. In most of situations you will do so. But sometimes in rare situations which are affected by many factors you will need something like what I asked. Not because it's not impossible to make it in different way (and maybe more safety). Exception is just a technique which allows you to manage your code.
Comment: So if Delphi could have `unraise` then this code is not meaningless: `try if b = 0 then raise EWarning.Create($DB0, 'division by zero'); c := a / b; except on E: EWarning do if E.ErrorCode = $DB0 then begin b := 1; unraise; end; end;`
Comment: I incorporated a bit of information on the SEH continuation mechanism and what are the candidates for that (even if it's not directly accessible from Delphi). Please re-read my answer, or at least the first half of it.
Answer: AFAIK no. You have to restructure your code to something like
procedure Test;
begin
  ShowMessage('1');
  try
    raise EWarning.Create(12345, 'Warning: something is happens!');
  except
    on E: EWarning do
      if IWantToContinue(E.ErrorCode) then
        // shows '1' then '2'
      else
        raise; // shows '1'
  end;
  ShowMessage('2');
end;

Comment: ...which is somewhat braindead. You could easily just ask the question without raising an exception then.
Comment: @Uwe: I guess that depends on how the real code looks like and if the exception originates from third-party code.
Comment: That is not what I want, because instead of `ShowMessage('1'), raise and ShowMessage('2')` will be a function, which can't be changed in a future. I will can only let it to continue its execution (handling `EWarning` and switching a flag as I showed above) or stop it.
Comment: @Victor: Can you add a parameter to this function which specifies whether to throw or not?
Comment: No, because there will be deep stack of calls inside this function with many another functions and much more... All that code will be not know anything about 'exception-throwing-or-not-flag'. I really need something like jumping to code beyond exception throwing (ShowMessage('2') in my case), because there are many others things which prevents me from restructuring the code. Only "jumping back" is acceptable. But thanks for answering anyway.
Answer: In C++, it is possible using an SEH __try/__except block whose __except expression evaluates to EXCEPTION_CONTINUE_EXECUTION.
In Delphi, it is not possible to use SEH directly, AFAIK.
Comment: AFAIK, SEH is Windows-specific, Linux does not have SEH.  Remember that language-based exception handling (`try/catch` in C++, `try/except` in Delphi) is different than SEH-based exception handling (`__try/__except` or `__try/__catch` in C++, depending on compiler). Language-based exception handling may be based on top of SEH (Embarcadero's implementation is, at least on Windows), but is not a requirement.  For instance, gcc does not support SEH at all, even on Windows (see http://gcc.gnu.org/wiki/WindowsGCCImprovements).
Comment: SEH is surely accessible from Delphi. Delphi exception handling is implemented on top of SEH.
Comment: Delphi's exception model is implemened on top of SEH, yes.  But that does not mean that user-written Delphi code can actually write SEH handlers directly.  Delphi exception handlers do not allow users to make use of `GetExceptionCode()`, `GetExceptionInformation()`, or `EXCEPTION_CONTINUE_EXECUTION`.
Comment: And it's not possible to issue some SEH instructions to supersede the Delphi native exception handling?
Comment: Not in native Delphi code, no.  You would have to drop down to the assembly level and write your own SEH code by hand.
Comment: +1. Is this EXCEPTION_CONTINUE_EXECUTION specific to Microsoft's SEH implementation? I'm trying this with the Linux g++ compiler and can't get it to compile.
Comment: As I can understand right, Delphi does not supports this type of exceptions' handling because it's must be implemented at the compiler  level? Or I can use some assembly language's magic to do this trick? (I mean `asm-end` block in Delphi code)
Comment: You would have to write your own assembly code to create a custom SEH exception handler, yes.  The technical details of how SEH works are on MSDN.
Comment: Could you give me direct link to it please? And how about throwing exceptions of that type in my code manually, not only handling them - is it possible?
Comment: See http://www.microsoft.com/msj/0197/exception/exception.aspx, you can use the Win32 API `RaiseException()` function to raise an SEH exception in code.
Answer: BASICally, your code wont work because ExceptAddr is a function, not a variable. So, your code snippet changes as follows:
{$O-}
procedure TForm1.FormCreate(Sender: TObject);
begin
  try
    OutputDebugString('entering');
    raise Exception.Create('Error Message');
    OutputDebugString('leaving');
  except on E: Exception do
    begin
      OutputDebugString(PChar(Format('ExceptAddr = %p', [ExceptAddr])));
      asm
        CALL  ExceptAddr
        JMP   EAX
      end;
    end;
  end;
end;

Comment: This code works, but crashes with runtime error when closing application ($O- is also doubtful)... Hope there are more ways for making that...
Comment: Er, what about the stack! You can't just jump into the middle of some random function lord knows where.
Comment: @DavidHeffernan that is probably what is causing the runtime error Victor said.
Comment: @EMBarbosa, yes, stack misalignment is present here, causing outerermost caller to fail. I'd like to spend more time in the RTL's guts, but no promises.
Comment: @user539484 You cannot fix this. You can't put the stack back to where it was when the exception was raised. What about all the finally blocks that have already run? How are you going to undo those. This is just a misthink.
Answer: ..you could nest multiple try-except and determine if continue inside each exception:
try
  try
    some code
  except
    ret := message('want to continue?');
    if ret <> mrYes then
      exit;
  end;
  some other code to perform when no exception or user choose to continue
except
  etc..
end;

Comment: You can read my other comments to see why this solution is not acceptable.
Answer: This is the example I used.
The following procedure will download files from several URLs (already in dataset form).
The problem is that http often has problems, so a retry mechanism is needed to try to download again. In this example I will try for 3 times, and each time I give 5 seconds sleep. After retry 3 times than will Break;
CDS is TClientDataset
Memo is TMemo
mnuDownload is a TButton or menu
uses IDHTTP;

procedure TForm1.mnuDownloadClick(Sender: TObject);
var
  S: String;
  HTTP: TIdHTTP;
  Stream: TMemoryStream;
  iRetry: Integer;

  function DoLoad_HttpXml: Boolean;
  begin
    try
      Result := True;
      HTTP.Get(CDS.FieldByName('url').AsString, Stream);
      Stream.SaveToFile(DataMod.XmlTarget +'\'+ S + IntToStr(CDS.RecNo)+ '.xml');
    except
      on E: Exception do begin
        inc(iRetry);
        Sleep(5000);
        Result := False;
        Memo.Lines.Add('File Number: '+IntToStr(CDS.RecNo)+' will Retry in 5 secs ( Attempt : '+IntToStr(iRetry)+' of 3 )');
      end;
    end;
  end;

begin
  mnuDownload.Enabled := False;
  HTTP := nil;
  Stream := nil;
  iRetry := 0;
  S := FormatDateTime('yyyy-mm-dd hh-mm-', Now);

  Memo.Clear;
  CDS.First;
  HTTP := TIdHTTP.Create(nil);
  HTTP.HandleRedirects := True;
  Stream := TMemoryStream.Create();

  while not CDS.Eof do begin
    Application.ProcessMessages;
    if iRetry = 3 then Break;
    if DoLoad_HttpXml then begin
      CDS.Edit;
      CDS.FieldByName('status').Value := True;
      CDS.Post;
      CDS.Next;
    end;
  end;

  if Assigned(HTTP) then FreeAndNil(HTTP);
  if Assigned(Stream) then FreeAndNil(Stream);
  mnuDownload.Enabled := True;
  CDS.First;
end;

Comment: That is no answer to the actual question.


Switched from apache to nginx: PHP Mail no longer working

Question: I switched to a new server, and from apache to nginx.
Everything is working great except the php mail function (returning true but mail not received).
What could I have possibly forget to install/configure during the switch that caused the issue ?
Thanks to all
Answer: 2 reasons pop to mind
You did not install sendmail.
You did not configure your php.ini for php-fpm correctly.
Comment: Installing sendmail did the trick, thanks. Testing the email I now get a "MyWebsite via subdomain.provider.com". Instead of subdomain.provider.com  I would like my messages to be sent from my original domain, I guess it has to do with headers but I didn't get that problem with my precedent server


How can I substitute a named route for a resource path in Rails 3?

Question: I have a named route to the user's inbox, which is maintained by the messages resource. I want to make sure that the users can only access their inbox from my named path, and remove "/messages" as an option.
  resources :messages
  match "/u/:nickname/inbox" => "messages#index", :as=>:inbox

Is there a simple way of doing that? Do I have to just create a matching path for "/messages"?
Answer: Solution 1:
I'd create a path for messages and remove resources :messages
This approach will delete all the normal routes for messages and you'll have to re-add the ones you want available.
Solution 2:
Only remove the index option for the routes and allow all other standards routes to be the same.
resources :messages, :except => :index
match "/u/:nickname/inbox" => "messages#index", :as=>:inbox

Comment: When I remove resources line, I get "No route matches {:action=>"create", :controller=>"messages"}" error on the new template.
Comment: Because we deleted the resources map you'll have to manually re-add the routes you want available for messages.


Wordpress - when I go to edit a page - Fatal error: Uncaught Error: Class 'WP_REST_Application_Passwords_Controller' not found

Question: I have a wordpress install and when I click to edit a post/page to edit I get this error:
Fatal error: Uncaught Error: Class 'WP_REST_Application_Passwords_Controller' not found
in /Users/kawnah/Sites/website/wp-includes/rest-api.php on line 269

Call stack:

create_initial_rest_routes()
wp-includes/class-wp-hook.php:287
WP_Hook::apply_filters()
wp-includes/class-wp-hook.php:311
WP_Hook::do_action()
wp-includes/plugin.php:484
do_action()
wp-includes/rest-api.php:521
rest_get_server()
wp-includes/rest-api.php:479
rest_do_request()
wp-includes/rest-api.php:2520
rest_preload_api_request()
array_reduce()
wp-admin/edit-form-blocks.php:82
require()
wp-admin/post.php:187

I went ahead and navigated to the file referenced and see:

And when I navigate to the actual class it is present:

My version of Wordpress is 5.6.2 - when I disable all plugins I get a TON of errors:
How do you even go about debugging this? What is the fix for this if any?
Answer: If anyone stumbles on this - what fixed this is downloading fresh core Wordpress (https://wordpress.org/download/) and replacing everything except wp-content directory to preserve your theme changes etc.


Viewing multiple source files simultaneously using MonoDevelop

Question: Is the above possible? I often do it in VS (usually to have the test and test target visible together) using the flexible window docking system. Is there some way to achieve the same thing in MonoDevelop?
Answer: Pretty sure it's not possible. The editor does have a split screen mode (as of Version 2.0) but that only allows looking at multiple places in the current file.
Comment: Yeah, found that, not quite what I need. Will have to raise a feature request..using MD more and more now, will have to get involved.


34/5000 why did you delete my post?

Question: Good morning,
why did you delete my post? Error on 'Newsletter Subscribers'
Could you give feedback please?
Comment: you should check [this](https://magento.stackexchange.com/help/deleted-answers)
Comment: @marius indicates using an answer to indicate you have the same problem is not the correct approach. A good approach if you have the same issue as the original poster is to upvote  the question, this will tag you on future answers.
Comment: For this type of things you can post a comment on users question, but for that you have to earn 50 rep in this site
Answer: Your answer was deleted because is was not an answer.
The Stackexchange network has a Q&A format where the question should describe the problem you are facing, and the answers should solve or try to solve the problem in the questions.
Posting "I have the same problem" as an answer does not count as an answer. It does not help the person who posted the question and it does not help future readers. It is just noise.

34/5000 why did you delete my post?


How to change TextFiled widget background color when focus

Question: I have a TextField widget which has default background color red.
I want to change the background color to blue when the TextFiled is focused. But I can't do that.
There are three relative properties about the color I have tried.
filled: true,
fillColor: Colors.red,
focusColor: Colors.blue,

The result is only filled is set to true, the fillColor worked and the focusColor never work.
Can you tell me what to do?
Comment: If an answer helped you fix your issue, remember to mark it as correct so that other users can find it easily.
Answer: You need to use a FocusNode on your TextField and a color variable to change the color:
Declarations
FocusNode _textFieldFocus = FocusNode();
Color _color = Colors.red;

@override
void initState() {
  _textFieldFocus.addListener((){
    if(_textFieldFocus.hasFocus){
      setState(() {
        _color = Colors.blue;
      });
    }else{
      setState(() {
        _color = Colors.red;
      });
    }
  });
  super.initState();
}

Widget
TextField(
  decoration: InputDecoration(
    fillColor: _color,
    filled: true
  ),
  focusNode: _textFieldFocus,
),


Indefinite integral of $\sin^8(x)$

Question: Suppose we have the following function:
$$\sin^8(x)$$
We have to find its anti-derivative
To find the indefinite integral of $\sin^4(x)$, I converted everything to $\cos(2x)$ and $\cos(4x)$ and then  integrated. However this method wont be suitable to find the indefinite integral $\sin^8(x)$ since we have to expand a lot. Is there any other way I can evaluate it easily, and more efficiently?
Answer: I copied and pasted this answer, since I actually wrote this answer to a different question which you can find here: Another way to solve $\int \frac{\sin^4(x)}{1+\cos^2(x)}\ dx$ without the substitution $y=\tan\left(\frac{x}{2}\right)$? ).
Define ${S_n = \int\sin^{2n}(x)dx}$. Then
$${S_{n}=\int \sin^2(x)\sin^{2n-2}(x)dx=S_{n-1}-\int \cos^2(x)\sin^{2n-2}(x)dx}$$
On the rightmost integral, using integration by parts yields
$${\int\cos^2(x) \sin^{2n-2}(x)dx=\frac{\cos(x)\sin^{2n-1}(x)}{2n-1}+\frac{1}{2n-1}\int \sin^{2n}(x)dx}$$
So overall
$${\Rightarrow S_n = S_{n-1}-\frac{\cos(x)\sin^{2n-1}(x)}{2n-1} - \frac{1}{2n-1}S_n}$$
And so
$${\left(\frac{2n}{2n-1}\right)S_n = S_{n-1} - \frac{\cos(x)\sin^{2n-1}(x)}{2n-1}}$$
$${\Rightarrow S_n = \frac{(2n-1)S_{n-1}}{2n} - \frac{\cos(x)\sin^{2n-1}(x)}{2n}}$$
Now you have a recursion relation that will help you compute the integral for higher even powers of ${\sin(x)}$:
$${S_{n} = \frac{(2n-1)S_{n-1}}{2n} - \frac{\cos(x)\sin^{2n-1}(x)}{2n}}$$
Comment: Had to scratch my brain for that integration by parts! Thanks for the detailed answer!
Comment: @DatBoi sorry! I should have specified. I used ${dv = \cos(x)\sin^{2n-1}(x)dx}$ and ${u=\cos(x)}$ :) no problem!
Answer: The development through the double angle formulae is not so long, let me show.
\begin{align}
\sin^8x
  &=(\sin^2x)^4=\\
  &=\left(\frac{1-\cos2x}{2}\right)^4=\\
  &=\frac{1}{16}(1-4\cos2x+6\cos^22x-4\cos^32x+\cos^42x)=\\
  &=\frac{1}{16}[1-4\cos2x+3(1+\cos4x)-4\cos2x(1-\sin^22x)+(\cos^22x)^2]=\\
  &=\frac{1}{16}\left[1-4\cos2x+3(1+\cos4x)-4\cos2x(1-\sin^22x)+\left(\frac{1+\cos4x}{2}\right)^2\right]=\\
  &=\frac{1}{16}\left[1-4\cos2x+3(1+\cos4x)-4\cos2x(1-\sin^22x)+{}\right.\\
    &\qquad\qquad\qquad\left.+\frac{1}{4}(1+2\cos4x+\cos^24x)\right]=\\
  &=\frac{1}{16}\left[1-4\cos2x+3(1+\cos4x)-4\cos2x(1-\sin^22x)+\right.\\
    &\qquad\qquad\qquad\left.+\frac{1}{4}\left(1+2\cos4x+\frac{1+\cos8x}{2}\right)\right]=\\
\end{align}
so we have
\begin{align}
\int\sin^8xdx
  &=\frac{1}{16}\left[x-2\sin2x+3\left(x+\frac{1}{4}\sin4x\right)-2\left(\sin2x-\frac{1}{3}\sin^32x\right)+{}\right.\\
  &\qquad\left.\frac{1}{4}\left(x+\frac{1}{2}\sin4x+\frac{1}{2}\left(x+\frac{1}{8}\sin8x\right)\right)\right]+C
\end{align}
Comment: Thats great! I was initially scared to apply. Now I've got three tricks up my sleeve ;)
Answer: There is well known recursion:
$$\boxed{I_n=\int\sin^nx \space dx = -\frac{1}{n}\sin^{n-1}x \cdot \cos x + \frac{n-1}{n} \cdot I_{n-2}}.$$
Comment: @Riemann'sPointyNose explained the derivation for even powers. With that knowledge and similar approach we can deduce this. Thanks
Comment: Hey! It's n-1 and not n+1
Comment: Thank you @DatBoi for the detection of an error, it is fixed now!
Answer: Hint: assume $  z=\cos x+i\sin x$ so $\frac{1}{z}=\cos x-i\sin x$ and $\sin x=\frac{1}{2i} (z-\frac{1}{z})$, also  $z^n =\cos nx+i\sin nx$
Comment: Then should I binomially expand $(z-1/z)^8$ ?
Comment: Yes,it may be lengthy but it could be done
Answer: By expanding
\begin{align}
\sin^8x
  &=\left(\frac{e^{ix}-e^{-ix}}{2i}\right)=\\
  &=\frac{1}{128}\left(
      \frac{e^{8ix}-e^{-8ix}}{2}
     -8\frac{e^{6ix}-e^{-6ix}}{2}
    +28\frac{e^{4ix}-e^{-4ix}}{2}
    -56\frac{e^{2ix}-e^{-2ix}}{2}+35\right)=\\
  &=\frac{1}{128}\left[\cos8x-8\cos6x+28\cos4x-56\cos2x+35\right]
\end{align}
or by using the identity
$$
(\sin x)^{2m}=\frac{2}{4^m}\left[\sum_{k=0}^{m-1}\binom{2m}{k}(-1)^{m-k}\cos[2(m-k)x]+\frac{1}{2}\binom{2m}{m}\right]
$$
that for $m=4$ provides
\begin{align}
\sin^8x
  &=\frac{2}{4^4}\left[\sum_{k=0}^3\binom{8}{k}(-1)^k\cos[2(4-k)x]+\frac{1}{2}\binom{8}{4}\right]=\\
  &=\frac{1}{128}\left[\cos8x-8\cos6x+28\cos4x-56\cos2x+35\right]
\end{align}
we have
\begin{align}
\int\sin^8xdx
  &=\frac{1}{128}\left[\frac{1}{8}\sin8x-\frac{4}{3}\sin6x+7\sin4x-28\sin2x+35x\right]+C\\
\end{align}
Comment: I appreciate your efforts. Now I can solve such questions using i)expansion(using complex numbers and binomial) ii)reduction. All thanks to y'all :)

Indefinite integral of $\sin^8(x)$


postfix NOQUEUE: reject: RCPT from Recipient address rejected

Question: I have setup Email filter appliance which utilises postfix.
postfix gives the following error in the logs
NOQUEUE: reject: RCPT from mail-oln040092070044.outbound.protection.outlook.com[22.214.171.124]: 451 4.7.1 <firstname.lastname@example.com>: Recipient address rejected: Greylisted for 5 minutes; from=<firstname.lastname@example.com> to=<email@example.com> proto=ESMTP helo=<EUR03-AM5-obe.outbound.protection.outlook.com>

below is my main.cf file contents
    alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-3.1.3/samples
readme_directory = /usr/share/doc/postfix-3.1.3/README_FILES
inet_protocols = ipv4

smtputf8_enable = no

meta_directory = /etc/postfix
shlib_directory = no
mynetworks = 127.0.0.0/8
header_checks = regexp:/etc/postfix/header_checks
myorigin = $mydomain
relay_domains = hash:/etc/postfix/transport
transport_maps = hash:/etc/postfix/transport
local_recipient_maps =
smtpd_helo_required = yes
smtpd_delay_reject = yes
disable_vrfy_command = yes
virtual_alias_maps = hash:/etc/postfix/virtual
default_destination_recipient_limit = 1
broken_sasl_auth_clients = yes
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain =
smtpd_sasl_path = smtpd
smtpd_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_type = cyrus
smtp_use_tls = yes
smtpd_use_tls = yes
smtp_tls_CAfile = /etc/postfix/ssl/smtpd.pem
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_tls_session_cache
smtp_tls_note_starttls_offer = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.pem
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.pem
smtpd_tls_CAfile = /etc/postfix/ssl/smtpd.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
tls_random_source = dev:/dev/urandom
smtpd_tls_session_cache_database = btree:/var/lib/postfix/smtpd_tls_session_cache
smtpd_tls_security_level = may
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtp_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_protocols = !SSLv2,!SSLv3
smtp_tls_protocols = !SSLv2,!SSLv3
smtpd_helo_restrictions = check_helo_access hash:/etc/postfix/helo_access, reject_invalid_hostname
smtpd_sender_restrictions = permit_sasl_authenticated, check_sender_access hash:/etc/postfix/sender_access, reject_non_fqdn_sender, reject_unknown_sender_domain
smtpd_data_restrictions = reject_unauth_pipelining
smtpd_relay_restrictions =
    permit_mynetworks,
    permit_sasl_authenticated,
    defer_unauth_destination hash:/etc/postfix/recipient_access, check_policy_service inet:127.0.0.1:2501
masquerade_domains = $mydomain
smtpd_tls_dh1024_param_file = /etc/postfix/ssl/dhparam.pem
smtpd_tls_ciphers = low

Answer: Your postfix greylisted sender. You need to wait until outlook servers will make another delivery attempt.
Comment: i just included the main.cf file i am now getting recipent address rejected having modified the transport map to include the domain. any further help. thanks
Comment: I misread your initial error message. I have updated my answer.


Angular 6 allowing dots "." in app name

Question: I'm just starting a new Angular app that will be part of an Asp.Net WebApi solution that consist of many projects which uses dots in their names like xxxx.Data, xxxx.Common, xxxx.Auth, etc and so I'd like to name the Angular frontend layer, following the same schema so its name should be xxxx.Web but executing ng new xxxx.Web throws an error advising app name is incorrect.
One quick solution I found is to create the app like xxxx-Web and then rename the folder to xxxx.Web and then replace all occurrences of the string in json files recursively and it works just fine but...
Is it safe to do this? Won't bring me problems in the future?
Why ng new doesn't allow dots in app names natively when using a dot is allowed for a folder name in OS?
Thanks.
Comment: Thank you very much for your comment @Stijn. Maybe you are right but I love uniformity across a whole project in what about naming schema (and other aspects) respects and presentation layer is a part of the whole project, that's why I prefer to follow the same naming convention, but only if I'm not going to came across with problems in the future.
Comment: That naming schema for .NET projects usually matches the root namespace of a project. Angular projects are unrelated to your .NET namespaces, so it makes little sense to follow the same schema.
Comment: whats SO? and why do you _need_ the `.` on it?
Comment: It's OS (Operating System) @mast3rd3mon, sorry I was thinking in spanish and wrote it the same way. Corrected.
Answer: @angular/cli doesn't allow naming apps like this. Please read this thread for more info on the same.
That being said, you can create your own schematic as a workaround. angular.io has an amazingly enlightening Medium Article that you can read about here.
Comment: Hello and thanks for your reply @Siddharth Ajmera. I don't know why you were downvoted but anyway I will have a look at the article you mention to see if I can find something interesting that helps.
Comment: I wasn't trying to convince you here. All I was saying is, there's a way to do what you're trying to do without manually changing the App names and its occurrences in your app.
Comment: Schematics is something that can help you develop a custom CLI that fits your needs. In fact, Angular CLI has been built on the top of Angular Schematics itself.
Comment: I'm not marking your answer as the correct because I'm not totally convinced @Siddharth because although Angular cli doesn't allow names with dots in it I was able to rename it after creation and after replaced all occurrences of the old name with the new with dots app started correctly (I have to say I have only tested with the base Angular app cli creates and not with a complex app though).
Comment: This is a year late and I just stumbled on this thread.  And regardless of the "correct" answer, @SiddAjmera does a great job of replying with an open mind and trying to understand the original question and Diego's point of view; rather than belittle the question or the approach as the other comments do.
Well done on contributing to a positive learning environment SiddAjmera.

Angular 6 allowing dots "." in app name


Creating a Christmas tree programatically in c?

Question: I need help with creating a Christmas tree in C which varies based on user input.
Firstly, the user is prompted for the number of levels they want on the tree. E.g. First level "*", second level "***". Two stars are added every level.
Valid levels run between 4 and 10 inclusive. Anything less than 4 or greater than 10 is invalid, an error message will be displayed in the program output and the minimum level of the tree will also be displayed (4 levels).
The final part of the tree is done by adding a trunk with a width of 3 stars and a height of 2 stars.
This is my c program. It is incomplete and I have no idea how to move on. I am totally confused.
 #include <stdio.h>
void main()
{
    char choice;
    int level, levelcount, star, starcount;

    printf("Do you want to print a Christmas Tree (Y/N)?");
    scanf_s(" %c", &choice);

    if (choice == 'Y')
    {
        printf("How tall is your Christmas Tree (Level 4 to 10)?");
        scanf_s("%d", &levelcount);

    starcount = 1;
    for (level = 1; level <= levelcount; level++)
    {
        for (star = 1; star <= starcount; star++)
        {
            printf("*");
        }
        printf("\n");
    }
        starcount += 2;
    }
    else if (choice == 'N')
    {
        printf("Merry Christmas and Goodbye!\n");
    }

}

Comment: Please provide details inside the question. Image sites can go offline, and that makes the question useless for future readers (Assuming it's a good question).
Comment: Also, "I am having a time doing it" is not a valid problem description, what exactly is the trouble you are facing?
Comment: What's this strange obsession with creating images of text among new programmers? Code is text. Use copy and paste and *post the text*.
Comment: I have edited my question.... hope this helps.
Answer: Firstly, your code is in C and not C++. If you're using C++ you'd use functions such as cin or cout but here you're using printf and scanf.
To create this tree you're going to have two sections. One part that deals with the main tree, and the other that deals with the trunk. In the code below I used a variable offset to calculate a certain number to determine the midpoint of the tree. Basically, each level has an odd number of stars. If you subtract the offset from the number of stars, you'll find the number at the mid-point. Starting from 3 the offset is 1. 3 - 1 = 2 which is the mid-point. For every two stars added to the level, the offset must go up by one.
To print the tree:
#include <stdio.h>
void main()
{
    char choice;
    int level, levelcount, star, starcount, offset;

    printf("Do you want to print a Christmas Tree (Y/N)?");
    scanf_s(" %c", &choice);

    if (choice == 'Y')
    {
        printf("How tall is your Christmas Tree (Level 4 to 10)?");
        scanf_s("%d", &levelcount);

        //Check if level is within valid range
        starcount = 1;
        offset = 0;
        if (levelcount < 4 || levelCount > 10)
        {
            //Prints default tree (4 levels)
            for (level = 1; level <= 4; level++)
        {
            for(star = 1; star <= starcount; star++)
            {
                printf("*");
            }
            printf("\n");
            //Adds two stars each level
            starcount += 2;
            offset += 1;
        }
    }
        else
        {
            //Prints tree with custom levels
            for (level = 1; level <= levelCount; level++)
            {
                for(star = 1; star <= starcount; star++)
                {
                    printf("*");
                }
                printf("\n");
                //Adds two stars each level
                starcount += 2;
                offset += 1;
            }
        }

        //Finds out the mid-point of the tree
        int midpoint = starcount - offset;

        //Prints the trunk
        printf("%*s%s\n", offset - 1, "***");
        printf("%*s%s\n", offset - 1, "***");

    }
    else if (choice == 'N')
    {
        printf("Merry Christmas and Goodbye!\n");
    }
}

For the trunk section, since it was at a fixed width of 3 stars and had only two levels, a loop wasn't exactly necessary but it would be good to include it. The %*s was a specific modifier to print some extra spaces to the left so it would be at the mid-point of the tree.
For more on padding with spaces in C check this answer by Bill the Lizard. One of the comments below the answer will show how I managed to print a certain number of spaces determined by the variable offset - 1.
Answer: #include <stdio.h>

int main()
{
    int a,b,c,d,e,f,g,h,i,j,k,row;

    printf("enter rows :");
    scanf("%d",&row);
    printf ("* * * * * *merry christmas* * * * * *\n\n");
    for (a=1;a<=row;a++)
    {
        for (b=row;b>=a;b--)
        {
            printf(" ");

        }
        for (c=1;c<=a;c++)
        {
            printf("* ");

        }
        printf("\n");
    }
    for (d=1;d<=row-2;d++)
    {
        for (g=row-1;g>=1;g--)
        {
            printf(" ");

        }
        printf("* *\n");

    }
    return 0;
}


Extracting last item from string in foreach loop

Question: I'm working on matrix that contains the name of a class, but sometimes the class name is very long and I only need two last sections of name.
I have string containing some text, separated with '.', and I need to extract last two text.
For example:
string : af.bf.cf.df.ef
my needed value : df.ef
I wrote some code, but it's not working:
<code>string[] split1 = "af.bf.cf.df.ef";
foreach (string item in split1)
{
 string myvalue = item;
}
</code>
Comment: Which programming language?
Answer: <code> string[] list  = "18.104.22.168.5".Split('.');
 string last2 = list[ list.count - 2] + "." + list[ list.count - 1];
</code>


Logical Equivalences for "F" as a subset of the powerset of "A"

Question: Are these two statements equivalent?
Suppose F is a a subset of the powerset of A.
So $F \subseteq P(A)$
Then,
Statement 1: $  \forall x \in F(\forall y(y \in x \implies y \in A ))$
Is it not the case that this statement would also be equivalent?
Statement 2:
$\forall x \in F(x \in F \implies x \in A)$
Comment: Statement 2 will become equivalent to Statement 1 if you replace it with $\forall x\in F(x\subseteq A)$ (i.e. replace $\in$ with $\subseteq$ and suppress the redundant "$x\in F\implies$").
Comment: Please choose a more descriptive title. (It may include formulas.)
Comment: x is a subset of $A$ hence it cannot be an element of $A$ you are comparing different objects
Comment: thank you, that makes sense
Comment: In "statement" 1, what are the brackets supposed to mean.  I usually wouldn't expect anything of the form "$\{....\}$" to be a statement at all.  I'd expect it to describe a set with "$....$" being a description.  If I were to interpret $\forall x\in F(\forall y(y\in x\implies y\in A))$ as a description of elements (to be honest I'm not sure if that is gramatically acceptable or not), then 1 is not a statement at all but merely a description of a subset of $F$ (which would happen to be $F$ itself).
Answer: No, without even reading what F is, we can tell from $\forall y$, if $y \in x$ then $y \in A$, that $x \subset A$, as any element in x appears in A as well. Because x is a subset of A, x is not inherently an element of A. For example, consider $$A = \{1,2,3,4,5\} \\ x = \{1,2,3\}$$ here, x is clearly not an element of A. The elements of x, namely 1,2,3, all appear in A but the set x istself does not ($\{1, 2, 3\} \not \in A$). But if we set $A = \{1,2,3,4,5, \{1,2,3\}\}$, x is now an element of A, as we can clearly see that x is inside of A. Statement 2 would be correct if it was changed to $$\forall x( x \in F \rightarrow x \subset A)$$ And we had previously defined $F \subseteq P(A)$.
Also, in the comments someone wrote that $x \subseteq A$, which is (to my knowledge) improper notation, as $\subseteq$ is a proper subset meaning x cannot equal A, which is not the case here.


C# IComparable IComparer with additional Param

Question: How can I implement IComparer
int CompareTo(object obj)
with an additional parameter, like
int CompareTo(object obj, Dictionary<int, int> preferences)
preferences is a dictionary with Id and NumberOfClicks<int, int>
What I want is compare contents which have categoryId by the number of clicks in the dictionary,
Example Cat 1 has 3 clicks, Cat 2 has 6 clicks.
Sort by comparing
preferences[this.CategoryId].value > preferences[object.CategoryId].value
So they are sorted by category, but in relation to the Dictionary.
Comment: The signature that you show is from `IComparable`, not `IComparer`.
Answer: You cannot pass extra arguments to IComparer's Compare method, because method signature must match the signature in the interface.
What you can do is to construct an instance of IComparer with the extra parameter, store it in the instance, and use inside CompareTo as needed:
class MyComparer : IComparer<object> {
    private readonly IDictionary<int, int> preferences;
    public MyComparer(IDictionary<int, int> preferences) {
        this.preferences = preferences;
    }
    public int Compare(object a, object b) {
        ... // Perform the comparison with preferences in scope
    }
}

Answer: Create a separate comparer class that implements IComparer<T>, rather than having the type itself implement IComparable, and have it accept the Dictionary in its constructor.  That comparer can then use the dictionary when it compares instances of your object.


Which out would not count here?

Question: Imagine that with one out and all bases loaded, the batter hits a fly ball that is caught out by the left outfielder. However, due to negligence, only the runner on second base remembers to tag up. The ball is then thrown to third base, beating the runner from 2nd.
With the batter being caught out, there are then two outs. However, it appears that the throw to third simultaneously doubles off the runner from third base and forces out the runner from second base. Since there can only be three outs per inning, one of the outs would not "count".
My question is: which would be the official third out?
Answer: Since the outfielder caught the fly for the second out, and the runner on second tagged up properly, he is not forced out on third – he would have to be tagged out on third for him to be out.  If he was tagged, he would have been the third out.  That out would "come first" relative to your question.
However, if the tag was missed, and the third baseman touched the base with the ball, I believe he would have to "appeal" to the umpire.  And assuming the umpire agreed that the third base runner at time-of-pitch did not tag up properly, then the out would be awarded.
Comment: The question says that the man on second was the only one to tag. If the others tagged and left early an appeal would be correct, but if they simply didn't tag, the runner would be out on a force out.
Comment: @Egroegw - Note: - I just thought of this - the third baseman would want to appeal anyway if the third base runner touched home plate BEFORE that third out tag was made – which very well may be the case if he left the base before the catch.  Otherwise that run would count because it's a 'time play' as the third out was not a force out.  So you'd want to appeal anyway to negate the run.
Comment: @diggers3: There is no force play after the fly ball is caught for the first out. The runner going from 2nd to 3rd must be tagged (while off base) to be put out. Also, the runner who left 3rd early should be called out after the 3rd baseman caught the ball and touched 3rd base, but that's not called an appeal play (which would come after the play was over and time was called).

Which out would not count here?


Java + Spark - temp folder not getting cleaned

Question: We are using Spark + Java in our project, and the Hadoop distribution being used is MapR.
In our Spark jobs we persist data (at disk level).
After the job completes, there is lot of temp data inside the /tmp/ folder.
How can we ensure that /tmp/ folder (temp data) gets empty after the job execution completes.
I found a link below:
Apache Spark does not delete temporary directories
But not sure how to set the following properties:

spark.worker.cleanup.enabled
spark.worker.cleanup.interval
spark.worker.cleanup.appDataTtl

Also, where to set these properties:
1. In Code
Or 2. In spark configuration
We are running the job in cluster mode (with master yarn), using spark-submit command.
Thanks
Anuj
Answer:
Create a backup of the spark-env.sh file.
Open the file in a text editor (e.g. vi) and locate "SPARK_WORKER_OPTS"
Immediately below this line, add or update:SPARK_WORKER_OPTS="-Dspark.worker.cleanup.enabled=true -Dspark.worker.cleanup.appDataTtl=172800"
This should enable work logs cleanup, and will retain logs for no longer than 48 hours, with a default check time of every 30 minutes.

Restart Spark and done!
Comment: Also this is only for cleaning logs. But we are looking to clean the temp directory.
Comment: Have you found any solution for this ?
Comment: But this is only for standalone mode. We are running the jobs in cluster mode. As per Spark documentation:  spark.worker.cleanup.enabled false Enable periodic cleanup of worker / application directories. Note that this only affects standalone mode, as YARN works differently. Only the directories of stopped applications are cleaned up.                                                spark.worker.cleanup.appDataTtl 604800 (7 days, 7 * 24 * 3600) The number of seconds to retain application work directories on each worker. This is a Time To Live and should depend on the amount of available disk spa


What is the idea behind the proof of the Theorem 7.2.1 in this book : Fundamental of the theory of operator algebras Vol II (Kadison and Ringros)

Question: I am writing about the following theorem:

7.2.1. Theorem. If $\mathcal R$ is a von Neumann algebra acting on a Hilbert space
  $H$ and $x_0$ is a unit generating vector for $M$, then, for each vector $z_0$ in $H$, there
  are operators $T$ and $S$ in $\mathcal R$ and a vector $y_0$ orthogonal to the null space of $T$
  such that $Ty_0=x_0$ and $Sy_0=z_0$.

The first paragraph of in this proof is completely clear.
In the second paragraph, a sequence a operators is introduced which makes the assertion is proved. I strongly would like to know how they have found if such a sequence is considered, then the assertion will be obtained!
Answer: In the first paragraph of the proof, the sequence $\{T_n\}$ is constructed with $\sum T_nx_0=z_0$. There is no reason for the series $\sum T_n$ to converge; so the idea is to get $T$ and $y_0$ such that $Ty_0=x_0$ and $\sum T_nT$ converges.
The point $y_0$ is chosen as a wot cluster point of a sequence $\{H_nx_0\}$. If one gets $\{H_n^{-1}\}$ to be convergent to a $T$, then such $T$ will satisfy $Ty_0=x_0$.
We also need $\sum T_nT$ to be convergent. One way to guarantee this is to have $\|T_nT\|\leq2^{-n}$, which we can write as
$$\tag{1}
4^nT^*T_n^*T_nT\leq I.
$$
Since we want $T=\lim H_n^{-1}$, for $(1)$ to hold we need
$$
4^kH_n^{-1}T_k^*T_kH_n^{-1}\leq I
$$
when $n\geq k$,
or
$$\tag{2}
4^kT_k^*T_k\leq H_n^2.
$$
This suggests taking $H_n^2=\sum_{k=0}^n4^kT_k^*T_k$. Since we want them to be invertible, we define
$$
H_n^2=I+\sum_{k=0}^n4^nT_k^*T_k.
$$
It is not clear a priori what happens with the norms of these $H_n$, but since $H_n\geq I$ and $I\leq H_n\leq H_{n+1}$, the sequence $\{H_n^{-1}\}$ is positive and decreasing, and so it has a sot limit $T$.
From $H_nx_0\to y_0$ (with a subsequence), one obtains $Ty_0=x_0$.
Comment: Thanks for your pay attention, but I mean something else. I understand the proof but it is really strange for me how such an idea is created!
Comment: Ok, I have edited.
Comment: Actually, your explanation is crystal clear. Thank you so much for your nice ant interesting comments.
Comment: Glad I could help.