ServiceStack: Routes.AddFromAssembly still uses /json/reply path and no URL-niceness for properties

Question: I have a ServiceStack self-hosted webservice, using the AppSelfHostBase.
WHen the Configure method is executed, I have this:
public override void Configure(Container container)
{
    Config.RouteNamingConventions = new List<RouteNamingConventionDelegate> {
        RouteNamingConvention.WithRequestDtoName,
        RouteNamingConvention.WithMatchingAttributes,
        RouteNamingConvention.WithMatchingPropertyNames,
    };

    Routes.AddFromAssembly(typeof(ServiceStackHost).Assembly);

and I expected the following service to be executed under /StartBankIdAuthentication path, but it resides under /json/reply/StartBankIdAuthentication instead.
public class StartBankIdAuthentication : IReturn<StartBankIdAuthenticationResponse>
{
    public string IdNbr { get; set; }
}

Also, is there an automatic way to make the properties in the DTO to be under "sub-paths", like /StartBankIdAuthentication/1234 instead of the /StartBankIdAuthentication?IdNbr=1234?
I know I can manually add the Route attribute, but it seems cumbersome and also messy in many ways (not Typed, error-prone etc).
Answer:
I expected the following service to be executed under /StartBankIdAuthentication path, but it resides under /json/reply/StartBankIdAuthentication instead.

The /json/reply/StartBankIdAuthentication is a pre-defined route that's always available by default, they have no relation to Auto Generated Routes.
The default Route generation strategies you've listed are already registered by default and are what's applied when you use Routes.AddFromAssembly(). You should only override with route strategies you want in addition to the defaults, and you should use SetConfig() for any configuration in ServiceStack, e.g:
SetConfig(new HostConfig {
    RouteNamingConventions = { MyCustomRouteStrategy }
});

The implementation for the different Route Strategies available in ServiceStack are in RouteNamingConvention.cs, you'll need to register your own strategy for anything additional Route strategies you want.
By default additional routes are generated for any Id or IDs property, the routing docs shows examples of how they can be customized:
The existing rules can be further customized by modifying the related static properties, e.g:
RouteNamingConvention.PropertyNamesToMatch.Add("UniqueId");
RouteNamingConvention.AttributeNamesToMatch.Add("DefaultIdAttribute");

Which will make these request DTOs:
class MyRequest1
{
    public UniqueId { get; set;}
}

class MyRequest2
{
    [DefaultId]
    public CustomId { get; set;}
}

Generate the following routes:
/myrequest1
/myrequest1/{UniqueId}
/myrequest2
/myrequest2/{CustomId}

I know I can manually add the Route attribute, but it seems cumbersome and also messy in many ways (not Typed, error-prone etc).

If you really want you can use nameof() for Typed Routes:
[Route("/" + nameof(StartBankAuthentication) +"/"+ nameof(StartBankAuthentication.IdNbr))]

Comment: Thanks, I have read the documentation, which I obviously misunderstood. So the question is, is there a way, using `RouteNamingConventions`, to create paths that start with `/` and that automatically maps all properties in the DTOs, in order, so `/SomeMethod/{FirstProp}/{SecondProp}` and so on? I know how to override the `GetRouteAttributes` and manually build the "base path", but unsure how to add the property as "parameters-in-a-path" :-)
Comment: I dont want to specify `RouteNamingConvention.PropertyNamesToMatch.Add("UniqueId");`, because that defeats the purpose; I just want to define the name and properties in the DTO, and then let ServiceStack auto-generate the rest ;-)
Comment: @Ted ServiceStack doesn't auto-generate anything, each custom [Route Convention Implementations](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack/Host/RouteNamingConvention.cs) is what registers the routes which gets called for each Request DTO/Actions. If the pre-build routing conventions don't do what you need you'll need to implement and register your own. See how the existing conventions are implemented for reference.
Comment: Alright, thx. If you see my answer below, is that a good/valid/reasonable solution, or is it a bad idea, and if so, why? =)
Comment: @Ted .NET's reflection APIs are not deterministic so you shouldn't rely on the order properties are defined on the class, you'll want to make them deterministic by either sorting them by name or adding an explicit order. Also it's poor form to design HTTP APIs like this, the route should be the resource/identifier for the Service where all other properties are modifiers of that Resource i.e. shouldn't be included in the route and should be left as queryStrings.
Comment: @Ted Routes define your public API which is why everyone explicitly defines them so they can control what external routes consumers bind to, so I'd be reluctant auto generate deep routes like this where you have limited control over your API and adding/removing properties could break multiple routes clients depend on.
Comment: I see, thanks for your input. I was always under the impression that all properties should be in the path, as below, but you mean they shouldnt, but instead use the more bloated `?varName=varValue` ... I will consider this.
Comment: @Ted Yes adding properties which aren't used to identify the service on the queryString. The resource/identifier for your Service should never change, but you can liberally add additional properties to customize the request, the appropriate API design to do that for GET requests is via the queryString.
Answer: I'm not sure if Mythz will maybe come up with a different of better solution, but I managed to achieve what I wanted by overriding the GetRouteAttributes, and by using reflection, I could create what I wanted. It looks like this:
public override RouteAttribute[] GetRouteAttributes(Type requestType)
{
    string fullname = requestType.FullName.Replace("AlfaOnlineServiceModel.Api.", "");
    string path = "/" + fullname.ToLower().Replace(".", "/");

    RouteAttribute[] routes = base.GetRouteAttributes(requestType);
    if (routes.Length == 0)
    {
        routes = new RouteAttribute[1];

        PropertyInfo[] pInfos = requestType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
        foreach(PropertyInfo pi in pInfos)
        {
            path += "/{" + pi.Name + "}";
        }

        routes[0] = new RouteAttribute(path);
    }
    return routes;
}

Which will give for example:
MyMethodResult
The following routes are available for this service:
All Verbs   /myCoolPath/mySubPath/myMethod/{MyProperty}


Template specializations in friend declarations post C++20

Question: Context: To our surprise, MSVC with C++20 mode and two-phase compliance enabled accepts the following code:
template<class T>
class X
{
    friend int foo<X>(X x);

    int a = 10;
};

template <class T>
int foo(T t)
{
    return t.a;
}

int main()
{
    return foo(X<float>{});
}

This compiles/links and returns 10 in MSVC and gcc (but clang barks): https://godbolt.org/z/98cd7v7a6.
Those who know about two-phase lookup will find that this looks pretty crazy - we can somehow befriend a template specialization before the corresponding template is even declared. Looks and sounds very wrong. And indeed, for earlier C++ versions, all compilers would immediately reject it: https://godbolt.org/z/M1733EPd5
But it appears that the following wording in C++20 paves the way for this (or at least makes it not outright ill-formed from the start): https://timsong-cpp.github.io/cppwp/n4861/temp.names#2.sentence-4 (emphasis mine)

A name is also considered to refer to a template if it is an unqualified-id followed by a < and name lookup either finds one or more functions or finds nothing.

Now, this leads to a whole host of... well, absurd corner cases. Note that outside of friend declarations you'd have to begin a template specialization with template<>, but that is not the case in friend declarations. Predictably, compilers cannot even remotely agree on what is now legal and what is not:

Befriend...
godbolt
MSVC
gcc
clang

...declaration of specialization of non-existent function template inside a class, call it
https://godbolt.org/z/9bczs6nde
✓
✗
✗

...declaration of specialization of non-existent function template inside an uninstantiated class template
https://godbolt.org/z/461h774sz
✓
✓
✗

