Up to isomorphism - number of graphs

Question:
Let $G = (V,E)$ be a loop-free undirected graph, where $|V| = 6$ and $deg(v) = 2$ for all $v \in V$, Up to isomorphism how many such graphs $G$ are there?

I understand this question as asking how many non-isomorphic graphs there are that satisfy:

$G$ is a loop-free undirected graph
$|V| = 6$
$deg(v) = 2$ for all $v \in V$

The solution given is 2: a cycle on six vertices and a disjoint union of two cycles (each on three vertices).
How come the answer isn't 3? The two solutions given above and also a disjoint union of three cycles (each on two vertices).
So something like 3 copies of the two-vertices cycle below.
Comment: If multiple edges are allowed, then there is a fourth solution: the disjoint union of a $4$-cycle and a $2$-cycle.
Comment: It might help to know **what book you are using** because terminology varies from one book to another, especially in graph theory. Anyway, the source of a quotation must be identified, because unattributed quotation is intellectual theft.
Comment: What would be the degree of each vertex?
Comment: a==b c==d e==f where (a,b,c,d,e,f are vertices and == are the two edges, top and bottom). So each vertex would have degree 2.
Comment: Trying drawing the graph. Each vertex has degree 1!
Comment: Assuming that == means two edges, your example does not produce a simple graph. If we allow for non-simple graphs in the problem, the graph a--b--c--d--a  e==f also works, so the answer then would be 4. The given answer makes me believe that the problem is missing an additional assumption that the graphs are simple.
Comment: @JavaMan See drawing in post
Answer: Unless stated otherwise, a graph has at most one edge between any pair of vertices. Put another way, an edge is completely defined by its two endpoints, and if two edges have the same endpoints then they are in fact the same edge. Your suggestion of three disjoint 2-cycles doesn't work because 2-cycles are never permitted.
(When this condition is relaxed, the resulting object is usually called a multigraph.)
If 2-cycles were allowed, you would have missed a fourth solution: the multigraph could have been the union of a 2-cycle and a 4-cycle.
Comment: Many (most?) authors use "graph" to mean "simple graph" but in that case the modifier "loop-free" would be redundant.

Up to isomorphism - number of graphs


Allowing IP's to access Apache Load Balancer

Question: Why it is not allowing my IP to access Apache Load Balancer
  <Location /balancer-manager>
   SetHandler balancer-manager
   Require host demo-002
   Order deny,allow
   Deny from all
   Allow from 127.0.0.1 10.201.165.186
  </Location>

Seeing the following error
 [access_compat:error] [pid 22702] [client 10.201.165.86:59524] AH01797: client denied by server configuration: /var/www/html/balancer-manager

Apache version: Apache/2.4.6

Please suggest .
Comment: Are you even running that configuration? The syntax isn't valid anymore. And Apache on RHEL will refuse a broken configuration and continue running with the old one, if asked to reload.
Comment: Can you please point me to the documentation link of new syntax
Comment: https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require
Answer: It seems on Apache 2.4 , we have to use Require parameter to allow an IP address . SO for my scenario , the following below works
<Location /balancer-manager>
   SetHandler balancer-manager
   Require ip 127 10.201.165.86
 </Location>


how do you stop downloads from AWS S3 with the object url

