Failed to load ApplicationContext: IllegalArgumentException

Question: I have a Java project that I am building with Maven, and I am sure that there is some silly configuration issue that I am running into.
Whenever I try to package my code via mvn package, I get an IllegalArgumentException.  All the context files are properly loaded, but there is an issue when parsing them, in the ConfigurationClassParser class.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:313)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)

Caused by: java.lang.IllegalArgumentException
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.asm.ClassReader.<init>(Unknown Source)
    at org.springframework.core.type.classreading.SimpleMetadataReader.<init>(SimpleMetadataReader.java:52)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:80)
    at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:102)
    at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
    at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:298)
    at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    at org.springframework.context.annotation.ConfigurationClassParser.getImports(ConfigurationClassParser.java:300)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:230)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:153)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:130)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:285)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:223)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:630)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:106)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:57)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
    ... 30 more

Placing a breakpoint at TestContext.getApplicationContext and re-running the test in Eclipse, I was able to see where it was throwing the exception: within the ConfigurationClassParser's getImports method.  Here's the logic:
if (visited.add(className)) {
        AnnotationMetadata metadata = metadataReaderFactory.getMetadataReader(className).getAnnotationMetadata();
        for (String annotationType : metadata.getAnnotationTypes()) {
            imports = getImports(annotationType, imports, visited);
        }

It throws the exception when it tries to getAnnotationMetadata from the java.lang.annotation.Target class.  I'm not exactly sure how this can be resolved through my configuration. I do not import that class in any of my bean classes or test classes.
I'll be happy to post any other aspect of my configuration, if needed.  My test class is extending AbstractJUnit4SpringContextTests, I am using JUnit 4.7 and Spring Core 3.2.1.RELEASE.
I'd appreciate any constructive feedback.
Answer: I was able to resolve this issue by updating my Spring version from 3.2.0.RELEASE to 4.0.5.RELEASE, where the stacktrace actcually gave me the reason why it was failing: Couldn't find a variable value. The properties file wasn't loaded.
Hope this may help someone else in the future, in case they're using Spring 3.2.0.RELEASE.... :-/ –
Answer: I was able to resolve this issue by using JDK1.7 with Spring3.X, As Spring 3.X RELEASE when used with JDK1.8 was throwing IllegalArgumentException.
Summary: Spring3.X use JDK1.7, Spring4.X use JDK1.8
Hope this may help someone else in the future..


Pre-defined color picking in the node admin in Drupal 7

Question: I want the user to select one of the predefined color for one my Article fields.
I am unable to find a suitable way for the user to do so though. What I want is that there is a color picker of selected colors and user is able to pick on.
Any idea ?
Thanks
Comment: I don't understand what you're trying to do here. What is these predefined colors, is they defined by you and how are you planning on using the actual value in an article e.g if an article has the color red is this just an attribute for the actual node? Does it matter how a color is stored in the database i.e as an integer, string, etc?
Answer: Like I said in my comment I'm having trouble understanding the actual question. If you want a user to be able to choose from a set of predefined colors and connect this value to a node of type article you could do like this:

Visit admin/structure/types/manage/article/fields
Add a new field of type List (text)
Set the widget to Selectlist and press save
On the next page under Allowed values list you then enter all your colors in the form key|value for instance Red|Red or Black|Black and then press Save field settings
In the next form you might set if this field is required or not and a default value

Now your users can select a color from a select list on the article edit screen. Not sure this is what you're asking for though.
Here is an example of what the user will see when editing an article:
Answer: Color Field is the module which exactly meets your requirement.


Querying a table using SQL - columns

Question: I am trying to query on a table. Let's say there 3 columns, color, car brand, and car model.
I want to exclude all blue and green colors cars, and no Honda Civic. This is the where statement I have below:
color not in ("blue", "green")
and (carBrand not = "Honda" and carModel not = "Civic").

I tried using the above statement, and it actually excludes all Honda, all Civic, and exclude any color that is blue or green. I've decided to break the query into two pieces and running them in sequence below:

color not in ("blue","green")
Then from that list run below:

carBrand not ="Honda" and carModel not = "Civic"

My question is, can I have done the above action with one query rather two queries.
FYI, I like Honda Civics, just thought it was a good example since a lot of people know that car model.
Thanks in advance.

Added new comments below for ease of reference.
I tried using the codes below. The code excludes the scenario of
Red,    Honda,  Accord. I have also added a sample table of the data for reference. Thanks for the help.
SELECT Color, CarBrand, CarModel
FROM ColorCarModel
WHERE (
(Color Not In ('green','blue'))
 AND (CarBrand Not In 'Honda')
 AND (CarModel Not In 'Civic')
);

Example data:
ID  Color   CarBrand    CarModel
1   Green   Honda   Civic
2   Blue    Honda   Civic
3   Red Honda   Civic
4   Green   Ford    Civic
5   Blue    Ford    Taurus
6   Red Ford    Taurus
7   Red Honda   Accord
8   Red Ford    Explorer

Comment: Do you mean that all Hondas and all Civics should be excluded, or only those records with Honda and not Civic, or Civic and not Honda?
Answer: I didn't get what you wanted to exlude based on the 3 filters ... try this
where not (color in ('blue','green') and carBrand ='Honda' and carModel = 'Civic')
Answer: SELECT Color, CarBrand, CarModel FROM YourTable
WHERE Color NOT IN ('green','blue')
AND CarBrand NOT IN ('Honda')
AND CarModel NOT IN ('Civic');
Try this and let me know if this helps you.
Comment: I tried using the codes below, which should be the same as above. The code excludes the scenario of Red, Honda, Accord. I have also added a sample table of the data for reference. Thanks for the help.

SELECT Color, CarBrand, CarModel
FROM ColorCarModel
WHERE (
(Color Not In ('green','blue'))
 AND (CarBrand Not In 'Honda')
AND (CarModel Not In 'Civic')
);

ID Color CarBrand CarModel
1 Green Honda Civic
2 Blue Honda Civic
3 Red Honda Civic
4 Green Ford Civic
5 Blue Ford Taurus
6 Red Ford Taurus
7 Red Honda Accord
8 Red Ford Explorer
Answer: The problem with your original where clause is that you applied the not in operator separately to the populations of CarBrand and CarModel.  You had:
(CarBrand Not In ("Honda")) and (CarModel Not In ("Civic"))
Instead, you want:
Not(CarBrand = "Honda" and CarModel = "Civic")
Here is a working example:
data ColorCarModel;
    format id best. color $20. CarBrand $20. CarModel $20.;
    input id color CarBrand CarModel;
    datalines;
1   Green   Honda   Civic
2   Blue    Honda   Civic
3   Red     Honda   Civic
4   Green   Ford    Civic
5   Blue    Ford    Taurus
6   Red     Ford    Taurus
7   Red     Honda   Accord
8   Red     Ford    Explorer
9   Red     Dummy   Civic
run;

proc sql;
    select color, CarBrand, CarModel
    from ColorCarModel
    where (
        upcase(color) not in ('GREEN','BLUE') AND
        NOT (upcase(CarBrand) = 'HONDA' AND upcase(CarModel) = 'CIVIC')
    );
quit;

Notice also that I apply upcase() to the variables before comparing them to strings.  This prevents problems caused by mixed case in the data set (i.e. where CarBrand = "Honda" would miss observations where CarBrand contains "honda").
If it's easier to think about the logic without any nesting, the following SQL provides an equivalent filter via concatenation of CarModel and CarBrand:
proc sql;
    select color, CarBrand, CarModel
    from ColorCarModel
    where (
        upcase(color) not in ('GREEN','BLUE') AND
        upcase(catx('-', CarBrand, CarModel)) <> 'HONDA-CIVIC'
    );
quit;

Because these filters are essentially propositional logic, a good tutorial or text on that subject could be a helpful reference.  In particular, learning rules like De Morgan's law can help you think through how to transform a where clause to a different, equivalent form, which can be helpful in simplifying complex logic.  If you're feeling ambitious, Discrete Mathematics by Rosen is a standard text used in CS curricula that includes an early chapter on propositional logic.

Querying a table using SQL - columns


How to change clear button image (x button) or atleast the color of the clear button image in UISearchbar?

Question: I need a fully transparent searchbar with cancel button. I have tried many solutions But I couldnt find a better solution yet. When I try to remove background color it shows scope bar. Can any one give me some source code for fully transperant Searchbar with can button.
 Here's
addSearchbar.backgroundColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.5];
UITextField *sbTextField = (UITextField *)[self.addSearchbar.subviews lastObject];

for (UIView *subview in addSearchbar.subviews)
{
    NSLog(@"%@",subview);
    if ([subview isKindOfClass:[UITextField class]])
    {
        sbTextField = (UITextField *)subview;
        UIImage *image = [UIImage imageNamed: @"06_magnifying_glass.png"];
        UIImageView *iView = [[UIImageView alloc] initWithImage:image];
        iView.frame = CGRectMake(0, 0, 24, 24);
        sbTextField.leftView.frame = CGRectMake(0, 0, 24, 24);
        sbTextField.leftView = iView;
        [sbTextField.rightView removeFromSuperview];
        CGFloat myWidth = 24.0f;
        CGFloat myHeight = 24.0f;
        UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, myWidth, myHeight)];
        [myButton setImage:[UIImage imageNamed:@"clear.png"] forState:UIControlStateNormal];
        [myButton setImage:[UIImage imageNamed:@"clear.png"] forState:UIControlStateHighlighted];

        [myButton addTarget:self action:@selector(doClear:) forControlEvents:UIControlEventTouchUpInside];
        sbTextField.rightView = myButton;
        sbTextField.rightViewMode = UITextFieldViewModeWhileEditing;
        break;
    }
    if([subview isMemberOfClass:[UISegmentedControl class]])
    {
        UISegmentedControl *scopeBar=(UISegmentedControl *) subview;
        scopeBar.tintColor =  [UIColor clearColor];
    }
}
[sbTextField removeFromSuperview];
[addSearchbar addSubview:sbTextField];
[addSearchbar setSearchFieldBackgroundImage:[UIImage imageNamed:@"SearchBar.png"] forState:UIControlStateNormal];
CGRect sbFrame = self.addSearchbar.frame;
// Set the default height of a textfield
sbFrame.size.height = 31;

/* 8 is the top padding for textfield inside searchbar
 * You may need to add a variable to 8 according to your requirement.
 */
sbFrame.origin.y = 6+self.addSearchbar.frame.origin.y;
sbTextField.frame = sbFrame;
sbTextField.textColor = [UIColor lightGrayColor];
[sbTextField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin];