...declaration of specialization of non-existent function template inside a class template, call it (note https://timsong-cpp.github.io/cppwp/n4868/temp.inject)
https://godbolt.org/z/fK6s9aj5G
✓
✗
✗

...declaration of specialization of non-existent function template specialization in class, provide function template definition, call it
https://godbolt.org/z/Mevr4EWzG
✓
✗
✗

...declaration of specialization of non-existent function template specialization in class template, provide function template definition, call it
https://godbolt.org/z/d9s9hWsa7
✓
✓
✗

...definition of specialization of previously declared function template inside a class, call it
https://godbolt.org/z/ebrhvGrM4
ICE
✗
✓

...definition of specialization of previously declared function template inside a class template, call it
https://godbolt.org/z/bsjKxWYco
✗
✗
✓

...definition (!) of specialization of non-existent (!!) function template inside a class template and call it afterwards (!!!)
https://godbolt.org/z/PnP6oKrrM
✓
✗
✗

In short, wtf.
Question: Does the C++20 standard currently have a clear and consistent stance on these points:

Is it legal for friend declarations to refer to a not-previously-declared function template? Does this depend on whether we are inside a template/involve dependent types?

Is it ever (or always?) legal to define a specialization of a function template via a friend declaration? (See again https://godbolt.org/z/bTaYraP6j, https://godbolt.org/z/Y7qf6PPxY - some compilers state it's illegal but then also randomly accept it)
Comment: Not an answer to the question, but the reason for the changed lookup rule was that - equally absurd - a totally unrelated local foo template would trigger an ADL search to find the one actually used. But without the local foo `foo<x` was an error.
Comment: @Afshin FWIW, the standard appears to more or less acknowledge what you say in this note: https://timsong-cpp.github.io/cppwp/n4861/temp.names#2.sentence-2. But I have no clear concept of how ADL applies to this whole situation around `friend`, and it appears that the compilers do not either.
Comment: _https://timsong-cpp.github.io/cppwp/n4861/temp.names#2.sentence-4 ... Cursory search points to this paper being the origin of that: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1787r6.html_ A document [Generated on 2020-04-03](https://timsong-cpp.github.io/cppwp/n4861/) got its wording from an October 23, 2020 paper? Where «A name is also considered to refer to a template if it» is being removed? Seriously?
Comment: @LanguageLawyer I admit it was *very* cursory. Removed that part from the question.
Comment: According to the answer in the Clang issue https://github.com/llvm/llvm-project/issues/46865, a declaration of a template named `foo` prior to the `friend` declaration of the specialization is required even in C++20 mode. (Note that the issue had been raised much later than the relevant change to the standard draft was made, see https://github.com/cplusplus/draft/commit/75516dac895d8a9ab7a925b8400989910e3b08ff). So that would mean Clang is correct to reject all of these cases. I am not sure how to get to this conclusion though.
Answer: It's true that there are no parsing difficulties here: C++20 does give the right meaning to the <, and template argument lists are parsed independently of the template declaration (which is how function template overloading and ADL can work).
Next, C++20 as published doesn't say much in general about the process of declaration matching, leaving a number of questions open about which declarations refer to the same entity (validly or no).  As such, it doesn't really address the friend-before-declaration case, although its [namespace.memdef]/3 says

If the name in a friend declaration is neither qualified nor a template-id and the declaration is a function or an elaborated-type-specifier, the lookup to determine whether the entity has been previously declared shall not consider any scopes outside the innermost enclosing namespace.

which implies that there is some sort of lookup performed, including in the template-id case, that could fail.
I say "as published" in the above because many of the fixes in the already-mentioned P1787R6 were considered to be Defect Reports (read: retroactive).  I don't recall an issue on specifically this subject, but the changes in that paper to [decl.meaning] to specify the special lookup process for declared names might best be considered retroactive as well.
As for defining a specialization, the only thing that any recent standard version says is in [temp.expl.spec]/1:

An explicit specialization […] can be declared by a declaration introduced by template<>; […]

This is unfortunately vague, but it's not unreasonable to take as an implication that there is no other means of defining an explicit specialization, including via a friend declaration.  Certainly that's the intent: specializations aren't found by name lookup, so there's no point in making them hidden friends.
Answer: I haven't checked C++20, but I think the latest draft standard says that the declaration of friend int foo<X>(X x); is ill-formed .
[dcl.meaning]/2:

If the declaration is a friend declaration:

If the id-expression E in the declarator-id of the declarator is a qualified-id or a template-id:

[...]
The declarator shall correspond to one or more declarations found by the lookup

In friend int foo<X>(X x);, the id-expression in the declarator-id is foo<X>. It is a template-id, so it is required to have a preceding declaration.
(For the reference, foo is looked up from the definition point ([temp.res.general]/1), because it is not a dependent name ([temp.dep.general]/2).)
Comment: The quoted passage originates from https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1787r6.html. Unfortunately I wasn't really able to determine whether the same restriction was already present in some other way in C++20 or whether this is a newly-added (maybe as a resolution of one of the listed issues?).


Migrating disqus comments from non drupal site to drupal 7 site

Question: I have installed an set up Disqus (add shortname and public key). How can i show/migrate my old comments to my new drupal site.
Answer: Disqus offers variety of migration tools depending on your needs - https://help.disqus.com/customer/en/portal/articles/286778-migration-tools. I performed migration of comment threads from static website to Drupal 7 recently. Main change to the pages with comments was new clean URLs, so in my case all I needed to do is to use URL mapper tool. It is very straight forward and comment threads were migrated in minutes.


Como eu pego o nome de um input

Question: Exemplo:
<input type="text" name="peixe">

Como eu consigo o nome peixe???
Observação: javascript puro
Comment: O que você quer exatamente? a sua tela só vai ter esse input? se sim
Comment: Você quer obter "peixe"? Sendo assim, se o input tivesse outro nome, você receberia esse outro nome? Ou quer obter o valor do input a partir do nome peixe?
Comment: AKU e consegiu resolver?
Answer: A maneira mais recomendada em pegar o nome seria com getElementsByTagName(), exemplo:

var nomes = document.getElementsByTagName("input");
console.log(nomes[0].name);
<input type="text" name="peixe">

porque, é mais suportados pelos navegadores:

Google Chrome 1
IE 6
Firefox 3
Safari 3
Opera 5

Nota: o getElementsByTagName() nesse caso em especifico pega todos os elementos input, ou seja, um array de informações, no caso da pergunta só tem 1 então nomes[0].name retorna o nome desse input, se tiver 30 input vai retornar um array desses 30. Talvez falte um contexto melhor, mas, do jeito que está na pergunta isso é o que precisa.

Tem um outra forma que é com querySelector, exemplo:

console.log(document.querySelector('input').name);
<input type="text" name="peixe">

e os navegadores suportados são:

Google Chrome 1
Firefox 3.5
IE 8
Opera 10
Safari 3.2

Referencia:

Document.getElementsByTagName()
HTML DOM getElementsByTagName() Method
Document.querySelector()
Comment: Não é maneira mais simples, e sim a mais recomendada...
Comment: @FelipeDuarte realmente já editada
Comment: Seria interessante essa resposta ser usada como referência pois tem um suporte quase nativo, mas em relação a simplicidade poderia ser editada ;)
Comment: Não entendi @FelipeDuarte?
Answer: Você também pode usar queryselector

console.log(document.querySelector("input").name)
<input type="text" name="peixe">

Definição e Uso
O método querySelector() retorna o primeiro elemento que corresponde a um seletor CSS especificado no documento.

Nota: O método querySelector() apenas retorna o primeiro elemento que corresponde aos seletores especificados. Para retornar todas as correspondências, use o método querySelectorAll().

Se o seletor corresponder a um ID no documento que é usado várias vezes (Observe que um "id" deve ser exclusivo dentro de uma página e não deve ser usado mais de uma vez), ele retorna o primeiro elemento correspondente.
Answer: Acredito que a maneira mais simples seria com querySelector, para vários elementos poderia usar o querySelectorAll...

console.log(document.querySelector('input').name);
<input type="text" name="peixe">

Como eu pego o nome de um input


How to load image from Custom Module with javascript?

Question: I'm trying to build a custom module
https://github.com/alexseif/drupal_infinite_scroll and
I need to load the image in the images folder "images/ajax-loader.gif"
in the js file alx-infinite-scroll.js
I have this in my js file
drupal_get_path('module', 'alx_infinite_scroll') + '/images/ajax-loader.gif' I have no clue where to start, any help would be much appreciated and/or link to the relevant documentation if possible.
Comment: You've added both Drupal 7 and Drupal 8 tags. The module you linked seems to be only for Drupal 7 so am I right to assume the Drupal 8 tag is a mistake?
Comment: Yes, thank you for pointing that out. I was trying to tag it 7, modules
Answer: drupal_get_path() is a PHP function so you cannot call it in your JS.
To use the result of that function in your JS you would need to call the function in your PHP and then add the output to the JS on the page. You can use Drupal.settings for this. For example:
// Settings to pass to our JS.
$settings = array(
  'loaderImgPath' => drupal_get_path(
    'module',
    'alx_infinite_scroll'
  ) + '/images/ajax-loader.gif',
);
// Add to the JS settings.
drupal_add_js(array('alx_infinite_scroll' => $settings), 'setting');

Then you can use something like this in your JS:
Drupal.behaviors.alxInfiniteScroll = {
  attach: function (context, settings) {
    var imgPath = settings.alx_infinite_scroll.loaderImgPath;
  }
}

I recommend reading some of the documentation on Drupal's JavaScript APIs as it goes over this. For example:  https://www.drupal.org/docs/7/api/javascript-api/managing-javascript-in-drupal-7
To do that though you need to add the above PHP code somewhere.
In your case you are loading your JS in the info file, which means it will load on every page.
I would advise against this unless you actually need your JS to run on all pages, but if you do want it on all pages you could use something like hook_page_build().
In that case since you are dealing with the page render array you can use the #attached method of adding JS and JS settings that is referred to on the documentation page I linked above.
Comment: Thank you very much :) I knew I was writing something wrong, mixing php and js but I couldn't imagine how to get to your answer, I'll give it a go


Big-O of division

Question: What is the Big-O of division on most modern day ISAs? Is there some kind of optimization or is it the naive O(numerator/denominator)? I'm writing code that relies heavily of modulus operation.
For example, what is the relative times taken to perform 10/5 and 20/5 and 40/5? Do modern processors from Intel, nVidia, Qualcomm etc. have the same Big-O for division?
NOTE: I could be wrong here by assuming that division is O(size of numerator) and this question may not make any sense at all. Please correct me if that's the case.
Comment: @mamdouhalramadan only because the input is fixed-size, but that's a cheat. You might as well say "well pointers are fixed size, therefore iterating through a linked list (without loops) is O(1) because there is a constant maximum number of nodes it can address". The number of steps division takes can depend on the value of the inputs as well, depending on the algorithm used.
Comment: For integer division it's typically constant but there is a high latency cost.
Comment: I think all mathematical operations has a big-O of 1.
Comment: Is it not also dependent on the algorithm of division used?
http://en.wikipedia.org/wiki/Division_%28electronics%29
Comment: @Sibi: If you consider it as a function of bitsize: yes. But as cpus always work on a certain word size, the usually always O(1), regardless which algorithm you use. This is because the runtime of the different algorithms depend on the the size of the data in bits. Just put constant 32- or 64 into the runtime formulas, and you will get constant runtime for the algorithms (but attention: They can differ huge - but that is only relevant for real performance/runtime, not for the Big O!).
Comment: In Intel processors at least, the time division takes depends on both the value of the result and the operand size (ie small results are computed faster, but 64-bit division is slower than 32-bit division even for the same result).
Comment: If you are using an unbounded width type, Big-O is the best approach to summarizing the effect of increasing operand size on operations. If you are dealing with a fixed with type, such as 32 or 64 bit built-in types, treat is as O(1) but the constant matters for reasonable problem sizes, and may depend on the type.
Comment: Just to be clear, are you asking about dividing one fixed-width integer by another?
Comment: @harold - notable point.
Answer: This question is not that good. But it is also not that "stupid", so I try to answer /clarify some points:
Almost all modern CPU/GPUs have a division instruction. As it works on the default word size, it doesnt matter how fast it is, in terms of Big-O it is constant, so its always O(1). Even for embedded processors, microcontrollers and similar, that do not have an division instruction this is true, as it is emulated in software and the software emulation is bound in terms of the size of a word, so its always a constant time to perform the operation (that means its also O(1)).
The exception is when speaking about operation performed on non-word sized data. This happens e.g. when talking about BigInt libararies. But in this case ALL operations (addition, multiplication,...) are no longer O(1) but depend on the size of the numbers.
But attention: Big-O does not say something about the real computation time. Its just the asymptotic behaviour neglecting a constant factor. That means, even when you have two algorithms that take O(n) the time difference can be a factor of 1000 (or one million or whatever you want). Best example the division: It an e.g. an addition are both O(1), but usually the division takes far more cycles/time to execute than the addition.
Comment: Even when the machine has no 64-bit div instruction it would be O(1), as it would be always a constant number of operation to perform/emulate the 64-bit div with 32-bit instructions. But again: The O-class is the same, but the difference in real execution time is approx a factor of 3-6 (just a guess, could be higher or lower, depends heavily on the used plattform/system).
Comment: what about long in java? On a 32-bit machine, it would be double the word size. Does it still have O(1) runtime?
Comment: You should also mention about amortized complexity. I don't know about the other operations, but addition is amortized O(1).
Comment: In what sense can you say it's O(1)? For O notation to make sense you need to be looking at what happens when length of input goes to infinity. So saying that it's a single instruction for word sized input tells you nothing about the complexity of multiplication. Unless your inputs are already bounded. In which case you are not talking about the complexity of multiplication but specifically about the complexity of multiplication of two word sized numbers.
Answer: However if your using a base of 2 and you know it you can optimize with this;
<code>public class Foo {
  public static void println(String s) {
    System.out.println(s);
  }

  public static void main(String [] args) {
    int size = 100;
    int[] randoms = new int[size];
    for (int i = 0; i < randoms.length; i++) {
      randoms[i] = (int) (Math.random() * 1000);
    }

    for (int i = 0; i < randoms.length; i++) {
      int j = randoms[i];
      int k = j >> 3;
      int l = j - (k << 3);
      println("value " + i + " " + j );
      println(" " + j + " / 8 =  " + k + " remainder " + l );
    }
    //println("hey got " + c + " from " + a + " >> " + b);

  }
}
</code>
Comment: You should clearly say that division or modulo by a power of two can be optimized with binary shifts instead of posting a very long example. (BTW Java is not the most low-level language for processor instruction speed)
Answer: Although you could create your own implementation with binary division;
https://www.youtube.com/watch?v=TPVFYoxna98
I think most processor optimizations would actually be MUCH faster, per the previous post.  You would need to look at the bytecode your creating to actually be sure, but it would probably involve putting stuff in the processors cache, so your stuck with this as the best solution;
int a = ...
int b = ...
int quotient = a / b;
int remainder = a - (quotient * b);
i.e. a=5, b=2
quotient: 2
remainder: 1
from here (although it has errors :)- );
Java - get the quotient and remainder in the same step?

Big-O of division


How to understand countability of rational vs irrational numbers

Question: [The question was edited 2024-01-09. Changes are marked with these brackets, mostly.]

[Edited again 2024-01-10 adding "final remarks".]