Question: i have a website similar to video hosting where i need to display upload videos and images and have the images be visible and also the videos if they are purchased, however their locations are saved in the database (MongoDB) and are displayed on the web-page and therefore show up in the network tab in the developer console.
this means that if you click on the link e.g. "https://s3.Region.amazonaws.com/bucket-name/key-name/folder/file-name.mp4" it will auto download, this only happens on chrome though but not Firefox where it just displays the object with no download option.  i have tried to change the bucket policy, add encryption but either that causes the images that i want to display to become invisible as they are not publicly accessible or just has no effect and still allows for the video to be downloaded. is there any way for me to have the images and videos in the same bucket and have them both be visible under the right circumstances but block access to the bucket and prevent them from being downloaded by anyone but the bucket owner?
Comment: The object being visible on the website in the browser is the **exact same thing** as the user downloading the object, to be able to view it the browser downloads the data. You cannot prevent that without breaking the website.
Comment: Does s3/cloudfront signed URLs (or cookies) fit your needs? You generate them dynamically and insert those links into your authenticated users session so only they will have a temporarily valid link. They can be time limited, ip restricted etc and accessing the url directly (without the signed cookie/url) would fail. Once you give out that URL (to a logged in user etc) as @luk2302 points out its easily downloaded though :-/
Comment: But note that there is absolutely no way to ultimately prevent a user from downloading the data, you can only make it slightly more difficult.
Answer: You cannot stop the downloads because the ability to show videos and images in a browser also means that the files are accessible via URL (that's how the browser fetches them).
One option is to use an Amazon S3 pre-signed URL, which is a time-limited URL that provides temporary access to a private object. The way it would work is:

Users authenticate to your back-end service
When a user requests access to one of the videos or images, your back-end checks that they are authorized to access the file
If so, your back-end generates an Amazon S3 pre-signed URL and includes it in the web page (eg )
When the user's browser accesses that URL, Amazon S3 will verify that the URL is correct and the time-limit has not expired. If it's OK, then the file is provided.
Once the time limit expires, the URL will not work

This will not prevent a file being downloaded, but it will limit the time during which it can be done.
Alternate methods would involve serving content via streaming instead of via a file, but that is a much more complex topic. (For example, think about how Netflix streams content to users rather than waiting for them to download files.)
Comment: And every movie that is available via streaming is freely downloadable a few minutes later because it is just a little bit more complicated to retrieve the full file.
Comment: thanks for the advice, i will look more into pre-signed URLs. hopefully that method will be sufficient until the project gains traction and i can afford to get professionals to help work on it. thanks.


How to resolve Apple Mach-O Linker Error?

Question: Here is a log
<code>CompileC /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.o Classes/iPadNewsbookViewController.m normal armv7 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    cd /Users/RAGOpoR/Desktop/trunk/src
    setenv LANG en_US.US-ASCII
    setenv PATH "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch armv7 -fmessage-length=0 -std=c99 -fobjc-arc -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wmissing-prototypes -Wreturn-type -Wno-implicit-atomic-properties -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-sign-compare -Wno-shorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -DDEBUG_MODE=1 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -Wprotocol -Wdeprecated-declarations -g -fvisibility=hidden -Wno-conversion -Wno-sign-conversion -mthumb "-DIBOutlet=__attribute__((iboutlet))" "-DIBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName)))" "-DIBAction=void)__attribute__((ibaction)" -miphoneos-version-min=4.0 -iquote "/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-generated-files.hmap" "-I/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-own-target-headers.hmap" "-I/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-all-target-headers.hmap" -iquote "/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-project-headers.hmap" -iquote../src -I/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Products/Debug-iphoneos/include -I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/include/libxml2 -I/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/DerivedSources/armv7 -I/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/DerivedSources -F/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Products/Debug-iphoneos -F/Users/RAGOpoR/Desktop/trunk/src -include /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/PrecompiledHeaders/iPortals_Prefix-gellvzrskltxesfcgpqcdmiyeqru/iPortals_Prefix.pch -MMD -MT dependencies -MF /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.d --serialize-diagnostics /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.dia -c /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.m -o /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.o

In file included from /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.m:9:
In file included from /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.h:10:
In file included from /Users/RAGOpoR/Desktop/trunk/src/Classes/WebViewerController.h:10:
In file included from /Users/RAGOpoR/Desktop/trunk/src/Classes/AppDelegate_iPhone.h:12:
/Users/RAGOpoR/Desktop/trunk/src/ShareKit/Reachability/Reachability.h:69:58: warning: declaration of 'struct sockaddr_in' will not be visible outside of this function
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
                                                         ^
0  clang             0x000000010cadf6a2 PrintStackTrace(void*) + 34
1  clang             0x000000010cadfb29 SignalHandler(int) + 553
2  libsystem_c.dylib 0x00007fff83d827ea _sigtramp + 26
3  libsystem_c.dylib 0x00007fff6b7b6300 _sigtramp + 18446744073300818736
4  clang             0x000000010c428828 findRetainCycleOwner(clang::Expr*, (anonymous namespace)::RetainCycleOwner&) + 312
5  clang             0x000000010c428b02 clang::Sema::checkRetainCycles(clang::Expr*, clang::Expr*) + 50
6  clang             0x000000010c44d33a clang::Sema::checkPseudoObjectAssignment(clang::Scope*, clang::SourceLocation, clang::BinaryOperatorKind, clang::Expr*, clang::Expr*) + 1242
7  clang             0x000000010bc85e86 clang::Sema::ActOnBinOp(clang::Scope*, clang::SourceLocation, clang::tok::TokenKind, clang::Expr*, clang::Expr*) + 1606
8  clang             0x000000010bc8507a clang::Parser::ParseRHSOfBinaryExpression(clang::ActionResult<clang::Expr*, true>, clang::prec::Level) + 570
9  clang             0x000000010bc7e4cb clang::Parser::ParseAssignmentExpression() + 171
10 clang             0x000000010bc7e401 clang::Parser::ParseExpression() + 17
11 clang             0x000000010bcd3bde clang::Parser::ParseExprStatement(clang::ParsedAttributes&) + 46
12 clang             0x000000010bc7de9c clang::Parser::ParseStatementOrDeclaration(clang::ASTOwningVector<clang::Stmt*, 32u>&, bool) + 1564
13 clang             0x000000010bc7d1b9 clang::Parser::ParseCompoundStatementBody(bool) + 409
14 clang             0x000000010c3fb1f0 clang::Parser::ParseLexedObjCMethodDefs(clang::Parser::LexedMethod&) + 272
15 clang             0x000000010bd1f6fe clang::Parser::ParseObjCAtEndDeclaration(clang::SourceRange) + 158
16 clang             0x000000010bcfd0d2 clang::Parser::ParseObjCAtDirectives() + 386
17 clang             0x000000010bc3e887 clang::Parser::ParseExternalDeclaration(clang::Parser::ParsedAttributesWithRange&, clang::Parser::ParsingDeclSpec*) + 759
18 clang             0x000000010bc3e519 clang::Parser::ParseTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&) + 249
19 clang             0x000000010bc2128b clang::ParseAST(clang::Sema&, bool) + 299
20 clang             0x000000010bc1fd19 clang::CodeGenAction::ExecuteAction() + 857
21 clang             0x000000010bbf20af clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) + 879
22 clang             0x000000010bbf0d3b clang::ExecuteCompilerInvocation(clang::CompilerInstance*) + 2683
23 clang             0x000000010bbe353e cc1_main(char const**, char const**, char const*, void*) + 5086
24 clang             0x000000010bbbdcd8 main + 648
25 clang             0x000000010bbbda44 start + 52
26 clang             0x0000000000000079 start + 18446744069217724009
Stack dump:
0.  Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -cc1 -triple thumbv7-apple-ios4.0.0 -S -disable-free -disable-llvm-verifier -main-file-name iPadNewsbookViewController.m -pic-level 1 -mdisable-fp-elim -relaxed-aliasing -target-abi apcs-gnu -target-cpu cortex-a8 -mfloat-abi soft -target-feature +soft-float-abi -target-linker-version 131.3 -g -coverage-file /var/folders/2s/0vbgmlf914d3x7m4xjqwdfh80000gp/T/iPadNewsbookViewController-qXtlG9.s -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/clang/4.0 -dependency-file /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.d -MT dependencies -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk -iquote /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-generated-files.hmap -iquote /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-project-headers.hmap -iquote ../src -include-pch /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/PrecompiledHeaders/iPortals_Prefix-gellvzrskltxesfcgpqcdmiyeqru/iPortals_Prefix.pch.pth -D DEBUG_MODE=1 -D IBOutlet=__attribute__((iboutlet)) -D IBOutletCollection(ClassName)=__attribute__((iboutletcollection(ClassName))) -D IBAction=void)__attribute__((ibaction) -I /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-own-target-headers.hmap -I /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Hope Demo-all-target-headers.hmap -I /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Products/Debug-iphoneos/include -I /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/include/libxml2 -I /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/DerivedSources/armv7 -I /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/DerivedSources -F/Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Products/Debug-iphoneos -F/Users/RAGOpoR/Desktop/trunk/src -fmodule-cache-path /var/folders/2s/0vbgmlf914d3x7m4xjqwdfh80000gp/T/clang-module-cache -O0 -Wno-trigraphs -Wno-missing-field-initializers -Wmissing-prototypes -Wreturn-type -Wno-implicit-atomic-properties -Wformat -Wno-missing-braces -Wparentheses -Wswitch -Wno-unused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wno-uninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-sign-compare -Wno-shorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wno-undeclared-selector -Wno-deprecated-implementations -Wprotocol -Wdeprecated-declarations -Wno-conversion -Wno-sign-conversion -std=c99 -fno-dwarf2-cfi-asm -fno-dwarf-directory-asm -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fblocks -fobjc-default-synthesize-properties -fobjc-arc -fobjc-exceptions -fexceptions -fsjlj-exceptions -fpascal-strings -fdiagnostics-show-option -serialize-diagnostic-file /Users/RAGOpoR/Library/Developer/Xcode/DerivedData/iPortals-hfedckfrrkbpaeeekwhpwwkrxkgz/Build/Intermediates/iPortals.build/Debug-iphoneos/iPortals.build/Objects-normal/armv7/iPadNewsbookViewController.dia -o /var/folders/2s/0vbgmlf914d3x7m4xjqwdfh80000gp/T/iPadNewsbookViewController-qXtlG9.s -x objective-c /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.m
1.  /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.m:77:60: current parser token ';'
2.  /Users/RAGOpoR/Desktop/trunk/src/Classes/iPadNewsbookViewController.m:57:20: in compound statement ('{}')
clang: error: unable to execute command: Segmentation fault: 11
clang: error: clang frontend command failed due to signal 2 (use -v to see invocation)
clang: note: diagnostic msg: Please submit a bug report to http://developer.apple.com/bugreporter/ and include command line arguments and all diagnostic information.
clang: note: diagnostic msg: Preprocessed source(s) and associated run script(s) are located at:
clang: note: diagnostic msg: /var/folders/2s/0vbgmlf914d3x7m4xjqwdfh80000gp/T/iPadNewsbookViewController-Q4pbhm.mi
clang: note: diagnostic msg: /var/folders/2s/0vbgmlf914d3x7m4xjqwdfh80000gp/T/iPadNewsbookViewController-Q4pbhm.sh
Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 254
</code>
Comment: It seems that some folks found a partial solution here : http://stackoverflow.com/questions/9335012/apple-llvm-compiler-3-1-error
Answer: If this happens consistently at roughly the same location in your code, then
you seem to have found an internal error in the compiler, i think best way to proceed is to first submit this as a bugreport to apple ( the URL is listed in the output you pasted ).
And then, if you would like to proceed, try to make changes to the code you are trying to compile, like comment out the first half, then retry, then comment out the second half, and retry.  This should point to the code causing the internal compiler error.
Sometimes reordering some code will solve the problem for you. So at least you can continue developing.
Comment: it happen when i integrated Facebook SDK. if i remove it, all done.


How not to insert specific value into database

Question: I have MS SQL Server database and insert some values to one of the tables.
Let's say that the table contains columns ID, int Status and text Text.
If possible, I would like to create a trigger which prevents from writing specific incorrect status (say 1) to the table. Instead, 0 should be written. However, other columns should be preserved when inserting new values:
If the new row written is (1, 4, "some text"), it is written as is.
If the new row written is (1, 1, "another text"), it is written as (1, 0, "another text")
Is it possible to create such trigger? How?
EDIT: I need to allow writing such record even if status column is invalid, so foreign keys will not work for me.
Comment: I am using ORM to write to a database and there are some situations when it inserts intermediate values with intermediate status. This is not too bad, however, if program crashes for some reasons, invalid status is stored in the database. So I cannot handle this in the code (this is third-party binary) and this is not user input.
Comment: Most definitely. An Insert trigger can do that. However for various reasons mostly related to ease of debugging and maintainability, i would suggest that you handle it in code instead of using triggers for this kind of logic. Also, if the status is a user input, wont you need to alert / warn the user if the status entered is incorrect instead of just changing it unknown to the user?
Comment: Use transactions to ensure ACID if at all possible...
Comment: Thanks, but this is third-party ORM, I cannot. I need this hack to workaround third-party.
Answer: I think you would need a foreign key to ensure data integrity even if you choose to use a trigger (though I would myself prefer a 'helper' stored proc -- triggers can cause debugging hell) e.g.
CREATE TABLE MyStuff
(
 ID INTEGER NOT NULL UNIQUE,
 Status INTEGER NOT NULL
    CHECK (Status IN (0, 1)),
 UNIQUE (Status, ID)
);

CREATE TABLE MyZeroStuff
(
 ID INTEGER NOT NULL,
 Status INTEGER NOT NULL
    CHECK (Status = 0),
 FOREIGN KEY (Status, ID)
    REFERENCES MyStuff (Status, ID),
 my_text VARCHAR(20) NOT NULL
);

CREATE TRIGGER tr__MyZeroStuff
ON MyZeroStuff
INSTEAD OF INSERT, UPDATE
AS
BEGIN;
INSERT INTO MyZeroStuff (ID, Status, my_text)
SELECT i.ID, 0, i.my_text
  FROM inserted AS i;
END;

Answer: An insert trigger has been mentioned, but another way to achieve this is to have a foriegn key on your Status column which points back to a Status table - this will not allow the write and change the value, instead it will simply disallow the write if the foriegn key is not valid.
Check out referential integrity for more info on this option.
Comment: Thank you for the answer, but the subtle thing is that due to the task specific I need to allow writing such record even if status column is invalid so foreign keys will not work for me.


if a mostrar botao ou texto

Question:     <?php

echo '

ID Pergunta
Pergunta
Responder

'
;
include ("ligabd.php");//CONECTAR A BD
$sql="SELECT * from pedido WHERE ID_pr=".$_SESSION['ID'];
$sql1="SELECT * from resposta";

$resultado = mysql_query($sql);
while ($sql = mysql_fetch_array($resultado)) {

    echo '

    <form method="post" action="resposta.php" class="login">
    <input type="text" name="pergunta_id" id="pergunta_id" value= ' ;?> <?php echo $sql['ID']; ?> <?php echo ' >
    '.$sql['pergunta'].'
      ';
    if (!isset($sql1['resposta'])!=""){
echo '<button type="submit" class="login-button">Responder</button>

';
}
else echo 'Pergunta Respondida';
}
    echo '
';
?>

Bom dia, estou com uma duvida neste código, quero que o if me mostre um botão caso o registo da resposta esteja limpo.
Por exemplo, tenho uma pergunta como na imagem seguinte:

caso já tenha sido respondida aparecia "Pergunta Respondida", e caso não tenha sido respondida aparecia o botão
Answer: Troque o isset por empty:
if (empty($sql1['resposta'])){
//mostra botão
}else{
//pergunta respondida
}

if a mostrar botao ou texto


put my data json in other file and call it into my controller

Question: Hello I am using AngularJS I am developing a simple application, I have some data in my json like :
angular.module('app', []).controller('MainController', ['$scope', function($scope) {
      $scope.cities = [{
        name: "city A",
        elements: [{
          id: 'c01',
          name: 'name1',
          price: 15,
          qte: 10
        }, {
          id: 'c02',
          name: 'name2',
          price: 18,
          qte: 11
        }, {
          id: 'c03',
          name: 'name3',
          price: 11,
          qte: 14
        }],
        subsities: [{
          name: "sub A1",
          elements: [{
            id: 'sub01',
            name: 'nameSub1',
            price: 1,
            qte: 14
          }, {
            id: 'sub02',
            name: 'nameSub2',
            price: 8,
            qte: 13
          }, {
            id: 'sub03',
            name: 'nameSub3',
            price: 1,
            qte: 14
          }]
        }, {
          name: "sub A2",
          elements: [{
            id: 'ssub01',
            name: 'nameSsub1',
            price: 1,
            qte: 7
          }, {
            id: 'ssub02',
            name: 'nameSsub2',
            price: 8,
            qte: 1
          }, {
            id: 'ssub03',
            name: 'nameSsub3',
            price: 4,
            qte: 19
          }]
        }, {
          name: "sub A3",
          elements: [{
            id: 'sssub01',
            name: 'nameSssub1',
            price: 1,
            qte: 11
          }, {
            id: 'sssub02',
            name: 'nameSssub2',
            price: 2,
            qte: 15
          }, {
            id: 'sssub03',
            name: 'nameSssub3',
            price: 1,
            qte: 15
          }]
        }]
      }, {
        name: "city B",
        elements: [{
          id: 'cc01',
          name: 'name11',
          price: 10,
          qte: 11
        }, {
          id: 'cc02',
          name: 'name22',
          price: 14,
          qte: 19
        }, {
          id: 'cc03',
          name: 'name33',
          price: 11,
          qte: 18
        }]
      }, {
        name: "city C",
        elements: [{
          id: 'ccc01',
          name: 'name111',
          price: 19,
          qte: 12
        }, {
          id: 'ccc02',
          name: 'name222',
          price: 18,
          qte: 17
        }, {
          id: 'ccc03',
          name: 'name333',
          price: 10,
          qte: 5
        }]
      }];
      $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
          $scope.data = itemSelected.elements;
        }
      }

    });