Need a fully transparent searchbar with cancel button and clear button but without scopebar.
Thanks in advance
Comment: http://stackoverflow.com/questions/9704562/remove-or-override-the-clear-button-on-uisearchdisplaycontroller-in-a-uipopove
Comment: I found out the solution but another pblm so I updated my ques
Answer: As of iOS 5.0 you can do the following:
UIImage *imgClear = [UIImage imageNamed:@"clear"];
[addSearchBar setImage:imgClear forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

Thats it. You might also want to repeat the line for the UIControlStateHighlighted state.
The last thing you should be doing is digging around inside the subviews of the search bar. It is guaranteed to break some day. Use the proper API to customize any control.
Comment: unfortunately the latter part of your answer does not work. [see here](http://stackoverflow.com/questions/14720026/customizing-uisearchbariconclear-for-uicontrolstatehighlighted-does-not-work).
Comment: In iOS 7.1 this solution http://stackoverflow.com/questions/13862050/custom-clear-button-in-uisearchbar-text-field#answer-19438100 works perfect.
Comment: You have to use different image for highlighted and normal states. I mean, that the image can be the same, but NOT the same UIImage* reference.
Answer: See that you set the UIControlHighlighted state image first and then the UIControlStateNormal state image or else you might face an issue wherein the clearIcon is not set in the highlighted state. (Not sure why this problem occurs.)
[_searchBar setImage:[UIImage imageNamed:@"ClearIcon"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[_searchBar setImage:[UIImage imageNamed:@"ClearIcon"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

Answer: For those of you trying this in Swift (I know someone is going to come here looking for this...) here you go:
    self.searchBar.setImage(UIImage(named: "ico-cancel"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Normal)
    self.searchBar.setImage(UIImage(named: "ico-cancel"), forSearchBarIcon: UISearchBarIcon.Clear, state: UIControlState.Highlighted)

Make sure you have the correct image in your Assets.xcassets folder.
Answer: Here's how you change the magnifying glass and clear button icon in a UISearchBar's UITextField
Without New Icons:
// Reference search display controller search bar's text field (in my case).
UITextField *searchBarTextField = [self.searchDisplayController.searchBar valueForKey:@"_searchField"];

// Magnifying glass icon.
UIImageView *leftImageView = (UIImageView *)searchBarTextField.leftView;
leftImageView.image = [LeftImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
leftImageView.tintColor = [UIColor whiteColor];

   // Clear button
UIButton *clearButton = [searchBarTextField valueForKey:@"_clearButton"];
[clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
clearButton.tintColor = [UIColor whiteColor];


Which of the following sets are closed under addition?

Question: (i) The set of all vectors in R^2 of the form (a, b) where b = a
(ii) The set of all 3 × 3 matrices that have the vector [-2  -3  3]T as an eigenvector
(iii) The set of all polynomials in P2 of the form a0 + a1 x + a2 x2 where a0 = a2^2
I'm pretty sure that i) is correct and iii) is wrong but I might be wrong.
Not sure about ii)
Answer: For the one(s) you think are true, try to prove them. For instance, in (i) take two arbitrary vectors of the form $(a,b)$ where $b=a$, e.g., $(c,c)$ and $(d,d)$, and add them. Do you again get something of the same form?
For the one(s) you think are false, try to come up with a counterexample. You said you think (iii) is false, why is that? Can you come up with explicit polynomials of the form described so that their sum is not of that form?
For the one(s) you're unsure about, start by trying to prove them. If it looks like the proof won't work, try to come up with a counterexample instead to disprove it.
Answer: Set (ii) is closed under addition.
Note $\mathbf{v} = (-2,-3,3)^T$. If $A_1.\mathbf{v} = \lambda_1 \mathbf{v}$ and $A_2.\mathbf{v} = \lambda_2 \mathbf{v}$ then
$$(A_1+A_2).\mathbf{v} = A_1.\mathbf{v} + A_2.\mathbf{v} = \lambda_1 \mathbf{v} + \lambda_2 \mathbf{v} = (\lambda_1 + \lambda_2) \mathbf{v}$$ hence $A_1+A_2$ has $\mathbf{v}$ as an eigenvector.


conditions on integral cyclic cubic polynomial

Question:
If the irreducible cubic polynomial $T^3 -pT+s$ with integral coefficients with $p\neq 3$ prime has cubic Galois group, then $s\equiv 0\mod p$.
Comment: You should give links to [the earlier developments](https://math.stackexchange.com/q/2272385/11619)
Answer: just so you know, $x^2 + 27 y^2 = 4 p^3$ is impossible for primes $p \equiv 2 \pmod 3.$ For primes $p \equiv 1 \pmod 3,$ there are two answers to $x^2 + 27 y^2 = 4 p^3$ with $x,y$ positive integers. One has $y$ divisible by $p.$ The other shows how your $T^3 - pT + s,$ with $s=y,$ becomes reducible; for example, $t^3 - 7 t + 6$ has positive integers roots $t=1,t=2$ and negative $-(1+2) = -3.$
Construction of these comes from this dichotomy: for $p \equiv 1 \pmod 3,$ we have one of these two expressions but not both:
$$ u^2 + 27 v^2 = p, $$
$$ 4 u^2 + 2 uv + 7 v^2 = p.  $$
The (form) class group of discriminant $-108$ is
$$ \langle 1,0,27 \rangle, \; \; \langle 4,2,7 \rangle, \; \; \langle 4,-2,7 \rangle.$$
Gauss composition gives explicit formulas from choices taken using the appropriate one of the above.  Why not, made two separate lists, then combined. Easier to see the patterns.
==================================
31 = 2^2 + 27 * 1^2
 x = 308;  y = 30 =  2 3 5 = 1 * 31 - 1 = 5 * 31 - 125
 x = 124;  y = 62 =  2 31

43 = 4^2 + 27 * 1^2
 x = 520;  y = 42 =  2 3 7 = 1 * 43 - 1 = 6 * 43 - 216
 x = 344;  y = 86 =  2 43

109 = 1^2 + 27 * 2^2
 x = 646;  y = 420 =  2^2 3 5 7 = 5 * 109 - 125 = 7 * 109 - 343
 x = 218;  y = 436 =  2^2 109

127 = 10^2 + 27 * 1^2
 x = 2540;  y = 254 =  2 127
 x = 380;  y = 546 =  2 3 7 13 = 6 * 127 - 216 = 7 * 127 - 343

157 = 7^2 + 27 * 2^2
 x = 3850;  y = 156 =  2^2 3 13 = 1 * 157 - 1 = 12 * 157 - 1728
 x = 2198;  y = 628 =  2^2 157

223 = 14^2 + 27 * 1^2
 x = 6244;  y = 446 =  2 223
 x = 3220;  y = 1122 =  2 3 11 17 = 6 * 223 - 216 = 11 * 223 - 1331

229 = 11^2 + 27 * 2^2
 x = 5038;  y = 916 =  2^2 229
 x = 4466;  y = 1020 =  2^2 3 5 17 = 5 * 229 - 125 = 12 * 229 - 1728

277 = 13^2 + 27 * 2^2
 x = 7202;  y = 1108 =  2^2 277
 x = 4030;  y = 1596 =  2^2 3 7 19 = 7 * 277 - 343 = 12 * 277 - 1728

283 = 16^2 + 27 * 1^2
 x = 9056;  y = 566 =  2 283
 x = 5600;  y = 1482 =  2 3 13 19 = 6 * 283 - 216 = 13 * 283 - 2197

====================================
7 =  4 * 0^2 + 2 * 0 * 1  + 7 *  1^2
 x = 20;  y = 6 =  2 3 = 1 * 7 - 1 = 2 * 7 - 8
 x = 7;  y = 7 =  7

13 =  4 * 1^2 + 2 * 1 * 1  + 7 *  1^2
 x = 70;  y = 12 =  2^2 3 = 1 * 13 - 1 = 3 * 13 - 27
 x = 65;  y = 13 =  13

19 =  4 * 2^2 + 2 * 2 * -1  + 7 *  -1^2
 x = 133;  y = 19 =  19
 x = 56;  y = 30 =  2 3 5 = 2 * 19 - 8 = 3 * 19 - 27

37 =  4 * 3^2 + 2 * 3 * -1  + 7 *  -1^2
 x = 407;  y = 37 =  37
 x = 110;  y = 84 =  2^2 3 7 = 3 * 37 - 27 = 4 * 37 - 64

61 =  4 * 1^2 + 2 * 1 * -3  + 7 *  -3^2
 x = 182;  y = 180 =  2^2 3^2 5 = 4 * 61 - 64 = 5 * 61 - 125
 x = 61;  y = 183 =  3 61

67 =  4 * 2^2 + 2 * 2 * -3  + 7 *  -3^2
 x = 880;  y = 126 =  2 3^2 7 = 2 * 67 - 8 = 7 * 67 - 343
 x = 335;  y = 201 =  3 67

73 =  4 * 1^2 + 2 * 1 * 3  + 7 *  3^2
 x = 1190;  y = 72 =  2^3 3^2 = 1 * 73 - 1 = 8 * 73 - 512
 x = 511;  y = 219 =  3 73

79 =  4 * 4^2 + 2 * 4 * 1  + 7 *  1^2
 x = 1343;  y = 79 =  79
 x = 884;  y = 210 =  2 3 5 7 = 3 * 79 - 27 = 7 * 79 - 343

97 =  4 * 5^2 + 2 * 5 * -1  + 7 *  -1^2
 x = 1843;  y = 97 =  97
 x = 1330;  y = 264 =  2^3 3 11 = 3 * 97 - 27 = 8 * 97 - 512

103 =  4 * 4^2 + 2 * 4 * -3  + 7 *  -3^2
 x = 1820;  y = 198 =  2 3^2 11 = 2 * 103 - 8 = 9 * 103 - 729
 x = 1339;  y = 309 =  3 103

139 =  4 * 6^2 + 2 * 6 * -1  + 7 *  -1^2
 x = 3197;  y = 139 =  139
 x = 2576;  y = 390 =  2 3 5 13 = 3 * 139 - 27 = 10 * 139 - 1000

151 =  4 * 4^2 + 2 * 4 * 3  + 7 *  3^2
 x = 2869;  y = 453 =  3 151
 x = 1748;  y = 630 =  2 3^2 5 7 = 5 * 151 - 125 = 9 * 151 - 729

163 =  4 * 6^2 + 2 * 6 * 1  + 7 *  1^2
 x = 4075;  y = 163 =  163
 x = 3400;  y = 462 =  2 3 7 11 = 3 * 163 - 27 = 11 * 163 - 1331

181 =  4 * 3^2 + 2 * 3 * -5  + 7 *  -5^2
 x = 3458;  y = 660 =  2^2 3 5 11 = 4 * 181 - 64 = 11 * 181 - 1331
 x = 1267;  y = 905 =  5 181

193 =  4 * 5^2 + 2 * 5 * 3  + 7 *  3^2
 x = 4439;  y = 579 =  3 193
 x = 1150;  y = 1008 =  2^4 3^2 7 = 7 * 193 - 343 = 9 * 193 - 729

199 =  4 * 4^2 + 2 * 4 * -5  + 7 *  -5^2
 x = 5236;  y = 390 =  2 3 5 13 = 2 * 199 - 8 = 13 * 199 - 2197
 x = 2189;  y = 995 =  5 199

211 =  4 * 2^2 + 2 * 2 * 5  + 7 *  5^2
 x = 6032;  y = 210 =  2 3 5 7 = 1 * 211 - 1 = 14 * 211 - 2744
 x = 2743;  y = 1055 =  5 211

241 =  4 * 3^2 + 2 * 3 * 5  + 7 *  5^2
 x = 7378;  y = 240 =  2^4 3 5 = 1 * 241 - 1 = 15 * 241 - 3375
 x = 4097;  y = 1205 =  5 241

271 =  4 * 8^2 + 2 * 8 * -3  + 7 *  -3^2
 x = 7859;  y = 813 =  3 271
 x = 812;  y = 1710 =  2 3^2 5 19 = 9 * 271 - 729 = 10 * 271 - 1000

==========================================
7 =  4 * 0^2 + 2 * 0 * 1  + 7 *  1^2
 x = 20;  y = 6 =  2 3 = 1 * 7 - 1 = 2 * 7 - 8
 x = 7;  y = 7 =  7

13 =  4 * 1^2 + 2 * 1 * 1  + 7 *  1^2
 x = 70;  y = 12 =  2^2 3 = 1 * 13 - 1 = 3 * 13 - 27
 x = 65;  y = 13 =  13

19 =  4 * 2^2 + 2 * 2 * -1  + 7 *  -1^2
 x = 133;  y = 19 =  19
 x = 56;  y = 30 =  2 3 5 = 2 * 19 - 8 = 3 * 19 - 27

31 = 2^2 + 27 * 1^2
 x = 308;  y = 30 =  2 3 5 = 1 * 31 - 1 = 5 * 31 - 125
 x = 124;  y = 62 =  2 31

37 =  4 * 3^2 + 2 * 3 * -1  + 7 *  -1^2
 x = 407;  y = 37 =  37
 x = 110;  y = 84 =  2^2 3 7 = 3 * 37 - 27 = 4 * 37 - 64

43 = 4^2 + 27 * 1^2
 x = 520;  y = 42 =  2 3 7 = 1 * 43 - 1 = 6 * 43 - 216
 x = 344;  y = 86 =  2 43

61 =  4 * 1^2 + 2 * 1 * -3  + 7 *  -3^2
 x = 182;  y = 180 =  2^2 3^2 5 = 4 * 61 - 64 = 5 * 61 - 125
 x = 61;  y = 183 =  3 61

67 =  4 * 2^2 + 2 * 2 * -3  + 7 *  -3^2
 x = 880;  y = 126 =  2 3^2 7 = 2 * 67 - 8 = 7 * 67 - 343
 x = 335;  y = 201 =  3 67

73 =  4 * 1^2 + 2 * 1 * 3  + 7 *  3^2
 x = 1190;  y = 72 =  2^3 3^2 = 1 * 73 - 1 = 8 * 73 - 512
 x = 511;  y = 219 =  3 73

79 =  4 * 4^2 + 2 * 4 * 1  + 7 *  1^2
 x = 1343;  y = 79 =  79
 x = 884;  y = 210 =  2 3 5 7 = 3 * 79 - 27 = 7 * 79 - 343

97 =  4 * 5^2 + 2 * 5 * -1  + 7 *  -1^2
 x = 1843;  y = 97 =  97
 x = 1330;  y = 264 =  2^3 3 11 = 3 * 97 - 27 = 8 * 97 - 512

103 =  4 * 4^2 + 2 * 4 * -3  + 7 *  -3^2
 x = 1820;  y = 198 =  2 3^2 11 = 2 * 103 - 8 = 9 * 103 - 729
 x = 1339;  y = 309 =  3 103

109 = 1^2 + 27 * 2^2
 x = 646;  y = 420 =  2^2 3 5 7 = 5 * 109 - 125 = 7 * 109 - 343
 x = 218;  y = 436 =  2^2 109

127 = 10^2 + 27 * 1^2
 x = 2540;  y = 254 =  2 127
 x = 380;  y = 546 =  2 3 7 13 = 6 * 127 - 216 = 7 * 127 - 343

139 =  4 * 6^2 + 2 * 6 * -1  + 7 *  -1^2
 x = 3197;  y = 139 =  139
 x = 2576;  y = 390 =  2 3 5 13 = 3 * 139 - 27 = 10 * 139 - 1000

151 =  4 * 4^2 + 2 * 4 * 3  + 7 *  3^2
 x = 2869;  y = 453 =  3 151
 x = 1748;  y = 630 =  2 3^2 5 7 = 5 * 151 - 125 = 9 * 151 - 729

157 = 7^2 + 27 * 2^2
 x = 3850;  y = 156 =  2^2 3 13 = 1 * 157 - 1 = 12 * 157 - 1728
 x = 2198;  y = 628 =  2^2 157

163 =  4 * 6^2 + 2 * 6 * 1  + 7 *  1^2
 x = 4075;  y = 163 =  163
 x = 3400;  y = 462 =  2 3 7 11 = 3 * 163 - 27 = 11 * 163 - 1331

181 =  4 * 3^2 + 2 * 3 * -5  + 7 *  -5^2
 x = 3458;  y = 660 =  2^2 3 5 11 = 4 * 181 - 64 = 11 * 181 - 1331
 x = 1267;  y = 905 =  5 181

193 =  4 * 5^2 + 2 * 5 * 3  + 7 *  3^2
 x = 4439;  y = 579 =  3 193
 x = 1150;  y = 1008 =  2^4 3^2 7 = 7 * 193 - 343 = 9 * 193 - 729

199 =  4 * 4^2 + 2 * 4 * -5  + 7 *  -5^2
 x = 5236;  y = 390 =  2 3 5 13 = 2 * 199 - 8 = 13 * 199 - 2197
 x = 2189;  y = 995 =  5 199

211 =  4 * 2^2 + 2 * 2 * 5  + 7 *  5^2
 x = 6032;  y = 210 =  2 3 5 7 = 1 * 211 - 1 = 14 * 211 - 2744
 x = 2743;  y = 1055 =  5 211

223 = 14^2 + 27 * 1^2
 x = 6244;  y = 446 =  2 223
 x = 3220;  y = 1122 =  2 3 11 17 = 6 * 223 - 216 = 11 * 223 - 1331

229 = 11^2 + 27 * 2^2
 x = 5038;  y = 916 =  2^2 229
 x = 4466;  y = 1020 =  2^2 3 5 17 = 5 * 229 - 125 = 12 * 229 - 1728

241 =  4 * 3^2 + 2 * 3 * 5  + 7 *  5^2
 x = 7378;  y = 240 =  2^4 3 5 = 1 * 241 - 1 = 15 * 241 - 3375
 x = 4097;  y = 1205 =  5 241

271 =  4 * 8^2 + 2 * 8 * -3  + 7 *  -3^2
 x = 7859;  y = 813 =  3 271
 x = 812;  y = 1710 =  2 3^2 5 19 = 9 * 271 - 729 = 10 * 271 - 1000

277 = 13^2 + 27 * 2^2
 x = 7202;  y = 1108 =  2^2 277
 x = 4030;  y = 1596 =  2^2 3 7 19 = 7 * 277 - 343 = 12 * 277 - 1728

283 = 16^2 + 27 * 1^2
 x = 9056;  y = 566 =  2 283
 x = 5600;  y = 1482 =  2 3 13 19 = 6 * 283 - 216 = 13 * 283 - 2197

==========================================
Comment: In fact, I only considered irreducible  cubics in which case I believe this is true (in which case I will edit my post - or correct it?). Your analysis is more general if I understand correcly but I know nothing about class group or Gauss composition


Reverse sort list by max element

Question: I have a list of vectors
l = list(c(1,2),c(3,4),c(2,3),c(7,8),c(5,6))

and would to reverse sort it by the vector maximums:
> l
[[1]]
[1] 7 8

[[2]]
[1] 5 6

[[3]]
[1] 3 4

[[4]]
[1] 2 3

[[5]]
[1] 1 2

Any idea how I could do this in a one liner? thx
Answer: One way is
l[order(sapply(l, max), decreasing=TRUE)]
#[[1]]
#[1] 7 8

#[[2]]
#[1] 5 6

#[[3]]
#[1] 3 4

#[[4]]
#[1] 2 3

#[[5]]
#[1] 1 2

You could replace sapply(l, max) with vapply(l, max, numeric(1L)) as well.
Or a compact form suggested by @DavidArenburg
l[order(-sapply(l, max))]

Comment: Nice answer, I think you can shorten it to just `l[order(-sapply(l, max))]`

Reverse sort list by max element


Getting "Object variable or With block variable not set" on first use of document.TypeText with Outlook Message

Question: Can anyone help me figure out what's going wrong and how to fix it?
I'm trying to automate sending an email with some daily status information.  I'd tried automating this from Access but kept running into (known but apparently unsolved) problems with GetObject(, "Outlook.Application") with Windows 8.1 64 and Outlook 2013. So I decided to automate starting from Outlook.
Anyway, I moved the mail message creation code into Outlook vba and had it start Access and run the Access code.  This is all well and good until I get to creating the mail message.  Everything starts just fine until it gets to writing to the body of message (using Word as the body editor).  At the first "TypeText" command, I'm getting the error message in the title. If I click debug on the error notification dialog and then single-step through the line of code in question, it works just fine. I thought that there was some timing problem, so I stuck a 2-second wait in the code. No luck.  The code in question, with some other oddities associated with testing (notably trying to type and then delete text), is below:
Public Sub CreateMetrics()
   ' Mail-sending variables
    Dim mailApp As Outlook.Application
    Dim accessApp As Access.Application

    Dim mail As MailItem
    Dim wEditor As Word.Document
    Dim boolCreatedApp As Boolean

    Dim i As Integer

    Set mailApp = Application

    ' Create an Access application object and open the database
    Set accessApp = CreateObject("Access.Application")
    accessApp.OpenCurrentDatabase dbLoc
    accessApp.Visible = True

    ' Open the desired form and run the click event hander for the start button
    accessApp.DoCmd.OpenForm ("ProcessStatus")
    accessApp.Forms![ProcessStatus].StartButton_Click

    ' Create the outgoing mail message
    Set mail = Application.CreateItem(olMailItem)
    mail.Display
    mail.BodyFormat = olFormatHTML
    Set wEditor = mailApp.ActiveInspector.WordEditor

    With accessApp.Forms![ProcessStatus]
        Debug.Print .lblToList.Caption
        Debug.Print .lblSubject.Caption
        Debug.Print .lblIntroduction.Caption
        Debug.Print .lblAttachFilepath.Caption
    End With

        mail.To = accessApp.Forms![ProcessStatus].lblToList.Caption
        mail.Recipients.ResolveAll

        mail.Subject = accessApp.Forms![ProcessStatus].lblSubject.Caption
        mail.Attachments.Add accessApp.Forms![ProcessStatus].lblAttachFilepath.Caption

        Sleep 2000

        ' Error occurs in the next line ***********************************************
        wEditor.Application.Selection.TypeText Text:="Test"
        wEditor.Application.Selection.HomeKey
        wEditor.Application.Selection.Delete Count:=4

        wEditor.Application.Selection.PasteSpecial DataType:=wdPasteBitmap
        wEditor.Application.Selection.HomeKey
        wEditor.Application.Selection.TypeText accessApp.Forms![ProcessStatus].lblIntroduction.Caption
        wEditor.Application.Selection.TypeText Text:=Chr(13) & Chr(13)
        wEditor.Application.Selection.EndKey

'        wEditor.Application.Selection.EndKey
'        wEditor.Application.Selection.TypeText Text:=Chr(13)
'        wEditor.Application.Selection.TypeText Text:=configs("EmailSignature")
'    End With

    With mailApp.Session.Accounts
        i = 1
        Do While i <= .Count
            ' Use either the specified email address OR the last outlook email address
            If RegEx_IsStringMatching(.Item(i).SmtpAddress, accessApp.Forms![ProcessStatus].lblSenderRegex.Caption) Or i = .Count Then
                mail.SendUsingAccount = .Item(i)
                i = .Count + 1
            Else
                i = i + 1
            End If
        Loop
    End With
    mail.Save

    accessApp.Quit
End Sub

Answer: I added a "mail.Display" just before the line that was causing the failure, which seemed, incorrectly, to have fixed the problem.
I have now solved this problem by executing a document.select on the document associated with the email I was creating. To select the right document (there doesn't seem to be any guarantee of which one that would be within the wEditor.Application.Documents collection, though it was typically the first one), I created an almost-certainly unique piece of text and assigned it to the body of the email, which I could then go and find.  Here's the new code that I added to the code above:
    Dim aDoc As Word.Document
    Dim strUniqueID As String
 . . .

mail.Attachments.Add accessApp.Forms![ProcessStatus].lblAttachFilepath.Caption
strUniqueID = accessApp.Forms![ProcessStatus].lblSubject.Caption & Rnd(Now()) & Now()
mail.Body = strUniqueID

' Search for the unique text. aDoc.Content has extra characters at the
' end, so compare only for the length of the unique text
For Each aDoc In wEditor.Application.Documents
    If Left(aDoc.Content, Len(strUniqueID)) = strUniqueID Then
        aDoc.Select
        mail.Body = ""
    End If
Next aDoc

wEditor.Application.Selection.TypeText Text:="Test"
. . .

I looked at a lot of examples of code that did this kind of thing. None of them performed a select or said anything about needing one.  Debugging was made that much harder because the select occured implicitly when the debugger was invoked.


cURL specific undefined reference

Question: I finally was able to link cURL correctly (I think) to Code Blocks (GNU compiler) and get all the dll issues sorted. It was able to compile and run correctly once, then stopped working with new errors associated with libcurl.a(url.o). The two errors are
undefined reference to 'idna_to_ascii_lz'
undefined reference to 'string_prep_locale_charset'.

The errors came up after a previously successful build, which doesn't make sense to me, because of the minimal modifications I had made.
My build options are -lcurl --lws2_32, and -lwsock32 (to get rid of another error that popped up after successful compile).
I think my linking is successful because of the previous successful builds, and I added all the dlls that it was previously asking for. How do I fix it, and why did it build fine before? Are there compiler settings I should turn on? The only one on is -Wall and -fexceptions
The test code is below and was taken directly from another website with few modifications.
#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h>
#include <curl/types.h>
#include <curl/easy.h>
#include <string>
#include <iostream>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    std::cout << "Hello World";
    char *url = "http://cnn.com";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Thanks for all your help
Update: Per TimRau's suggestion, I added the -lidn to linker options. I now get the following errors:
||=== Build: Debug in Curl2 (compiler: GNU GCC Compiler) ===|

C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ssluse.o)|| undefined reference to `ERR_remove_thread_state'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_err2stringA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_set_optionA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_simple_bind_sA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_search_sA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_err2stringA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_err2stringA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_set_optionA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_initA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_get_dnA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_first_attributeA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_get_values_lenA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_memfreeA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_next_attributeA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_memfreeA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_memfreeA'|
C:\libs\curl-7.34.0-devel-mingw32\lib\libcurl.a(ldap.o)|| undefined reference to `_imp__ldap_memfreeA'|
||=== Build failed: 17 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

For link libraries, I have the following linked:
c:\libs\libcurl_imp.lib
c:\libs\libeay32.lib
c:\libs\openldap.lib
c:\libs\ssleay32.lib
I also have the curl lib in my linker search directories and curl include compiler search directories. I put them in according to the instructions found online at http://www.learncpp.com/cpp-tutorial/a3-using-libraries-with-codeblocks/
 Because it built and worked once, I think these settings are correct but I am at the limits of my understanding this part of programming.
Update 2: GOt rid of first error by adding
Answer: You need to add -lidn -lwldap32 in the end of the compilation command.
Comment: Thanks for taking a look at my question. Tried it in compiler settings/ other options. Errors did not go away. Also tried in linker settings, but more errors included the original 2 popped up.  Could this be an issue with the library?
Comment: @SP00N Yes it should be linker settings. What errors popped up? Did you set the library path correctly?
Comment: TimRau, I updated the main body to answer your questions. Thanks again for your help.
Comment: Do I need to install additional libraries or capabilities? Like OpenSSL. LibSSH, etc?

cURL specific undefined reference


How can trusted host patterns be set dynamically?

Question: I'm working on a site which uses the Groups module that will allow users to create groups on the site. The site will then allow for users to point custom domain names at the site, with the content for their group being available at that domain.
I've got this set up, except for the trusted host patterns. At the moment I have to manually add the domains to $settings['trusted_host_patterns'] in settings.php. I do not want to have to handle this manually however and would like to set these trusted host patterns dynamically based on domain names stored in a field in the database.
I've been looking at DrupalKernel::initializeSettings(), and I've found that it does not appear any method exists to override the settings:
// Initialize our list of trusted HTTP Host headers to protect against
// header attacks.
$host_patterns = Settings::get('trusted_host_patterns', []);
if (PHP_SAPI !== 'cli' && !empty($host_patterns)) {
  if (static::setupTrustedHosts($request, $host_patterns) === FALSE) {
    throw new BadRequestHttpException('The provided host name is not valid for this server.');
  }
}

So I'm thinking maybe I could use a kernel event, adding trusted host patterns to the settings before the trusted host patterns are called, but I'm starting to think I may be out of luck, due to trusted hosts being set before the database connection is initialized, meaning I won't be able to set trusted host patterns from DB variables.
Does anyone have an ideas of how to get around this?
Comment: What if you write those to a .txt or .csv file rather than to DB?
Comment: That's a nice suggestion. I may consider that as an option.
Answer: By design you can't access the database from a non trusted host within Drupal. The kernel checks the trusted host patterns when the settings are read from file, but without the settings you don't have the credentials to open the database connection.
There are a lot of ways to work around this. As mentioned in the comment by @NoSssweat you can write the trusted hosts to a file and include the file in settings.php. Or you can access the database from outside of Drupal and invoke this PHP script in settings.php. Or use a wildcard trusted host pattern matching all possible domains and then enhance security by adding a second check against the custom domain names in a kernel event subscriber when the database is available.
Comment: Thanks for the great write up. I like your final suggestion on working with an event subscriber as a whitelist filter.


display nodes of types on a menu item : drupal 7

Question: I have created some nodes of type books and now I want to display some of them on a menu item. How can I do that without using views?
Mome | Books | Atricles |
node type: (Machine name: books)
For example above is my menu structure. And when a user click books it will show some of the books I have created.
Comment: "without using views" will require that you write some code to perform the same task. Have a look at the [module developer's guide](https://drupal.org/developing/modules), and if you're struggling with specific aspects of development we'll be able to help you here
Comment: It Sounds views is the only easy way to achieve this.
Answer: Is it just the book name? Like a list of the names and then you can click on it and view more information? In that case, you could just put those book links in the menu itself (if you have a drop-down).
Otherwise, and the more doable option is to just use Views and have it create a page that displays the names of all of the books you've entered.
Is there a reason why you are opposed to using Views to do this?


Find $\int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx$

Question: $$\int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx=\frac{u}{v}$$ where $u$ and $v$ are in their lowest form. Find the value of $\dfrac{1000u}{v}$
$$\int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx=\int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^2(x^2-1)+1}}dx$$ I put $x^2-1=t$ but no benefit. Please guide me.
Answer: Given $$\displaystyle  I = \int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx = \int_{1}^{2}\frac{x^2-1}{x^3\cdot x^2\sqrt{2-2x^{-2}+x^{-4}}}dx$$
$$\displaystyle = \int_{1}^{2}\frac{x^{-3}-x^{-5}}{\sqrt{2-2x^{-2}+x^{-4}}}dx$$
Now Let $2-2x^{-2}+x^{-4} = t^2\;,$ Then $\displaystyle \left(x^{-3}-x^{-5}\right)dx = \frac{2t}{4}dt$
so we Get $$\displaystyle I = \frac{1}{2}\int_{1}^{2}\frac{t}{t}dt = \frac{1}{2}t = \frac{1}{2}\left[\sqrt{2-2x^{-2}+x^{-4}}\right]_{1}^{2} = \frac{1}{2}\left[\frac{\sqrt{2x^4-2x^2+1}}{x^2}\right]_{1}^{2}$$
So we get $$\displaystyle I = \int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx = \frac{1}{8}$$
But Here Given $$\displaystyle I = \frac{1}{8} = \frac{u}{v}.$$ So we get $\displaystyle u=1\;, v=8$
So  we get $$\displaystyle \frac{1000u}{v} = \frac{1000 \times 1}{8} = 125.$$
Answer: Notice, we have $$\int_{1}^{2}\frac{x^2-1}{x^3\sqrt {2x^4-2x^2+1}}dx$$
 $$=\int_{1}^{2}\frac{x^2-1}{x^3\sqrt {2\left(x^2-\frac{1}{2}\right)^2-\frac{1}{2}+1}}dx$$
$$=\frac{1}{2}\int_{1}^{2}\frac{2x(x^2-1)}{x^4\sqrt {2\left(x^2-\frac{1}{2}\right)^2+\frac{1}{2}}}dx$$ Now, $$x^2-\frac{1}{2}=t\implies 2xdx=dt$$
$$=\frac{1}{2}\int_{1/2}^{7/2}\frac{\left(t-\frac{1}{2}\right)dt}{\left(t-\frac{1}{2}\right)^2\sqrt {2t^2+\frac{1}{2}}}dx$$
$$=\frac{1}{2}\int_{1/2}^{7/2}\frac{dt}{\left(t-\frac{1}{2}\right)\sqrt {2t^2+\frac{1}{2}}}dx$$
I hope you can take it from here.
Answer: A couple of hints (not a full solution):
$x\to 2 \sin x$
\begin{align}
\int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}\,dx&=\int_{\pi/6}^{\pi/2}\frac{\cot (x) \left(3-\cot ^2(x)\right)}{4 \sqrt{-12 \cos (2 x)+4 \cos (4 x)+9}}\,dx\\
\end{align}
now you may use  $$\cot (x) \left(3-\cot ^2(x)\right)=\Big[\frac14(24 \sin (2 x)-16 \sin (4 x)) \csc ^2(x)\Big]-\Big[(-12 \cos (2 x)+4 \cos (4 x)+9) \cot (x) \csc ^2(x)\Big]$$
Answer: Let $$\displaystyle I = \int_{1}^{2}\frac{x^2-1}{x^3\sqrt{2x^4-2x^2+1}}dx = \int \frac{\left(1-x^{-2}\right)\cdot x^{-3}}{\sqrt{2-2x^{-2}+x^{-2}}}dx\;,$$
Now Let $x^{-2} = u\;,$ Then $-2x^{-3}dx = du$ and Changing Limit, We get
$$\displaystyle I = -\frac{1}{2}\int_{1}^{\frac{1}{4}}\frac{1-u}{\sqrt{u^2-2u+2}}du = -\frac{1}{2}\int_{1}^{\frac{1}{4}}\frac{(1-u)}{\sqrt{(1-u)^2+1}}du$$
Now Let $(1-u) = t\;,$ Then $du = -dt$ and Changing Limit, We get
$$\displaystyle I = \frac{1}{2}\int_{0}^{\frac{3}{4}}\frac{t}{\sqrt{1+t^2}}dt=\frac{1}{2}\left[\sqrt{1+t^2}\right]_{0}^{\frac{3}{4}} =\frac{1}{8}$$
So we get $\displaystyle I = \frac{1}{8} = \frac{u}{v},$ So $u=1,v=8$
So we get $\displaystyle 1000 \times \frac{u}{v} = 1000 \times \frac{1}{8} = 125$


Android XML Resource Values Error

Question: I am getting an error after modifying some of my xml resource files and I'm not quite sure how to fix it.
I was modifying my "main_activity.xml" layout file and went in to alter some text. Not wanting to hard code the values, I went in to create a "text style" by selecting my text, clicking "style" in the properties menu on the right hand page, then clicking the expand menu option to see all the available styles. This opened a "resources" dialog, these resources had resources like: "Base.TextAppearance.AppCompat.Body2" and "Theme.AppCompat.Light" (I'll put a screenshot of the dialog box below)

I saw a "new style button" and attempted to create a couple of styles named things like "txtSize_28sp" with a value of 28sp for the text sizes. I do know that at one time I did create resource that had a name and no value, most likely with the: "txtSize_28sp" name. Problem is after doing this it has messed with my gradle build and I can no longer compile or run my project. The "R" in my R.layout.activity_main is no longer resolving and I keep getting this error message:
<code>C:\Users\Ethan\Dropbox\Development\Android\Projects\DontTapTheAd\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.1.1\res\values\values.xml
Error:(380, 5) String types not allowed (at 'txtSize_28sp' with value '').
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Users\Ethan\AppData\Local\Android\sdk\build-tools\23.0.2\aapt.exe'' finished with non-zero exit value 1
</code>
I have tried cleaning gradle, cleaning project, and syncing with gradle files. I can't find where to remove or fix my "txtSize_28sp" value.
Does anyone know how to fix this? Any help would be appreciated.
Comment: There is a Find function in Android Studio that can search through the entire project files. Search for "txtSize_28sp" and ignore results in generated files (files created from building the project).
Comment: You could add your styles.xml file
Comment: Thanks for the replies. As far as using the "find function" I am not sure which one of the many find functions to use, I've tried pretty much all of them that I think would apply to be able to find the value. Like Anders said below I think it might be in one of the other API folders, which is why I can't find it. I'm not quite sure where to search for my different API values though. I don't really want to add my styles.xml file manually because I want to revert my IDE / SDK to the way it was.
Answer: There are multiple values for different APIs so check all the multiple folders of values for different APIs like value-21, it must be in one of the other APIs values folder.
Comment: well your `logcat` is telling you the problem is here `C:\Users\Ethan\Dropbox\Development\Android\Projects\DontTapTheAd\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.1.1\res\values\values.xml` so go to that directory and remove that line of code, if its not in that directory then you should check your `yourproject/app/main/res/allvaluesfolders`
Comment: I'm going to attempt to find the values in the different API's, do you have any suggestions on where and how to look at the different API folders?
Comment: Thanks so much for the response, I will try this and come back with the results. (I did already try the first directory and the code was not their so hopefully it will be in my main/res/allvalues folders.)
Answer: Thanks to Ander who answered the question, after looking everywhere for these hidden lines of code and where they get added to the project I finally found them in the C:\Users\Ethan\Dropbox\Development\Android\Projects\AppName\app\src\main\res\values\dimens.xml file! Project was fixed after I removed the lines of code (such as: txtSize_28sp) in this file. (Screenshot of location where values were added in this post.)

Android XML Resource Values Error


What do array keys in the database definition array mean?

Question: I have following code in my settings.php file:
$databases['default']['default2'] = array(
  'driver'    => 'mysql',
  'database'  => 'rotary',
  'username'  => 'root',
  'password'  => 'root',
  'host'      => 'localhost',
  'prefix'    => '',
);

$databases['rotary2']['default1'] = array(
  'driver'    => 'mysql',
  'database'  => 'rotary2',
  'username'  => 'root',
  'password'  => 'root',
  'host'      => 'localhost',
  'prefix'    => '',
);

I know that the first keys i.e. default & rotary2 are the database names.
What are the keys default2 & default3 for?
Answer: Here is the explanation from the setting.php file:

For each database, you may optionally specify multiple "target" databases.
  A target database allows Drupal to try to send certain queries to a different database if it can but fall back to the default connection if not. That is useful for master/slave replication, as Drupal may try to connect to a slave server when appropriate and if one is not available will simply fall back to the single master server.

The general format for the $databases array is as follows:
$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;

In the above example, $info_array is an array of settings described above. The first line sets a "default" database that has one master database (the second level default). The second and third lines create an array of potential slave databases. Drupal will select one at random for a given request as needed.  The fourth line creates a new database with a name of "extra".

I hope this will give you clear idea about default2 and default3.


Inserir com "for" em uma lista encadeada

Question: Galera estou com uma duvida, o professor pediu para inserir elementos na lista encadeada usando o "for" mas estou com dificuldade, a Classe que cria o nó ja esta funcionando perfeitamente e a parte que eu consegui desenvolver foi isso mas esta dando nullPointException quando eu tento inserir do segundo elemento em diante.
public void inserir(Node novoNode){
        if(inicio == null){
            inicio = novoNode;
        } else {
            Node aux = inicio;
            for(int i = tamanho ; i < (tamanho +1) ; i++){
                aux = aux.getProximo();
             }
            aux.setProximo(novoNode);
        }
        tamanho ++;
}

Comment: Quem é "inicio"? Como você inicializa o tamanho? Quem chama o método inserir passando o novoNode?
Answer: O problema está mesmo no próprio for. Ele deveria ter outra instrução de inicio assim como outra de fim. Desta forma:
//de 0 até ao tamanho - 1 para parar no ultimo
for(int i = 0; i < tamanho - 1; i++){
    aux = aux.getProximo();
}

Códigos de listas são normalmente escritos com while e costumam executam até apanhar o fim da lista, o null. Mesmo com uma restrição de usar um for podemos usar a mesma lógica, o que simplifica:
else {
    Node aux;

    //escrito desta maneira fica sem conteúdo, servindo so para navegar até ao ultimo
    for(aux = inicio; aux.getProximo() != null ; aux = aux.getProximo());

    aux.setProximo(novoNode);
}

Neste ultimo exemplo começamos a navegar no inicio, e navegamos até que o próximo seja null, que é o caso de paragem. Quando o próximo é null significa que estamos no ultimo elemento que é onde queremos parar. Para cada navegação vamos andando para o próximo elemento com aux = aux.getProximo(); como já era feito anteriormente.


Como direcionar uma Action para uma view dentro de uma pasta?

Question: No meu Controller UGController tenho uma Action de nome Cadastro que me leva até a View Cadastro.cshtml que está na pasta UG.
Ou seja:

Controller: UGController
Action: Cadastro()
Link: /UG/Cadastro
View: /UG/Cadastro.cshtml

Até ai normal. Mas gostaria de criar uma pasta dentro da View UG para colocar outro arquivo

Controller: UGController
Action: ?
Link: /UG/PDF/Lista
View: /UG/PDF/Lista.cshtml

Dúvida: Como fazer com que a Action me leve até o Lista.cshtml com o link que eu descrevi?
Answer: Use:
return View("caminho/para/sua/pasta/NomeDaView");

Por exemplo:
Controller: MyController
Action: MyAction
Link: MyController/MyAction
View: Views/MyController/PastaQualquer/MyAction

public ActionResult MyAction()
{
   return View("PastaQualquer/MyAction")
}

Se você não resolver no return View(""), terá que criar uma nova rota.
Answer: Para o teu caso ficaria:
return View("UG/PDF/Lista");


Learning Violin Online

Question: I have a violin at home and I would really like to learn. The only problem is, I cannot find a teacher in my area (India) and so I thought I could, maybe, learn just the basics online.
I completely understand the need for a teacher when it comes to subtle points and technique (developing a real feel for the instrument), but perhaps I could start off by myself. I taught myself to play the harmonium by ear.
Is learning online going to benefit/harm me in any way? Can I get past the novice stage by learning online?
Comment: It's the basics that form the foundation, and I would advise you not to take any risks with that. Unlearning mistakes is not easy.
Comment: Where in India do you live? I find it hard to believe India wouldn't have a good violin teacher. I think there are even orchestras in Kolkata, Mumbai, etc.
Comment: Watch videos and learn (something like the ProfessorV videos on YouTube)
Comment: Do you mean, you want to watch videos as inspiration, or do you mean, you want to hire a private teacher and have your lessons over skype?
Answer: Learning online is always a great start, but could never replace a teacher.
However, just a few things.

Beware of your posture. Buy a music stand, and play standing, at first. Spread your legs out so your feet are underneath your hips, and do some shoulder circles to loosen up your back. Stand straight, but make sure you are not stiff, either. It is normal to feel like you are about to drop everything, at first, because you are focusing on so many things. However, just keep trying.
How you hold your violin. Look at this diagram of the violin, and place your fingers on the belly of the violin and your thumb on the other side. Hold the violin at arm's length with the scroll closer to the ceiling and the chin rest towards the floor.
Now, turn the violin 180 degrees, still at arms length. The scroll should be facing the floor and the chin rest towards the ceiling.
Finally, slowly bring the violin towards your neck, and lightly place your chin on the violin. Your chin will not be on the chin rest but will be more between the chin rest and the tailpiece; it never should be fully on the chin rest.
Find some painters tape (different color than the violin) and cut two thin pieces, and find where the first and third fingers should go. Your thumb, in violin, does not count as a finger, so your pointer finger is the first, middle is the second, etc. Since you are already musically inclined, it should not be so difficult to do so.
The strings on the violin are G - D - A - E, so the first finger on the G string should be A and third should be C. It will take a few tries to get the tape exactly right, and it will slip even after you find the place, but in the beginning, this will help a lot.
Your hand will also be very tense, so a useful exercise I have found is called the siren, which is when you press a finger onto the finger board, run your hand (by bending your elbow) up and down the finger board, from the tip of the neck to the edge of the fingerboard. Eventually, pick a string, and do the siren on that string as well as bowing it, and it will sound like a siren.
Holding a bow is a very interesting, but this is a good starting position. You will feel like you are about to drop the bow, so there are a few exercises you can do. Start with windshield wipers, which is when you arm in a way that the bow will swing from flat left to vertical to flat right, and back. Do this 10 times, readjust, and repeat a few times.

Good luck in your studies!
Answer: You can learn online.
If you do it on your own without someone listening and seeing your posture that might bring some dangers. You can take some online lessons maybe or try to find a teacher from time to time.
Be aware of your posture, so you don't heart yourself. Filming yourself can be a good tool to find problems with holding the violin or bow. When you are looking at yourself thru the video you might see things you didn't think of before.
You can ask here exercises for specific technique you want to achieve and method for studying/memorizing or organizing your study.
Keep an eye on the posture as said before and good luck!
Answer: Learning online is very difficult,  but if you have graded pieces and take things slowly you can try.  At least that way you will find out if you like playing the violin without spending too much money.  You can look at many sites and they say EASY violin pieces, but they are often quite difficult.  Self-learners in my experience tend to have a go, but then give up because it's simply too challenging.  So finding the right material is always a good start and if something seems too difficult, just look elsewhere, don't give up. It's probably not you, its the material they are asking you to play.  I have a background of music education and composing and writing for beginner players. Have a look at www.3dmusic.tv and you'll find some really easy pieces to get you started all for free.  Although I know a bit about writing for strings, I'd never learnt to play the violin, but I'm giving it a go.
However, once you're past playing a few open string pizzicato notes and have pressed down  your first finger you are probably going to need someone who can guide you.  Having the correct posture (for you) and not carrying tension into your playing will not only make it more enjoyable, but you will also avoid repetitive strain injuries.

Learning Violin Online


Edit urls in wagtail (social-auth-app-django problems)

Question: I want to add social-auth-app-django to my wagtail project to let normal users comment posts on blog. To make social-auth-app-django work, I need to add this urlpattern:
urlpatterns = [
    url(r'^auth/', include('social_django.urls', namespace='social')),
]

How to do it? I didn't find any way to edit urls.py in wagtail, and I didn't find any social-auth-app-django wagtail equivalent.
Answer: There will be a urls.py in the folder where settings.py will also be present.
Add the URL in urlpatterns list present in the urls.py like this:
urlpatterns = [
    url(r'^auth/', include('social_django.urls', namespace='social')),
]

Comment: Note that this URL pattern needs to be placed above the existing `url(r'', include(wagtail_urls)),` line, so that it takes precedence over being handled as a Wagtail page.


Insights on differential element

Question: I can solve a lot of integrals, differentiation problems, and their applications by dividing curves/ regions into infinitesimal elements and then integrating them.  But I don't have a clear physical interpretation of the differential element ($dx$ or anything) in Nature.  I am not convinced that because it is very small we can regard the $f(x)$ as constant as $dx$ changes.  Is there any physical and clear meaning for it? And if it is very small why do we not regard $f(x) dx =$ zero ?
I hope the question does not appear stupid and superficial to you.
Comment: Try to think of $dx$ as a number greater than zero, but smaller than all possitive Reals.
Comment: i can't :D how is that ?
Answer: Since you want a physical interpretation of the differential elements, I'll assume you know what mechanical work is.
The differential elements are not really infinitesimals.  That may have been how Newton and Leibniz thought about them, but in standard analysis today they are just linear functions.
Think about it this way.  Say you have a constant force field -- for instance the gravitational force field near the surface of the Earth is constant to a very good approximation.  Then consider a straight line segment -- positioned however you like -- in that force field.  Now we'll say that that line segment is actually the path followed by a particle through the Earth's gravitational field -- so just pick one side of the line segment to call the starting position and the other end to be the final position of the particle.
Then the situation looks (in $2$d) like:

Now the differential form $F_x(x,y)dx + F_y(x,y)dy$ is just a function which assigns to oriented line segments, like the one above, a number.  The $dx$ and $dy$ parts tell you by how much the $x$ and $y$ parts of the oriented line segment changes and the $F_x$ and $F_y$ are the $x$ and $y$ components of force at some point in each line segment.  It also scales linearly with the length of those oriented line segments -- thus it is a linear function of line segements.
In this case, $dx$ is the function which associates the (signed) number $x$ to any oriented line segment $x\hat x + y\hat y$ and $dy$ is the function which associates the (signed) number $y$ to any oriented line segment $x\hat x+ y\hat y$, and we can choose any point along the path as our point at which to evaluate $F_x$ and $F_y$.  Then the work due to gravity on this particle moving along the red path is $$W=F_x(x,y)dx + F_y(x,y)dy = mgy$$
Well, that was really easy, right.  But what happens when $F_x$ and $F_y$ are NOT constant?  Or when the path the particle follows is not a straight line -- but curved.  In both cases we do the same thing: we approximate the answer by very small oriented lines segments.  Then as we construct an approximation with smaller and smaller line segments our approximation should get better and better.
Here's a picture that might help you visualize what I mean.  In it the black curve is the actual path and the blue and red curves are made of line segments to approximate the path.  While the blue curve sort of approximates this sinewave, the red curve -- which has nearly $3$ times as many line segments -- follows the curve much more closely.

So for any partitioning we do of the curve, we end up with several oriented line segments at which to evaluate our differential form that we can then add to get an approximation for the work of the particle along the indicated path:
$$\text{Work} \approx \sum_i [F_x(x_i, y_i)dx_i + F_y(x_i, y_i)dy_i]$$
Then in the limit as the size of each line segment goes to zero (and assuming that everything is nice enough) we end up with the exact amount of work.  So differential forms aren't infinitesimals -- they're just functions which associate line segments with numbers.  Then integrals are defined as limits of sums of a differential form evaluated along many oriented line segments as the lengths of those line segments approach $0$.
Has that given you some intuition about what differential elements are?

Insights on differential element


Carregar linhas em listview a partir de um OpenDialog

Question: Preciso carregar items de um arquivo de texto num Listview usando Opendialog, como preceder?
Existe alguma propriedade LoadFromFile?
Answer: O método LoadFromFile não é disponível no Listview, o que você pode fazer é carregar as informações do arquivo num StringList e popular o Listview com TListItem. Veja um exemplo:
procedure AddItemsListview(Listview: TListView; Arquivo: string);
Var
  Items: TStringList;
  Item: TListItem;
  I: Integer;
begin
Items := TStringList.Create;
try
  Items.LoadFromFile(Arquivo);
  for I := 0 to Items.Count -1 do begin
    Item := Listview.Items.Add;
    Item.Caption := Items[I]; // Coloca o valor na primeira coluna do Listview
  end;
finally
  Items.Free;
end;
end;

E para utilizar o método acima, supondo que você já adicionou OpenDialog, faça o seguinte:
procedure TForm1.Button1Click(Sender: TObject);
begin
OpenDialog1.InitialDir := ExtractFilePath(ParamStr(0)); // Abre o diálogo no diretório do programa
OpenDialog1.Filter := 'Arquivos de texto (.txt) | *.txt'; // Somente arquivos de texto

if OpenDialog1.Execute = false then exit;
AddItemsListview(ListView1, OpenDialog1.FileName);
end;

Comment: Perfeito, muito obrigado.
Comment: Funcionou perfeitamente, porém teria como eu limitar a quantidade de items neste listview? por exemplo, de 600 items ele carregar apenas 200?
Comment: @Fake No laço `for` que é feito no método `AddItemsListview`, você pode fazer algo assim: `if I = 200 then Break;`. Isso irá adicionar somente os *200* primeiros itens ao `Listview`.
Comment: Teria como limitar os items do TStringList?
Comment: @Fake Eu acredito que não seja possível, a [documentação](http://email@example.com) pelo menos não diz nada sobre isso.


Prime number question?

Question: If I want to calculate all the primes, could I do this?
Let $N = \{2,3,4,5,6,7,8,..\}$
Then the elements in $N - NN$ are prime? Because they are the ones that aren't composite?
Comment: This is what's in action  in *Eratosthenes's sieve*.
Comment: It seems to me it's only theoretically faster. You first have to set up the list of all products of two numbers.
Comment: What is $NN$? And what is $N-NN$?
Comment: NN is the set product, and N - NN is all the elements in N which are not contained in NN.
Comment: @bernard but in a very effective way! Deleting the numbers sequentially is very slow.
Comment: Who's more effective? Our old friend Ἐρατοσθένης?
Answer: Yes, that is correct.
If $m$ is a composite, then it can be written as $n\cdot k$ for some $2\leq n,k<m$, which means that $m\in NN$.
If $m$ is a prime number, then it cannot be written as such product, so it is not in $NN$. Therefore $N-NN$ is exactly the prime numbers.
Answer: Essentially, yes. You may struggle to compute $N-NN$, but that set would contain the primes and only the primes.
If you want to actually calculate prime numbers, a good way would be to use the Sieve of Eratosthenes (the animation uses $n=10$). The idea is you start with a list of primes up to some number $n$, and then consider the integers up to $n^{2}$. Every composite number in this interval must have at least one prime factor at most as large as $n$, so if you eliminate all the multiples of primes up to $n$, you have all the primes up to $n^{2}$.

Prime number question?


Does this morphism extend to projective varieties?

Question: We work over the complex numbers.
Let $\mathbb{A}^1\times \mathbb{A}^1\to \mathbb{A}^1$ be the morphism given by $(x,y)\mapsto x-y$.
Does this extend to a morphism $\mathbb{P}^1\times \mathbb{P}^1\to \mathbb{P}^1$?
I have the feeling it does not because it contracts the diagonal (which is ample on $\mathbb{P}^1\times \mathbb{P}^1$), but I can't think of an "easier" argument.
Answer: I'm not entirely sure this works, but here's an idea: the "minus" operation is defined on $\mathbb{P}^1$ (it's basically $y \longmapsto y,x \longmapsto -x$ in homogeneous coordinates) so it's obviously equivalent to consider the addition.
Let $\mu: \mathbb{P}^1 \times \mathbb{P}^1 \rightarrow \mathbb{P}^1$ be an extension of the addition, it is proper. Now, it's easy to see that $\mu(\{\infty\} \times \mathbb{A}^1)=\{\infty\}$, and same the other way around. By the rigidity lemma, it follows that $\mu$ is constant: contradiction.
Comment: Well, it's easier to see for $\mathbb{A}^1$. And thus it's $\mathbb{P}^1$ by continuity.


arrumar paginação automatica

Question: essa paginação está funcionando perfeitamente, só tem uma coisa, quando a pessoa dece até o final ela traz o último registro do banco tudo certo, ai  ela fica mostrando a mensagem de  Carregando... mesmo não tendo mais nada a exibir, como poderia arrumar isso? outra coisa, ao subir o scroll esconder novamente os resultados do banco exibido com o scroll rolado para baixo
HTML

Carregando...

PHP
<? php

require "Db.php";

$db = new Db;

$ipp = 10;

$pagina = (isset($_GET['pagina'])) ? (int) $_GET['pagina'] : 0;

$itens = $pagina * $ipp;

$ret = $db - > query(sprintf("SELECT codigo, titulo, texto, imagem FROM post LIMIT %d OFFSET %d", $ipp, $itens));

if ($ret - > num_rows > 0) {
  // retorna os dados para a tela no formato json

  $retorno = array();

  while ($post = $ret - > fetch_assoc()) {
    $retorno[] = $post;
  }

  response(array("erro" => false, "inicio" => $itens + 1, "fim" => $itens + $ret - > num_rows, "itensporpagina" => $ipp, "posts" => $retorno));

} else {
  // retorna erro = true no formato json para a tela
  response(array("erro" => true));
}

// retorna dados no formato json para a tela do sistema
function response($response) {
  header("Content-Type: application/json");
  echo json_encode($response);
}

jquery
var pagina = 0;

function loadPosts() {
  $("#carregando").show();

  $.ajax({
    url: "dados.php?pagina=" + pagina,
    dataType: "json"
  }).done(function(data) {
    $("#carregando").hide();

    if (data.erro) return;

    var divposts = $("#posts");

    $.each(data.posts, function(key, val) {
      divposts.append("

" + val.titulo + " / " + val.codigo + "

" + val.texto + "

");
    });

    pagina++;

  });

}

$(function() {
  $("#carregando").hide();

  loadPosts();

  $(window).scroll(function() {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
      // carrega os posts
      loadPosts();
    }
  });

});

Comment: Conseguiu resolver?
Answer: Dentro da sua função loadPosts, verifique se houve mais de '0' dados na resposta:
function loadPosts() {
  $("#carregando").show();

  $.ajax({
    url: "dados.php?pagina=" + pagina,
    dataType: "json"
  }).done(function(data) {
    $("#carregando").hide();

    if (data.erro) return;

    var divposts = $("#posts");
    if(data.posts.length > 0){
          $.each(data.posts, function(key, val) {
          divposts.append("

" + val.titulo + " / " + val.codigo + "

" + val.texto + "

");
        });

        pagina++;
    }else{
        $("#carregando").hide();
    }

  });

}

Answer: Retire o segundo $("#carregando").hide(); (dentro do $(function() {) que não precisa.
O $("#carregando").show(); você altera para $("#carregando").stop().show();. O .stop() evita atropelamentos no método.
E após o $.each coloque $("#carregando").delay(1000).hide(0);. Isso irá dar um pequeno delay de 1 segundo para o carregando... sumir (você pode diminuir ou aumentar o tempo se quiser).
O script para remover os elementos que saírem da tela:
$(function(){

   loadPosts();

   $(window).scroll(function() {
      if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        loadPosts();
      }

     $.each($("#posts div"), function(){
       var dist = $(this).offset().top-$(window).scrollTop(); // verifica a distância do elemento ao topo
       // remove todos os elementos fora da tela
       if(dist > $(window).height()) $(this).remove();
    });

   });
});

Exemplo ilustrativo sem Ajax:

function loadPosts(){
   $("#carregando").stop().show();
   $("#posts").append('
div 2
');
   $("#carregando").delay(1000).hide(0);

}

$(function(){

   loadPosts();

   $(window).scroll(function() {
      if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        loadPosts();
      }

     $.each($("#posts div"), function(){
       var dist = $(this).offset().top-$(window).scrollTop();
       if(dist > $(window).height()) $(this).remove();
    });

   });
});

carregango..

div 0

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

div 1

Comment: pra dispositivo não funciona, sera que uma solução seria colocar um botao de carregar mais ?
Comment: Seria uma solução tb.

arrumar paginação automatica


How to retrieve last MySQL INSERT ID from db_merge()

Question: I am using db_merge for inserting or updating new records in my table.
I want to get the last inserted record id from this table, Thank you.
Comment: Perhaps having a timestamp column will make it easier to get last updated/inserted record. `SELECT foo FROM bar ORDER BY timestamp DESC LIMIT 0,1`
Comment: No Need to add additional column.
Answer: While there is RETURN_INSERT_ID which can be used with db_query(), I could not find a way to use with db_merge().
<?php
  $query = "INSERT INTO {table_name} (col1, col2) VALUES (:arg1, :arg2)";
  $args = array(':arg1' => $val1, ':arg2' => $val2);
  $last_id = db_query($query, $args, array('return' => Database::RETURN_INSERT_ID));
?

I think you will have to retrieve the last ID with another query, but you would need to check with MergeQuery::STATUS_INSERT.
$status = db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute()

if( $status == MergeQuery::STATUS_INSERT ) {
      $last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();
}

Comment: @Ravindra Have you come across [`drupal_write_record()`](http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_write_record/7)? If you don't need the advanced functionality provided by `db_merge()` (conditional updates, etc) then you can just use that and save yourself the headache
Comment: @Clive you're right, but calling `LAST_INSERT_ID()` vs `MAX(id)` in the same function, directly after db_merge should give the same result afaik which I think is what OP is wanting to do there... Maybe some chance of race condition on the select from separate insert process, so perhaps last_insert_id() is ok there if mysql.
Comment: @Ravindra I don't understand why you can't just use this one? You already know whether or not you're performing an Insert/Update based on the contents of `$keyvalue`, so just add a simple `else { $last_id = $keyvalue; }` to the above code and you're done :)
Comment: hey i tried this but not working..
Comment: `SELECT LAST_INSERT_ID()` is MySQL only, pretty much the same result as `SELECT MAX(id)` where id is the auto_increment/serial field
Comment: @DavidThomas If I remember rightly `LAST_INSERT_ID` is thread safe while `MAX` isn't (necessarily). I might be wrong though I would have read that some years ago now
Comment: @DavidThomas I think so long as it's in a transaction that's true, outside of a transaction I'm not sure if there's a potential race condition there. But I'm not bothered enough to check ;)
Comment: @RavindraSingh, check how `LAST_INSERT_ID()` is used with db_select() at [the other question](http://drupal.stackexchange.com/questions/59000/last-insert-id-with-selectquery).
Answer:
I want to get the last inserted record id from this table...

You could do a second query, to get the latest inserted id:
$max_id = db_query("SELECT MAX(id) FROM {table}")->fetchField();

That will return the latest inserted id, but not the id of the latest updated.
Comment: If an existing record was updated this would give incorrect result right ?
Comment: David in case of db_merge() it is not mandatory that the Max id in the table is new record it may be older and updated on that time only.
Comment: Just check the returned value from db_merge, if it was an insert you MUST query for the highest id value, if it was an update then no ID should be returned.
Comment: if id does not insert any new records that time it fails.
Comment: If you have DESC LIMIT 1 in your query, no need MAX().
Comment: @Sithu, yeah, it's a bit of overkill ;)
Comment: No last insert id for an update, perhaps I misunderstood the question.
Answer: Hey in Drupal 6  we can use
db_last_insert_id('table_name', 'name');

This gives the last inserted id.
Comment: [db_last_insert_id() is not in D7 anymore](http://drupal.org/node/729970).
Answer: You can use this.

      $node = db_select('table_name', 'f')
      ->fields('f', array('field_you_want'))
      ->condition('field', 'condition', 'expression')
      ->orderBy('id', 'DESC')
      ->range(0,1);
      ->execute()
      ->fetchAll();

Comment: Suppose i need to get last inserted id so please give me an example.
Comment: We are already getting the last inserted by using the orderBy() method, If you send DESC and limit results to 1
Comment: If it does not insert new record that time it only updates the values and may be last (Max) id of row will not affect


Curl, SSL e Segurança

Question: Olá
Tenho uma pequena dúvida quanto ao CURL e SSL.
Tenho visto que é inseguro colocar false em CURLOPT_SSL_VERIFYPEER, pois faria o CURL não verificar o SSL, possibilitando interceptação de dados.
Porém não entendi como isso poderia ocorrer. Por exemplo, tenho um script em um servidor que acessa outro servidor via https. Para alguém interceptar isso, ele necessitaria estar na mesma rede física do servidor onde meu script está hospedado, não? Se não, como se explicaria tal insegurança?
Obrigado
Comment: É possível sim, por isso que é recomendado o uso de criptografia para a transmissão de informações importantes.
Answer: Colocar "false" não torna nada inseguro, pois conexão ainda será SSL e criptografada. Você só não pode colocar false se estiver fazendo isso em um serviço ou link que necessita de certificados com validação, pois nesse caso, você receberia muitas queixas sobre não estar podendo fazer a autenticidade do certificado no site. Neste caso, é necessário este segurança, para evitar códigos maliciosos que assume a identidade da "microsoft.com" e que começa a criar hosts próprios de Windows Update, que podem ameaçar e comprometer a integridade do servidor, podendo enviar vírus ou abrir portas através de chaves que se instalam ou scripts maliciosos. Independentemente de qualquer configuração que você faça nisso, se você forçar uma conexão SSL, ela será segura e criptografada. Resumindo, colocar "true" só se faz necessário, se houver requisição de certificados, pois daí tem entrada de dados, aí existem perigos.
Aqui tem mais detalhes, se entender inglês.
Comment: Quando você diz entrada de dados, refere-se por exemplo ao envio de algum texto específico nessa chamada CURL?
Answer: Supondo que esteja se conectando com um servidor HTTPS e define o CURLOPT_SSL_VERIFYPEER para false você se torna vulnerável a ataques de MITM, inclusive algumas bibliotecas já possuíram problemas com isso no passado, como por exemplo o Google AdWords PHP Client, uma vez que o stream_context_get_default() no PHP 5.6 e inferior não verificava os certificados eram emitidos por uma autoridade confiável (self-signed era válido), assim tornando vulnerável a conexões que não são reais da Google.
Em geral NUNCA desligue esta verificação.
Ter os dados transmitidos de maneira criptografadas não faz ser seguro, só será seguro se você garantir que o receptor da informação é realmente quem diz ser. Isso somente será possível se você definir o CURLOPT_PINNEDPUBLICKEY (disponível no PHP 7.0.7+) este é o mais seguro dos métodos. Uma outra opção e mais versátil é confiar em um autoridade (ex. Comodo) e então utilizar o CURLOPT_CAINFO para determinar quais autoridades são confiáveis para você e o CURLOPT_SSL_VERIFYPEER para true para verificar se o certificado foi emitido por alguém que você confia.

Caso não utilize o VERIFYPEER você está vulnerável para:

DNS Poisoning
Spoofing
Proxy Attacks
ARP Spoofing

etc...

O SSL sem utilizar o VERIFYPEER o máximo que pode ocorrer é a informação ser trafegada de maneira criptografada, mas não garante que o destino da sua  conexão é real, o que anula parcialmente o proposito do SSL.
Imagine deseja se conectar com o https://google.com, então você precisa de um DNS que encontre o real host do google.com. O DNS é atacado e lhe envia para o 188.8.131.52. Este 126.96.36.199 utiliza um certificado self-signed com o nome de  google.com, o seu CURL irá se conectar nele normalmente. Então este falso servidor terá como obter as informações que você enviaria para o google.com e para você não desconfiar ele faz um proxying para o real google.com, retornando resultados verdadeiros. Agora o servidor intermediário (126.96.36.199) tem as informações que você enviou e as resposta reais do google.com.
Do que adiantou ter o tráfego criptografado? Nada.
Se você desligar o CURLOPT_SSL_VERIFYHOST o certificado pode até ser de abc.com e está se conectando em xyz.com e será válido.

A "interceptação de dados" não vai ocorrer porque parou de usar o SSL! Vai ocorrer porque não necessariamente está se conectando com o servidor real, devido a não verificação do certificado.

Não precisa confiar em mim, palavras do próprio CURL:

WARNING: disabling verification of the certificate allows bad guys to
  man-in-the-middle the communication without you knowing it. Disabling
  verification makes the communication insecure. Just having encryption
  on a transfer is not enough as you cannot be sure that you are
  communicating with the correct end-point.
Comment: Agora eu entendi.... Obrigado pela explicação

Curl, SSL e Segurança


Multiple video's on a single page Not loading all the video's Chrome

Question: I'm loading multiple video's on a single page,
My code snippet is something like,

    1
    <video  width="213" height="120" controls class="video_tag">
        <source src="<MY VIDEO SOURCE>" type="video/mp4" />
    </video>

    2
    <video  width="213" height="120" controls class="video_tag">
        <source src="<MY VIDEO SOURCE>" type="video/mp4" />
    </video>

    3
    <video  width="213" height="120" controls class="video_tag">
        <source src="<MY VIDEO SOURCE>" type="video/mp4" />
    </video>

    4
    <video  width="213" height="120" controls class="video_tag">
        <source src="<MY VIDEO SOURCE>" type="video/mp4" />
    </video>

Sometimes I'll get 20+ video's on a single page, so that time I'll create those many video tags.
Whenever I try this code in my localhost it works fine, but if I host this code in remote server and try only few video's will be loading, but in my chrome inspect element there is no error message.
I tried re-loading video's one by one using JQuery with some time interval, that time I'll be getting "Provisional headers are shown" kind of warning in chrome's Inspect element.
Could anyone please help me to fix this issue?
Thanks in advance.
Answer: Chrome limits the number of videos/audio files to 4 or 6 (I can't remember which) so, as brianchirls mentions, you need to set the preload attribute, although you need to set it to none.
My recommendation is to provide a poster image (via the poster attribute) for all your videos and to set preload="none" to all of them. That way the browser only actually tries to load them if the user actively clicks the play button.
Alternatively you could set the first 4/6 videos with preload="metadata" and the rest to preload="none".
Answer: That can be a lot of data for the browser to download all at once, depending on how big the file is and how fast and far away the server is. Try giving each video tag a preload attribute and set it to "metadata". Like this:
<video  width="213" height="120" controls class="video_tag" preload="metadata">

That should limit the number of files the browser needs to load all at one time, only loading the header of each video file. The rest of the file will load once you start playing. If that doesn't work, try setting preload to "none".
Also, you'll want to make sure the remote server is using HTTP Byte Serving. i.e., the HTTP status header on the video files should be "206 Partial Content", not "200 OK".


Check property exist in object or not in JavaScript?

Question: I have one problem statement.
Implement a function propertyExists(obj, path) that takes in an object and a path (string) as arguments and returns 'False' if the property doesn't exist on that object or is null, else returns the value of the property.
And here is solution.
function propertyExists(obj,path) {
    // Write logic here
    let result =  obj.hasOwnProperty(path);
    if(result)
    {
     return (obj.path);
    }
    else
    {
        return result;
    }
}

Is this correct way of doing it?
Comment: Are you facing any type of issue with this implementation?
Comment: It depends on what the definition of path is, for me a path would be something like..  `header.customer.address.lines[0]`  etc.  But then your have called it `propertyExists`,  so its likely property anyway, so not sure why its not `propertyExists(obj, property)`   You likely want `return obj[path]` too.
Comment: The check seems incomplete based on requirements.  You could be specific here. -> `if (obj[path] === undefined || obj[path] === null) { return false; } else { return obj[path]; }`
Comment: @SifatHaque Yes when I am submitting the solution I am getting wrong answer message
Answer: Multiple issues:
the first name of the function should represent what it is doing,
Path as variable name is vague but propertyName as a variable is clear.
what you should do is either:

write function called, "getValue" it returns value if exist or null

    function getValue(obj,propertyName) {
            if(!obj) { // if object not exist
           return null;
            }
           return  obj[propertyName];
        }

write function called, "propertyExists" should return true if exist else false.

   function propertyExists(obj,propertyName) {
        if(!obj) { // if object not exist
       return false;
        }
       return  obj.hasOwnProperty(propertyName);
    }

Answer:

function propertyExists(obj,path) {
    // Write logic here
    for(i in path){
        if(obj.hasOwnProperty(path[i]) === true){
            obj = obj[path[i]];
        }else{
            return false;
        }
    }
   return obj;
}
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: it may help to understand
Answer: object->obj,propertyname->path
function propertyExist(obj, path){
           if (obj.hasOwnProperty(path)) return obj[path];
                   else return false;
                      };

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Here, as far as I can understand, the objects could be nested also.
Let's take obj as {"a":{"b":"dadsa"}} and path as ab
Now, the the solution which you have posted will not work. Ideally, it should return dadsa, but it will return false.
Try the below code, it will work for nested objects also.
function propertyExists(obj,path) {
    // Write logic here
    var val=obj;
    for(a of path){
        val=val[a];
        if(!val)
            return false;
    }
    return val;
}

Answer: function propertyExists(obj,path) {
    var val = obj;
    for (a of path) {
     val = val[a];
    if (!val){
      return false;
     }
     return val;
 }


Como é que o sistema operativo distribui o processador pelos vários programas?

Question: Nos sistemas operativos atuais há possibilidade de ter vários programas em execução. É trabalho do sistema operativo garantir que todos os programas tenham oportunidade de executar trabalho (processar instruções de código).
Tudo seria mais fácil se existisse um limite do número de programas que o sistema operacional tenha em execução. Por exemplo, 1 programa para cada core do processador. O limite nos computadores hoje em dia estaria então entre 4 a 8 programas nos computadores para consumidores mais modernos.
Mas a realidade é que existe um número muito maior de programas que eu posso ter em execução. Já para não falar que cada programa pode ter mais que uma thread, uma thread corre sempre num core do processador (embora seja possível mudar de core durante a execução, pelo que sei).
Como é que esses programas continuam em funcionamento? Porque é que eles não travam? Como é que o sistema operativo distribui o processador entre os vários programas/threads?
Answer: Introdução
Quase sempre os sistemas operacionais permitiram funcionar assim. Claro que alguns não o fazem, mas não precisa ter vários processadores, físicos ou lógicos, para que vários processos ou mesmo threads possam rodar "ao mesmo tempo".
Há ganho em fazer isso sempre que existe estado de espera por alguma razão. Seja porque o hardware está manipulando dados por ele próprio, seja porque a própria aplicação está em estado de espera. Então limitar a quantidade de linhas de execução traria prejuízos já que nada estaria sendo feito durante essas pausas.
Seria mais fácil mas não seria o ideal. A dificuldade foi o preço que resolveu-se pagar para aproveitar melhor os recursos disponíveis. A ideia é manter o processador ocupado.
Colocar mais processadores não resolve isso. O motivo está explicado em É sempre garantido que uma aplicação com múltiplas threads rode mais rápido que usando uma única thread?.
Agendamento
Há um sistema de agendamento que é um algoritmo específico de sistemas operacionais para ir dando controle do processador para cada linha de processamento existente. O sistema operacional deixa uma linha executar por um tempo e depois há uma interrupção que devolve o controle do processador para o sistema operacional que poderá decidir em seguida o que fazer com o processador.
Isso é feito com instruções específicas do processador que cria a interrupção na execução depois do tempo estabelecido pelo sistema operacional. A interrupção é como um evento que muitos conhecem em alto nível, só que é controlado pelo hardware.
Esses algoritmos começam com a criação de listas de linhas de execução que são pedidas através da API de processos de threads. De acordo com as configurações o sistema operacional alocará um processador para aquela linha, podendo trocá-la seguindo alguns critérios, e um tempo específico (poucos microssegundos) para que ele execute até que retorne para o sistema operacional. Esse tempo pode variar de acordo com a quantidade de linhas existentes.
O SO fica em um laço e quando recebe o controle de volta ele entrega para outra linha de execução. A frequência que uma linha é chamada pode ser controlada também algum SOs, então não é preciso que todas linhas existentes executem uma vez para voltar executar outra vez.
Tudo isso depende da implementação de cada sistema e das condições do ambiente que está executando.
Alguns usam algoritmos bastante sofisticados para dar o melhor resultado possível para cada situação.
Pense nele como um guarda de trânsito ou um semáforo inteligente. Bom, tecnicamente um semáforo básico já é uma boa analogia, só que os SOs costumam ser melhor que isto.
Isso é a multitarefa preemptiva. No passado alguns SOs usam a multitarefa cooperativa. Não havia a interrupção, então o SO contava com a boa vontade da aplicação de devolver o controle para ele. Isso travava tudo se a aplicação "enroscasse". Com o hardware ajudando e o SO usando a preempção a aplicação não pode se apoderar do processador. A instrução de configuração interrupção só é acessível pelo SO.
Existem sistemas operacionais de tempo real que precisam dar mais garantias sobre a execução.
Obviamente isto é um resumo para leigos.
Artigo da Wikipedia sobre o assunto.
Coloquei no GitHub para referência futura.


Density of the orbit of a pure state.

Question: Let $A$ be a simple unital $C^*$-algebra and denote $U(A)$ the group of unitaries in $A$.
For $u\in U(A)$ lets define the $^*$-automorphism $\text{Ad}u:A\to A$ given by $a\mapsto uau^*$.
It is a known fact that if $\varphi$ is a pure state of $A$ then the set $\{\varphi\circ\text{Ad}u:u\in U(A)\}$ is weak*-dense in the space of pure states of $A$. There exists some variants that also holds and it is not necessary to consider the set of $\textbf{all}$ unitaries in $A$. For example, the set $\{\varphi\circ\text{Ad}\exp(ia):0\leq a\leq\pi\}$ is also a weak*-dense subset of the pure state space.
I am wondering if it is possible to require the unitaries to be "not to far from 1", that is, if for all $\epsilon>0$ the set $\{\varphi\circ\text{Ad}u:\|1-u\|<\epsilon\}$ is weak*-dense in the pure state space.
Thank you very much!
Answer: My previous answer did not satisfy all assumptions from the question, as was pointed out by Aweygan in the comments, but one can fix this by considering the finite-dimensional case instead
Let $A=M_n(\mathbb{C})$. The states of the form $\phi_\xi=\langle\,\cdot\,\xi,\xi\rangle$ for $\xi\in \mathbb{C}^n$ with $\|\xi\|=1$ are pure states on $A$, and $\phi_\xi\circ \mathrm{Ad}(u)=\phi_{u^\ast\xi}$. Let $\xi,\eta\in H$ be orthogonal unit vectors and $p$ the orthogonal projection onto the span of $\eta$. If $u$ is unitary with $\|1-u\|<\epsilon$, then
$$
|\langle pu^\ast\xi,u^\ast\xi\rangle|\leq \|p(u^\ast \xi-\xi)\|+\|p\xi\|<\epsilon,
$$
while $\langle p\eta,\eta\rangle=1$. Thus $\phi_\eta$ does not lie in the weak$^\ast$ closure of $\{\phi_\xi\circ\mathrm{Ad}(u)\colon \|1-u\|<\epsilon\}$ if $\epsilon<1$.
Comment: It looks like the asker wanted the algebra to be unital, and that the unitaries lie in the algebra.
Comment: @Aweygan You are absolutely right. One can fix this by considering the finite-dimensional case instead.

Density of the orbit of a pure state.


HP-Proliant DL380 G6

Question: Was able to get a Windows 10 based Operating System functioning on the server, sadly the other motherboard broke from other unrelated issues, replaced the motherboard, and cannot remember which setting partitions the drive sections to actually work and allow the Windows 10 based OS to install, it worked fine on the previous motherboard, but there was a setting I adjusted, though I cannot for the life of me remember what setting it was.
The OS Won't install due to the drives being GPT Partitioned.
I am using a Standard Windows 10 64BIT installer Disk, the same disk that worked fine on the previous Motherboard.
In other cases it just gives me a black screen saying Attempting to Boot from C:, and in other cases it gives me a red screen saying "illegal Opcode" And some error codes, I will keep trying, but extra help would be appricated.
Hopefully someone can help me I really gotta get this machine back up and running, these clients won't wait long.
Server Specifications:
<code>CPUs: x2 Intel Xeon X5670 2.93GHz 6 Cores 12 Threads at 32nm Technology (Total of 12 cores and 24 Threads)
Motherboard: HP ProLiant DL380 G6 Intel® 5520
RAM: Currently 4GB per CPU (Will increase later)
PSU: Dual 750W (Total Draw of 1500W)
HDD#1: 146GB
HDD#2: 146GB
HDD#3: Blank
HDD#4: Blank
HDD#5: 146GB
HDD#6: 146GB
HDD#7: 146GB
HDD#8: 146GB
GPU: Nvidia Quardo K2000```
</code>
Answer: I would suggest first updating the firmware to the latest version.
Secondly, it sounds like you may have created and booted mbr Windows 10 install disk, can you ensure that you have created an uefi/gpt version?
Comment: I'm not too sure, My main skill is hardware, when it comes to Software I'm essentially clueless, would you be able to provide more specific instructions, By the way I am using WIndows 10 Installer Disk to install a workstation OS, since this server is repurposed to a Workstation.

Otherwise I am thinking a PCI-E NVM SSD might allow the OS to install.
Comment: Unfortunately, there is too little information provided to be able to help much further. However, this youtube video may help: You will likely need to load the storage array driver for Windows 10: https://www.youtube.com/watch?v=qMXiHfv1NTY

HP-Proliant DL380 G6