I'm struggling with getting my head around some aspects of transfinite numbers and sets in general. This question is about my struggle with the properties and countability of rational vs irrational numbers.
I think these are common facts, please correct me if I got anything wrong:

The rational as well as irrational numbers are "dense" on the real number line, meaning roughly that the resolution is unlimited, and there are no gaps of size >0.

The rational as well as irrational numbers are an "incomplete" total order, meaning roughly that there are indeed gaps (of size 0), and ... (yada yada existence of supremums).

The (set of) rationals is countable while the irrationals aren't. (I have not seen a direct proof of the latter, only that it follows from reals being proved uncountable while rationals are proved countable.)
[Update 2024-01-09: the remark has been answered in a comment.]

(a.) As a consequence of density; between every pair of distinct irrational numbers there is at least one (and actually infinitely many) rational numbers, no matter how small the distance as long as >0.

(b.) Symmetrically, exactly the same for irrationals between rationals.

The Dedekind cut is one way (of several) to construct all the reals from the rationals. Each real number $x$ is uniquely associated with the set of all rational numbers that are strictly smaller than $x$.

[Added remark 2024-01-09:]
"5b." [Probably irrelevant but included for symmetry]
Except that it may be without  purpose, is there anything to stop me from defining "Hallström cuts" in exactly the same way as Dedekind cuts, but instead using the irrational numbers as a base for modeling all the reals.

[Probably not relevant here] The rational numbers are closed under basic arithmetic ops (add and mul). The irrationals aren't.

[Sidenote] I slightly wonder if there exists subsets of the irr:s that are closed under such ops.
[Update 2024-01-09: this sidenote has been answered in a comment.]

The question
My main headache: given (4) above, how can it be possible that one type has larger cardinality than the other (acc to (3) above)? They have such striking symmetry with each other. Intuitively and informally, they should be sort of perfectly interleaved with each other. (I know intuition is not necessarily a reliable guide here. I also realise that assuming perfect interleaving is not a consistent model.)
Put another way: where could all the additional irrationals be hiding from being forced into 1-1 correspondence with the rationals? If there were a hideout anywhere with several (distinguishable) irrs in a row without any rats in between them, it would be in breach of (4) and would also invalidate the D. cut.
Another argument:
The D. cut is not using the power set of the set of rats, only an interval. The only difference between different cuts is the upper bound of the interval. ([Edit 2024-01-09] The upper bound is a real number here.) When using only the domain of the rational numbers, how can there exist more such distinct intervals  (uncountable) than there are rats (countable)??