In order to make a clean code and for a good practice, I need to put data in other json file and call it like :
angular.module('app', []).controller('MainController', ['$scope', function($scope) {
      $scope.cities = /*call my json here please how can do that*/;
      $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
          $scope.data = itemSelected.elements;
        }
      }

    });

Please anybody could help me.
UPDATE
After your answers I applied them but it didn't work with me , please take a look at what I did :
I installed a server web (xampp) and put all my files on the server
I changed my script like :
angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/controllers/data.json').then(function(response) {
            $scope.cities = response.data;
  });
  $scope.extractSubsities = function(itemSelected) {
    if (itemSelected && itemSelected.elements) {
        $scope.data = itemSelected.elements;
    }
  }
 }]);

and this is my data data.json
{
"data":[{
        "name": "city A",
        "elements": [{
          "id": "c01",
          "name": "name1",
          "price": "15",
          "qte": "10"
        }, {
          "id": "c02",
          "name": "name2',
          "price": "18,
          "qte": "11"
        }, {
          "id": "c03",
          "name": "name3",
          "price": "11",
          "qte": "14"
        }],
        "subsities": [{
          "name": "sub A1",
          "elements": [{
            "id": "sub01",
            "name": "nameSub1",
            "price": "1",
            "qte": "14"
          }, {
            "id": "sub02",
            "name": "nameSub2",
            "price": "8",
            "qte": "13"
          }, {
            "id": "sub03",
            "name": "nameSub3",
            "price": "1",
            "qte": "14"
          }]
        }, {
          "name": "sub A2",
          "elements": [{
            "id": "ssub01",
            "name": "nameSsub1",
            "price": "1",
            "qte": "7"
          }, {
            "id": "ssub02",
            "name": "nameSsub2",
            "price": "8",
            "qte": "1"
          }, {
            "id": "ssub03",
            "name": "nameSsub3",
            "price": "4",
            "qte": "19"
          }]
        }, {
          "name": "sub A3",
          "elements": [{
            "id": "sssub01",
            "name": "nameSssub1",
            "price": "1",
            "qte": "11"
          }, {
            "id": "sssub02",
            "name": "nameSssub2",
            "price": "2",
            "qte": "15"
          }, {
            "id": "sssub03",
            "name": "nameSssub3",
            "price": "1",
            "qte": "15"
          }]
        }]
      }, {
        "name": "city B",
        "elements": [{
          "id": "cc01",
          "name": "name11",
          "price": "10",
          "qte": "11"
        }, {
          "id": "cc02",
          "name": "name22",
          "price": "14",
          "qte": "19"
        }, {
          "id": "cc03",
          "name": "name33",
          "price": "11",
          "qte": "18"
        }]
      }, {
        "name": "city C",
        "elements": [{
          "id": "ccc01",
          "name": "name111",
          "price": "19",
          "qte": "12"
        }, {
          "id": "ccc02",
          "name": "name222",
          "price": "18",
          "qte": "17"
        }, {
          "id": "ccc03",
          "name": "name333",
          "price": "10",
          "qte": "5"
        }]
      }];
}

but it still couldn't load data
Comment: Try adding error handling to monitor the error,

    $http.get('js/controllers/data.json').then(function(response) {
        $scope.cities = response.data;
    }, function(error) { console.log(error); });
Comment: Store it at server and make http call to fetch it.
Comment: @HarryLim please see my question again I had updated
Comment: what's the error message in browser console for the failed http call ?
Comment: @HarryLim there is no error in my console
Comment: @HarryLim Finally it works thank you so much for your help
Answer: You need to use ajax to fetch the file:
$http.get('file.json').then(function(response) {
    $scope.cities = response.data;
});

Answer: You got to inject $http service to fetch data from an external source, in your case it is just a JSON file.
angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
  $http.get('link to json').then(function(response) {
            $scope.cities = response.data;
  });
  $scope.extractSubsities = function(itemSelected) {
    if (itemSelected && itemSelected.elements) {
        $scope.data = itemSelected.elements;
    }
  }
 }]);

Comment: @Abderrahim what is the error you are seeing in the console?  make sure you have the right path of the JSON file in the $http.get()
Comment: yeah I check my console this is the error  XMLHttpRequest cannot load file:///C:/web/web/carbu_new/carbu/carbu/js/controllers/data.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Anyhelp please
Comment: @Abderrahim  I believe you are using google chrome which prevents cross origin requests. Try it on a different browser, it should work.  To make it work in google chrome,see this post http://stackoverflow.com/questions/8449716/cross-origin-requests-are-only-supported-for-http-but-its-not-cross-domain
Comment: I use the firefox and internet explorer I had the same probleme
Comment: @Abderrahim are you using a web server?
Comment: NO I have no web server
Comment: @Abderrahim that's the problem , you got to use webserver for http requests.
Comment: I installed a server web and I put all my files on the server but it doesn't work with me
Comment: @Abderrahim  what do you see in the console.log ? any errors
Comment: @Abderrahim glad I could help :)
Answer: You would need to inject the $http service into your controller, and fire a get request to the json file in your file directory.
Your controller would then look like this:
angular.module('app', []).controller('MainController', ['$scope', '$http', function($scope, $http) {
    $scope.cities;
    $scope.extractSubsities = function(itemSelected) {
        if (itemSelected && itemSelected.elements) {
            $scope.data = itemSelected.elements;
        }
    }

    function getCities() {
        $http.get('/data/cities.json').then(function(response) {
            $scope.cities = response.data;
        });
    }

}]);