[Addendum 2024-01-09]
Here is a new attempt to quantify my mental issue with the countable rational numbers, by focusing on the Dedekind cuts.
Construct the Dedekind cuts for all rational numbers, and only those to begin with. Now for every rat num $r$ there is a uniquely associated set of rat nums, containing the open interval $(-\infty, r)$. For two rat nums $r_2>r_1$, $D(r_2)=D(r_1)\cup[r_1, r_2)$, so the sets only differ "on the top", so to say.
Now, at least intuitively, in constructing all these intervals $D(r)$, all available rats have been consumed already. How could there exist any more intervals of that same kind, containing rat nums exclusively.
If there was the largest rat num in the open interval (I know there isn't), then every rat num $r$ would clearly be busy being the top member of exactly one $D(s)$.
If there was such a thing as "the next rat num" (I know there isn't), it would be clear that the set of all $D(r)$ so far equals the set of all possible $D(x)$ at all (for any real number $x$).
(The outcome of this: I'm trying to claim that the set of all possible D cuts, mentally, cannot   exceed the set of all possible rat nums $r$.)
Given the argument in the prev paragraphs, how can now unique D. cuts be added for the irrational numbers when they were already exhausted by the rational mumbers? There would be no "free" rat nums left that can be used to uniquely create a new cut. It seems to require that there are more rat nums than there are rat nums. (Sic.)
Yet another angle: in how many different ways can one create an interval containing rational numbers only? (Please note that the interval can be bounded by real numbers but contains only rationals.) Arguably only countably many. Imagine adding one rat at a time to the top of the interval, ignoring the fact that the rats cannot really be enumerated in order like that. Any enumeration of rats can only go on for a countable number of times.

[2024-01-10 "Final remarks" by the author]
Thank you for helpful comments and answers. It may look like it but I have not been trying to prove that something is wrong, because I can't. I have tried to reason about my main source of "headache" in this subject, and was seeking some guidance about it.
For the record, I already know that for the time being I must accept (reluctantly) such parts of math that I am intuitively at odds with (at least until I develop ability to prove inconsistencies).
Comment: There is no such thing as 'the upper bound of the interval', not in the rational numbers, anyway. The least upper bound can be one of those 'gaps of size zero' you were talking about.
Comment: The countability is not so easy to grasp intuitively. The algebraic irrational number still form a countable set ! Countable means that there is a method to list all elements in such a way that it is guaranteed that every element will eventually occur. That this is not necessarily the case , even in the countable case : Consider the method to list first the even numbers , then the odd ones. What is wrong with this ? Correct, $1$ will never be reached.
Comment: Answer to your Sidenote: The set of all expressions of the form $\sum_{i=1}^n a_i \pi^i$ with $n\geq 1$, $a_1, a_2,\ldots, a_n$ integer $\geq0$, and $a_n>0$ consists of irrational numbers only.  And it is closed unter addition and multiplication.
Comment: I don't know exactly what you mean by a "direct proof", but the standard Cantor diagonalization argument used to show that the reals are uncountable work: given a countable list of irrational numbers, you may construct an irrational number different from every number of the list by a diagonal argument (modify the original argument to make sure you are constructing a non-repeating decimal. E.g. use digits 1 or 2 for the first digit, use digits 8 and 9 for the following two digits, then 1/2 again for the next three digits, then 8/9 again for the next four digits, and so on...)
Comment: A similar question: https://math.stackexchange.com/questions/4743188
Comment: @Peter, regarding listing all elements in the right way. Your counter-example is of type "$\omega+\omega$", right? Are you saying that a "correct" enumeration must reach infinity only once? If so, ("and here is the trap...") how is this accomplished for the rationals $m/n$ where two variables simulaneously approach inf?
Comment: @AndersH They are enumerated as follows (it is enough to show it for the positive rationals , we can list the negative one direct after the positive one occured) : Consider the sum of the denominator and the numerator , assuming the rational number is written in lowest terms. List the cases with sum 1 , then with sum 2 , then with sum 3 and so on. This way , you get every rational number (sum $1$ corresponds to $0$).
Comment: You mentioned that you have not seen a proof that the irrationals are uncountable.
You said that you already know that the rationals are countable, and that the reals are uncountable. As $\mathbb R=\mathbb Q\cup (\mathbb R\setminus \mathbb Q)$, $(\mathbb R\setminus \mathbb Q)$ must be uncountable - if not, $\mathbb R$ would be countable as well, as the union of two countable sets is countable.
Comment: @spaceisdarkgreen: Sorry about this late comment, just attempting to set the record straight. The statement "There is no such thing as 'the upper bound of the interval'"  is not true. Even qualified with rational numbers, it is not true. There "is" certainly such a thing as it, although it does not always exist, and so on.
Comment: @AndersH "it doesn't exist" and "there is no such thing" mean the same thing.
Answer: The simple short answer is that infinity is weird and does not fit well with intuition which was developed in the real world of finite things.
An early challenge to intuition is whether or not there is a single infinity.  Is the set of integers greater than or equal to zero bigger than the set of integers strictly greater than zero because it has one more element?  Is the set of all integers twice as big because it has the negatives as well?
We can only start to answer this after we have defined what we mean for two, possibly infinite sets, to have the same size.  The most common definition is that two sets have are the same size if a bijection (one-to-one and onto map) can be found between them.  We quickly run into another challenge.  With familiar finite sets, if we find a map which is one-to-one but not onto then we would deduce that one is smaller than the other.  So, this suggests that the examples which I just gave are different sizes.  However, we find that the existence of a one-to-one but not onto map does not preclude a bijection.  A bijection can be found between all of those sets so they are the same size.  We find that further intuitively bigger sets are also the same size e.g. the rational numbers and the algebraic numbers.  The algebraic numbers are those which are the roots of polynomials with integer (or rational) coefficients.  They include some irrationals, e.g. $\sqrt 2$ but not others, e.g. $\pi$.
We usually say "cardinality" rather than "size" which mainly emphasizes that we are using this interpretation.  I will stick to "size" as we are talking about intuition.
We might start to develop the intuition that all infinite sets are the same size but now we find that the real numbers are strictly bigger.  A bijection between the natural numbers and the real numbers is not possible.
How much bigger?  Is it the next biggest set or is there something with an intermediate size?  Now it gets really weird.  Not only do we not know but we can prove that we cannot prove that there is or is not a set with an intermediate size.  Look up the Continuum Hypothesis if you want to know more.
We know that the reals are not the biggest set.  For any set, we can construct a bigger one so there is no biggest one.
Now back to some of your points.  It is indeed counter-intuitive that all of these are true at once:

Between any rationals there is an irrational
Between any irrationals there is a rational
There are more irrationals than rationals

1 and 2 suggest that they alternate along the real line and hence there are equally many but 3 contradicts this.  Along with the Continuum Hypothesis, I think that you just have to work on understanding the proofs and then learn to accept it.  I still find it weird but not as weird as the Continuum Hypothesis.
The problem with Hallström cuts is that you don't have the irrationals until you have the reals.  The irrationals are just the reals which are not rational.  So, you would have to obtain the irrationals somehow else before you could start work on Hallström cuts.  We know how to construct the rationals without the reals so we can use them as a starting point.  You could perform cuts on the algebraic numbers and that would work because we could construct them without the reals.  However, you would just get something isomorphic to the usual reals.
It is often said, without good evidence, that contemplating infinity drove Cantor mad.  Even if not true, the existence of the story shows that struggling to understand infinity is common.
Comment: +1 for the first and last paragraphs, which I borrowed in my answer to stress what I think the OP is struggling with.
Comment: +1 for pretty much all of it. It was a long answer but who am I to say that. I (OP) especially appreciate the commentary in the middle about the counter-intuitive facts. I reckon this is the best answer that I'm gonna get, and I'm going to accept it. For the record, I already know that I for the time being must  accept (reluctantly) such parts of math that I am intuitively at odds with.
Comment: Actually, I considered saying more.  There is a great book: The Road to Reality by Roger Penrose.  He looks at many weird areas of maths, e.g. complex numbers, and shows uses for them in physics.  He seems surprised when it comes to infinite cardinals that they have not (yet) proved useful in physics.  Also search for "unreasonable effectiveness of mathematics", this will lead you to an article by Eugene Wigner expressing surprise at how useful maths is in physics.  Together. they are saying that maths is very useful but not a perfect description of reality.
Answer: The essential answer to your question is that you can't trust your intuition about infinity. All you can do is follow the formal definitions to their logical conclusions and then train your intuition to bring it into accord with those conclusions. Until you do that, none of the carefully written answers here is likely to satisfy you. The first and last paragraphs from @badjohn say it well:

The simple short answer is that infinity is weird and does not fit
well with intuition which was developed in the real world of finite
things.
...

It is often said, without good evidence, that contemplating infinity
drove Cantor mad. Even if not true, the existence of the story shows
that struggling to understand infinity is common.
Answer:
Given the argument in the prev paragraphs, how can now unique D. cuts be added for the irrational numbers when they were already exhausted by the rational mumbers? It seems to require that there are more rat nums than there are rat nums.

There are Dedekind cuts which are not of the form $D(r)$ for any rational number $r$. For example, the Dedekind cut corresponding to the interval $(-\infty, \sqrt{2})$ (i.e., the set of all rational numbers less than $\sqrt{2}$) is not equal to $D(r)$ for any rational $r$. You can replace $\sqrt{2}$ by any irrational number.
Comment: You keep making arguments relying on things that you know are wrong, like "if we ever allowed a rat to exist immediately above sqrt(2)", "ignoring the fact that the rats cannot really be enumerated in order like that", etc. Why do you do that?
Comment: Thanks, but this is exactly the argument I'm feebly trying to make. It is "not reasonable" that $D(\sqrt{2})\not =D(r)$ for all rational $r$ because there would be no free rat num left to put in its set to make it unique. Between any $r_1$ and $D(\sqrt{2})   $ there are always many $r_2$ that already have their cut, and the argument is that $D(\sqrt{2})$ cannot possibly be different from all of those. This all informal, I know. But I think there is something deeply fishy about the D cuts. It is always dodged by saying "there is no rat $r$ closest to irr $i$".
Comment: You've given the correct reason  "there is no rat $r$ closest to irr $i$" so why do you still think it is fishy?
Comment: To me it is like a fallacy by denying access to the evidence, much like the Heisenberg uncertainty or the Schrödinger cat. We can never go deep enough to really check whether      the Dedekind claims hold at the smallest scale (because there is no smallest scale).
Comment: Please note: I have no problem with the D cuts as long as we limit it to comparing two arbitrary reals. That always works. My issue is with the idea that one could uniquely construct all those cuts at once for every real (and implicitly collect them in a set).
Comment: @AndersH But we know exactly what $D(\sqrt2)$ is (you can easily tell for any rational number whether it is in the set or not) and we know that $\sqrt2$ is not rational. So there is some flaw in your intuition when you say this cannot happen.
Comment: $DavidK All such arguments crumble if we ever allowed a rat to exist immediately above sqrt(2): those two different numbers could never be resolved by the cut. (About to write a new argument in next comment...)
Comment: (Updated the question *again*, with said new argument at the end)
Comment: The only thing that has crumbled so far is the argument that says $D(\sqrt2)=D(r)$ for some rational number $r$. If such an $r$ existed, its square would be less than $2$ and we could find a greater rational number in $D(\sqrt2)$, a contradiction. You may not **like** the fact that irrational numbers exist (which is what this is essentially about), and you are in good company there (supposedly they killed the first person who discovered this fact), but they exist and they define their own distinct set of Dedekind cuts. So you need to expand your intuition to make room for that.
Comment: There also is no rational "immediately above" $\sqrt2$; no matter what rational $r$ can conceivably exist, there is an algorithm to find another rational number between $\sqrt2$ and $r$. If I were to write up such an algorithm, would that answer the question?
Comment: I fear this could go on forever, and we would be asked to continue in a meta forum instead. @DavidK to your latest comment: no, that's exactly point (4) in my question. To your prev comment: I accept irr nums. What I don't "**like**" is the unintuitive way the supposedly countable rats can "stretch all over the place" to match every irr num as closely as one desires. And that no mathematician appears to be bothered by that, imho a "paradox". ...(t.b.c.)
Comment: ...(cont) What I am failing to convey with the D cuts is the thought that an interval is compact and imho not at all like a power set. Yet one can make an uncountable number of intervals out of countably many numbers. I certainly don't **like** that. Of course I'm unable to prove any of it wrong. I was seeking guidance to help me find "intuitive" ways of understanding these ihmo annoyingly contradictory things.
Comment: Oops I slipped there about D cuts; meant to say that in my limited mind the *set of all* intervals could not match, in complexity, the *power set* of all the numbers in question.
Comment: OK, and you absolutely don't have to like any of this. I agree that the answer you accepted is probably the best you can expect.
Answer: To be honest this post is giving me headache so I'm only gonna address the new additions today (9th Jan 2023) in the end. I'll use $r$ to consistently stand for some rational number.
Unfortunately, all arguments you've made seem to me to be begging the question: you start by assuming all Dedekind cuts are $D(r)$, and conclude there can be no more other Dedekind cuts. I think you need to let go of this premise, and start thinking "maybe there are Dedekind cuts that are not $D(r)$". Until then, we are going nowhere.
You can also take a look at this post by Eric Wofsey. It gives a proof that a countable dense totally ordered set cannot be Dedekind complete. In it, the author assumes $\mathbb{R}$ is countable and arrives at a contradiction using only the dense total order on $\mathbb{R}$. Hopefully, since this proof relies purely on countability and dense total order, with no arithmetics, algebra, or calculus involved, it can convince you better. If it doesn't, I really doubt if you will ever be convinced.
Comment: @AndersH The intent of the proof I linked is, as you said, different, but it would be helpful to this issue if you replace $\mathbb{R}$ that is assumed countable with the actual countable $\mathbb{Q}$. A total order being Dedekind complete just means every Dedekind cut is $D(x)$ for some $x$ in it. Thus, the proof basically says because $\mathbb{Q}$ is countable, there will always be a Dedekind cut (in fact, uncountably many) that is not $D(r)$, which I was hoping can show you the very premise you repeatedly rely on, that every Dedekind cut must be $D(r)$, is false.
Comment: Thank you for your link. However it appears to be another proof of the uncountability of the reals, which was not quite the issue. I have read and (reluctantly) accepted a couple of such proofs. Unfortunately I fail to see the connection to my rambling about D cuts, and I can only guess the meaning of "D. complete", but nevermind. Besides I think you  missed the point of said rambling, but you're not alone and who could blame you. I do understand the general point you are making that I need to relax and accept some things as they are (until I develop ability to prove otherwise).


What carries out SQL Server Mirroring?

Question: I'd like to know what service(s)/process(s) carries out Mirroring in SQL Server.
For example, we have various Agents carrying out the different steps for SQL Database Replication. Similarly, what is taking care of the various aspects of Database Mirroring in SQL?
I guess it is a question of "Mirroring Internals", I've not been able to find any convincing answers on MSDN.
Links to any related information would be appreciated as well.
Thanks a lot.
EDIT: Just the names and/or a brief description will do, I can go from there. Hopefully this question doesn't seem too broad or to require an elaborate answer.
Comment: here are some important things which needs to consider when setting up database mirroring in SQL Server http://www.sqlmvp.org/things-to-consider-when-setting-up-database-mirroring-in-sql-server/
Comment: As far as I know, SQL Mirroring itself is done within the SQL engine itself, because it's a part of the ACID compliance (consistent). It's not like Transaction Log Shipping which is really just a collection of SQL Agent jobs.
Answer: SQL Server Mirroring is part of the core engine.  When you setup mirroring, SQL Server enables a TCP endpoint to support the flow of log records from the primary server to the secondary server, and to optionally connect the witness server.
Mirroring actually consists of sending log data from the primary to the secondary.  Since Mirroring can be configured to provide synchronous commits at the secondary, the mirroring code needs to be processed in the core SQL Server engine.  The process name for SQL Server is sqlservr.exe, there is no other component that runs mirroring.
You may be able to determine if SQL Server is using Mirroring by looking for the TCP endpoints.
If you have access to a machine with mirroring active, you can confirm that the SQL Server Engine runs mirroring simply by looking at the process that created the TCP mirroring endpoint, via the command-line utility netstat:
C:\> netstat -a -b

Output will look like:
 TCP    [::]:5022              MYMACHINE:0           LISTENING
[sqlservr.exe]

What carries out SQL Server Mirroring?


I'm getting an error in the following program as KeyError Traceback (most recent call last)

Question: Here is my code-
import pandas as pd

df5=pd.read_csv(r'C:\Anaconda3\airtravel.csv')

print(df5)

   Month   "1958"   "1959"   "1960"
0    JAN      340      360      417
1    FEB      318      342      391
2    MAR      362      406      419
3    APR      348      396      461
4    MAY      363      420      472
5    JUN      435      472      535
6    JUL      491      548      622
7    AUG      505      559      606
8    SEP      404      463      508
9    OCT      359      407      461
10   NOV      310      362      390
11   DEC      337      405      432

But when I try to access this:-
print(df5['1960'])

I get an error.
KeyError: '1960'

I can't understand why is that happening.
File link: https://people.sc.fsu.edu/~jburkardt/data/csv/csv.html
Thanks
Comment: do `df5.columns` to see what the column name is, but, based on your sample data, it looks like it should be `df5[' "1960"']`
Answer: Your column includes quotations along with the column name. maybe df5['"1960"'] would work
Answer: I've checked this file. We have two problems here. In the column names there is a space at the beginning and "" between the years.
Possible solutions:

Put a parameter 'skipinitialspace'. It will remove spaces and quatation marks. Then you can print it like you wanted:
 df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv', skipinitialspace=True)
 print(df5['1960'])

Remove spaces on both sides and add "" to the name:
df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv')
df5.columns = [x.strip() for x in df5.columns]
print(df5['"1960"'])

Leave it at it is and add space at the beginning:
df5 = pd.read_csv(r'C:\Anaconda3\airtravel.csv')
print(df5[' "1960"'])

Comment: Thank you very much. That works. I also removed the spaces from the original file and was able to print it as df5['1960']. So I guess print(df5['1960']) will only work if there would be no spaces.


Cubical delusion : Cubes one coloured red and other green except on 1 face are cut into 27 & 64 cubes. How many are red only on 1 face?

Question: There are two cubes of different sizes. One of these is coloured red on all the faces, while other is coloured green on all the faces except one which is coloured red. The one which is red on all faces is cut into 27 equal cubes, while the other one is cut into 64 equal cubes which are mixed up with other cubes.

How many cubes are coloured red only on one face?
  (a) 10                         (b) 16
  (c) 20                          (d) 22

The answer is given as (b) i.e. 16.
But, when I tried I got it as
cube I : 6 cubes with only one red face
cube II: 4 cubes with only one red face
         8 cubes with one red and one green face
         4 cubes with one red faceand two green faces
So, it should be either 22 (if I take it as "How many cubes are coloured red, only on one face?") or 10 (if I take it as "How many cubes are coloured red only, on one face?")
So can you tell me whether the answer in the book is correct, or the answer I got (which one? first or second?) is correct?
Help me !! I am having exam tomorrow!
Comment: I guess the "which are mixed..." is just to mix up matters ;-)
Comment: I think that from your interpretations, your answers are right. I would say 22. I don't get why the problem says: "which are mixed up with other cubes." ¿Why is that relevant?
Comment: Agree, the answer is 22 to me too. I still don't get what is meant by `which are mixed up with other cubes` though
Comment: I also am confused. Please ignore it
Comment: I think Ross Millikan is correct
Answer: I agree with your logic and can read the question either way to get 10 or 22.  I think the mixed up with the other cubes is just supposed to tell you to count small cubes from both big cubes, which you are doing.
Comment: @chndn:  I don't think the question is clearly written.  Your logic resulting in each of 10 and 22 is correct.  I think I would go with 22, but without conviction.
Comment: So the answer is 10 or 22?


Let $a,b,x,y\in \mathbb{Z}$, with $ax-by=1$. How to prove that $gcd(a+b,x+y)=1$?

Question: My guess is that if i start with this  $ax-by=1$, by transforming that into a $gcd()$ form, like $gcd(ax,-by)$, or $gcd(a,-b)$ and this way i could be able to reach the end result. However, i can't reach anywhere useful and i'm very unsure about a lot of things. I'm new in number theory. If anyone could help, i would be very grateful. Thanks in advance!
Answer: Notice that:
$(a+b)x - (x+y)b = ax - by = 1$
By Bezout's identity, we get the result
Comment: @RestlessC0bra Bezout's identity is very important and you should keep it in mind whenever the task is to prove that the gcd of two numbers is $1$. Here, we also have an equation relating $a,x,y,b$ and $1$, so it is highly likely that Bezout's identity might be useful. Now, the task is to find two numbers such that $m(a+b) + n(x+y)=1$, which can be fairly easily found by looking at the equation
Comment: @AhmedHussein Conceptually it can be viewed as a row operation on  determinant - see my answer.
Comment: Thanks for your response. Can you please explain a bit more? How did you get $(a+b)x-(x+y)b$ ? How did you start?
Answer: Suppose that we have $ax-by=1$.
If $\gcd (a+b,x+y)\geq2=k$ then you would have $a+b=ck$ and $x+y=dk$ for some integers $c$ and $d$. Then if you substitute $a=ck-b$ and $x=dk-y$ into $ax-by$ you arrive at $ax-by=(ck-b)(dk-y)-by=cdk^2-cky-dkb=k(cdk-cy-db)$ which is product of two integers where one is $k\geq2$ and so $k(cdk-cy-db)$ would not be equal to $1$ if $\gcd (a+b,x+y)\geq2=k$, so we arrived at the contradiction so we have $\gcd (a+b,x+y)=1$.
Comment: Not as elegant as Ahmed Hussein's answer, but I prefer this because it shows how the result could be gotten by a natural series of steps.
Comment: @martycohen Thanks, this is really the most elementary way that I could think of.
Answer: It is immediate from a row operation on a determinant
$$ 1 \,=\, \begin{vmatrix} a & b\\ y & x\end{vmatrix} \,=\, \begin{vmatrix} a & a+b\\ y & y+x\end{vmatrix}$$


SLRequest twitter access now requires SSL

Question: -(void) vSLRequest:(SLRequest*) SLRequest1 WithHandler:(NSString *) errorTitle andD1: (NSString *) errorDescription FP1:(NSString *) errorParse FP2:(NSString *) errorParseDesc ifSuccess:(void(^)(NSDictionary * resp))succesBlock
{
    [self vSuspendAndHaltThisThreadTillUnsuspendedWhileDoing:^{
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [SLRequest1 performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                if(error != nil) {
                    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
                        [[[UIAlertView alloc] initWithTitle:errorTitle message:errorDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]show];
                    }];
                }

Now the response data contains the following:
(lldb) po resp
{
    errors =     (
                {
            code = 92;
            message = "SSL is required";
        }
    );
}

Okay so, twitter now requires SSL. https://dev.twitter.com/discussions/24239 is the discussion.
How should I change my code?
Answer: SLRequest has an account property. You need to set this to the user's twitter account (which is an ACAccount object you get from the ACAccountStore class.
If you set this, the connection is authenticated and OAuth is performed for you.
So, you need to do the following:

Create an ACAccountStore object
Request access to twitter accounts using requestAccessToAccountsWithType:...
Once access is granted, get the ACAccount object from the account store
Add this to your SLRequest object.
Answer: I did get the same error when I used url NSURL *requestURL = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"];
But I solved that error by changing url to this :NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"];
-> The error message = "SSL is required" says that "SSL requirement will be enforced on all api.twitter.com URLs, including all steps of OAuth and all REST API resources."
which means that now onwards we have to use "https://" instead of "http://" we were using previously.
Below is whole the code which will help you to understand better:
- (void) postTweet
{
    ACAccountStore *account = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier: ACAccountTypeIdentifierTwitter];

    [account requestAccessToAccountsWithType: accountType
                                     options: nil
                                  completion: ^(BOOL granted, NSError *error)
    {
        if (granted == YES){

            // Get account and communicate with Twitter API
            NSLog(@"Access Granted");

            NSArray *arrayOfAccounts = [account
                                        accountsWithAccountType:accountType];

            if ([arrayOfAccounts count] > 0) {

                ACAccount *twitterAccount = [arrayOfAccounts lastObject];

                NSDictionary *message = @{@"status": @"My First Twitter post from iOS 7"};

                NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/1/statuses/update.json"];

                SLRequest *postRequest = [SLRequest requestForServiceType: SLServiceTypeTwitter
                                                            requestMethod: SLRequestMethodPOST
                                                                      URL: requestURL
                                                               parameters: message];

                postRequest.account = twitterAccount;

                [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
                 {
                    NSLog(@"Twitter HTTP response: %i", [urlResponse statusCode]);
                    NSLog(@"Twitter ResponseData = %@", [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]);
                 }];
            }
        }
        else {

            NSLog(@"Access Not Granted");
        }
    }];
}


Problema : Array dinâmico x indexar valor

Question: Boa pessoal.
Tenho um array dinâmico que recebe dados associado em botões onde deveria indexar a cada interação os valores (0, 1, 2, 3...). O problema é que o valor do índice persiste no zero (0) ? Segue o code :
$(document).ready(function() {
  // method click(action: atribui valores as variaveis declaradas:)

  $(".btn_data_add").click(function() {
    // method .attr(action: retorna o valor do atributo) :
    var $ws_item_in   = $(this).attr("data-item");
    var $ws_price_in  = $(this).attr("data-price");
    var $ws_icon_in   = 'delete_outline';

    // estrutura colunas de uma linha de tabela html :
    var $ws_row_open  = '
';
    var $ws_col_item  = '' + $ws_item_in + '	';
    var $ws_col_price = '' + $ws_price_in + '	';
    var $ws_col_icon  = '' + $ws_icon_in + '	';
    var $ws_row_close = '
';

    // estrutura linha da tabela html :
    var $ws_row_in    = $ws_row_open + $ws_col_item + $ws_col_price + $ws_col_icon + $ws_row_close;
    // organiza indexando dentro de uma array :

    var $ws_array_row = [$ws_row_in];
    //
    for(var i=0; $ws_array_row.length; i++) {
      //
      console.log(i, $ws_array_row[i]); // i é o índice, matriz[i] é o valor
      break;
    }
  });
});

Answer: Acredito que a condição de execução do seu loop for esteja incorreta.
Se você escreve for (var i = 0; $ws_array_row.length; i++), você está falando pro JS rodar o seu loop enquanto $ws_array_row.length for truthy (que olhando para o código acima dele, seria 1, que é truthy) ele deverá rodar o bloco de código pra sempre.
Talvez o que você queira fazer é o seguinte:
for (var i = 0; i < $ws_array_row.length; i++) {
  console.log(i, $ws_array_row[i]);
}

Comment: Não funcionou ? Continua indexando o valor zero (0) para cara variavel adicionada !
Comment: O problema era que o array estava dentro do evento .click(), precisa ser declarado fora e no inicio. Obrigado pela força !


Python always getting invalid syntax error

Question: I dont understand why i get always a invalid syntax error.
Can you please help?
def steigung(a,b,c,d,x):

Ausgabe= 3*a*x**2+2*b*x+c
Ausgabe2= 6*a*x+2*b

if Ausgabe >= 1:
    print("Die Funktion Steigt")
elif Ausgabe <= -1:
    print("Die Funktion Fällt")
elif Ausgabe=0 and Ausgabe2 > 0:
    print("Die Funktion hat ein lokales Minimum")
elif Ausgabe=0 and Ausgabe2 < 0:
    print("Die Funktion hat ein lokales Maximum")
elif Ausgabe=0 and Ausgabe2 = 0:
    print("die Funktion einen kritischen Punkt unbekannten Typs")

return print

Comment: Equality comparison is `==`. Your indentation is wrong.
Comment: and what is `return print` ?
Comment: @Arman: `return print` returns the `print`-function.
Comment: @Daniel , is it a use able action or it's just a miss functionality here?
Comment: @Arman: it is probably not useful, but also no syntax error.
Answer: You are using an assignment to compare the values rather than using the comparison operator ==. Also, I would refer to local variables using lowercase letters.
Finally, I don't get why you are returning the print function, remove that.
def steigung(a,b,c,d,x):

   ausgabe= 3*a*x**2+2*b*x+c
   ausgabe2= 6*a*x+2*b

   if ausgabe >= 1:
      print("Die Funktion Steigt")
   elif ausgabe <= -1:
      print("Die Funktion Fällt")
   elif ausgabe==0 and ausgabe2 > 0:
      print("Die Funktion hat ein lokales Minimum")
   elif ausgabe==0 and ausgabe2 < 0:
      print("Die Funktion hat ein lokales Maximum")
   elif ausgabe==0 and ausgabe2==0:
      print("die Funktion einen kritischen Punkt unbekannten Typs")


variable declared outside jQuery.each becomes undefined within jQuery.each body

Question: I was facing some iisue with jQuery.each. I have declared a varible outside jquery.each satement. After first time of initialization of variable from jquery.each body the variable is not available for the next iteration. It says undefined.
Here is the sample code
var cname= '';

jQuery.each(candidate_arr['data'], function(index, data){
    if(index == 0){
        jQuery('.list').append('
'+ data['cname'] +'
');
        cname= data['cname'];
    }

    if(cname != data['cname']){
        // cname is undefined for index = 1, 2, 3....
        jQuery('.list').append('
'+ data['cname'] +'
');
        var cname = data['cname'];
    }

    jQuery('.list').append('
'+ data['candidate_name'] +'
');
})

Comment: Can you show what `candidate_arr` looks like? And try by removing `var` from `var cname = data['cname'];` as this creates a local `cname` variable.
Comment: have you checked to ensure that the assignment is happening? debug?
Comment: Yes. I see it by creating breakpoints and seen the intermediate values.
Comment: @WaleedIqbal Yes variables are look alike. Actually it comes from db from same table.
Comment: the scope within the callback function is different. you can just use normal js looping over the object
Comment: @CME64 Yes. Actually I am working on its alternative. But I want to know why this happening and what could be done in this case.
Answer: The scope in the call back function is different so the variable will not be accessible
try a normal js loop
var cname= '';
var candidate_arr = {
  data: [{cname:"123"},{cname:"1234"},{cname:"1235"}]

};

for(var index=0; index< candidate_arr['data'].length;index++){
  var data = candidate_arr['data'][index];
  console.log(data);
  console.log(cname);
    if(index == 0){
        jQuery('.list').append('
'+ data['cname'] +'
');
        cname= data['cname'];
    }

    if(cname != data['cname']){
        // cname is undefined for index = 1, 2, 3....
        jQuery('.list').append('
'+ data['cname'] +'
');
        var cname = data['cname'];
    }

    jQuery('.list').append('
'+ data['candidate_name'] +'
');
}

Answer: You have set inside the each block var cname is it tell to the JavaScript engine to create a new variable cname in each iteration. It to not use the global variable instance of the variable outside of the block.
You should learn about variables scopes in JavaScript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var


Método de Newton-Raphson junto com Horner

Question: Estou tendo problemas para implementar o método de Horner para diminuir o custo computacional dos cálculos de polinômios e, feito isso, usar o método de Newton para achar a raiz do polinômio
No código, b armazenaria o valor do polinômio e c o valor da derivada
n=len(a)-1
print("k\ta\tx\tpx")
for k in range (1, iterMax):
    b=a[n]
    c=0
    for i in range (n-1,1):
        c=b-(x*c)
        b=(x*b)+a[i]
    b=x*b+a[0]
    if (b<epsilon and b>-epsilon):
        print ("raiz encontrada: ")
        print (x)
        return (0, x)
    x=x-(b/c)
print("erro. Maximo de interações atingido")
return (1, x)

Ao aplicar o método de Newton (x=x-(b/c)), acusa erro dizendo que estou dividindo por zero, mas não entendo porque.
Chamada da função:
a = [3, -9, 0, 1]
x0 = 0.5
epsilon = 0.0001
maxIter = 20
(houveErro, raiz) = newton_poli(a, x0, epsilon, maxIter)

Obs: pelo que eu entendi, a lista a armazena os coeficientes de trás pra frente, ou seja, 3 é o termo independente e 1 é o termo que multiplica x³
Answer: O problema está no  seu segundo for. Você está tentando fazer um loop decrementando e o loop nunca está sendo executado, logo c não tem o seu valor atualizado. Para isso funcionar você precisa adicionar o terceiro parâmetro na função range, logo seu loop ficaria da seguinte maneira:
for i in range (n-1,1,-1):


Linear Independence via Induction

Question: I know that Wronskian method is easy to apply in order to find if there is linear independence for a family of functions and also mathematical induction too is applicable as given in this post for a family of trigonometric functions of $\sin(kx)$ where $k \in \mathbb{N} - \{ 0 \}$ However, I could not figure out how to apply the induction for this problem to prove $S$ is linearly independent where $S = \{ f_{k}(x) = x^{k} : k \in \mathbb{N} \}$ for all $x$ except for $x = 0$ since indeterminate form $0^0$.
How can I prove $S$ is composed of linearly independent functions via mathematical induction?
Answer: Let's show by induction that for all $n \geq 0$, the family $\lbrace f_0, ..., f_n \rbrace$ is linearly independant.
This is true for $n=0$, since $f_0 \neq 0$. Let's suppose that it is true for an integer $n$. Then let's suppose that you have $a_0$, ..., $a_n$, $a_{n+1}$ real numbers such that
$$a_0 f_0 + ... + a_n f_n + a_{n+1}f_{n+1} = 0 \quad \quad \quad (1)$$
Differentiating this equality (and because $f_0'=0$ and $f_k'=kf_{k-1}$) you get
$$\sum_{k=0}^{n} (k+1)a_{k+1} f_{k}= 0$$
By the induction hypothesis, the family $\lbrace f_0, ..., f_n \rbrace$ is linearly independant, so you deduce that $(k+1)a_{k+1} = 0$ for all $k=0, ..., n$, i.e. that $a_{k+1} = 0$ for all $k=0, ..., n$. Injecting this information in the equation $(1)$, you deduce finally that $a_0= 0$. So all the $a_0, ..., a_{n+1}$ are zero, so the family $\lbrace f_0, ..., f_n, f_{n+1} \rbrace$ is linearly independant.
This completes the induction.

Linear Independence via Induction


Question on Independence of Events

Question: I'm working on this below problem, and am having difficulty.

Suppose that there are two types of drivers: good drivers and bad drivers. Let G be
  the event that a certain man is a good driver, A be the event that he gets into a car accident next year, and B be the event that he gets into a car accident the following year. Let $P(G) = g$ and $P(A|G) = P(B|G) = p_1$, $P(A|G^c) = P(B|G^c) = p2$, with $p1 < p2$. Suppose that given the information of whether or not the man is a good driver, A and B are independent (for simplicity and to avoid being morbid, assume that the accidents being considered are minor and wouldn't make the man unable to drive).
(a) Explain intuitively whether or not A and B are independent.
(b) Find $P(G|A^c)$.
(c) Find $P(B|A^c)$.

It seemed to me that $A$ and $B$ were not independent, since if a driver gets into an accident in year $i$, he is more likely to fit into the "bad driver" category, and so will be more likely to get into an accident in year $i + 1$. The event $A$ will then increase the probability of the event $B$, in which case they wouldn't be unconditionally independent.
However, this creates quite a lot of  issues in terms of working out part (c) due to the absence of information of conditional probabilities involving $B$ and $A$, which seems to almost imply that $A$ and $B$ must be independent, which would mean that $B$ and $A^c$ are also independent. But even though I think I have worked backwards to the intended answer, I am having difficult understanding why this is the case.
I would greatly appreciate any helpful insights.
Comment: In fact it seems the problem is fine as stated, to compute $P(B\cap A^c)$ one can decompose it as $P(B\cap A^c\cap G)+P(B\cap A^c\cap G^c)$, each of which is a product of probabilities given in the question, by way of conditional independence of $A$ and $B$ given the (lack of) occurrence of $G$.
Comment: Using this reasoning, do you see why $P(B\cap A^c)=gp_1(1-p_1)+(1-g)p_2(1-p_2)$?
Answer: Your reasoning is correct that $A$ and $B$ are dependent. At the same time, your intuition that it is hard to work out probabilities without exploiting some form of independence is correct as well. The next best thing to independence is conditional independence, which is what this exercise is teaching you to use. The idea is that when we lump good and bad drivers together we have lost the independence (since good vs bad is a confounding variable) but by splitting them apart, we can restore the independence.
Using this "splitting out" philosophy, our way of calculating $P(G|A^c)$ is to expand it out as
$$
P(G|A^c)=\frac{P(G\cap A^c)}{P(G\cap A^c)+P(G^c\cap A^c)}=\frac{g(1-p_1)}{g(1-p_1)+(1-g)(1-p_2)},
$$
and we can use the same approach in a slightly more elaborate way to solve part (c) - you will need to write both the numerator and denominator as a sum over cases depending on whether the driver is good or bad, using conditional independence to compute each term in the sum as a product of the corresponding probabilities.
One final question: do you see why the answer to (a) relies on the assumption $p_1\not=p_2$?
Comment: Thank you for this very helpful answer. I was able to solve (b), but am still somewhat confused on (c). How does this look? First, $P(B \mid A^c) = \frac{\Pr(B \cap A^c | G) \Pr(G)}{\Pr(A^c | G) P(G) + \Pr(A^c | G^c) \Pr(G^c)}$, and by conditional independence the numerator becomes $\Pr(B | A^c) \Pr(A^c | G) \Pr(G)$.
Comment: Your application of conditional independence is not quite right, since you are effectively "throwing out" the bad drivers and only calculating the contribution from the good drivers. Thus, in addition to a term involving $G$, you should get a second term in the numerator involving $G^c$. By the way, I find it clearest to write conditional probability in terms of intersections of events to avoid confusion - for instance, you managed to end up with a $P(B|A^c)$ expression inside your term for the numerator of $P(B|A^c)$, which is a little too recursive don't you think?
Comment: If you are still stuck, take a look at my comment under @Did above, and if still stuck let me know and I can post the details of the calculation.
Comment: Thank you again, and sorry for the very foolish errors in my above comment. How is this (which I first worked out on paper): $P(B \mid A^c) = \frac{P(A^c \cap B \mid G) P(G) + P(A^c \cap B \mid G^c) P(G^c)}{P(A^c \mid G) P(G) + P(A^c \mid G^c) P(G^c)}$. Then, by conditional independence, we break up the numerator into $P(A^c \mid G) P(B \mid G)P(G) + P(A^c \mid G^c) P(B \mid G^c) P(G^c)$.
Comment: Your first equation is correct (except for what looks like a latex error on the left side, by $C$ I assume you meant to write $A^c$?) and your second expression looks great to me :)
Comment: Thank you! (And, yes, I meant to write $A$.)
Comment: My apologies, but I have just one more question: from the problem, $A$ and $B$ are conditionally independent given $G$. But does this allow us to argue that $A^c$ and $B$ are also conditionally independent given $G$? I certainly used this above, but I haven't been able to find any corroborating evidence of such a rule in my textbook or elsewhere.
Comment: Pay careful attention to the wording of the question: "Suppose that **given the information of whether or not** the man is a good driver," this means that they are conditionally independent both on the event of being a good driver, and on the event of not being a good driver. You are right that only knowing one side (e.g. conditionally independent on the event of being a good driver) does not imply the other (e.g. conditionally independent on the event of being a bad driver).
Comment: This is a good point I actually hadn't considered. Thank you. But I think I'm still unsure on whether, given that $A$ and $B$ are conditionally independent given $G$ and now $G^c$, whether, say, $A^c$ and $B$ are also conditionally independent. I'm fairly certain such a rule holds for unconditional independence. My apologies for all of the follow-ups: thank you again for all of the help.
Comment: This does in fact follow mathematically by manipulating the definition of conditional independence :) and I encourage you to work it out for yourself.
Comment: I will definitely do so -- thank you again!
Answer: For (c), $P(B|A^c) = \frac{P(B\cap A^c)}{P(A^c)}$. We need to find $P(A^c)$ and  $P(B\cap A^c)$.
We know that $P(A|G) = \frac{P(A \cap G)}{P(G)} = p_1 \implies P(A\cap G) = gp_1$. Similarly, $P(A\cap G^c) = (1-g)p_2$. Now, $P(A) = P(A \cap G) + P(A \cap G^c) = gp_1+(1-g)p_2 \implies P(A^c) = 1 - (gp_1+(1-g)p_2)$.
$P(B\cap A^c) = P(B \cap A^c \cap G) + P(B \cap A^c \cap G^c) = P(B\cap A^c|G)P(G) + P(B\cap A^c|G^c)P(G^c) = p_1(1-p_1)g + p_2(1-p_2)(1-g)$.
Finaly, $P(B|A^c) = \frac{p_1(1-p_1)g + p_2(1-p_2)(1-g)}{1 - (gp_1+(1-g)p_2)}$
Comment: While your expression for $P(A)$ is correct, your expression for $P(A^c)$ is a little off - this is easy to see since according to your calculations, $P(A)+P(A^c)=p_2$, not 1!
Comment: Thank you, I'll fix that.

Question on Independence of Events


git allowing uncommitted changes to be visible in newly created feature branch

Question: I have created a file sample1 on master branch and edited it with a line "changes made to file in master". It was still untracked file as I did not add to git yet.
Then I created a branch using

git checkout -b feature_branch

First thing I observed was the file sample1 was visible in the new feature_branch. I think this is ok.
Then I made changes to this file in the feature_branch.
I then went back to master branch using

git checkout master

I opened the file and to my surprise, I see the changes made in feature branch in the master without me committing the changes or merging the files.
And then I made changes to the master again and switched to feature_branch and still found the changes.
Can anyone explain if this is intended behaviour?
Comment: git only does version control in files that were added to git via `add` and `commit`, otherwise git won't "take responsibility" over that file.
Comment: Does this answer your question? [Modified files in a git branch are spilling over into another branch](https://stackoverflow.com/questions/246275/modified-files-in-a-git-branch-are-spilling-over-into-another-branch)
Answer:
It was still untracked file as I did not add to git yet.

As long as the file is untracked (not in the index), you can switch branches (using nowodays the new git switch command rather than the old git checkout), the untracked file will remain there, untouched.
Any modification done on that file will not depend on your current branch.
See "git checkout without deleting untracked files" for more.


Evaluate the Integral $\int \sqrt{1-4x^2}\ dx$

Question: $\int \sqrt{1-4x^2}\ dx$
I am confused as I get to the end. Why would I use a half angle formula? And why is it necessary to use inverses?
Comment: Integrating $\cos^2(\theta)$ can't be done using any basic formula we know for integration. This is where the half angle formula $\cos(2\theta) = \cos^2(\theta)-\sin^2(\theta) $ comes into play. The expression $\frac{1}{4}[\theta + \frac{1}{2}\sin(2\theta)]$ isn't in terms of the $x$ variable (Recall that you want to antiderivative of $\sqrt{1-4x^2}$, which is a function of $x$!). That is why we need to use the inverse trig function.
Comment: I don't follow what you mean. I am stuck at the point where I integrated and multiplied my constant back into the product of my integration.$ \frac{1}{4}[\theta + \frac{1}{2}\sin(2\theta)]$. At this point I'm unsure what is going on. Why am I not allowed to just plug in the values I calculated from my triangle as I have done with other problems of this type? Is it because the angle lacks a trig function?
Comment: Since $\sin(\theta) = 2x$, you have $\theta = \sin^{-1}(2x)$. Since $\sin(2\theta) = 2\sin(\theta)\cos(\theta)$ by the double angle formula, you have by your triangle that $\sin(\theta) = 2x$, $\cos(\theta) = 2\sqrt{1/4-x^2}$. Plug these back in $\theta/4 + \sin(2\theta)/8$.
Answer: In general case whenever you have something like $1-a^2x^2$. Remember $\sin^2x+\cos^2x=1$ and so we should multiply it by $a$. Thus take $\sin y=\frac{1}{a}x$. Now we have
$\sqrt{1-a^2x^2}=\sqrt{1-\sin^2y}=\cos y$.
Hence one can see that
$\int\sqrt{1-a^2x^2}dx=\int\sqrt{1-\sin^2y}\times a\cos y \,dy=\int a\cos^2 y dy$
Now we have $\int \cos^2y$. The standard technique to deal with this is using the gold formula $\cos^2y=\frac{1}{2}(1+\cos 2y)$. In fact the gold formula is revealing the connection between $\cos^2$ and $\cos$.
The most controversial part is the integral of $\int\cos 2ydy$.
It is $\frac{1}{2}\sin 2y$ or in other words it is equal to $\sin y\cos y$. Now recall that $\sin y=\frac{1}{2}x$. Thus one can see that $\cos y=\sqrt{1-\frac{1}{4}x^2}$ and we are done, as we only need to have $\sin y$ and $\cos y$.
Comment: @Cetshwayo Unfortunately, this is probably the **best** explanation there is to solving this. If you're confused as to what he did, he basically used a trigonometric substitution, and then invoked the half-angle formula for $cos^{2}(x)$
Comment: Please tell me which part then I elaborate it.
Comment: Your explanation is confusing.
Comment: I am calculus two student. Your explanation is too sophisticated. I need a simpler explanation.
Comment: Ok which part is too sophisticated for you i am going to simplify it. If you need to explain, then we can move to chat :)
Comment: @Cetshwayo what part of the answer is too sophisticated/can be made simpler?
Comment: @Simon Hu  - Okay, where in my work have I failed. Can you make me aware?
Comment: @Cetshwayo You need to represent $\theta$ in terms of x. So your work is good, but what you need to do is finish it off. From your work, you know that
\begin{equation}
\frac{x}{\frac{1}{2}} = sin(\theta)
\end{equation}
Take the inverse, and theta will be in terms of x.
Replace $\theta$ in your final answer and you get the right answer.

As to *why* you need to represent theta in terms of x, remember that in the beginning, you did a *u-substitution*. Your final answer cannot be in terms of "u"
Comment: If you need a simpler explanation that this one then perhaps you need a simpler course...
Answer: When you're doing the trigonometric substitution, you write $x=a\sin\theta$, which is good; you should also remember how to get back from $\theta$ to $x$, that is,
$$
\theta=\arcsin\frac{x}{a}=\arcsin\frac{x}{1/2}=\arcsin(2x)
$$
which actually should be the starting point, because it guarantees the angle $\theta$ is between $-\pi/2$ and $\pi/2$.
When you arrive to
$$
\frac{1}{4}\theta+\frac{1}{8}\sin(2\theta)=
\frac{1}{4}\theta+\frac{1}{4}\sin\theta\cos\theta
$$
you indeed need to get back to $x$. Since $-\pi/2\le\theta\le\pi/2$, you know $\cos\theta\ge0$ and so
$$
\cos\theta=\sqrt{1-\sin^2\theta}=\sqrt{1-4x^2}
$$
In conclusion your integral is
$$
\frac{1}{4}\arcsin(2x)+\frac{1}{2}x\sqrt{1-4x^2}
$$

However, there's no need for trigonometric substitutions. Consider
$$
\int\sqrt{1-t^2}\,dt=
\int\frac{1-t^2}{\sqrt{1-t^2}}\,dt=
\int\frac{1}{\sqrt{1-t^2}}\,dt+\int\frac{-t^2}{\sqrt{1-t^2}}\,dt
$$
The first one is immediate; the second one can be computed with integration by parts:
$$
\int t\frac{-t}{\sqrt{1-t^2}}\,dt=
t\sqrt{1-t^2}-\int\sqrt{1-t^2}\,dt
$$
All in all, we have
$$
\int\sqrt{1-t^2}\,dt=
\arcsin t+t\sqrt{1-t^2}-\int\sqrt{1-t^2}\,dt
$$
so we can transport the integral from the right-hand side to the left-hand side and get
$$
\int\sqrt{1-t^2}\,dt=
\frac{1}{2}\arcsin t+\frac{1}{2}t\sqrt{1-t^2}
$$
For your integral use the substitution $2x=t$.
Answer: $$\int\sqrt{1-4x^2}\space\space\text{d}x=$$

Substitute $x=\frac{\sin(u)}{2}$ and $\text{d}x=\frac{\cos(u)}{2}\space\space\text{d}u$. Then $\sqrt{1-4x^2}=\sqrt{1-\sin^2(u)}=\cos(u)$ and $u=\sin^{-1}(2x)$:

$$\frac{1}{2}\int\cos^2(u)\space\space\text{d}u=$$
$$\frac{1}{2}\int\left(\frac{1}{2}\cos(2u)+\frac{1}{2}\right)\space\space\text{d}u=$$
$$\frac{1}{4}\int\cos(2u)\space\space\text{d}u+\frac{1}{4}\int 1\space\space\text{d}u=$$

Substitute $s=2u$ and $\text{d}s=2\space\space\text{d}u$:

$$\frac{1}{8}\int\cos(s)\space\space\text{d}s+\frac{1}{4}\int 1\space\space\text{d}u=$$
$$\frac{\sin\left(s\right)}{8}+\frac{u}{4}+\text{C}=$$
$$\frac{\sin\left(2u\right)}{8}+\frac{u}{4}+\text{C}=$$
$$\frac{\sin\left(2\sin^{-1}(2x)\right)}{8}+\frac{\sin^{-1}(2x)}{4}+\text{C}$$
Answer: This is called Trigonometric Substitution.
$$\int\sin^2 x\cos xdx, \color{green}{\text{let }u=\sin x}\implies du=\cos xdx$$
$$\int\sin^2 x(\cos xdx)=\int u^2du =\frac{u^3}{3}+C =\frac{\sin^3 x}{3}+C$$
Whereas this is called Inverse Trigonometric Substitution
$$\int\sqrt{1-4x^2}dx = \int\sqrt{1-(2x)^2}dx, \color{green}{\text{let }\sin u=2x}\implies \cos u du=2dx$$
$$\begin{array}{lll}
\int\sqrt{1-(2x)^2}dx&=&\frac{1}{2}\int 2\sqrt{1-(2x)^2}dx\\
&=&\frac{1}{2}\int \cos u\sqrt{1-\sin^2 u}du\\
&=&\frac{1}{2}\int \cos^2 udu\\
&=&\dots\\
\end{array}$$
Notice that the substitution $\sin u = 2x$ can be rewritten as
$$u = \sin^{-1} (2x)$$
Compare the differences between the substitutions in the two examples, and it should become clear why inverses are necessary.
It may be instructive to use implicit differentiation to derive
$$\frac{d}{dt}\sin^{-1}t = \frac{1}{\sqrt{1-t^2}}$$
and then explicitly make the substitution $u = \sin^{-1}(2x)$
$$\frac{du}{dx} = \frac{d}{d2x}\sin^{-1}(2x)\cdot\frac{d}{dx}2x = \frac{2}{\sqrt{1-(2x)^2}}$$
$$du =  \frac{2dx}{\sqrt{1-(2x)^2}}$$
Getting back to our integral
$$\int\sqrt{1-(2x)^2}dx=\int\sqrt{1-(2x)^2}\cdot\frac{\color{green}{2}\sqrt{1-(2x)^2}}{2\color{green}{\sqrt{1-(2x)^2}}}dx = \int\frac{1}{2}(1-(2x)^2)\cdot\color{green}{\frac{2}{\sqrt{1-(2x)^2}}}dx$$
$$= \int\frac{1}{2}(1-\sin^2(\sin^{-1}(2x)))\cdot\frac{2}{\sqrt{1-(2x)^2}}dx$$
$$= \int\frac{1}{2}(1-\sin^2 u)du = \frac{1}{2}\int\cos^2 udu=\dots$$


Forcing a column to require sorting in Ant Design

Question: So currently I have a table with sorting enabled on one of the columns, the column being createdAt. I want the table to always be sorted but currently how its working is that the column will toggle between DESC, to none, to ASC. This is causing me some headache since for the end user experience the table should always be sorted in some direction, and for future tables with multiple sorting columns I also want sorting to be required. I can't find any properties on the table or column to support this type of behavior so for a temporary work around I'm just checking on the back-end if its receiving the sorting params and if it isn't it just defaults to DESC on id.
Columns are defined in an array of objects and then used as a property on the ant design table. below is my date created column object
{
  title: 'Date Created',
  dataIndex: 'createdAt',
  key: 'createdAt',
  width: '17%',
  sorter: (a, b) =>
    (new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) /
    (1000 * 3600 * 24),
  defaultSortOrder: 'descend',
  ...getColumnSearchProps('createdAt'),
  render: createdAt => {
    return (

        {new Date(createdAt).getMonth()}/{new Date(createdAt).getDate()}/
        {new Date(createdAt).getFullYear()}

    );
  }
},

and the ant design table component

 record.id}
    dataSource={data}
    pagination={pagination}
    loading={loading}
    onChange={handleTableChange}
  />

Update:
Below is a link to a code sandbox from the ant design website showcasing how sorting on tables works. My issue has to do with the ant design framework and not my code. If you sort the columns after the column is already ascending it disables the sort. I want my table to always have sorting on, all I need to do is remove the ability to disable the sort. Just looking for ideas.
https://codesandbox.io/s/y4pxx
Thanks for any help in advance!
Comment: You should definitely provide some code, sort feature in a table is not standard html.
Comment: @Apolo just updated, this is in reference to the Ant Design react UI framework and is definitely not using standard html. Hope that helps
Comment: Everything look okay in the code above, could you post a code sandbox and show what the issue is? My best guess right now would be that the sorter that you wrote now isn't working as you expect it to.
Comment: @ShivamGupta Not an issue with the code at all, has to do with the framework. I updated the question above to have a link to a code sandbox. Just play around with sorting and you'll see what I mean.
Comment: Ah now I understand what you mean. You want to disable the default sort (no sort option for the table) right?
Comment: @ShivamGupta Close, the default sort is fine because it defaults to sorting by age descending. But if you try to change the sort direction to ascending it disables the sort. I want to make it so sorting is required and you can't disable the sort.
Comment: Let me look a bit more into it, right now I don't see any way of doing this. Like you said, its part of the library functionality. i'd recommend dropping an issue on their github and seeing if they respond with any solution.
Comment: Maybe look at (https://ant.design/components/table/#components-table-demo-reset-filter) and use the sortedInfo object as used in the example and keep it set to descend onClick.
Comment: any solution for this?
Comment: I cannot believe ANTD added a hidden 3rd sort order option of  "none", it's not even in their API docs. Every 3rd click appears to be "none" which i also do not understand.  Any fix on this?
Answer: I have just faced with the same issue, and there is my solution:
At the columns define the sort directions like this:
sortDirections: ['ascend', 'descend', 'ascend']

Instead of this:
sortDirections: ['descend', 'ascend']

Comment: Hell man! Thank you. Developers say they are not going to add this feature but looks like even they do not aware of this workaround
Comment: Thanks a ton man! I spent almost half a day looking for this configuration in their documentation. You saved my night. Thanks again.
Answer: You can just render the column filter as you want, there is an official example for it.
Use filterDropdown with filterIcon to render a custom sorter as you like,
both properties accepts ReactNode as expected.

filterDropdown Customized filter overlay React.ReactNode | (props: FilterDropdownProps) => React.ReactNode

filterIcon
  Customized filter icon ReactNode|(filtered: boolean) => ReactNode

Reference:
 - Column component.


Can we calculate the standard error of prediction just based on simple linear regression output?

Question: The standard error of prediction in simple linear regression is $\hat\sigma\sqrt{1/n+(x_j-\bar{x})^2/\Sigma{(x_i-\bar{x})^2}}$.
My question is to calculate the standard error of prediction for $pop=1029$ just based on the following regression output. I can get all except $\bar{x}$. And I also know how to calculate the approximate standard error of prediction based on the standard errors of intercept and coefficient of $pop$, ignoring their correlation.
Comment: How would the regression output change if you were, say, to add $10^6$ to each `pop` value and add $-0.0116584\times 10^6$ to each `fuel` value? Intuitively, that shifts the data far from `pop=1029` without altering the regression line and therefore should result in a much wider prediction interval. That means you can focus your research on those elements of the output that change.  (Even if you don't have the actual data you can make some up and run both regressions to see what happens.)
Comment: Thanks very much! Only the standard error of the intercept (therefore t, p-value and CI) changes. This inspired me to figure out that $Var(\hat{\beta}_0)=\sigma^2(1/n+\bar{x}^2/SXX)$, then I can get $\bar{x}$ to calculate the standard error of prediction.
Comment: The standard error of a *predicted value* isn't what you said. What you have there is the standard error for the mean at a given $x$.
Comment: Sorry I just followed the description of the option `stdp` in `Stata`. It can be thought of as the standard error of the predicted expected value, mean or the fitted value.
Answer: The question is to calculate the following statistic from the above regression output:
$$s.e.(\hat\mu|x_j)=\hat\sigma\sqrt{1/n+(x_j-\bar{x})^2/\Sigma{(x_i-\bar{x})^2}}.$$
The answer is inspired by @whuber:

get $\hat\sigma$ from $\hat\sigma^2=SS_{Residual}/(n-p-1)$,
where $p=1$;
$n$ and $x_j$ are known;
obtain $\bar{x}$ from
$\hat{Var}(β_{cons})=\hatσ^2(1/n+\bar{x}^2/\Sigma{(x_i-\bar{x})^2})$;
$\Sigma{(x_i-\bar{x})^2}=SS_{Model}/\hat{\beta}_{pop}^2$.
Answer: For simplicity, we are working with the following model:
$$y=\beta_0 + \beta_1x + \varepsilon,$$
where $\varepsilon\sim N(0, \sigma^2)$.
Now suppose that for $x=5$, we would like to predict $E(y|x=5) = \beta_0 + 5\beta_1$, denoted by $pre$.
We note that $pre$ is just a value if we know $\beta_0$ and $\beta_1$. However, they are unknow and each of them has its own sampling distribution (where the sd of this distribution is called the se). Therefore, the standard error associated with $pre$ is computed as:
$$Var(pre) = Var(\beta_0 + 5\beta_1) = Var(\beta_0) + 10 Cov(\beta_0, \beta_1) + 25Var(\beta_1).$$
Now you can see that you cannot compute this variance if you do not know the covariance $Cov(\beta_0, \beta_1)$.
Answer: See Section 6-4a of Wooldridge (2020), Introductory Econometrics: A Modern Approach, 7ed, Cengage.
Variance of prediction error
It's not $\sigma^2 [ 1/n + (x_j-\bar{x})^2 / \sum_i (x_i - \bar{x})^2 ]$.
For the correct expression, let me use vector notations. The model is $y=x\beta + u$, where $x=(1,pop)$. Let $x_0 = (1,1029)$. The value to predict ($y_0$) is not yet labeled. The predictor is $\hat\theta = x_0 \hat\beta$, where $\hat\beta$ is the OLS estimator, and the label to predict is $x_0 \beta + u_0$. The prediction error is thus $y_0 - \hat\theta = u_0 - x_0 (\hat\beta-\beta)$.
As $\hat\beta$ is a function of the sample and $u_0$ (out of sample) is assumed to be independent of the sample, the variance of the prediction error is $\sigma^2 + x_0 V(\hat\beta) x_0'$, where $'$ stands for transpose. As $V(\hat\beta) = \sigma^2 (X'X)^{-1}$, where $X$ is the feature matrix (including the constant term in the first column), the variance of the prediction error is $\sigma^2 [ 1+ x_0 (X'X)^{-1} x_0' ]$ so the standard error is
$$\sigma \sqrt{1 + x_0 (X'X)^{-1} x_0'}.$$
Calculation of se(prediction error)
If we change the variable $pop$ to $pop-1029$, then $\hat\theta$ is reported as the intercept estimate:
<code>/* Stata */
gen pop2 = pop - 1029
reg fuel pop2
</code>
You see that the reparameterizated model $fuel = \theta + \beta_1 (pop-1029) + u$ gives $\theta = \beta_0 + 1029 \beta_1$ so the intercept estimator $\hat\theta$ is your predictor.
The reported standard error is, however, $se(\hat\theta) = \hat\sigma \sqrt{x_0 (X'X)^{-1} x_0'}$, not the desired $\hat\sigma \sqrt{1+x_0 (X'X)^{-1} x_0'}$. For the correct one, you can simply compute $\sqrt{\hat\sigma^2 + se(\hat\theta)^2}$.


How to stop Privatemsg showing user role in 'To' field

Question: With the module Privatemsg (v7.x-1.3) the 'To' field will show the username and then their role in brackets when composing a new message with the user id passed in the url:
/messages/new/567

I've searched the code but cannot seem to find where the role is being added so that I can disable it. Does anyone know?
Comment: Are you using special configuration for Privatemsg? Because I'm using the latest updated version of v7.x-1.3 and I don't see user role when composing a new message.
Answer: Inside the privatemsg module, in hook_menu search for $items['messages/autocomplete'] this is where the menu defines the auto complete path.
Search for privatemsg_autocomplete function where the output is defined.
UPDATE:
To remove just the role, here is a patch for that. Here is a thread on drupal that shows how this has progressed https://drupal.org/node/1852746
Comment: Are you sure this is the function that adds the role to the username? As the role is only added when the user id is passed through the url. When you enter the username directly in the 'To' field then the autocomplete looks up the username but doesn't add the role.
Comment: I have updated my answer.
Answer: I've found what I was looking for in the file 'privatemsg.theme.inc' within this function:
function theme_privatemsg_username($variables) {
  $recipient = $variables['recipient'];
  $options = $variables['options'];
  if (!isset($recipient->uid)) {
    $recipient->uid = $recipient->recipient;
  }
  if (!empty($options['plain'])) {
    $name = check_plain(format_username($recipient));
    if (!empty($options['unique'])) {
      $name .= ' [user]';
    }
    return $name;
  }
  else {
    return theme('username', array('account' => $recipient));
  }
}

I've just commented out the lines below which mean it won't add the text ' [user]' after the name of a user.
    // if (!empty($options['unique'])) {
    //   $name .= ' [user]';
    // }

As I'm also using the sub module 'Privatemsg roles' I've edited the file 'privatemsg_roles.module' and within this function:
function theme_privatemsg_roles_format($variables) {
  $role = $variables['recipient'];
  $options = $variables['options'];
  if (!empty($options['plain'])) {
    $name = $role->name;
    if (!empty($options['unique'])) {
      $name .= ' [role]';
    }
    return $name;
  }
  return t('%role (role)', array('%role' => $role->name));
}

Commented out the lines below to make sure a role is always marked as such.
// if (!empty($options['unique'])) {
  $name .= ' [role]';
// }


Como mover vários arquivos ZIP de uma vez com Python

Question: eu estou criando uma função para gerenciar arquivos usando python.
eu gostaria que essa função fizesse o seguinte: pegasse todos os meus arquivos zip ou mp3 (ou com outros formatos) e movesse todos de uma vez para uma pasta.
   os.chdir('C:\\')
   shutil.copy('C:\\Users\\ODIN\\Downloads\\*.*', 'C:\\ODIN\\d')

Comment: Tem como descrever pelo menos uma das suas tentativas? Se pressionar [edit], você pode alterar a sua pergunta para poder adicionar o código.
Comment: Já deu uma pesquisada no google alguém já deve ter passado por esse problema ou por algo semelhante!
Comment: OBRIGADO VOU VERIFICAR
Answer: Acho que você está procurando por shutil.move():
shutil.move("pasta/atual/seu.doc", "nova/pasta/seu.doc")
Não apenas para arquivos, mas também para diretórios.
Recomendo uma lida na documentação.
Comment: OK OBRIGADO VOU USAR  E VERIFICAR A DOCUMENTACAO
Answer: Creio que esta solução atende a tua necessidade.
__author__ = '@britodfbr'

import shutil
from os import listdir
from os.path import isfile, join, basename

def move(path_origem, path_destino, ext='zip'):
    for item in [join(path_origem, f) for f in listdir(path_origem) if isfile(join(path_origem, f)) and f.endswith(ext)]:
        #print(item)
        shutil.move(item, join(path_destino, basename(item)))
        print('moved "{}" -> "{}"'.format(item, join(path_destino, basename(item))))

if __name__ == '__main__':
    move('/tmp/a', '/tmp/b')

Saída:
moved "/tmp/a/file7.zip" -> "/tmp/b/file7.zip"
moved "/tmp/a/file4.zip" -> "/tmp/b/file4.zip"
moved "/tmp/a/file0.zip" -> "/tmp/b/file0.zip"
moved "/tmp/a/file3.zip" -> "/tmp/b/file3.zip"
moved "/tmp/a/file1.zip" -> "/tmp/b/file1.zip"
moved "/tmp/a/file6.zip" -> "/tmp/b/file6.zip"
moved "/tmp/a/file9.zip" -> "/tmp/b/file9.zip"
moved "/tmp/a/file2.zip" -> "/tmp/b/file2.zip"
moved "/tmp/a/file5.zip" -> "/tmp/b/file5.zip"
moved "/tmp/a/file10.zip" -> "/tmp/b/file10.zip"
moved "/tmp/a/file8.zip" -> "/tmp/b/file8.zip"
moved "/tmp/a/file01.zip" -> "/tmp/b/file01.zip"

Comment: OK OBRIGADO VAI SER MUITO UTIL