This is assuming your json file is named cities.json and is in the location of data/cities.json
Hope this helps.
For more info on best practice, you can refer to John Papa's styleguide @ github:
Styleguide by John Papa
Comment: where '['  of  ['$scope', '$http', function($scope, $http) is closed ?
Comment: Yes sorry, forgot to close the array apparently!
Comment: But yeah, as mentioned in the other answer you need to use a webserver. you can install one through npm by typing "npm install http-server" and when done, type "http-server -o". After this you simply go the url specified in the console.
Comment: I installed a server web and I put all my files on the server but it doesn't work with me


BigQuery GetQuery result API is giving duplicate entry

Question: I have create a BigQuery Sink to export the query logs i.e to have analytic data over the query my Sink filter
protoPayload.methodName="jobservice.getqueryresults"

When i run a query on Big query i am seeing two entry in the result i.e for single query run two logs are generated how to make sure we have only one unique logs per query.

Is it because my service is calling the api twice ?
 "GET /bigquery/v2/projects/bq-project/queries/cef367ca-89b4-4ab9-b255-4285435197bd?maxResults=0&location=US&prettyPrint=false HTTP/1.1" 200 None
DEBUG:urllib3.connectionpool:https://bigquery.googleapis.com:443 "GET /bigquery/v2/projects/bq-project/queries/cef367ca-89b4-4ab9-b255-4285435197bd?fields=jobReference%2CtotalRows%2CpageToken%2

Is there any way in i can assure that there would be only one entry per query ?
Comment: What do you want to have as data in your analytics table to perform stuff?
Comment: @guillaumeblaquiere i want to have details `query`, `user`, `source`, ` execution time` , `schema`, `tables`  query related stuff
Answer: To get the required data, I recommend you to use this filter for you sink
resource.type="bigquery_resource"
protoPayload.serviceData.jobCompletedEvent.job.jobStatus.state="DONE"
protoPayload.methodName="jobservice.jobcompleted"

Indeed, the JobCompleted in state DONE provide you all the information at the end of the request.
The GetQueryResult is a query to BigQuery to fetch the data. If you fettch page of 10 rows for a total of 200 rows, you will have 20 entries of the same request, with the same information as the JobCompleted entry.
Comment: i am not getting the query logs it's mostly the `load_job` logs
Comment: if i do `select * from my datasets`  i am not getting this logs


Help with contextual filter and entity reference fields

Question: I have a content type with an entity reference field that allows users to assign multiple other nodes to be referenced from the current node.
I am trying to create a view that will list the related nodes for the current page.
What Relationship/s and contextual filters must be set to achieve such a thing?
I have read a number of other posts asking similar questions, though most seem to be in reference to Drupal 7 and their suggestions either do not work, or appear to not exist in Drupal 8.
I can get a list which shows all the other nodes that reference the current node by setting a contextual filter to: Content:field_related_pages and setting the default value to Content ID from URL this, however, is the exact opposite of what I want...
I have tried creating a relationship based on the Entity Reference field, however there are two options I can see:

Content referenced from field_related_pages
Content using field_related_pages

I have also tried using a contextual filter of: Content: ID with the default value set to Content ID from URL
I feel like I have attempted every conceivable combination of the above and none seems to work. Can someone please put me out of my misery and incompetence and please how to get a contextual filter to show a list of nodes related to the current via a entity reference field?
Answer: Apparently I had the following selected under the "more" tab in the contextual filter:
Exclude If selected, the numbers entered for the filter will be excluded rather than limiting the view.
Which lead to all kinds of odd behaviour...
If it is of use to anyone else, the correct answer appears to be:

Content using field_related_pages with the relationship required.
The contextual filter set to Content: ID with  with the ```default value set to Content ID from URL`` and
Relationship dropdown set to the field_related_pages


Can I use the newer versions of Visual Studio to do "old" things?

Question: I have several ATL/COM-based DLLs that I've been using Visual C++ 6.0 on.  I require a couple of "old" things out of the generated DLLs:
(1) They must be compatible with projects developed in Visual Basic 6.0 (the old VB6, emphatically not VB.Net).
(2) They must be compatible with old operating systems - minimum Windows 98 SE.  To be clear, I mean they must run on such OSes, not that I would have to be able to develop them on a machine running such an OS.
I am sick of Visual Studio 6.0.  Converting to Dot Net (or any other major change like that) is out of the question at the current time, so I must continue to use VB6.  But can I switch to the newer Visual Studio's C++, with a minimum of effort (i.e. little if any required recoding)?
If so, are there any "gotchas" I should watch out for?
Thanks.
Answer: The various versions of VS.Net can open up older .Net projects to an extent, but none of them can open up anything pre-.Net, which includes 6.0 of either language.
You should be able to create a new C++ project in one of the .Net VS applications and rebuild your C++ project there, and it should work because unmanaged C++ code doesn't require the .Net runtime (and it still compiles to native machine code), but I haven't done much C++ in a long time, so I don't know for sure 100% that it will work.
Comment: The VC++ manual contradicts you. You can upgrade projects going back to C++ 4.0 in the latest Visual Studio. http://msdn.microsoft.com/en-us/library/kyb7zzw4(v=VS.80).aspx
Comment: That contradicts nothing that I said. It merely confirms and expands upon it.
Comment: Eh? Didn't you say "none of them can open up anything pre-.Net, which includes 6.0 of either language"? But they can, they can go back to 4.0.
Answer: Yes, but it's mildly painful. This is why most shops stick with VC6. I admit I haven't tested COM DLLs on Windows 98, but as far back as NT 4.0 w/ Visual Studio 2005.
I'd like to emphasize that there is no minimal effort. Depending on how your code is written, the conversion can be quite painful. In one project, search & replace fixed 9 out of 10 problems. YMMV. You may need to rewrite some of the low-level COM plumbing.


Using Custom Environment.ts Value for app relative paths in the CLI

Question: I have developed an angular2 app - without the cli and am now trying to move it inside the cli to take advantage of the built in testing and build processes.
The problem I have is that the app I've developed is going to be deployed inside a web content management system (ie DNN, drupal, joomla, etc...).  So the app cannot assume that it's files reside relative to the root of the website directory. (I currently solve this with systemjs by having two different config files)
For example, from the cli build the index.html file in the dist folder looks like this:

    <app-root>Loading...</app-root>

But I need it to look like this:

    <app-root>Loading...</app-root>

If I make these changes manually then the app works.  (I have only moved in the first / root component and anticipate some more issues moving forward.)
I am comfortable creating a gulp task to perform this but hope there is a way to have these differences handled by the angular-cli
ONE IDEA:
If I add a custom environment file to the app/environment folder (environment.cms.ts) ie:
export const environment = {
    production: false,
    envName: 'cms',
    dnnPath: '/DesktopModules/cms/'
};

Is there a way to use the environment file or other setting/option to tell the cli that when I use the ng build --prod --env=cms to add the path I show above in the second index.html file script paths.
Thanks in advance
JK

PS: I am not sure if this is the best place for this.  I did not feel that this was a bug and so did not want to create an issue in the github repository.  Is there another way people are discussing these types of things?
Answer: Okay,
If i just ready the documentation more closely i would have found my answer
see this link to the docs
It states:

Base tag handling in index.html
When building you can modify base tag () in your
  index.html with --base-href your-url option.
Sets base tag href to /myUrl/ in your index.html

ng build --base-href /myUrl/
ng build --bh /myUrl/


Using hook_user submit and after_update in the same module

Question: Extending from this question (I am now using devel, and know that I need to compare r.rid in my logic), I am trying to place a query into my drupal 6 module, that checks that a certain role has been selected prior to save. if after_update will push these details to an external database. else the normal drupal functionality will be the only function.
My code looks like the below, with the bottom hook_user working correctly. If I place the first hook_user (submit) into my module I start getting internal server errors.
Any suggestios?
 function assigncoordinator_user($op, &$edit, &$account){
 switch($op){
 case 'submit':
       drupal_set_message(t('Legend worked'), 'error');
    }
   }

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':
  //The rest of my code.......................

Extra info
If (r.rid = 25) { //How to I check this

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':
  //The rest of my code.......................
 }
 }
 } else {
 //do nothing
 }

Comment: You should not declare `assigncoordinator_user()` function twice in `drupal` site.
Comment: ahh ok thanks. I added an extra example of what I am attempting to do. How would I pull the currently selected role id before it has been submitted? on the user edit pages. @JayendraKainthola
Comment: @Tom 2 PHP bugs in one question. Don't get me wrong but could you try to play with basics, like PHP logic and loops, for few days, and only then come back to Drupal? It'll save everyone's time. Including you. `Switch` has no `else`.
Comment: @tom, you should not include `assigncoordinator_user()` function in if condition.
Comment: @JayendraKainthola actually it's not uncommon to conditionally define functions and classes. Of course here it may make a little less sense. But in general, it is OK.
Comment: @Mołot, yes, we can define in general case. But, here `r.rid` is not define and it will always show the error.
Answer: PHP does not allow multiple functions with same name. That's the point of the case statement there. Instead of
 function assigncoordinator_user($op, &$edit, &$account){
 switch($op){
 case 'submit':
       drupal_set_message(t('Legend worked'), 'error');
    }
   }

function assigncoordinator_user($op, &$edit, &$account, $category = NULL){
 switch($op){
 case 'after_update':

you should:
function assigncoordinator_user($op, &$edit, &$account){
  switch($op){
    case 'submit':
      drupal_set_message(t('Legend worked'), 'error');
      break;
    case 'after_update':
      // Your other code
      break;
  }
}


How can CMAN restart after a network failure

Question: I try to configure a 3-nodes HA cluster with pacemaker/cman on centos 6.5.
STONITH is disabled (pcs property set stonith-enabled=false).
When I simulate a network issue (iptables -A INPUT -s $OTHER_NODES_IP -j DROP),
the master resource is moved to another node, and is stopped on the failed one.
When I enable network again (iptables -D INPUT -s $OTHER_NODES_IP -j DROP),
the failed node can't automatically join the cluster.
In the log we have: corosync[3323]: cman killed by node 3 because we were killed by cman_tool or other application
How can cman restart instead of being killed ?
Answer: The idea here is that you want cman to be killed if it looses contact with the cluster. This is referred to as "fencing". During this time, the node will drift from the rest of the cluster. If it were to simply come back into production without review, you could get some rather serious corruption or undefined behaviour among your nodes.
The idea here is, by fencing your malfunctioning node you help to ensure data integrity. Once you have fixed the malfunction and verified that the node is back up-to-date you can easily just restart cman.
Comment: In my case, when the resource is started, it is in slave mode, and it resync with the master. Fencing is then no needed, and I just want the resource to be started (it was stopped because quorum was missing). Can't a cluster be able to autorestart without manual intervention ? (with cman or other tools)
Comment: To my knowledge, there is nothing out-of-the-box that will do this. These nodes are getting fenced for a reason, so the ability to bypass the fence becomes self-defeating.

However, if you really do want to do this, you can write a script that can check the status on cman and start it for you if it's down. I wouldn't recommend doing this, but it is an option.


What's the usage difference between element_validate and validate hook?

Question: From what i've learned today, there are two ways one can go about validating input.
One is the #element_validate field which is passed along the form hook, and the other is the validate hook.
Why use the validate hook if input can be validated with the #element_validate field? Is it a necessity to implement the validate hook in this case?
Or is it a method that should be implemented for complex validation while all simple validation(is number, is date, is url) can be done via the #element_validate option?
Answer: @Haider Ali with #element_validate, we can add our own custom validation functions to a field or we can pass the validation functions provided by Drupal, e.g., element_validate_integer_positive(), element_validate_number(), etc.
This #element_validate works only on the field we added it to.
When we want to add custom validation to multiple fields, we add it in form validate hook, so that we do not need to add separate function to each field and call multiple validate functions.
Comment: Yeah further reading into the API just told me the same thing, thank you however. :)

However, the validate hook stops execution after first error is thrown, it doesn't seem possible to make a list of errors out of it. Which might be possible from the #element_validate field
Comment: What kind of errors?


Creating Primary Sub menu's programmatically

Question: I want to display the latest 10 nodes of node type 'ABC' as a sub menu link under my primary menu. Are there any modules for Drupal 6 to help me achieve it.
I have created a view which gives me a latest 10 nodes sorted by creation date. However, I am unable to figure out how to integrate as an submenu links under the primary menu link.
So is there any other way I can achieve this?
Answer: You could use the menu views module:

What Menu Views Does
Menu Views is a utility module. It provides back
  end support for replacing a standard menu item link with a menu item
  view. Menu items (in any menu) now have the option of toggling between
  two different menu item types: link or view. Depending on which option
  is selected, the appropriate configuration form is displayed on the
  admin side and the appropriate type of item is rendered on the
  front-end.

Once you create a submenu, you can attach a view to it. Your title suggests you're asking to do this programmatically. From what i know, i'm not totally sure if that's possible without a lot of headache.
Comment: I am using drupal 6 ...and i have to show 10 node titles of node type 'ABC' as the sub menu links of the primary link, which is the link to their respective nodes.
Answer: I think what you are expecting is described here. For following the tut you also need to enable Views build menu module. I haven't tried it but by reading it I'm sure its worth a try.


Finding the integral $\int \frac{2x^{12} + 5x^9}{(x^5 + x^3 + 1)^3}dx$ with substitution - how to think?

Question:
Find
$$\int \frac{2x^{12} + 5x^9}{(x^5 + x^3 + 1)^3}dx$$

In the above question, I was literally stumped, and wasn't able to solve it for a long time. Turns out that you had to divide the numerator and the denominator by x15, and then we could substitute. Now this got my thinking, how can we understand where to divide what? I mean obviously, in this question - one big hint would be the numerical coefficients of the numerator, but other than that is there any logical way to proceed or is it basically a hit and try?
Link to the solution
Comment: To me, the very last result does not seem correct.
Answer: Such problems are designed where author of the problem has the tool to be applied in mind and the problem is tailor-made to force the application of the tool. There are much more intense pathological problems devised to make the application of that tool all the more obscure. I remember problems by Titu Andreescu where he wants the student to apply simple AM-GM inequality which is so obscurely hidden behind many steps of algebraic manipulation, that logical approach seems difficult. In your case, its relatively easy to see that leading term of denominator is $x^{15}$, so divide by it as a rule of thumb (you want to deal with lower powers) and then use the second rule of thumb when integration is not straightforward--change of variables.
Answer: Generally these type of questions we simply put $\displaystyle x = \frac{1}{t}$ and then use normal substution method
Now let $$I = \int \frac{2x^{12}+5x^9}{(x^5+x^3+1)^3}dx$$
Put $\displaystyle x= \frac{1}{t}\;,$ Then $\displaystyle dx = -\frac{1}{t^2}dt$
So $$I = -\int\frac{2+5t^3}{\left(t^5+t^2+1\right)^3}\cdot \frac{t^{15}}{t^{12}}\cdot \frac{1}{t^2}dt = -\int\frac{2t+5t^4}{\left(1+t^2+t^{5}\right)^3}dt$$
Now using normal substution method, Put $(1+t^2+t^5)=u\;,$ Then $(2t+5t^4)dt=du$
So we get $$I = -\int\frac{1}{u^3}du = \frac{1}{2u^2}+\mathcal{C} = \frac{1}{2(1+t^2+t^5)^2}+\mathcal{C}$$
So $$I = \int \frac{2x^{12}+5x^9}{(x^5+x^3+1)^3}dx = \frac{x^{10}}{2(x^5+x^3+1)^2}+\mathcal{C}$$

$\bf{Bonus\; Question}::$ Evaluation of $$\int\frac{5x^4+4x^5}{(x^5+x+1)^2}dx$$
Comment: Got it! The answer for the bonus question should be $ \frac{x^5}{x^5 + x + 1} + C $.
Comment: Thanks a lot! It is certainly an interesting way to solve this question. I am attempting the bonus question, but can you please elaborate the reasoning behind doing this substitution. Also, where all does this substitution work.
Comment: http://math.stackexchange.com/questions/1395564/find-int-frac5x44x5x5x12/1395569#1395569


Why is the time incorrect when I convert from milliseconds to local time in Android?

Question:     fun format(input: Long, outputFormat: String = "yyyy-MM-dd'T'HH:mm:ss", locale: Locale = Locale.US): String {
        SimpleDateFormat(outputFormat, locale).apply {
        return format(Date(input))
    }

I have the following method above, when I enter the following command:
println(format(1596095340000))

I am expecting to get
2020-07-29T17:49:00

however I end up getting this instead
2020-07-30T07:49:00

Do I have to manually do the offset myself, and if I do how would I do that? I thought that this type of offset would  be handled automatically?
I've also adapted answer from another SO post at Converting from Milliseconds to UTC Time in Java and results were different but still not what I expected:
    val sdf = SimpleDateFormat()
    sdf.timeZone = TimeZone.getTimeZone("PST")
    println(sdf.format(Date(1596095340000)))

7/30/20 12:49 AM
Comment: Where did you get those milliseconds from?
Comment: After almost going insane, I've pretty much come to the conclusion that the source where these milliseconds are coming from is probably incorrect.
Answer: The time stamp 1596095340000 corresponds to the instant 2020-07-30T07:49:00 UTC - you can verify this at any online date/time conversion site.
By default, SimpleDateFormat uses the system time zone. From your output, it looks like the system time zone coincides with UTC.
To get the result you expect 2020-07-29T17:49:00 you would need a time zone with a 14 hour offset:
var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
sdf.setTimeZone(TimeZone.getTimeZone("GMT-1400"))
sdf.format(new Date(1596095340000L)) // "2020-07-29T17:49:00"

No place in the world has a 14 hour time zone offset. Either your time stamp is wrong, or the result you expect is wrong. For example, if you got the date wrong, your expected time zone might be Australia/Sydney:
sdf.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"))
sdf.format(new Date(1596095340000L)) // "2020-07-30T17:49:00"

Comment: Hmm, I was pretty much pulling hairs out when I was trying to figure out what the issue was. The ebst answer I came to was that the source of truth that is feeding me these milliseconds has an incorrect time.


Retrospective cohort study with case:control matching 1:5. Is clogit really appropriate?

Question: I study school grades in children with brain tumors (=cases), using databases.
Every case in the database has five healthy controls, matched on sex, birth year and residency. The hypothesis is that cases have worse school grades than controls (this is of course already known, but I will also look at other covariates here).
I am not starting by looking at grades, and then trying to determine whether or not the children with low grades were exposed (=had a brain tumor or not) - which would make it a case-control study. No, instead, I look at whether or not a child is a case (=brain tumor) or a control (=no brain tumor), and then find out what grades they have - this makes it a retrospective cohort study.
So I do exposure first, then look at outcome = retrospective cohort study.
Not outcome first, then look at exposure = not a case-control study.
This took me quite some time to realize, and also my statisticians got this wrong, because if you have cases and controls, people (including myself) easily think it is a case-control study.
So, my questions here are:

Do you agree with me that this is a retrospective cohort study, and not a case-control study (even though it uses the terms "case" and "control")?

Since the controls are matched against the cases (on at least some variables that are known to influence school grades, i.e. sex and residency), I have been told to use conditional logistic regression (clogit) when investigating the relationship between being a case (yes/no) and failing a school subject (yes/no). Any thoughts on this, as opposed to using ordinary logistic regression models?

When I read more on this, it is usually assumed that clogit is used mainly in case-control studies. Is it not valid in retrospective cohort studies?

Specifically, this quote from the following article (https://www-ncbi-nlm-nih-gov.proxy.kib.ki.se/pmc/articles/PMC9188848/) gets me thinking:
"Matching in case–control studies can also have other counterintuitive effects because the matching is across outcome groups rather than exposure groups, and thus does not necessarily result in balancing the matching factors across exposure groups. "
I would argue that the matching in my study is not "across outcome groups" - the controls are not selected based on school grades - but rather "across exposure groups" - the controls ARE selected based on that they DO NOT have brain tumors, and also based on sex,  birth year, and residency.
I have asked different statisticians to clarify the above for me, and get mumbling or unclear answers only, or otherwise answers that later turn out to be incorrect. PLEASE, can someone shed a light on this?
Or, to put it in more succintly: IS there really a statistical dependency between cases and controls in my particular study, such that I cannot use Chi-square (for simple proportion comparisons between cases and controls), or that I have to use clogit?
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Answer: This analysis is not a case-control analysis, and using the words "case" and "control" will only muddy things and make them confusing. In your case, children with brain tumors are exposed, and those without brain tumors are unexposed. All the causal inference methods that are used with cohort studies, which examine the effect of an exposure on an outcome without selecting on the outcome, are applicable here. So all the literature on, e.g., propensity score matching is useful; all the literature on matching for case-control studies is not. I can understand why this would be confusing for your analysts; typically, diseases are outcomes, not exposures.
You should consider your population as children you have access to and do an analysis that targets the part of that population most relevant for you. This refers to the estimand, the quantity you are trying to estimate. Performing the analysis you had planned to perform (finding unexposed children with similar backgrounds to exposed children) allows you to estimate the "ATT", which compares the observed outcomes for the exposed children with the counterfactual outcomes for these children had they not been exposed (i.e., had they not developed the tumor). See this paper for an explanation of this and other estimands.
Note the kind of study you are running is not too dissimilar from one of the foundational studies done to examine the effectiveness of causal inference methods. Lalonde compared the treated units in a randomized trial to untreated units collected from a public survey. He used matching to estimate the ATT by finding untreated units similar to his treated units.
After propensity score matching, you should run a regular (generalized) linear outcome model and use a cluster-robust standard error with pair membership as the cluster variable. This is explained the MatchIt vignette on estimating effects, which should be your guide here.
Note that it is inappropriate to look at the relationship between covariates and the outcome when treatment and other covariates are included in the outcome model or when adjusting for a consequence of that covariate. To do so is to commit the table 2 fallacy. You can examine moderation by the covariates, but this requires you to match on the covariates as well. The same vignette above explains how to do moderation analysis with matching.
Comment: Thank you! I will look into the suggested papers.
Answer: The analysis is not a case-control analysis, but neither is it exactly a retrospective cohort study. I am in a very similar situation with a study I have in hand and I will try to explain my thoughts on the subject.
The point is that the distribution of your outcome is not the real one in the population, and that makes your estimators may be biased. I understand that the first idea is to think that this does not have to be true, since the only thing we know for sure is that the distribution of your exposure, brain cancer, is not the one in the general population, as cases are over represented. The truth is that if we assume that there really is a relationship between brain cancer and the outcome, school grades, by taking a subset of the population that has a different distribution in the brain cancer variable, the distribution of school grades will not be the real one either, therefore your population is not representative, since you are over representing the population with bad grades.
If I understood correctly, you took 5 controls randomly from all the children free of brain cancer of the same age, sex and residency. If this is the case I believe the best option for you is to use a Weighted Logistic Regression, i.e., to do a logistic regression but using inverse probability weighting to balance the sample.
The general idea is to use a weight on each observation. For the brain cancer cases this weight would be $1$, as you have observed all. For people without brain cancer this weight will be $1/p_i$ with $p_i$ being the probability of the subject $i$ of having been selected for the study. This $p_i$ could be easily calculated using the matching variables if you have the real population information.
For example, imagine that you had $1$ case from residency $X$ who was $10$ years old and who is a male. You have taken $5$ controls with these characteristics. Imagine that the real population with these characteristics is $2000$ children. To each of these $5$ controls you would have to put a weight of $2000/5 = 400$, and to your control $1$.
Weighting all your controls would solve your problem, since you would have a "complete cohort".
In this Chapter of the book Modeling Binary Correlated Responses using SAS, SPSS and R you can find more information about Weighted Logistic Regression.
Another reference that could help you is Logistic Regression in Rare Events Data by King, G., & Zeng, L. (2001). Find it here.


Populate dropdown select elements with input value onchange using jQuery

Question: i have input field
 <input class="form-control" type="number" id="val-level" name="st_no" value="<?php echo $st_no; ?>" max="10" min="1" placeholder="How Many Levels..">
And have Jquery function
$(document).ready(function() {
     var level_value = $("#val-level").val();

        $("#val-level").on("change",function(){
            level_value = $(this).val()

             var option = '';
            for (var i=0;i<level_value;i++){
option += '<option value="'+ level_value + '">' + level_value + '</option>';
                                        }
                $('#val-skill2').append(option);
                });

 });

I want to populate option elements like 1,2,3 if I insert 3 on input field and when change to 2 populate 1,2. and so on
My dropdown
<select class="form-control" id="val-skill2" name="level">
        <option value="" selected disabled>Select Level</option>

      </select>
  Levels

Comment: So whats the problem?
Comment: if when i input 3 it gives 3,3,3 instead of 1,2,3 and when change to let say 2 it append 3,3,3,2,2
Answer:
One of the problems what this line option += '<option value="' +
level_value  + '">' + level_value  + '</option>'; , It would always
write the value of the input in every option, Use i instead.
Another thing i did was to clear the select option when the input changed

$(document).ready(function() {
  var level_value = $("#val-level").val();

  $("#val-level").on("change", function() {
    level_value = parseInt($(this).val())
$('#val-skill2 option').remove()
    var option = '';
    for (var i = 1; i < level_value +1; i++) {
      option += '<option value="' + i + '">' + i + '</option>';
    }
    $('#val-skill2').append(option);
  });

});

<input class="form-control" type="number" id="val-level" name="st_no" value="" max="10" min="1" placeholder="How Many Levels..">

<select id="val-skill2"></select>
Comment: @japharyjuma Mark the answer if this is what you need.


Spring MVC configure url-pattern

Question:
I try to configure simple Controller.

I have:
in web.xml
<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/index.jsp</url-pattern>
</servlet-mapping>

in mvc-dispatcher-servlet.xml
<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="urlMap">
        <map>
            <entry key="/index.jsp">
                <ref bean="mainPage"/>
            </entry>
        </map>
    </property>
</bean>

<bean name="mainPage" class="ru.mypack.TBController" />

here is my Controller:
public class TBController extends AbstractController {

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    System.out.println("It is here");
    ModelAndView model = new ModelAndView("index");
    return model;
}}

I run in on Tomcat 6 and in this configuration it (/index.jsp) works perfect!
But if I change url-pattern like this
<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>*.jsp</url-pattern>
</servlet-mapping>

it returns 404 accessing /index.jsp
I see "It is here" in console, it means url-pattern works fine but ModelAndView doesn't get initialized
Strange thing is that it looks like he tries to access empty resource
(Chrome dysplays me "HTTP Status 404 - ")
Please, help me to understand what is going on.. May be I missed something in url-pattern specification?
UPD:
Thanks to Pavel Horal, the solution has been found.
I just replaced my url-pattern in web.xml with
<url-pattern>/test/*</url-pattern>

And now it responds by /test/index.jsp
Comment: Please take a look at this thread. It should help. http://stackoverflow.com/questions/15385596/servlet-mapping-web-xml
Answer: Spring is working with the information how the servlet mapping is defined. If you are using suffix mapping (*.something), then Spring uses just the first part (without the suffix). This means you shuold map just /index in your url-pattern (without the suffix).
JavaDoc in Spring's UrlPathHelper#getPathWithinServletMapping gives a better description what is being used in the mapping process:

Return the path within the servlet mapping for the given request, i.e.
  the part of the request's URL beyond the part that called the servlet,
  or "" if the whole URL has been used to identify the servlet.
Detects include request URL if called within a RequestDispatcher
  include.
E.g.: servlet mapping = "/test/*"; request URI = "/test/a" -> "/a".
E.g.: servlet mapping = "/test"; request URI = "/test" -> "".
E.g.: servlet mapping = "/*.test"; request URI = "/a.test" -> "".
Comment: Well this particular JavaDoc is not easy to find. This is internal Spring class. However what I love about Spring is, that even internal classes are well defined and documented (unlike in many other frameworks).
Comment: Thank you, now that's clear! I promise, next time I'll read JavaDoc more carefully :)
Comment: @PavelHoral Could you help me with this question? Thanks. http://stackoverflow.com/questions/33522888/how-does-the-getservletmapping-affects-the-url-in-spring-webmvc

Spring MVC configure url-pattern


$u \in W^{2,2}(\Omega)$ implies $\Delta_p u \in L^q(\Omega)$ for some $q>1$?

Question: Let $\Omega$ be a bounded smooth domain in $\mathbb{R}^N$, and let $p \in (2, 2^*)$, where $2^* = \frac{2N}{N-2}$.

Take any $u \in W^{2,2}(\Omega)$. Is it true that $\text{div}(|\nabla u|^{p-2} \nabla u) \in L^{q}(\Omega)$ for some $q>1$?

Evidently, if $p=2$, then $\Delta u \in L^2(\Omega)$, since
$\|\Delta u\|_{L^2} \leq \|u\|_{W^{2,2}} < +\infty$.
The choice $p < 2^*$ is mostly motivated by the fact that $W^{2,2}(\Omega) \hookrightarrow W^{1,p}(\Omega)$ compactly.
Answer: It seems true. If you actually calculate the divergence, you obtain something bounded by $|D u|^{p-2} |D^2 u|$ times a constant. Since $|D u|^{p-2} \in L^{\frac{p}{p-2}}$ and $|D^2 u| \in L^2$, the product lies in $L^r$, where
$$ \frac{1}{r} = \frac{p-2}{p} + \frac{1}{2} < \frac{1}{2n} + \frac{1}{2} \leq 1 \quad \text{for } p<2^*. $$
If needed, the bound on $r$ can be improved by noting that $|D u|^{p-2} \in L^{\frac{2^*}{p-2}}$.
Comment: Thanks a lot! I think it is a correct way.


Prob. 14, Sec. 30, in Munkres' TOPOLOGY, 2nd ed: If $X$ is Lindelof and $Y$ is compact, then $X\times Y$ is Lindelof

Question: Here is Prob. 14, Sec. 30, in the book Topology by James R. Munkres, 2nd edition:

Show that if $X$ is Lindelof and $Y$ is compact, then then $X \times Y$ is Lindelof.

My Attempt:

Let $X$ and $Y$ be topological spaces such that $X$ is Lindelof and $Y$ is compact.
Now let $\mathscr{A}$ be an open covering of the product space $X \times Y$.
Let $x \in X$. Then let $\mathscr{A}_x$ be the subcollection of $\mathscr{A}$ such that $\mathscr{A}_x$ covers $\{x\} \times Y$, which is compact being homeomorphic with the compact space $Y$.  Therefore some finite subcollection of $\mathscr{A}_x$ also covers $\{x \} \times Y$; let one such subcollection be
  $$
\left\{ \mathbf{A}_{x, 1}, \ldots, \mathbf{A}_{x, n_x} \right\}, \tag{Definition 0}
$$
  and then let us put
  $$
\mathbf{S}_x \colon= \bigcup_{k=1}^{n_x} \mathbf{A}_{x, k}. \tag{Definition 1}
$$
  Then $\mathbf{S}_x$ is an open set of $X \times Y$ such that $\mathbf{S}_x$ covers $\{x \} \times Y$, and since $Y$ is compact, therefore by Lemma 26.8 (The tube lemma) in Munkres there exists an open set $U_x$ of $X$ such that $x \in U_x$ and such that $\mathbf{S}_x$ also covers the tube $U_x \times Y$.
In this way we obtain an open covering $\left\{ U_x \colon x \in X \right\}$ for the Lindelof space $X$, and so a countable subcollection $\left\{ U_{x_1}, U_{x_2}, U_{x_3}, \ldots \right\}$ of the collection $\left\{ U_x \colon x \in X \right\}$ also covers $X$. Thus the collection
  $$ \left\{ \mathbf{S}_{x_1}, \mathbf{S}_{x_2}, \mathbf{S}_{x_3}, \ldots \right\} $$
  covers $X \times Y$.
Therefore using (Definition 0) and (Definition 1) above we can conclude that the collection
  $$
\bigcup_{j=1}^\infty \left\{ \mathbf{A}_{x_j, k} \colon k = 1, \ldots, n_{x_j} \right\}
$$
  is a countable subcollection of $\mathscr{A}$ that covers $X \times Y$.
Thus every open covering $\mathscr{A}$ of $X \times Y$ has a countable subcollection that also covers $X \times Y$.
Hence $X \times Y$ is Lindelof.

Is this proof correct and accurate in each and every detail? Or, are there any errors in my reasoning?
Answer: Yes, the proof works and is a copy-paste of 26.7 , the proof that the product of $X \times Y$ is compact when $X,Y$ are (except that a finite subcover must be replaced by a countable one). From that product proof Munkres abstracts the tube lemma that you re-use here for a Lindelöf factor. The write-up I have no issues with.
Note that the product of two Lindelöf spaces is not always Lindelöf, as shown by $\Bbb R_l \times \Bbb R_l$, the "canonical" example of this phenomenon, so the compact factor is quite essential.
There is another generalisation to be made here (due to Michael, I believe, and covered in Engelking's excellent text book General Topology (2nd ed.)): if $f: X \to Y$ is a perfect map (onto, continuous, closed and all fibres $f^{-1}[\{y\}], y \in Y$ are compact) and $Y$ is Lindelöf, then so is $X$. This is a generalisation, because if $X$ is compact, the projection map $\pi_Y: X \times Y \to Y$ is closed by that same tube lemma; the other parts of the definition of a perfect map for $\pi_Y$ are clear, so from that generalised theorem we can also conclude from the Lindelöfness of the non-compact factor that the whole product is Lindelöf.


How to place custom module template file in theme folder

Question: I am using Drupal 6, and I have created a custom module which is in the  "sites\all\modules\custom" folder; in the same folder there is also the custom.tpl.php file.
I want to place the custom.tpl.php file in the theme folder.
Here is my code:
function custom_menu() {
  $items = array();

  $items['custom'] = array(
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {
  $result = db_query('SELECT * from node');
  return theme('custom', array('output' => $result));
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function template_preprocess_custom(&$variables) {}

Answer: Well you can place in the theme folder or you can leave it in the module. Drupal will look in both places. So if your implementation of hook_theme is a template, Drupal will look for the following files:

themes/bluemarine/custom.tpl.php
modules/custom/custom.tpl.php

If you read the documentation for hook_theme you'll get your answer for the question when you get to the path key:

path: [...] Ordinarily the module or theme path will be used [...]
Comment: Thanks @max the whole point of the exercise is that I don't need to tell drupal where the file is located it should try the module or the theme folder at the moment is only trying the module folder unless I explicitly tell it which is a bit silly.
Comment: I can't get this to work, there is a missing step somewhere.  It always uses the module template file.
Comment: did you clear the theme cache?
Comment: I cleared all caches.
Comment: Did you try sathishkumar addition? You have to tell the theme engine where your file is located, otherwise he will have the behavior in my answer. Paste the new code you tried. And what I don't understand is why do you need to keep 2 versions of `custom.tpl.php` one in your module and one in your theme. It should stay in your module, not in the theme folder.
Answer: Please give path key in theme registry.
function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
       template' =>  path_to_theme() . '/custom',
      'path' => '/'
     ),
  );
}

Comment: This just makes it check the root directory for the template?


Does any competition currently give solid gold medals to winners?

Question: I read from some sources that the dream of every sportsman, the Olympic Gold Medal, is not 100% pure gold. (Olympic Gold medals are required to be made from at least 92.5% silver, and must contain a minimum of 6 grams of gold).

The last series of Olympic medals to be made of solid gold were awarded at the 1912 Olympic Games in Stockholm, Sweden.

Do any of the present sports competitions give pure solid gold medals for the winners?
Comment: Are you asking if any sport *currently* awards solid gold medals, or are you asking if any sport has ever awarded solid gold in the past?
Comment: Present,to be more clear 'active' Competitions.
Answer: Yes, some sports competitions still give out solid gold awards to the winners.
According to Wikipedia, the Kentucky Derby awards the only solid gold trophy in sports.
Professional sports championship rings (such as Super Bowl rings, World Series rings, and NBA championship rings), are usually solid gold.
Championship belts are usually gold plated. However, there are occasionally solid gold championship belts made for special events, such as the 2013 WBC Mayweather vs. Alvarez belt and the 2015 WBC Mayweather vs Pacquiao belt (source).
To be clear, although these examples are solid gold, they are not always pure 24K gold; they may be a lesser purity number.


Arranging an array with as few adjacent values as possible

Question: With an array like this:
[google, google, yahoo, yahoo, yahoo, msn, msn, msn, google]

what's the best way to arrange it with as few adjacent values as possible?
The goal is to get something like this, for instance:
[google, msn, yahoo, google, yahoo, msn, yahoo, msn, google]

Even better would be an algoritnm that ensures that any similar values are as far as possible from each other.
And even better would be to do it directly in SQL.
I'm doing that for a script I'm working on that sends newsletters, and I'd like to avoid sending too many emails to the same domain at once.
[edit] I'm using MySQL
Comment: Is this sorting? Seems more like shuffling with certain restrictions... in any case, what have you tried so far?
Comment: @user996651 - what database are you using?
Comment: @Felix Kling - for now I select them randomly : SELECT * FROM table ORDER BY 'RAND()'
Answer: Using SQL Server 2005 and up, you might take advantage of the ROW_NUMBER functionality

Add a row number to each item, partitioning on sitename.
select from this subquery
order the results on the rownumber and name.

Your requirement that they should be as far away from each other as possible might not be met but all in all, this would suffice.
SQL Statement
SELECT  Site
FROM    (
            SELECT  Site, o = ROW_NUMBER() OVER (PARTITION BY Site ORDER BY Site)
            FROM    q
        ) q
ORDER BY
        o, Site

Results

google msn yahoo google msn yahoo google msn yahoo

Test script
;WITH q ([site])AS (
    SELECT 'google'
    UNION ALL SELECT 'google'
    UNION ALL SELECT 'yahoo'
    UNION ALL SELECT 'yahoo'
    UNION ALL SELECT 'yahoo'
    UNION ALL SELECT 'msn'
    UNION ALL SELECT 'msn'
    UNION ALL SELECT 'msn'
    UNION ALL SELECT 'google'
)
SELECT  Site
FROM    (
            SELECT  Site, o = ROW_NUMBER() OVER (PARTITION BY Site ORDER BY Site)
            FROM    q
        ) q
ORDER BY
        o, Site

Answer: Thanks Lieven, I adapted your answer to MySQL and it works perfectly :
select *
from (
    select
      @i := if(@last_name != t2.name, 1, @i + 1) as row_number,
      @last_name := t2.name as `name`
    from
      site t2,
      (select @i := 0) vt1,
      (select @last_name := null) vt2
    order by t2.name
) t1
order by t1.row_number, t1.name
;

gives :
+------------+--------+
| row_number | name   |
+------------+--------+
|          1 | google |
|          1 | msn    |
|          1 | yahoo  |
|          2 | google |
|          2 | msn    |
|          2 | yahoo  |
|          3 | google |
|          3 | msn    |
|          3 | yahoo  |
+------------+--------+


Integration training?

Question: I've been pretty frustrated lately with my poor integration skills. A lot of times I find that in my math or physics classes I understand the concepts behind a question, reduce it to an integral, and then find myself unable to solve it. Yet some people both on this board and at my university are deft hands at solving complicated integrals with a variety of tricks. I'd really like to get better at integrals and start approaching their level. I was hoping that there might be suggestions of workbooks or textbooks that are designed purely on increasing the reader's ability to solve difficult integrals, and also suggestions on a good general philosophy to take to get better at this as well.
Also, I'm unsure if this is the wrong place to ask this question. If so, I apologize and I'll remove the question.
Comment: I like this question and I think alot of students/mathematicans have asked themself the same question. My professor told me: to differentiate is easy since you "only" have to use different rules like product, sum etc rule - but **integration is an art** since you never know how to because even nicely looking integrals can turn out to be super ugly.
Comment: Instead of looking for a book I think it could be very interesting to collect different methods. Maybe this has already been done :)
Comment: for some classes of integrals there exist canonical procedures to solve them. for example integrals of rational functions of trigonometric expressions can be reduced to integrals of rational functions via Weierstrass subsitutionen. These in turn can be solved canonically by partial fraction decomposition...
Learning this cases where a "simple" algorithm exists save you a lot of work
Answer: I'd have to agree with the other answer, I do not consider myself to be an integration master, nowhere near one, however your "basic" (avoiding things like residue and other crazy stuff) difficult integrals I can do fairly easily. I saw a certain beauty to an integral which motivated me from going to your basic reverse power rule to u subs, some interesting trig substitutions, and I would practice with those. Once you can handle those you can escalate, I liked looking for difficult integrals and then looking at how someone else solved them to add a new technique to my toolbox. So to sum all this up, start small and then master the little things, from there try and like google "really hard integrals" and see if you can see how those are done and then practice with more difficult stuff. (When you're ready for the big leagues MIT has an amazing integration bee whose problems and solutions are online)
Comment: Second the recommendation for the MIT Integration Bee!
Comment: @JohnHughes when I first started that's where I went after I had the basics and I could like not even do one in under 10 minutes. Now I can do like almost all of the ones on the more recent integration bees
Comment: "residue and other crazy stuff" hum hum. The method of residues is among the most efficient, and furthermore has beautiful aspects. Of course, this is beyond what the OP asks: he/she needs advise in real analysis methods
Comment: @JeanMarie oh really didn't know that, I'm actually trying to further build a base in complex analysis to work up to the residue theorem
Answer: I suggest doing the exercises in Spivak's Calculus, in the "techniques of integration" chapter. When you've done all of those, you'll be a pretty solid integrator. (BTW, almost none are easy). I guess the short form of this is "practice makes perfect, but only if you practice stuff you don't already know."

Integration training?


Proof verification of $\sum_{k=1}^n kq^{n-k}$ is unbounded for $n \in \mathbb N$ and $q\in\{\mathbb R\setminus0\}$

Question: As opposed to the sum in this question I want to prove the following:

Given $n\in \mathbb N$, $q\in \{\mathbb R \setminus0\}$ and:
  $$
x_n = \sum_{k=1}^n kq^{n-k}
$$
  Show that $x_n$ is an unbounded sequence.

Proof:
Expand $x_n$:
$$
x_n = q^{n-1} + 2q^{n-2} + 3q^{n-3} + \cdots+ (n-1)q^1 + nq^0
$$
Closed form for this sum may not be easily obtained in this form so try to transform it. Multiply $x_n$ by $(1-q^{-1})$:
$$
\begin{align}
(1-q^{-1})\cdot x_n = q^{n-1} + &\color{red}{2q^{n-2}} + \color{green}{3q^{n-3}} + \cdots + \color{blue}{(n-2)q^2} + \color{orange}{(n-1)q^1} + nq^0 - \\
- &\color{red}{q^{n-2}} - \color{green}{2q^{n-3}} -\dots- \color{blue}{(n-3)q^2} - \color{orange}{(n-2)q^{1}} -(n-1)q^0-nq^{-1}
\end{align}
$$
Which after some transformations results in:
$$
\begin{align}
(1-q^{-1})\cdot x_n &= q^{n-1} + q^{n-2} + \cdots + q^1 + 1 - nq^{-1} = \\
&= \sum_{k=1}^{n-1}q^k + 1 - nq^{-1} =\\
&=\frac{q^n -q}{q-1} + 1 -nq^{-1} \tag1
\end{align}
$$
Now if we multiply $(1)$ by $(q-1)$:
$$
(1-q^{-1})(q-1)\cdot x_n = q^n - 1 -n +nq^{-1} \implies \\
\implies x_n = \frac{q(q^n - q) -nq+n}{(q-1)^2}
$$
Now consider $q^n$ and $nq$. Here $nq$ is obviously unbounded since $q$ is some given number such that $q \ne 0$. For $q^n$ consider the case when $0 < q < 1$. Let:
$$
q={ 1 \over 1+r } \\
r>0
$$
Then:
$$
q^n = {1\over (1+r)^n}
$$
By Bernoulli:
$$
(1+r)^n \ge 1+nr \iff {1\over (1+r)^n} \le{1\over 1+nr} \implies \\
\implies q^n \le{1\over 1+rn}
$$
If $q > 1$ then $q^n$ is unbounded. Therefore $x_n$ is an unbounded sequence.
End of proof.
Is it valid or have i missed something? Not sure whether I also need to prove for negative $q$, do I?
I forgot to mention that i'm only allowed to use precalculus methods. This problem is given even before the definition of limits.
Comment: Is $q$ always positive? According to the title, it can be negative too.
Comment: @Oldboy, you are right, it may be negative. That's why i've put a remark doubting whether i should consider that case as well.
Comment: Well, in that case, you should. Your proof looks valid but only for the half of possible values of $q$.
Answer: hint write $x_n$ as
$$x_n=\sum_{k=1}^n(n-k)q^k$$


Three independent variables + moderator (started with three-way anova but not sure about it)

Question: I have a conceptual model with 3 regular independent variables and one dependent variable.
Next to those three independent variables, I have another moderator variable possible affecting the relationship of two out of three regular independent virables. This makes it actually four independent variables.
I am currently running a three-way anova test with the three regular independent variables. However, I am not sure how to investigate the potential role of the moderator.
Actually, I am not sure if I am approaching it in the right way at all.
Below a screenshot of my conceptual model is attached
Review Extremety, Review Breadth and Identity Disclosure are dummy variables (I did an experiment). Product involvement is a continuous variable.
Does anyone know what would be a good way to investigate this?
Thanks in advance!
Answer: Your diagram pretty much answers your question, once you recognize that (1) a moderator is represented as an interaction term in a regression model and (2) you should include a term for the moderator itself besides the interaction term. Don't worry about whether this ends up being called a "three-way ANOVA" or whatever. If you construct the regression according to your model, the result will represent what you intend to test regardless of what you call it.
If Perceived Review Helpfulness is a continuous outcome then you have a multiple linear regression. All the various types of ANOVA, ANCOVA, etc. can be represented as multiple linear regressions; software typically fits them all with multiple regression methods. You would include Review Extremity, Review Length, Identity Disclosure and Product Involvement as predictors, and add interactions of Product Involvement with each of Review Length and Identity Disclosure. That gives you 6 terms (besides the intercept) in your model. If you have on the order of 60 to 120 cases, you should be able to fit your model without too much risk of overfitting.


Compute the accuracy of a clustering algorithm

Question: I have a set of points that I have clustered using a clustering algorithm (k-means in this case). I also know the ground-truth labels and I want to measure how accurate my clustering is. What I need is to find the actual accuracy. The problem, of course, is that the labels given by the clustering do not match the ordering of the original one.
Is there a way to measure this accuracy? The intuitive idea would be to compute the score of the confusion matrix of every combination of labels, and only keep the maximum. Is there a function that does this?
I have also evaluated my results using rand scores and adjusted rand score. How close are these two measures to actual accuracy?
Thanks!
EDIT: I have been through the sklearn documentation to read about clustering evaluation techniques, but what I need is really an accuracy measure. Many metrics are good for explaining the quality of clustering, and I've used them before, but they are not what I need now.
(I'm actually surprised that what I need does not exist in a package like sklearn or anywhere else, I'm sure I'm not the first one that has a problem like this.)
Comment: How many clusters/classes are you working with? If they are few, you could use a brute-force approach, trying all the possible combinations of corresponde between classes and clustering labels and take the best one
Comment: There should be around 10 clusters, but I will need to extend this approach at some point, so I would like a well-defined function
Comment: Well, if the number of clusters K is big then a brute-force approach may be untractable. Anyway, it would require you to try all possible correspondences between clusters and classes, but that escalates exponentially with K
Answer: Since you use sklearn I suggest you use the package from sklearn for evaluation, and check out the find manual of sklearn.
The most important metrics are ARI and NMI (although AMI may be a good idea to use, too).
https://scikit-learn.org/stable/modules/clustering.html#clustering-evaluation
Comment: I have been through it already, but what I need is really an accuracy measure. These two metrics are good for explaining the quality of clustering, and I've used them before, but they are not what I need now.
I'm actually surprised that what I need does not exist in a package like sklearn, I'm sure I'm not the first one that has a problem like this one.
Comment: Clearing is not classification. The standard measures are ARI and NMI. Stuck to the established standards... The Rand Index (RI) is, in fact, an accuracy: on pairs.
Comment: The problem with the classification measure is when there is not a 1:1 correspondence. And outside of KMeans toy problems there never is a 1 to 1 match.


RAID configuration HPE Proliant DL360 G6

Question: I've got an old server and I would like some advice on the RAID configuration. I have 8 disks of 300GB.
And I'm not sure which setup is more desirable.

2x RAID1 (os: hyper-V)
6x RAID5 (VMs)

or

8x RAID5

If I choose for 8x RAID5, will the host OS see it as one disk or can that be changed in the Array Controller?
Is partitioning in the host OS desirable?
Answer: I would not recommend you using RAID5. The following thread describes it.
RAID with three disks (RAID 5 vs RAID 1E)
In addition, assuming your drives are HDDs, you will get low random write performance, which can be critical for VMs. I would recommend you going RAID10 for your VMs it will give you decent performance.


Replicating R model in SAS

Question: I've got a model that I've developed in R, but also need to express in SAS. It's a double GLM, that is, I fit both the mean and (log-)variance as linear combinations of the predictors:
$E(Y) = X_1'b_1$
$\log V(Y) = X_2'b_2$
where Y has a normal distribution, $X_1$ and $X_2$ are the vectors of independent variables, and $b_1$ and $b_2$ are the coefficients to be estimated. $X_1$ and $X_2$ can be the same, but need not be.
I can fit this in R using gls() and the varComb and varIdent functions. I've also written a custom function that maximises the likelihood using optim/nlminb, and verified that it returns the same output as gls.
I would now like to translate this into SAS. I know that I can use PROC MIXED:
proc mixed;
  class x2;
  model y = x1;
  repeated /group = x2;
run;

However, this only gives me what I want if I have 1 variable in the /GROUP option. If I enter 2 or more variables, MIXED can only handle this by treating each individual combination of levels as a distinct group (that is, it takes the cartesian product). For example, if I have 2 variables in $X_2$, with 3 and 4 levels respectively, MIXED will fit 12 parameters for the variance. What I want is for the log-variance to be additive in the variables specified, ie 6 parameters.
Is there a way of doing this in MIXED or any other proc? I could probably code something in NLP, but I'd really prefer not to.
Answer: Rather than the code you present, I assume you're doing something like class x21 x22 followed by the repeated clause group=x21*x22 to end up with 12 parameters.  This is the only option I'm aware of within SAS, i.e. I don't think you can get a straightforward stratification of the variation across the combined levels of two variables.  But, unless I'm missing something, you should be able re-code your variable into a combined x3 to achieve this.
Also, just to check -- I assumed that your x2 variable is prepared such that it holds the appropriate exponential values for your log-linear variance model.  Otherwise, you may want to check out the local option to the repeated statement.  For example, the following model in R:
wgt <- varExp(form =~ x)
fit <- gls(y ~ x, weights=wgt, data=dat)

corresponds to something like the following in SAS:
proc mixed data=dat;
  model y = x / solution;
  repeated / local=exp(x);
run;

The covariance parameter estimates will differ by a factor of 2 between R and SAS.  This is because the R version models $var(\epsilon_{ij}) = \sigma^2 e^{ 2bx_{i} }$ (see ?varExp).  I'm guessing you're processing your input and not using varExp because this isn't easy to accomplish in R if you have factor variables, but I thought I'd mention it in case it's helpful.

Replicating R model in SAS


Need to create dfs.domain.socket.path manually in Hadoop-2.0.0 to use Impala?

Question: I am following the instructions to configure hadoop-2.0.0 cluster for installing Impala. In hdfs-site.xml, I add two properties "dfs.client.read.shortcircuit" and "dfs.domain.socket.path" (/var/lib/hadoop-hdfs/dn_socket).
But when I start the Hadoop cluster by start-dfs.sh, it fails to start datanodes. The log in datanode says that "failed to stat a path component: '/var/lib/hadoop-hdfs'". Then I create /var/lib/hadoop-hdfs manually, and start Hadoop cluster again. It fails again and log says that it's the permission problem about that directory. OK, fine. I change the owner of hadoop-hdfs from root to ubuntu (ubuntu is the machine username). Now it finally works normally.
I am just confused. Am I doing in the right way? Do we really need to create /var/lib/hadoop-hdfs by ourselves and change the permission or the owner of that directory? Or I missed some configuration setting?
Comment: Are you doing this command line or using or using Cloudera Manager? What version?
Comment: I did it by command line and never tried Cloudera Manager before. You mean that Cloudera Manager will handle those configuration automatically?
Answer: I was running into similar problems using Cloudera Manager. It was an issue of trying to run in 'single-user mode' instead of using root. I think you are doing something similar with user ubuntu. Is this a clean install or are you upgrading / did you have a failed install last time?
I'm guessing you sudo-ed somewhere you should have run something as 'ubuntu'.
If you can make it work by manually setting permissions, go for it.  I have a feeling there are lots of other files owned by root that should be owned byubuntu lurking about in your system.
Anecdotally, if there is no critical data in the server, I have found it is easier to very thoroughly remove any and all files from the old install and then reinstall fresh.
Answer: I was facing a similar issue with starting the datanodes. Then, I came across this link https://github.com/cloudera/Impala/wiki/Build-prerequisites, where it states that we need to create the /var/lib/hadoop-hdfs manually and set the appropriate permissions. This has also fixed my problem.
Answer: Make certain directory /var/lib/hadoop-hdfs/present is OK.