Recommended architecture for a .NET Facebook Game

Question: What is a good architecture for implementing a real-time, multi-player Silverlight-based game that is intended to integrate and run from Facebook?
The idea is to build a Silverlight-based game that uses social network information from Facebook as part of its play environment.
Specifically,

Where should the game rules be implemented, in the client or on some server?
How should the game obtain credentials and session information from Facebook?
What should or should not be cached in the game (social network data, interactions, session keys, etc)
How should the game notify players about asynchronous world events - polling? out-of-band-push?, some other technique?
How should the game be implemented to minimize the risk of hacking or malicious disruption?
How should the game be architected to minimize latency and other network bandwidth constraints?
Comment: I guess if you outsource it to experts here then you will get something acomplished, otherwise i dont think anyone can help you do your job for free.
Comment: My purpose was neither to outsource it or have someone do my job, but rather to learn what practices and architectures make sense that other's may have already struggled through.
Comment: I think this is a really good question, but I bet that the answer depends heavily on the specifics of the game design.  For instance, when PopCap pushed out the new version of Bejeweled Blitz they recorded 90 million plays the first week.  I don't think that this means that a Facebook game needs to handle 90 million plays a week.
Comment: I was wondering if you already found a good solution for your problem I am facing the same issues right now.

Hope you can help me. What do you thing about Silverlight + RIA services?
Answer: Make the game work first. Stick stuff wherever it's easiest to get it done - whether that makes sense to keep it on the client or your server or whatever. If you follow good coding practices - SoC, IoC, unit tests, interfaces - it will be extremely easy to profile your working prototype and move things around as performance wins become obvious. Trying to anticipate how to optimize ahead of time is a losing game.
Comment: @Lbushkin sure, that's what I'm getting at - you're worried about client-side security, so put everything on the server first. You don't know if it'll be too chatty 'till you try. Then selectively move things back to the client as needed, and solve security problems as they arise, not before.
Comment: +1 for "do not optimize first."  Premature Optimization is a nasty antipattern, especially with new stuff like Silverlight.
Comment: My concerns are not so much about optimization, but rather what will result in functional problems. For example, allowing game decision logic to live the Silverlight client may make the game easier to hack and cheat - but putting game logic in the server may make the game too chatty.
Answer: Saw this tip online today from a former Microsoft Silverlight Program Manager.
Executive Summary:  Silverlight is new for everybody, expect to throw away a lot of code while we all figure out how best to do this stuff.
Based on your requirements, I'd say your game is quite ambitious and will push the boundaries of what has been done with Silverlight (did I mention I'm jealous you're getting paid to do this? :)
Silverlight was first released less than three years ago and is just starting to come into its own.  If you're going to embark on a project like the one you've described, you'll be at the forefront of the community learning curve.  Bon Voyage!


What does increased Luck do?

Question: I just got an artifact with a stat I've never seen before in a game in the franchise.
It says it gives me +8.33 Luck.

What exactly does this do? Do I get better/more loot? More money? Or is it just a tiny hidden cosmetic effect like + Friendship in Borderlands 2?
Answer: Luck is a stat that determines how often you get rare, very rare, and legendary loot drops in the game. This stat can also be seen in your Guardian Ranks, where its labelled "Luck (Rarity Rate)"

What does increased Luck do?


add +n to the name of some Strings id ends with "v + number"

Question: I have an array of Strings
Value[0] = "Documento v1.docx";
Value[1] = "Some_things.pdf";
Value[2] = "Cosasv12.doc";
Value[3] = "Document16.docx";
Value[4] = "Nodoc";

I want to change the name of the document and add +1 to the version of every document. But only the Strings of documents that ends with v{number} (v1, v12, etc).
I used the regex [v]+a*^ but only i obtain the "v" and not the number after the "v"
Comment: Please explain why you expect that regex to work. What is ``a*`` going to do?
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the "edit" link to improve your *question* - do not add more information via comments. Thanks!
Answer: The Regex v\d+ should match on the letter v, followed by a number (please note that you may need to write it as v\\d+ when assigning it to a String). Further enhancement of the Regex depends in what your code looks like. You may want to to wrap in a Capturing Group like (v\d+), or even (v(\d+)).
The first reference a quick search turns up is
https://docs.oracle.com/javase/tutorial/essential/regex/ ,
which should be a good starting point.
Answer: If all your strings ending with v + digits + extension are to be processed, use a pattern like v(\\d+)(?=\\.[^.]+$) and then manipulate the value of Group 1 inside the Matcher#appendReplacement method:
String[] strs = { "Documento v1.docx", "Some_things.pdf", "Cosasv12.doc", "Document16.docx", "Nodoc"};
Pattern pat = Pattern.compile("v(\\d+)(?=\\.[^.]+$)");
for (String s: strs) {
    StringBuffer result = new StringBuffer();
    Matcher m = pat.matcher(s);
    while (m.find()) {
            int n = 1 + Integer.parseInt(m.group(1));
        m.appendReplacement(result, "v" + n);
    }
    m.appendTail(result);
    System.out.println(result.toString());
}

See the Java demo
Output:
Documento v2.docx
Some_things.pdf
Cosasv13.doc
Document16.docx
Nodoc

Pattern details

v - a v
(\d+) - Group 1 value: one or more digits
(?=\.[^.]+$) - that are followed with a literal . and then 1+ chars other than . up to the end of the string.
Answer: Try a regex like this:
([v])([1-9]{1,3})(\.)

notice that I've already included the point in order to have less "collisions" and a maximum of 999 versions({1,3}).
Further more I've used 3 different groups so that you can easily retrieve the version number increase it and replace the string.
Example:
String regex = ;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(time);
if(matcher.matches()){
  int version = matcher.group(2); // don't remember if is 0 or 1 based
}


How to set current default font-families to websites in Chromium?

Question: I would like to set a default font-family in Chromium. I want to make a Chinese font !important for all the pages.
Answer: Cick on the "tools spanner" in the top right then click on Preferences.
From here click on "Under the Botnet" and then "Customize fonts".
The screenshot below is from Chromium 10 Beta, in earlier versions the dialogues will look a little different.
Comment: I want to make a Chinese font `!important` for all the pages.
Comment: @janoChen You might want to edit your question to make that explicit
Answer: You can change the font in chromium from preferences > under the hood > change font and languages settings. Won't that do ?
Answer: Create a folder by running mkdir .config/chromium/Default/User\ StyleSheets/ and into this put a file called Custom.css containing your modifications much in the same way that Firefox has userChrome.css. Any changes you make will be immediately processed by Chromium, unlike Firefox. This feature was made available around the beginning of this year.
Answer: Add the appropriate CSS to your custom userstyle, which is usually located at $HOME/.config/chromium/Default/User Stylesheets/Custom.css.


Dark theme word processor for ubuntu or the web? Ideally that doesn't change every other application

Question: I enjoy the way most of my applications look, but I wanted something like LibreOffice with a dark theme. The only ways I could find to make LibreOffice have a different look though involved changing the theme that every application in Ubuntu uses.
I just need:

to edit text
a dark theme
the ability to bold / italicize text
a way to make bullet point lists

I am using Ubuntu 14.04.1 with gnome-flashback. I am just looking for an application, web-based or desktop, that could do these things but could not find anything for the life of me. Does anyone have any recommendations?
Comment: If I'm not mistaken, LibreOffice can be themed using Firefox themes. Go to `Tools > Options > LibreOffice > Personalization > Own Theme > Select Theme`
Comment: I tried the Firefox themes but they only seem to affect the toolbar area of LibreOffice. I was mostly interested in the document area where I write.
Comment: So you mean a dark background (paper) or the area behind the "paper"?
Comment: You can adapt the color schemes somwhere next to "Personalization" as well
Comment: Ah you're right, that's perfect actually. It was under Appearance and Custom Colors - quite a lot of customization is possible. Searching for "theme" was leading me down the wrong road. If you put your comment as an answer I can accept it.
Answer: Actually, LibreOffice is quite customizable.
You can go to Tools→Options→LibreOffice→Tools→Appearance to customize the colors of LibreOffice. There, you can basically change every color ever used in LO.


unclear circular dependency with FeignClient and Spring boot

Question: My springboot app was working fine untill I added the following class:
@Service
@RequiredArgsConstructor
public class AutoopsClientPostBootListener implements ApplicationListener<ContextRefreshedEvent>
{
    private final IAutoOpsGnsFlowInitiator gnsFlowInitator;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
      gnsFlowInitator.startClient(event);
    }
}

For some odd reason after that, I get a circular dependency error stemming from
feign client dependent on AutoopsClientPostBootListener from above.
It happens becasue IAutoOpsGnsFlowInitiator is dependent on the feign client which depend on AutoopsClientPostBootListener. But FeignClient doesn't even have any members.. (feign auto generates it) so how can it be dependent on the Listener?!!
whats the problem??
Thanks for the help
Answer: So the problem was with ApplicationListener(no idea why).
Using @EventListener solved the problem.
@EventListener
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
      gnsFlowInitator.startClient(event);
    }

Comment: Thank you. This worked. I couldn't find any explanation in the documentation why this happens. The combination of an `@Auwowired` `@FeignClient` and `implements ApplicationListener` results in a circular dependency error although there is no such dependency.
Answer: The issue depends on the phase of your context, once your context is initialized or changes there is a call on refresh, so you event will be fired, if you need to execute your startClient once your context is fully initialized then you @EventListener will be trigger with ContextStartedEvent which is only called once your application context was fully initialized so feign is already loaded.
Hopefully this can be helpful.


Xcode7: unknown type name error in a basic C++ program

Question: I am working on a C++ program about STL with the latest version of Xcode, and I get the error "Unknown type name 'ubResultData'" and "Unknown type name 'ubFirstArgument'". I have tried to rewrite the program with standard unary_function and binary_function, and the errors remained the same. Then, I build the progaram with VS2010 and VS2013, and it built successfully. What's wrong with the program?
The errors are in the last line of class binder2ND.
#include <iostream>
#include <vector>
using namespace std;

template<typename InputIterator, typename Predicator>
inline int countIF(InputIterator First, InputIterator Last, Predicator Pred){
    int count = 0;
    for (; First != Last; ++First) {
        if(Pred(*First))++count;
    }

    return count;
}

template<typename Arg1, typename Result>
struct UnaryBase{
    typedef Arg1 ubFirstArgument;
    typedef Result ubResultData;
};

template<typename Arg1, typename Arg2, typename Result>
struct BinaryBase{
    typedef Arg1 bbFirstArgument;
    typedef Arg2 bbSecondArgument;
    typedef Result bbResultData;
};

template<typename T>
struct LESS:public BinaryBase<T, T, bool>{
    bool operator()(const T& Left, const T& Right)const{
        return (Left < Right);
    }
};

template<typename BinOP>
class binder2ND:public UnaryBase<typename BinOP::bbFirstArgument, typename BinOP::bbResultData>{
protected:
    BinOP OP;
    typename BinOP::bbSecondArgument Arg2;
public:
    binder2ND(const BinOP& Oper, const typename BinOP::bbSecondArgument& valRight):OP(Oper),Arg2(valRight){}
    ubResultData operator()(const ubFirstArgument &ubArg1)const{return OP(ubArg1,Arg2);}
};

template<typename BinOP, typename rightVal>
binder2ND<BinOP> bind2ND(const BinOP& OP, const rightVal& vRight){
    return binder2ND<BinOP>(OP, vRight);
}

int main(){
    vector<int> myVec;
    for (int i = 0; i < 50; ++i) {
        myVec.push_back(rand()%100);
    }

    int countNUm = countIF(myVec.begin(), myVec.end(), bind2ND(LESS<int>(), 30));
    cout << "Numbers=" << countNUm << endl;

    return 0;
}

Comment: I know that errors and warnings when you have templates can be long-winded, but please include them all, verbatim and in full and unedited.
Comment: Thanks for your suggestion. These are exactly the errors I got, and I just copy them down. And the location is in the last line of class binder2ND.
Comment: Fyi, [gcc promotes the same error](http://coliru.stacked-crooked.com/a/82ddccaf5d9cebd6) as clang (your xcode toolchain, in case you weren't aware).
Answer: I don't remember the exact phrasing from the standard, but here's the simplified code that demonstrates the same behavior as yours:
template <typename T> struct A {
  typedef T X;
};

template <typename T> struct B: public A<T> {
  X x(void) { return 5; }
};

And here's the version that compiles without any errors:
template <typename T> struct A {
  typedef T X;
};

template <typename T> struct B: public A<T> {
  typename A<T>::X x(void) { return 5; }
};

So basically, you need to specify exactly where this type comes from.
It looks like VS* compilers are a bit more permissive than gcc or clang. :)


How to check the last time a database table updated

Question: In Sql Server,there is a table called 'Product'
Is there any way to check the recent time/last time ,when data was populated in 'Product' table
Answer: SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID('DbName')
AND OBJECT_ID=OBJECT_ID('TableName')

This will give you the details when the table was last updated.
Answer: Use sys.dm_db_index_usage_stats to figure out when was the table updated last time.
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'Database_Name_Here')
AND OBJECT_ID=OBJECT_ID('Table_Name_here')

If WHERE condition is entirely removed it will provide details of the entire database.
Refer this link


Complex integration Cauchy Formula

Question: $\oint_{\left | z \right |=0.5} \frac{dz}{(z-1)(\sin z)} $
Define:
$f(z) = \frac{z}{(\sin z)(z-1)}$
Define:
$g(z) = \frac{f(z)}{z}$
Now integrate using Cauchy Integration Formula
$\oint_{\left | z \right |=0.5} g(z) dz=2i\pi f(0)=-2i\pi $
where the minus sign comes from the following limit:
$\lim_{z \to 0}f(z) = \frac{0}{0} = \frac{1}{(\cos z)(z-1) + \sin z}=-1$
I see that zero is a removable discontinuity point for f(z). Under these conditions may i also apply the Cauchy Integral Formula? Is the result correct?
Comment: It seems you're looking at [this](http://math.stackexchange.com/questions/1076491/evaluating-a-complex-integral-using-the-cauchy-integral-formula/1076508#1076508) question.
Answer: Looks like you are using L'Hospital's Rule in the last step, which doesn't apply in the complex setting. However, you can show that
$$\lim_{z\to 0}\frac{\sin z}{z}=1$$
by using the Taylor expansion of $\sin$.
Other than that, your answer looks fine.

Complex integration Cauchy Formula


On Click on Buttons when created on the fly

Question: I have two button classes, when clicked, I want something to happen.
I have:
$('.btn-comment, .btn-youtube').click(function(){

This used to work when the buttons were static. They are now created ad hoc.
I have tried this:
$('.btn-comment, .btn-youtube').on('click', function(){

But no luck.
Comment: Asked hundred times a week...
Comment: @hima there is no selector targeting ID here
Comment: You need to bind events, or delegate events, to ancestor elements that exist in the DOM at the point of binding.
Comment: Do they have the same id as it in `$('.btn-comment, .btn-youtube').on('click', function(){`?
Answer: That's not how it works.
You should add the delegation to the parent element. The one who is going to suffer from modification.
You can do it with the whole document:
$(document).on('click', '.btn-comment, .btn-youtube', function(){ ... });

But it would be better to do it with the modified element.
Comment: Stack Overflow needs a *sticky* in each tag. jQuery Event Delegation should be it.
Comment: @RGraham what do you mean?
Comment: It's just it's such a frequently asked question, there should be a big warning label when you add a jQuery tag to a question saying "Use the following syntax to make sure your events always fire" :)
Answer: You need to register the handler on a common static ancestor (worst case document, but the nearer the better) and then use the new .on syntax for delegated handlers, e.g.:
$(document).on('click', '.btn-comment, .btn-youtube', function() {
     ...
});

Comment: @panthro indeed, unless the list element itself is also dynamically replaced.  The common ancestor must be _static_.
Comment: So if they are in a list it would be better to do: $('#myList').on('click', '.btn-comment, .btn-youtube', function(){
Answer: Check out the jQuery docs for .on().
You need to use:
$('body').on('click', '.btn-comment, .btn-youtube', function(){ ... });

The problem with your code is that if .btn-comment, .btn-youtube are being inserted dynamically, then they probably don't exist at the point at which you're trying to attach your event handlers.
The above line of code attaches the handler to body but is only triggered by elements matching the second argument ('.btn-comment, .btn-youtube').
And ideally, you'd replace 'body' with the closest ancestor that the new elements are being inserted into.


When does Windows Error Reporting create a dump file? Is it configurable? Has this changed in Windows 7?

Question: I'm relying on Windows Error Reporting to create full user-mode dumps for a large, multi-threaded application.  I know that when I started using it (early 2012) these dumps contained all application memory, and full stacks for all threads that were accurate for the time the application crashed (threw the unhandled exception, etc).  But at at some unknown point in the last year, crash dumps created by WER have changed.  They still contain all memory, but only show one thread, and the stack appears to be from after the process is already shutting down:
    ntdll.dll!_LdrpCallInitRoutine@16()  + 0x14 bytes
    ntdll.dll!_LdrShutdownProcess@0()  + 0x141 bytes
    ntdll.dll!_RtlExitUserProcess@4()  + 0x74 bytes
    kernel32.dll!_UnhandledExceptionFilter@4()  + 0x18928 bytes

This is an unmanaged (unmanagable?) 32-bit C++ application compiled with VS2010 SP1, running on 64-bit Win7 SP1 (and kept updated).  Does anyone know of any Windows updates that have changed WER behavior in the last year?  Is there something configurable other than 'HKLM\SOFTWARE\Microsoft\Windows\Windows Error Reporting\LocalDumps\AppName.exe'?
Also, killing the application by calling 'RaiseFailFastException' still results in a good dump with valid stacks for all threads.
Comment: Nothing I heard.  The simple explanation is that your app is just crashing for a different reason.
Comment: No, I am explicitly throwing an exception to test the dump creation, and I am missing stacks on both the latest version of the application and the version from a year ago that originally worked.  Thanks though.
Answer: Aha!  A third-party library was calling SetUnhandledExceptionFilter, which prevented Windows Error Reporting from getting the original exception.  Their handler did some internal cleanup, then called abort, at which point WER was finally able to create a dump.
For anyone encountering this sort of problem, I recommend checking that the installed handlers (the return values of SetUnhandledExceptionFilter, set_terminate, etc) are what you expect (null if you're relying on WER, or your own handlers or CrashRpt).
Answer: It is better to make your application self-dump-writer when it crashes. You just need to call SetUnhandledExceptionFilter function, specify the call back. In the call back, use MiniDumpWriteDump function with MiniDumpWithFullMemory dump type.
Your exception filter will be called whenever unhandled (by your code) exception occurs. In the call back, it will be better to enumerate and suspend all other threads of your process.
You may also need to install a hook for SetUnhandledExceptionFilter itself! Why? Well, CRT would always disable any installed exception filter, and by the hooked function, you may avoid that.
Comment: If it is feasible to rely on the WER dumps (i.e. no additional stuff needed in the unhandled filter, no specific user notification), using WER is *way better* (if you don't have to support WinXP). It will give you a dump in *all* crash scenarios, even corrupted stack where UHEF isn't even called. Plus: (quote MS) *MiniDumpWriteDump should be called from a separate process if at all possible, rather than from within the target process being dumped(...)* And I can tell you that this really gets complicated.
Comment: Sorry, but I have to say that this is a piece of an extremely bad advice. @MartinBa correctly points to the docs, but the docs do not tell *why* one should not do that. In fact, `MiniDumpWriteDump` calls `LoadLibraryEx()` internally, and, if you happen to be holding the loader lock, the process inevitably deadlocks inside the call. [This discussion thread](https://groups.google.com/d/msg/microsoft.public.windbg/Kca8A-pV914/UEd48t2OzccJ) has a good explanation from one of the WER developers why this is simply unavoidable.
Comment: Looks like this is what I'll have to do.  I'll go back to using the [CrashRpt](https://code.google.com/p/crashrpt/) library.


Is there any use for the small crystal cave on the starting island?

Question: On the starting island, you can go to the beach and enter a small cave full of purple crystals.
However, there seems to be nothing there besides two easy monsters.
Is there any use for the cave at all? Do I need it for a quest, or is there some item there that I haven't found?
Answer: There is something in that cave if you look around carefully. A torch might be helpful to see it.

 Somewhere to the right side of the cave (from where you enter it) is a Hero's Crown, which gives you a permanent increase to some defensive stats.
Answer: You can find a treasure in there. But first you'll need to get a corresponding quest. Go to the room to the left of Carlos and open chest in it - you'll find a map.


Would device registration id of C2DM expires?

Question: Well, I know that the registration id of server would expire. However, how about the device registration id?
If yes, how do the server and client know about that?
Now I just simply save the id into database and assume it would never change.
Btw, is the registration id of server associated with the device registration id? Why the tutorial from the internet store them in the pair
Answer: Short answer is Yes, as stated here.

The application should store this ID for later use. Note that Google may periodically refresh the registration ID, so you should design your application with the understanding that the REGISTRATION Intent may be called multiple times. Your application needs to be able to respond accordingly.

Basically what would have to happen is that your application needs some sort of communication with your server to notify it that it received a new id. What you could do is when the app receives a registration id, store it on some remote database along with some additional unique information about that device (or user credentials if app has authentication). When Google decides to change the registration id, just update the previous entry on the remote db with the new id. Then when your server needs to push a message to some device, it matches the device to an up-to-date registration id in the database and uses that id to push the notification.
Comment: For a particular device the registration id will be the same (a constant value?), even if the user clears the application data?


Create multiple list columns dynamically in data.table at once

Question: Is there a way to create multiple list columns at once in data.table?
Using code below i create two list columns, c1_list and c2_list, while grouping by x
DT = data.table(x  = c('a','a','b','b'),
            c1 = c(1,2,3,4),
            c2 = c(2,4,6,8))

DT[, .(c1_list = list(c1), c2_list = list(c2)), by = 'x']
#   x c1_list c2_list
#1: a     1,2     2,4
#2: b     3,4     6,8

Instead, I was hoping for a dynamic shortcut somthing like
note: code below does not work - this is merely a suggestion of how it might look like
DT[, (c('c1_list', 'c2_list')) = lapply(mget(c('c1','c2')), list), by = 'x']

or
DT[, lapply(.SD, list), by = 'x', .SDcols = c('c1','c2')] %>%
    setnames(c('c1','c2'), c('c1_list','c2_list')

UPDATE: as RyanD pointed out the second solution works.
Comment: oops. Thank you. Will remove the question if i can.
Answer: You can do
DT[, lapply(.SD, list), by = x, .SDcols = paste0("c", 1:2)]
#   x  c1  c2
#1: a 1,2 2,4
#2: b 3,4 6,8


Prove that $\sqrt 2 + \sqrt[3]2$ is not rational

Question: How do I prove that the following is not rational?
$$x=\sqrt 2 + \sqrt[3]2$$
To prove a simpler case like $\sqrt{2}=a/b$, I can raise both sides to the power of 2 and get $a^2=2b^2$, therefore both $a$ and $b$ must be even numbers which can't be true.
Comment: This is unreadable.  If you are asking about $\sqrt 2 +\sqrt[3] 2$ then that is irrational so you can't prove that it is rational.
Comment: For algebraic numbers , the most straightford way to decide their rationality is to determine their minimal polynomial. If and only if its degree is $1$ , the given number is rational.
Comment: Sorry, updated the question.
Comment: For the given $x$, the proof is not so easy as in the mentioned simpler example.
Comment: "therefore both a and b must be even numbers which can't be true." Why not? (I am asking the OP this)
Comment: Are you allowed to use the precalculus/school-algebra rational root theorem? If so, then a little algebra leads you to a 6th degree polynomial whose only possible rational roots are $\pm 1,$ $\pm 2,$ $\pm 4,$ each of which is is easily seen to not be a root of that 6th degree polynomial.
Comment: @AdamRubinson we could assume that a/b don't have any common factor, otherwise we would simplify it to a'/b' with common factors removed.
Comment: That's right. You should have written those details in the question as it highlights where the contradiction arose in the proof if irrationality of $\sqrt{2}.$
Answer: Let
$$x=\sqrt 2 + \sqrt[3]2$$
then
$$x-\sqrt 2 = \sqrt[3]2$$
$$\left(x-\sqrt 2 \right)^3=2$$
$$x^3-3x^2\left( \sqrt 2 \right)+3x(2)-2\left( \sqrt 2 \right)=2$$
$$\sqrt 2= \frac {x^3+6x-2}{3x^2+2}$$
$x$ cannot be rational because $\frac {x^3+6x-2}{3x^2+2}$ will then be rational and yet $\sqrt 2$ is irrational.
Comment: Straightforward and simple. Well done!


Isomorphism between elliptic curves over $\mathbb Q$ and $\mathbb F_5$

Question: Given are the Elliptic curves $E_1 : y^2 = x^3+x$ and $E_2 = y^2 = x^3+3x$. Are these isomorphic over
a) $\mathbb Q$?
b) $\mathbb F_5$?
I see they are isomorphic over $\mathbb C$, as they have the same $j$-invariant. I suppose they aren't isomorphic, but how to prove this?
Answer: Hint: They are isomorphic over $K$ if and only there exists a $u\in K^{\times}$ such that $u^4=3$, see here.
Actually, for $y^2=x^3+x$ we have $E(\Bbb F_5)\cong C_2\times C_2$, and for $y^2=x^3+3x$ we have $E(\Bbb F_5)\cong C_{10}$.


How to transform an R data frame with multiple classes into one class?

Question: When I call the dput() function on my df data frame I am presented with multiple classes.
df %>% dput()
#> ...
#> class = c("tbl_df", "tbl", "data.frame")
#> ...

How do I transform this data frame into a single class? I would get something like this I imagine:
df %>% dput()
#> ...
#> class = "data.frame"
#> ...

I'm having a separate issue and I suspect this (multiple classes in a date frame) may be a contributing factor.
Comment: what does `str(df)` show?
Comment: @developer when I `str(df)` I get `tibble [5,856 x 10] (S3: tbl_df/tbl/data.frame)` followed by the column types which include "chr', "Date", and "logi".
Answer: You can override the class like that:
class(df) <- "data.frame"

If you want to change the class in a pipe, from there, use df %>% "class<-"("foo")
Example:
data.table::data.table(x = rnorm(10)) %>% "class<-"("foo")
$`x`
 [1] -1.7728669 -0.3643645  0.4410907  0.3494225 -0.3214129  0.8595643  0.8794649  0.3891513
 [9] -2.2456579 -0.6045959

attr(,"row.names")
 [1]  1  2  3  4  5  6  7  8  9 10
attr(,"class")
[1] "foo"

Comment: can you also add the way to write that into a pipe? is it something like `df %>% class("data.frame")` which doesn't quite seem to work.


Masking only a certain range of indices in numpy

Question: I have an ndarray. I need to mask any number less than 50 until the first number encountered is greater than 50. This should be done both at the beginning and at the end of a row. Right, when the first number encountered is >50, the masking should stop.
One row looks like:
    [ 0   1   1   0  57  121  120  157  77  14   0   3   0   0   0   0  67 100
    98  97 101 129 139 105  97 105 181 126  10   0   0]

I want something like:
    [-- -- -- -- 57 121 120 157 77 14  0  3  0  0  0  0 67 100 98 97
 101 129 139 105 97 97 105 181 126 -- -- --]

The masking should stop right before 57 in the second line, and at 126 in the 4th last line.
I have tried ma.masked_where, but it masks the 0s in between as well, which I don't want.
So, if there a way to do this, or can you help me so that I can specify a range of indices, eg: [0:40] only which should be masked.
I do not want to change the dimension of the array after it is masked. Also, the presence of -- wouldn't make a difference to my purpose.
Comment: What should the masking achieve? I am not seeing the expected output.
Comment: @a_ran Simply mention about the threshold (50) and don't confuse yourself and others with the zeros mention.
Comment: @jpp's Boolean indexing solution (with a minor tweak) will *select* the middle which should be the same as excluding the ends.
Comment: have made the changes.
Comment: What about the two `ones` at positions 29 and 30?
Comment: it should be masked, as all values which are less than 50 should be masked, until the first number encountered is greater than 50.
Comment: @Divakar I just saw what you meant. Have edited.
Comment: What is your region of interest? Are you using the mask to operate on/with the two ends or the middle - are you excluding the ends from your operations or excluding the middle?
Comment: @wwii This is just one row. I need to produce geojson files with the position of values belonging to a certain group, but I have to exclude the boundary values which are < 50.
Comment: Was the full size of your actual array really needed? Couldn't you make a more minimal example? Right now it's just annoying to look for what you are after...
Comment: Sure, I will do that.
Answer: You can use either Boolean indexing or manual iteration. The former is more efficient for small arrays; the latter for large arrays with a small number of out-of-scope values either side.
Boolean indexing
x = np.array([0, 0, 0, 2, 3, 51, 34, 1, 23, 32, 32, 52, 0, 0, 0])

start = (x > 50).argmax()
end = len(x) - (x[::-1] > 50).argmax()

print(x[start: end])

[51 34  1 23 32 32 52]

Manual iteration
Using next with a generator expression and enumerate:
start = next(idx for idx, val in enumerate(x) if val > 50)
end = len(x) - next(idx for idx, val in enumerate(reversed(x)) if val > 50)

print(x[start: end])

[51 34  1 23 32 32 12]

Masking
If you wish to replace out-of-scope values with np.nan, you can assign accordingly, remembering to convert to float first, as NaN values are float:
x = x.astype(float)
x[:start] = np.nan
x[end:] = np.nan

print(x)

array([nan, nan, nan, nan, nan, 51., 34.,  1., 23., 32., 32., 52., nan, nan, nan])

Comment: @a_ran, `--` is not a valid element in a numeric array, I've edited to include a solution to replace with `np.nan`.
Comment: @jpp I'm gleaning this from hints in the question, but OP appears to be looking to manipulate the mask in a masked array. `--` appears to be a valid printout in that case.
Comment: I do not want to change the dimension of the array. I have put the expected output.
Comment: I agree, but that wouldn't matter in what I want to achieve.


I don't want any metadata added/extracted

Question: I'm using Tika to index PDF files and in the Solr-UI I can see that a lot of metadata and other "stuffs" that I don't care are indexed too:
<code>"response": {
    "numFound": 1,
    "start": 0,
    "docs": [
      {
        "meta": [
          "dc:subject",
          "",
          "meta:save-date",
          "2014-01-09T11:07:45Z",
          "subject",
          "",
          "Author",
          "smalik",
          "dcterms:created",
          "2014-01-09T11:07:45Z",
          "date",
          "2014-01-09T11:07:45Z",
          "creator",
          "smalik",
          "Creation-Date",
          "2014-01-09T11:07:45Z",
          "meta:author",
          "johndoe",
          "stream_content_type",
          "",
          "created",
          "Thu Jan 09 12:07:45 CET 2014",
          "stream_size",
          "null",
          "meta:keyword",
          "",
          "cp:subject",
          "",
          "xmp:CreatorTool",
          "PScript5.dll Version 5.2.2",
          "Keywords",
          "",
          "Last-Save-Date",
          "2014-01-09T11:07:45Z",
          "dc:title",
          "E-Mail zur Archivierung",
          "meta:creation-date",
          "2014-01-09T11:07:45Z",
          "dcterms:modified",
          "2014-01-09T11:07:45Z",
          "dc:creator",
          "johndoe",
          "Last-Modified",
          "2014-01-09T11:07:45Z",
          "modified",
          "2014-01-09T11:07:45Z",
          "xmpTPg:NPages",
          "1",
          "producer",
          "www.adlibsoftware.com:EXS41012-Windows 2008 R2:TNG",
          "Content-Type",
          "application/pdf"
        ],
        "div": [
          "page"
        ],
        "id": [
          "aaa11besd4effsujqub6toubqr4m3.pdf"
        ],
        "dc_subject": [
          ""
        ],
        "meta_save_date": [
          "2014-01-09T11:07:45Z"
        ],
        "subject": [
          ""
        ],
        "author": [
          "johndoe"
        ],
        "dcterms_created": [
          "2014-01-09T11:07:45Z"
        ],
        "date": [
          "2014-01-09T11:07:45Z"
        ],
        "creator": [
          "johndoe"
        ],
        "creation_date": [
          "2014-01-09T11:07:45Z"
        ],
        "title": [
          "E-Mail zur Archivierung"
        ],
        "meta_author": [
          "johndoe"
        ],
        "stream_content_type": [
          ""
        ],
        "created": [
          "Thu Jan 09 12:07:45 CET 2014"
        ],
        "stream_size": [
          "null"
        ],
        "meta_keyword": [
          ""
        ],
        "cp_subject": [
          ""
        ],
        "xmp_creatortool": [
          "PScript5.dll Version 5.2.2"
        ],
        "keywords": [
          ""
        ],
        "last_save_date": [
          "2014-01-09T11:07:45Z"
        ],
        "dc_title": [
          "E-Mail zur Archivierung"
        ],
        "meta_creation_date": [
          "2014-01-09T11:07:45Z"
        ],
        "dcterms_modified": [
          "2014-01-09T11:07:45Z"
        ],
        "dc_creator": [
          "johndoe"
        ],
        "last_modified": [
          "2014-01-09T11:07:45Z"
        ],
        "modified": [
          "2014-01-09T11:07:45Z"
        ],
        "xmptpg_npages": [
          "1"
        ],
        "producer": [
          "www.adlibsoftware.com:EXS41012-Windows 2008 R2:TNG"
        ],
        "content_type": [
          "application/pdf"
        ],
        "fullText": [" abcdef"],
        "uid": "d41d8cd98f00b204e9800998ecf8427e"
      }
    ]
  }
</code>
As I'm only interested in "fullText" and "id", I would like to know how/what I have to set/define in the schema.xml and/or solrconfig.xml to avoid all the unnecessary data.
What I would like is something like this:
<code>"response": {
        "numFound": 1,
        "start": 0,
        "docs": [
          {
            "id": [
              "aaa11besd4effsujqub6toubqr4m3.pdf"
            ],
            "fullText": [" abcdef"],
            "uid": "d41d8cd98f00b204e9800998ecf8427e"
          }
        ]
      }
</code>
Actually my schema and solrconfig.xml look like this:
<code><?xml version="1.0" encoding="UTF-8" ?>
<schema name="simple" version="1.1">
    <types>
        <fieldtype name="string" class="solr.StrField" postingsFormat="SimpleText" />
        <fieldtype name="text" class="solr.TextField" postingsFormat="SimpleText">
            <analyzer>
                <charFilter class="solr.PatternReplaceCharFilterFactory" pattern="\n" replacement=""/>
                <tokenizer class="solr.StandardTokenizerFactory"/>
                <filter class="solr.LowerCaseFilterFactory" /> <!--Lowercases the letters in each token. Leaves non-letter tokens alone.-->
                <filter class="solr.ClassicFilterFactory" /> <!--Removes dots from acronyms and 's from the end of tokens. Works only on typed tokens produced by ClassicTokenizer or equivalent.-->
                <filter class="solr.TrimFilterFactory"/> <!--Trims whitespace at either end of a token. -->
                <filter class="solr.StopFilterFactory" ignoreCase="true"/> <!--Discards common words.  -->
                <filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
            </analyzer>
        </fieldtype>
    </types>

    <fields>
        <field name="uid" type="string" indexed="true" stored="true"
            multiValued="false" />
        <dynamicField name="*" type="string" multiValued="true"
            indexed="true" stored="true" />
        <field name="content" indexed="true"  type="text" multiValued="true" />
    </fields>

    <defaultSearchField>content</defaultSearchField>

    <solrQueryParser defaultOperator="OR" />
    <uniqueKey>uid</uniqueKey>
</schema>

<?xml version="1.0" encoding="UTF-8" ?>
<config>
    <luceneMatchVersion>LUCENE_45</luceneMatchVersion>
    <directoryFactory name='DirectoryFactory' class='solr.MMapDirectoryFactory' />

    <codecFactory name="CodecFactory" class="solr.SchemaCodecFactory" />

    <lib dir='${solr.core.instanceDir}\lib' />
    <lib dir="${solr.core.instanceDir}\dist\" regex="solr-cell-\d.*\.jar" />
    <lib dir="${solr.core.instanceDir}\contrib\extraction\lib" regex=".*\.jar" />

    <requestHandler name="standard" class="solr.StandardRequestHandler" default="true" />

    <requestHandler name="/update" class="solr.UpdateRequestHandler">
        <lst name="defaults">
            <str name="update.chain">deduplication</str>
        </lst>
    </requestHandler>

    <requestHandler name="/update/extract"
        class="solr.extraction.ExtractingRequestHandler">
        <lst name="defaults">
            <str name="captureAttr">true</str>
            <str name="lowernames">true</str>
            <str name="overwrite">false</str>
            <str name="captureAttr">true</str>
            <str name="literalsOverride">true</str>
            <str name="uprefix">ignored_</str>
            <str name="fmap.a">link</str>
            <str name="fmap.content">fullText</str>
            <!-- the configuration here could be useful for tests -->
            <str name="update.chain">deduplication</str>
        </lst>
    </requestHandler>

    <updateRequestProcessorChain name="deduplication">
        <processor
            class="org.apache.solr.update.processor.SignatureUpdateProcessorFactory">
            <bool name="overwriteDupes">false</bool>
            <str name="signatureField">uid</str>
            <bool name="enabled">true</bool>
            <str name="fields">content</str>
            <str name="minTokenLen">10</str>
            <str name="quantRate">.2</str>
            <str name="signatureClass">solr.update.processor.TextProfileSignature</str>
        </processor>
        <processor class="solr.LogUpdateProcessorFactory" />
        <processor class="solr.RunUpdateProcessorFactory" />
    </updateRequestProcessorChain>

    <requestHandler name="/admin/"
        class="org.apache.solr.handler.admin.AdminHandlers" />

    <lockType>none</lockType>

    <admin>
        <defaultQuery>*:*</defaultQuery>
    </admin>

</config>
</code>
Answer: See Alexandre's answer and examples here. If you are getting fields you do not need, then you need to explicitly declare them in your schema and set both indexed and stored to false (meaning Solr will ignore the field). You can also use dynamic fields to ignore a whole bunch of them with common prefix or suffix, which is typically the case with docs generated by Tika.


Clojure: Attaching annotations to AOT-compiled methods

Question: I have a module for the BaseX Java interface which I'm writing in Clojure. The interface provides a number of annotations which can be used to determine how methods are called and optimized; however, I'm having trouble getting these to actually attach to the generated class:
(ns net.dyfis.svnkit_wrapper.SvnWrapper
  (:import (org.basex.query QueryModule
                            QueryModule$Requires
                            QueryModule$Permission
                            QueryModule$Deterministic))
  (:gen-class
    :main false
    :extends org.basex.query.QueryModule
    :methods [
      ^{:static true}
      [^{QueryModule$Requires QueryModule$Permission/NONE,
         Deprecated {}}
       cat [java.lang.String] java.lang.String]

      ^{:static true}
      [^{QueryModule$Deterministic {},
         QueryModule$Requires QueryModule$Permission/NONE}
       catRev [java.lang.String int] java.lang.String]]))

However, only the Deprecated annotation gets attached -- the QueryModule$Requires and  QueryModule$Deterministic annotations are silently discarded:
>>> cat
public static java.lang.String net.dyfis.svnkit_wrapper.SvnWrapper.cat(java.lang.String)
>>> cat.getAnnotations()
array(java.lang.annotation.Annotation,[@java.lang.Deprecated()])

This is happening with Clojure 1.4.0-beta6, whereas support for annotations in AOT-compiled methods is supposed to be present from Clojure 1.2. As such, this is presumably a usage error -- but what should I be doing differently?
Answer: Except for classes in java.lang (like Deprecated), all classnames must be fully qualified in gen-class declarations.  So, your code should be:
^{org.basex.query.QueryModule$Deterministic {},
  org.basex.query.QueryModule$Requires org.basex.query.QueryModule$Permission/NONE}

Note that the same restriction does not apply to annotation metadata on/in deftype, defprotocol, or defrecord forms.
Answer: Moving the gen-class definition out of the ns declaration allowed the imports to apply:
(ns net.dyfis.svnkit_wrapper.SvnWrapper
  (:import (org.basex.query QueryModule
                            QueryModule$Requires
                            QueryModule$Permission
                            QueryModule$Deterministic)))

(gen-class
  :name com.indeed.svnkit_wrapper.SvnWrapper
  :main false
  :extends org.basex.query.QueryModule
  :methods [
    ^{:static true}
    [^{QueryModule$Requires QueryModule$Permission/NONE,
       Deprecated {}}
     cat [java.lang.String] java.lang.String]

    ^{:static true}
    [^{QueryModule$Deterministic {},
       QueryModule$Requires QueryModule$Permission/NONE}
     catRev [java.lang.String long] java.lang.String]
  ])


Safari doesn't understand my Content-Security-Policy headers

Question: Every other browser understands when I say:
add_header Content-Security-Policy default-src 'self'; script-src 'self' unsafe-inline; connect-src wss://mysite.com;

In my headers. But Safari says:

Refused to connect to wws://mysite because it doesn't not appear in
  the connect-src directive in Content Security Policy. [Error]
  SecurityError (DOM Exception 18): The operation is insecure.
  (anonymous function) (myjavascripturl.js)

Why does Safari not understand my Content-Security-Policy headers?
Comment: I started a bounty because I can't accept the first answer. I want to make it possible for all stages of my software. The first answer would resolve it for only one stage
Answer: In the policy you have provided there are no single quotes around unsafe-inline which are required. Change this:
add_header Content-Security-Policy default-src 'self'; script-src 'self' unsafe-inline; connect-src wss://mysite.com;

To this:
add_header Content-Security-Policy default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src wss://mysite.com;
-------------------------------------------------------------------------^-------------^

That could be affecting the parsing of the policy.

The other concern is in the error message you provided.
Refused to connect to wws://mysite
-----------------------^

Do you have a typo somewhere in your code, should this be wss?


do something when an ajax call is successful in axios - chaining then() in axios

Question: I'm trying to do something when an ajax call is successful in axios
    save() {

      this.isUpdateTask ? this.updateProduct() : this.storeProduct()

      this.endTask()

    }

if the ajax call to update or store the product is successful, I want to run the endTask() function.
I don't want the endTask() function to be run when the ajax call is not successful.
how can I do that?
the store function:
    storeProduct() {
      return axios
        .post("products", this.getFormData())
        .then(
          response => this.products.push(response.data.data)
        )
        .catch(
          error => (this.serverErrors = error.response.data.errors.detail)
        )
    },

Answer: You can call this methods inside a new promise like this below example:

   save() {
      Promise.resolve()
      .then(() => {
        return this.isUpdateTask ? this.updateProduct() : this.storeProduct()
      })
      .then(() => {
        this.endTask()
      })
    }

Have other ways to do also:
save() {
  (this.isUpdateTask ? this.updateProduct() : this.storeProduct()).then(() => {
    this.endTask()
  })
}

Or assign to a variable:
save() {
  const promiseUpdate = this.isUpdateTask ? this.updateProduct() : this.storeProduct()

  promiseUpdate.then(() => {
    this.endTask()
  })
}

Or with async/await:
async save() {
  await this.isUpdateTask ? this.updateProduct() : this.storeProduct()
  // this code runs only if everything happen successful
  await this.endTask()
}

And about the endTask execute until when response is not successful, is because you treat the error inside the storProduct.
.catch(
  error => (this.serverErrors = error.response.data.errors.detail)
)

So, in this case, is necessary re-throw the error again:
.catch(
  error => {
    this.serverErrors = error.response.data.errors.detail
    throw error
  }
)

The catch of Promise, have same effect of try/catch from javascript.
Have more reference about catch on promise here.
Comment: You should be able to assign `this.isUpdateTask ? this.updateProduct() : this.storeProduct()` to a variable, so `Promise.resolve()` isn't necessary.
Comment: awesome!! I added the "throw error" and now everything works how it's supposed to. Thanks a lot Fuechter
Comment: Good, I'm gonna add more examples :)
Comment: I tried the second way yesterday, but today I noticed that the endTask() runs even when the response is not successful and for example, there is a validation error.
Comment: the endTask() in promiseUpdate.then() is supposed to run when the response is successful. but it is run even when there is a validation error.
Comment: Good, now I got you, I added more exemplo about this on end post.
Answer: Anything inside the .then is only executed when a successful response is received
.then(response => {
    this.products.push(response.data.data)
    this.save()
    })

Answer: Try this:-
storeProduct() {
  return axios
    .post("products", this.getFormData())
    .then(
      response => this.products.push(response.data.data)
      this.endTask();  //call endtask() here after successfull api call and response back from api
    )
    .catch(
      error => (this.serverErrors = error.response.data.errors.detail)
    )
}

Comment: I did this at first, but I want the storeProduct() to have one single responsibility. I don't want it to be involved with ending the task.
Comment: Then set any boolean flag for the API success response. Means if API gives success response then set flag true. If flag true then call this.endTask() function. Make initially flag false.
Comment: yeah, this is what I'm doing temporarily. it is not the best way but it does the job. I wonder why then() function runs when there is validation error.


What is $X\cap\mathcal P(X)$?

Question: Does the powerset of $X$ contain $X$ as a subset, and thus $X\cap \mathcal{P}(X)=X$, or is $X\cap \mathcal{P}(X)=\emptyset$ since $X$ is a member of the
$\mathcal{P}(X)$, and not a subset?
Answer: Actually: $$A \subset X \iff A \in \wp(X).$$ All situations can happen. If $X = \{  0,1\}$, then $$\wp(X) = \{  \varnothing, \{0\},\{1\},\{0,1\} \},$$ so $X \cap \wp(X) = \varnothing$. But if you take, say $Y = \{ 0, \{0\}  \}$, then: $$\wp(Y) = \{ \varnothing, \{0\}, \{\{0\}\}, \{ 0,\{0\} \}  \},$$ so $Y \cap \wp(Y) = \{\{0\}\} \neq \varnothing.$
Comment: Then you compute $\wp(\{1,2,3\})$ and see... looking quickly it seems that the intersection will be empty. I think it is a good exercise to check if my guess is right.
Comment: The intersection will be empty every time $X$ is composed purely of urelements.
Comment: Thanks allot... What if you suppose X = {1,2,3}?
Answer: This can be many things.
If $\varnothing\in X$, then $X\cap\mathcal P(X)$ is definitely not empty, since $\varnothing$ is an element of both sets. And if $X=\varnothing$, then $X\cap\mathcal P(X)=X=\varnothing$.
Moreover, we say that $X$ is a transitive set if whenever $A\in X$, then $A\subseteq X$. Recall, before pondering this definition, that in modern set theory, everything is a set. So this makes sense. If $X$ is a transitive set, then $X\subseteq\mathcal P(X)$, in which case $\mathcal P(X)\cap X=X$.
But, thinking about this naively, or perhaps from a "naive type theoretic" point of view, where the objects inside of $X$ are of type I, and the objects in $\mathcal P(X)$ are sets of objects of type I, and sets of objects of type I, are not objects of type I themselves. For example, sets of natural numbers "are not" natural numbers (type theoretically, sure; but set theoretically this is certainly not necessarily the case). In this naive thinking, indeed $X\cap\mathcal P(X)=\varnothing$ since each holds objects of different a type.
But, again, this depends on how you view your foundation of mathematics, and what exactly is the set $X$. In some ways you can arrange that $X\cap\mathcal P(X)=X$, or at least is non-empty; and in other ways you can arrange that it is not the case.
Comment: I'm having a really difficult time conceptualizing $X \in P(X)$, other than when $X$ is the empty set. I take it these are rather strange sets?
Comment: @Jonathan: ***Every*** set is an element of its power set.
Comment: Sorry, I mean $X \subseteq P(X)$. If $X \cap P(X) = X$, then I must have $X \subseteq P(X)$ and $X \subseteq X$ (given).
Comment: Every ordinal satisfies that property. $\{\varnothing\}$, and $\{\varnothing,\{\varnothing\}\}$ and $\{\varnothing,\{\varnothing\},\{\varnothing,\{\varnothing\}\}\}$, and other ordinals. In general, if $X$ is a transitive set ($X\subseteq\mathcal P(X)$), then $X\cup\{X\}$ and $\mathcal P(X)$ are both transitive sets as well. And the union of transitive sets is also a transitive set. This means that in some sense "most" sets are transitive.
Answer: The powerset of $X$ intersects $X$ only when some member of $X$ is also a subset of $X$.
If $X=\{a,b,c\}$ then its power set is $\{\{\}, \{a\}, \{b\}, \{c\},\{a,b\},\{a,c\},\{b,c\},\{a,b,c\}\}$.
If $X=\{a,b,c,\{a,b\}\}$ then $\{a,b\}$ is both a member and a subset of $X$ and thus $X$ and the powerset of $X$ have one member in common --- they intersect.
Comment: What does the first computation of the power set of $X$ tells us? What if $b=\{a\}$ and $c=\{a,b\}$? What if $a=\{\}$? And what if $c=\{b\}$?
Comment: @AsafKaragila : If you want to get into things like that, then what it tells us is that any of several things can happen.
Answer: It depends.
For "normal" sets, this intersection will be empty, so in general, your second thought is the correct one.
However, if we have something like:
$X = \{1,2,3, \{2,3\}\}$ then intersecting $X$ with its own power set will actually have an element - $\{2,3\}$
The distinction to be made here is subsets vs elements.
Answer: Define a set X={a,b,c} having 3 elements(let).
So, power set of X={{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c},{}}, [i.e it has 2^(3)=8 elements.]
So, X AND P(X) means the common part in 'X' & p(X)
So, X intersection/and P(X)={}

What is $X\cap\mathcal P(X)$?


Raspberry pi wifi hotspot in nodejs configuration

Question: I need some help on my project with Rpi.

The RPi should create wifi network
This network is not connected to the internet
This network should redirect the users to a local nodejs website
All of this need to be launched on reboot

For 1 & 2.  I have found This tutorial  but as I reboot

It create the wifi hotspot (good)
I lose ethernet connection for ssh access (bad)
to the pi
AND if i try to connect with my Android phone, the IP configuration failed. (bad++)

For 3. i have seen this about iptables.
For 4. "sudo update-rc.d node path/to/index.js" should do the trick, I think.
For your understanding, I use :

Raspberry Pi 3B
RASPBIAN STRETCH LITE Version: March 2018, Release date:2018-03-13, Kernel version:4.9

Can you help me to configure this hotspot ?
Answer: Take a look into how https://github.com/sabhiram/raspberry-wifi-conf has implemented their access point; it includes a lightweight webserver page that can be accessed through the access point and a startup script for launching at boot.
The library is specifically for connecting a pi to wifi through an 'ad-hoc' style network (like a lot of IoT devices do these days) but could be adapted to whatever you had in mind. Nodejs based.
Comment: You are a life saver ! THANKS !


Why constructor is used instead of functions?

Question: This is a very basic question, I searched it but i just want to ask this community that we have both constructors and methods. But normally we use constructor to initialize the variables instead of the methods. I think that both can be used to initialize variables. So what is the basic difference between both. Is there any solid reason?
this is a very basic question so bear it for sake of beginner level.
thanks in advance..
Answer: The most important difference: When you instantiate an object it's constructor will be invoked whereas calling a method is always optional. You therefore might forget to call your initialization method and fail to initialize everything correctly.
For example, all these normal ways of instantiating an object will call the constructor
Foo* p = new Foo();
Foo p;

Or if you have mandatory arguments, don't define a default constructor and instead require construction with parameters:
class Foo
{
private:
   Foo();
public:
   Foo(int param1, double param2)
};

This has the advantage of requiring the arguments before you even instantiate the class. So you're forced to do:
Foo* p = new Foo(1, 5.0);

and failing to construct with valid arguments becomes a compiler error:
Foo* p = new Foo(); // compiler error

So whenever possible, always err on the side of doing your initialization in a constructor. There are a few cases where a constructor might not be viable. For example, the only way to fail a constructor is by using an exception. The failure to construct may be "routine" and not truly exceptional. Also exceptions might be expensive on some architectures. Another case might be when you want to ensure that virtual methods are fully bound, which is guaranteed to be true only after construction.
Comment: Actually i am asking the initialization with some values demanded by user, let's suppose that for simulation purpose we have to initialize about 20 variables to the given values. If i initialize each variable correctly then in this case will you stick to your argument?
Comment: @kashmirilegion see my edits. If you need to initialize 20 variables you can either define a constructor that takes 20 variables or one that takes a struct.
Answer: They can't both be used to initialize member variables.  It is the job of the constructor to initialize members, and it is called automatically whenever you create a new instance.
Consider the following:
class Foo {
public:
    // Constructor
    Foo() : x(53)   // Initialise x
    {}

    void bar() {
        x = 42;     // Error, attempt to *assign* a const member!
    }

private:
    const int x;
};

Without the constructor, there would be no way to initialise member x.
Comment: Which is all well and good until you need to return an error code at runtime. :P
Comment: +1 for your good answer. thank you your argument gave strength to mind to make a clear way about constructors.
Answer: Constructors are called automatically, so there's no need to worry whether the user has invoked an initialization method yet. However, the Google style guide does have something to say about constructors:

There is no easy way for constructors to signal errors, short of using exceptions.
If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state.
If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion.
If someone creates a global variable of this type, the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code.

Google's recommendation is to have straightforward initiation in a constructor, and non-trivial initiation in a separate method.
Comment: Which is all well and good, unless you're a fan of immutable objects.
Comment: The main argument for following Google's C++ style guide seems to be the Big Name. I totally dislike their view on (not) using exceptions. If you don't use exceptions, you're using a very C-like style of C++. A well known C++ expert once said: http://www2.research.att.com/~bs/3rd_safe0.html

To answer your bulleted list:

(1) then just use exceptions (you just found out that there essential for using constructors/RAII)
(2) again, you won't have an invalid object if you throw an exception
(3) I agree, some nasty problems can arise, the compiler should warn you.
(4) so, no code in constructors?
Answer: The constructor is invoked automatically when you create the object unlike a function. Also, the constructor is used to indicate the intent that this is for the initialization of the object.
Answer: Imagine you have a member variable that has no empty constructor. Then you have no other option but to initialize it in the initializer list of your constructor.
Also the constructor is called when you allocate an array with the new operator, while initialization with methods will make the code way more complicated.
In general having complex logic in the constructor is not very good idea, but simple initialization should be done there(the things you need to do to ensure that your object is in some valid state).
Answer: Initializing variables is no doubt, a very important programming practice. when using classes, the option is to initialize them inside methods. Thus, we have two steps:-

Define the method
Call the method to perform the initialization

But if the 'calling of method' is forgotten, variables end up having junk values. To make life easier for the programmer, concept of a constructor method was brought in.
With Constructors, we just have one step:-
Define the constructor
The 'calling part' is performed automatically whenever a new Object of the class is created.
Answer: Constructors can be used for efficient memory management, which is not possible with functions.
Destructor can be used to destroy the constructors when not needed.
Moreover, the use of copy constructor is known to prevent difficulties or errors due to memory mis happenings.


The fraction of k-juntas with low influences in all of the coordinates

Question: Let $f:\{-1,1\}^n\to\{-1,1\}$ be a boolean function.
Define the influence of the $i$'th coordinate of $f$ as follows:
$$\operatorname{Inf}_i(f)=\Pr_{x}[f(x)\neq f(\hat x_i)]$$
where $x$ is uniformly picked from $\{-1,1\}^n$, and $\hat x_i$ is $x$ with its $i$'th coordinate flipped (e.g., say $x=(1,1,1,1,-1)$, then $\hat x_3=(1,1,-1,1,-1)$).
Denote by $J_k$ the set of all the k-juntas for which the influencing variables are the first $k$ variables. That is, for each $f\in J_k$, the function $f$ is a boolean function that holds $Inf_i(f)>0$ for $1\leq i\leq k$ and $Inf_i(f)=0$ for $i>k$.
Let $0\leq \epsilon \leq 1$. What is the probability (over uniformly selecting such a k-junta) that the influence in each influencing coordinate of the junta will be less than $\epsilon$ ? Formally:
$$\Pr_{f\in J_k}[\forall i\quad Inf_i(f)< \epsilon]=?$$
Comment: Why do you even mention the remaining $n-k$ variables? If I understand the problem correctly, they don't change the influences, and the question is equivalent to simply asking about the probability of a random function of $k$ coordinates having all $k$ influences below $\epsilon$?
Comment: @joriki Just for clarity. It is indeed equivalent to asking about the probability of a random function of k coordinates having all $k$ influences below $\epsilon$.
Comment: After playing with some examples, I tend to believe that the probability for each coordinate behaves like a binomial R.V. up to normalization. That is, for every $i$ holds $\Pr_{f\in J_k}[Inf_i(f)<\epsilon]=\Pr[\frac{B(2^{k-1},0.5)}{2^{k-1}}<\epsilon]$. But I can't seem to prove it.
Answer: I'm afraid the marginal distribution for the influence of a single coordinate is the easier part :-) I gave up on this problem because the interrelations between the influences of different coordinates seem too complicated. But if you're interested in the marginal distribution, here's why it's binomial: A given influence for the $i$-th coordinate corresponds to a given number $m$ of pairs of points differing only in the $i$-th coordinate that have different function values. There are $2^{k-1}\choose m$ different ways of choosing the remaining $k-1$ coordinates for these $m$ pairs. For each pair with different function values, there are $2$ possibilities, $(-1,1)$ and $(1,-1)$, and for each pair with the same function values, there are also $2$ possibilities, $(-1,-1)$ and $(1,1)$. Thus the factor $2^{2^{k-1}}$ arising from these possibilities is independent of $m$ and cancels out in the probabilities, which are therefore completely determined by the number $2^{k-1}\choose m$ of choices for the coordinates for the pairs.
Here's another idea I tried: We can write the influence of the $i$-th coordinate as
$$\operatorname{Inf}_i(f)=\Pr_{x}[f(x)\neq f(\hat x_i)]=\frac{1-2^{-n}\sum_xf(x)f(\hat x_i)}2\;.$$
With the Walsh–Fourier transform of $f$,
$$f(x)=\sum_j a_jf_j(x)\;,$$
this becomes
$$
\begin{align}
\operatorname{Inf}_i(f)
&=\frac{1-2^{-n}\sum_x(\sum_j a_jf_j(x))(\sum_{j'} a_{j'}f_{j'}(\hat x_i))}2\\
&=\frac{1-2^{-n}\sum_j\sum_{j'}a_ja_{j'}\sum_xf_j(x)f_{j'}(\hat x_i)}2\\
&=\frac{1-2^{-n}\sum_j\sum_{j'}a_ja_{j'}\sum_xf_j(x)(\pm f_{j'}(x))}2\\
&=\frac{1-\sum_j(\pm a_j^2)}2\;,\\
\end{align}
$$
where the sign depends on whether $f_j$ changes sign with $x_i$.
Unfortunately I think this doesn't get us much closer to solving the problem, because although the $a_j$ are linearly uncorrelated, they're not independent and their squares are highly correlated.
Comment: Thanks for the explanation of the marginal distribution ! I actually tried something very similar to your Fourier approach, but I keep getting stuck. Do you think that finding a (somewhat) tight bound might be significantly easier ?
Comment: @Tom: I don't know -- I don't have any idea how to find one -- it all seems rather complicated.


What can cause a Garbage Disposal to trip the breaker besides blockage?

Question: My garbage disposal works intermittently. More often than not there is a few seconds of high pitched whine before the breaker trips. About one time in ten, it works correctly.
There is no blockage and it spins freely with the key inserted in the bottom.
Time to go shopping for a new one?
Bonus question: would it be easy enough to install myself?
Answer: Well, I have to admit I am not a Garbage Disposal Expert, but if the key turns freely and it is tripping the breaker, then I would think it is time to go shopping.
Is it easy to install? That's pretty subjective and depends on your skills. But, in general, they are not difficult for someone who is use to doing DIY stuff around the house, especially if you are replacing it with the same or very similar model. Find a brand that you are interested in (In-Sink-Erator is pretty common, but by no means the only one), then go out to their web site and download the instructions and evaluate it for yourself.
One word of caution if you try to do it yourself. Do you have a dishwasher? If so, you will see a hose from the dishwasher going into the side of the disposal. On a new disposal the assumption is you don't have a dishwasher and this tube is sealed! If have a dishwasher and you don't open it your dishwasher will back up. Also, after you knock out the seal, remember to remove it from the inside of the disposal since it is hard plastic.
Comment: great answer Jim. The plug in the disposals is a gotcha!
Comment: I'm pretty sure that my dishwasher drain goes to an outlet above the sink - not the garbage disposal - but I'll check tomorrow. Thanks for the tip!
Comment: @Kevin-"to an outlet *above* the sink". That would be unusual. Please double check. Without seeing it, I am guessing you are referring to a "dishwasher air gap" (do a web search for a picture). And if that is what it is, then it will come back down to the disposal. It's code in some areas. The concern (from what I understand) is that if the sink backs up with sewage, then the dishwasher will not fill with sewage since the air gap is above the level of the sink (in other words, it will be on your floor before it goes in to the dishwasher).


how can i grep something out of a list

Question: How can i grep, sed, cut, xargs or awk the output of lspci
I'm looking to get the latency time, the name of the device and the number on the left, whatever that is
I've tried
lspci -vv | egrep latency | awk '{print $6,$7}'

but It show other Information with It that I'm not Interested in
 00:16.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller (prog-if 10 [OHCI])
 Subsystem: Dell SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
 Flags: bus master, 66MHz, medium devsel, latency 32, IRQ 18, NUMA node 0
 Memory at feb05000 (32-bit, non-prefetchable) [size=4K]
 Kernel driver in use: ohci-pci
 Kernel modules: ohci_pci

 00:16.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller (prog-if 20 [EHCI])
 Subsystem: Dell SB7x0/SB8x0/SB9x0 USB EHCI Controller
 Flags: bus master, 66MHz, medium devsel, latency 32, IRQ 17, NUMA node 0
 Memory at feb04000 (32-bit, non-prefetchable) [size=256]
 Capabilities: [c0] Power Management version 2
 Capabilities: [e4] Debug port: BAR=1 offset=00e0
 Kernel driver in use: ehci-pci
 Kernel modules: ehci_pci

Answer: How about this?
lspci -vv  | grep -e ':'[0-9] -e "Latency"

how can i grep something out of a list


.removeClass() jQuery adds the removed class instantly

Question: I'm having a issue here: http://jsfiddle.net/wkCV6/
When i click the contacto button it is ok and it opens properly. But when I click on volver, it removes the classes and  immediately adds it again. I noticed this, when I put some alerts between the execution.
You can see it in my jsfiddle.
Here is the JS I'm using.
$(function () {
    $("div.arrastre").on("click", function () {
        $(this).find("div.bloque").addClass("rotated");
        var esto = $(this);
        setTimeout(function () {
            esto.find("div.bloque div.back").addClass("agrandar");
            esto.addClass("agrandar")
        }, 100);
    });
});

$(function () {
    $("div#volver").on("click", function () {
        var esto = $(this);
        setTimeout(function () {
            esto.closest("div.bloque").removeClass("rotated");
            if (esto.closest("div.back").hasClass("agrandar")) {
                esto.closest("div.back").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en back ");
            };

            if (esto.closest("div.arrastre").hasClass("agrandar")) {
                esto.closest("div.arrastre").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en arrastre");
            };
        }, 100);
    });
});

Answer: When you click div#volver, the click event is dispatched and bubbles up to the document, triggering on every ancester.
You trigger the call back that you first set on div.arrastre because it's a parent of #volver.
setTimeout is called, causing the class to be added 100ms after the click on #volver.
To prevent a click event from bubbling, you can just return false; in the set callback or stopPropagation :
$("div#volver").on("click",function(event){
    // your code
    event.stopPropagation();
    return false;
}

Working fiddle
Answer: Solution http://jsfiddle.net/2S34N/
Note: code acting funny because of the event aligned :) I have added new settimeout also jsut for a precaution sake e.preventDefault().
hope htis fits the need :)
Code
//CAJAS DE CLICK

$(function () {
    $("div.arrastre").on("click", function (e) {
        e.preventDefault();
        $(this).find("div.bloque").addClass("rotated");
        var esto = $(this);
        setTimeout(function () {
            esto.find("div.bloque div.back").addClass("agrandar");
            esto.addClass("agrandar")
        }, 100);
    });
});

$(function () {
    $("div#volver").on("click", function (e) {
        e.preventDefault();
        var esto = $(this);
        setTimeout(function () {
            esto.closest("div.bloque").removeClass("rotated");
            if (esto.closest("div.back").hasClass("agrandar")) {
                esto.closest("div.back").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en back ");
            };

            if (esto.closest("div.arrastre").hasClass("agrandar")) {
                esto.closest("div.arrastre").removeClass("agrandar");
                alert("se supone que quité la clase agrandar en arrastre");
            };
        }, 200);
    });
});


inox browser: build and patch chromium from source

Question: I recently stumbled over a set of patches for chromium which promise to focus on privacy by disabling data transmission to google. You can read more about it here. It originates from a Archlinux AUR but the pachtes are availabe to download.
I would like to patch Chromium from Source for Ubuntu, but I never did that before. I'm more or less familiar with building from source with config, make & make install, but it seems rather difficult for Chromium. I found some instruction here and here.
Can someone provide a proper step-by-step tutorial on how to build and patch chromium from source?
Answer: (Note that the link to Ubuntu's instructions for building Chromium appears to be heavily outdated.)
Disclaimer: I'm the maintainer of the Chromium Beta and Dev PPAs.
If you run apt-get source chromium-browser, you'll get the source code for the current stable version of Chromium that's in the repos along with the patches that Ubuntu applies on top of Chromium (which are in the debian/patches folder). You can add additional patches to be applied to Chromium here, but note that some of the patches you add may conflict or be the same as the patches Ubuntu uses. Also, update the series file, which describes what patches to apply and in what order.
The build script is at debian/rules. It's quite long, but the most important variable you'll probably be interested in is GYP_DEFINES, which is where you would specify the build flags to build Chromium with. For example, if you wanted to build Chromium with enable_google_now=0, then add a line saying GYP_DEFINES += enable_google_now=0 (you can add it around the other lines starting with GYP_DEFINES). Note that some build flags on that page conflict with the build flags Ubuntu uses (I know enable_webrtc is set to 1 in debian/rules).
As for building it, the simplest way would probably be to run dpkg-buildpackage -b from the chromium-browser-* directory. This will apply the patches, run through the debian/rules file, and then make several deb files. If there are build dependencies missing, it should notify you of those and stop the build. You can then install those deb files.
Note that building Chromium takes about 4-5 hours on a 4-core machine and takes about 15 GB of space (with debugging symbols included). Without debugging symbols (if you comment out the line that adds the -g flag), I'd estimate that it would take about 7-8 GB of space.
Comment: There is now a github project which does what I was heading for. https://github.com/Eloston/ungoogled-chromium


how can the empty set ∅ and {ϵ} be considered regular languages? (automaton)

Question: On an NFA, how can the empty set ∅ and {ϵ} be considered regular languages? Does it make sense that a machine that accepts no symbols or a machine that takes the empty symbol exist? I could think of a machine (laptop) that is in off mode, where no entries (symbols) are accepted, but, is that of interest? or could it still be considered as a machine? the same model could apply for a rock for example.
thanks!
Comment: Brain's answer is a good one. I would like to make the following point: You ask, "could it still be considered as a machine?". We are not talking about machines at all. Finite automata are formal mathematical objects.
Answer: We will play a game. There is a machine with buttons and a green lamp. Your job is to press the right sequence of buttons that make the green lamp light up.
For example, perhaps the machine has only one button, labeled a. When you press it, the lamp lights up!  Then you press the button again and the lamp turns off. Then you press a third time and the lamp turns on again. You find that pressing the button always turns the lamp on if it was off, and off if it was on. To light up the lamp and win the game all you need to do is press the button an odd number of times. We say that the machine accepts the language a(aa)*, which is a regular expression that represents the set of all strings of as of odd length—all the possible winning sequences of button presses.
Now imagine an even simpler machine: the green lamp is already lit! And there is a sign over the button that says DON'T PRESS THE BUTTON. Indeed, if you do press the button the lamp goes off and no amount of pressing makes it turn on again. Don't you wish you had followed the sign's advice? This machine accepts only the string $\epsilon$, which is the string of zero button presses. The regular expression $\epsilon$ represents the set that contains this one string and nothing else.
Now imagine the simplest machine of all: the green lamp never lights up no matter what buttons you press. Here you can't win the game. The set of strings accepted by the machine is empty, which we write $\varnothing$.
Answer: Let $M$ be a machine with any alphabet, one state, $q_0$, that is the initial state, and no transitions. If $q_0$ is not an acceptor state, $M$ accepts $\varnothing$, and if $q_0$ is an acceptor state, $M$ accepts $\Sigma^*$, where $\Sigma$ is the alphabet.
Now let $M$ have any alphabet and two states, the initial state $q_0$ and one other state $q_1$; $q_0$ is an acceptor state, and $q_1$ is not. The transitions are simple: in state $q_0$ every input sends $M$ to $q_1$, and in $q_1$ every input also sends $M$ to $q_1$. This $M$ accepts the empty word and nothing else.


What is the correct way to use RequestScoped Bean and rendered attribute?

Question: does anybody know how to use RequestScoped bean together with rendered attribute in jsf? The rendered attribute is evaluated before applyValues phase and therefore is not correctly evaluated. I don't want to preserve any state. The example could be an outputPanel with a datatable and a button. The datatable gets a list of values. The wrapping outputPanel has the rendered attribute like:

        ...

After loading the page and clicking on the button, nothing happens, because the view is restored and expressions are evaluated - the bean does have an empty datalist and therefore the panel should not be rendered. This causes that the action method is not even called - because the button doesn't exist.
Comment: This is not the first time that one has to remove [java] tag from your [jsf] question. Can you please take that as a hint to not add the [java] tag to a future [jsf] question anymore? Thank you :)
Answer: If you're not interested in having a filled data table at that moment, just add an extra check in rendered attribute if the command button of interest has been invoked. You can do that by checking the presence of button's client ID in request parameter map.

    ...

See also:

How to let validation depend on the pressed button?
Comment: Don't use a stateful view then. Conditionally show/hide at client level. E.g. `` with `.hidden { display: none; }`.
Comment: Yes. This does the trick. But on a page with more controls this would get pretty huge and unreadeable, not to mention hard to maintain. Isn't it then a rule that properties of RequestScoped beans should never be used in rendered, disabled, etc... attributes?
Comment: Nope, it's part of JSF's safeguard against tampered requests. The technical correct solution is using a view scoped bean instead of a request scoped bean.
Comment: What is then the correct way to have a search page with search results that I don't want to ever expire? I mean, to have search results displayed somewhere and update a block of page on click on one of the results. I don't need to preserve the list of results anywhere on server, they are displayed just once. And on click on one of them I would like to load additional info and show in a different block of a page.


How do I redirect 'stdout' to 'stderr' and 'stderr' to 'stdout'?

Question: I want to redirect everything that is supposed to go to stdout to stderr, and everything that is going to stderr to go to stdout instead.
The following code does not work:
$ bin/stdout-test 1>&2 2>&1

I'm sure there is a practical use for this somewhere out there, but currently it's just a mental exercise to help learn and understand io redirection.
In Ubuntu, both stdout and stderr get redirected to the console anyway, so you can't really tell if you are making any progress, but the command tcpserver will redirect stdout to the connecting remote user, and stderr to the terminal that started the tcpserver session, making it a perfect place to test this type of redirection.
I created a test project just for this purpose:

GitHub: IQAndreas-testprojects/stdout-stderr-testing
Answer: Your attempt does not work because 1>&2 merges stdout into stderr, and after that there is no hope of ever separating them again.  You need a third temporary file descriptor to do the swap, like when swapping the values of two variables.
Use exec to move file descriptors.
( exec 3>&1- 1>&2- 2>&3- ; bin/stdout-test )

or just
bin/stdout-test 3>&1- 1>&2- 2>&3-

Explanation:

3>&1- moves stdout (FD 1) to FD 3
1>&2- moves stderr (FD 2) to FD 1
2>&3- moves FD 3 to stderr (FD 2)

See Moving File Descriptors.
Comment: FYI: This does not generally work in POSIX shells. The moving of FDs is a bash extension.


Kubuntu 18.04 Redshift Control Plasmoid has no effect

Question: I added Redshift Control Plasmoid, added some settings, but nothing happens. Running redshift from command line changes colort temperature, but plasmoid always shows 6500K. However mouse wheel up/down changes this value.
Here is screenshots of plasmoid settings:

What am I missing? Forums say that nothing else has to be done.
Comment: UPD: this happens on laptop Lenovo x260 with two external monitors. However, when I use only built-in monitor, redshift widget works as expected.
Answer: Finally, I solved it by removing plasmoid and starting redshift from a script (KDE built-in autostart):
<code>andreyv@desktop-99:~$ cat ./redshift.sh
/usr/bin/redshift -v 2>&1 | tee /home/andreyv/log/redshift.log &

andreyv@desktop-99:~$ cat ./.config/redshift.conf
[redshift]
temp-day=6500
temp-night=4000
transition=0
gamma=1.0
location-provider=manual

[manual]
lat=56.0
lon=60.0
</code>


Options after completing Borderlands

Question:
Possible Duplicate:
Start another Borderlands playthrough

I'm about to finish my first playthrough of Borderlands. Apparently I'll be given the choice of restarting the game with the same character (playthrough 2), or continuing on playthrough 1. If I choose to continue, can I start playthrough 2 at any time? How would I do so?
Also, I haven't yet decided whether to get any DLC yet, but if I did I would like to be able to play it straight away. Do you have to be a certain level for any of the DLC? As far as the DLC is concerned, would I be better off in Playthrough 1 or 2?
Comment: As far as DLC, I seem to remember Zombie Island requiring about low 50's level, And General Knoxx closer to 60, otherwise they didn't scale really well if you were a lower level. I may be off on the numbers, hence, just the comment (and it could be because I was terrible and played the game solo)
Comment: LOL Doozer. I probably depends on which class you're playing and how you build them. I played through as Brick, soloing all the DLC from about lvl 40-ish (i think). Playing as Lilith would be harder (i imagine)...
Comment: I read that other question before posting this one, it asks what happens when you start P2, whereas I wanted to know if/how I could start P2 despite continuing with P1. I didn't know I could switch between playthroughs at will, and now I do.
Answer: So, playthroughs first. Once you have completed the game once, when you load a character you are given the option of going to Playthrough 1 (the one you just finished) or Playthrough 2 (a new game, same character).
As for the DLC, I got it all with the GOTY edition, and then played it straight through after finishing the base game. You should only need to have finished the game once (depending, of course, on how many side missions etc you have completed).
Answer: You can keep using your character to play either playthrough at any time. The advantage to playing playthrough #2 is that you get more challenge, more XP, better guns, and you get to do all the quests again. However, you can still run around in playthrough #1 if you prefer, basically killing everything without much difficulty *cough***Crawmerax***cough* and finishing up side quests.
Comment: Isn't Crawmerax still level 61 in playthrough #1?
Comment: Not sure, I just meant that he would _not_ be part of the 'killing everything without much difficulty' list :)

Options after completing Borderlands


What is the best way to integrate Angular2 with Salesforce?

Question: I'm a salesforce developer and I wonder what is the best way to integrate Angular2 with Salesforce. So far I did some work using gulp and webpack, but I wonder if there is a better way.
Answer: There are a lot of tutorials how to use Angular2 and Salesforce together, for instance:

Angular 2 with VisualForce
Sample Application with Angular 2 and Salesforce REST Services

Maybe you have some specific question related to this topic?


Keeping Records That Are Not Joined MYSQL

Question: I have the following query in my application:
SELECT
p.old_product_id,
l.product_id,
p.sku,
p.title,
p.option_one,
p.option_two,
FROM
lookup_id l
JOIN temp_price_tables_data p USING (sku);

And it works great. However, a small percentage of records from the temp_price_tables_data tables don't make it to the results.
This is because the skus from the lookup_id table don't exist in the temp_price_tables_data.
Is there a way to keep these records in the new data?
Or is there a way to only get those records so I can store the result for later processing?
EDIT:
First table columns = old_product_id, sku, title, option_one, option_two
Second table column = product_id, sku
Tables should have SKU in common.
Comment: `LEFT JOIN`/`RIGHT JOIN`
Comment: What is "the new data"?
Answer: Use a left outer join:
SELECT
*
FROM
lookup_id l
LEFT OUTER JOIN price_tables_data p on l.sku = p.sku
WHERE old_product_id IS NULL;

That will get you all the records that are in temp_price_tables_data but not in lookup_id
Comment: Unfortunately, the tables do not both have the product_id field so this didn't work, I've added the columns in the OP
Comment: I've got it, thanks to your help, I'll edit your answer with changed solution for this situation, thanks :)
Comment: I see. I didn't realize that. Thanks for editing. (I initially rejected the edit - I didn't know it was you. But now I changed it back to your edit).


How to plot mean of observations grouped by more than one column using ggplot?

Question: Say I have a dataframe:
date ID times value
1   B048669    1    41
2   B048669    1    29
3   B048669    1    37
4   B048669    1    31
5   B048669    1    NA
6   B048669    1    23
1  Y2929021    1    43
2  Y2929021    1    10
3  Y2929021    1    NA
4  Y2929021    1    NA
5  Y2929021    1    29
6  Y2929021    1    NA
1  Y2929021    2    43
2  Y2929021    2    NA
3  Y2929021    2    15
4  Y2929021    2    3
5  Y2929021    2    29
6  Y2929021    2    NA

I want to calculate the mean of each day grouped by ID&times.Then x = date, y = value.
So the first point is x=1,y=(41+43+43)/3, the second point is x=2,y=(29+10+NA)/2
Comment: From your example output I don't see how `ID` and `times` matter at all? `DF %>% group_by(date) %>% summarise(x=date, y =mean(value, na.rm =TRUE))`
Comment: @StephenHenderson You are right, I made a mistake.
Answer: You should use the package dplyr to aggregate the data and ggplot2 to plot it (from the tidyverse). It's worth reading up on the tidyverse in general because it has incredibly powerful and easy to use packages. Assuming your data is in a dataframe df:
require(dplyr)
require(ggplot2)

aggregated_df <-
  df %>%
  group_by(date) %>%
  summarize(value = mean(value,na.rm=TRUE))

ggplot(aggregated_df, aes(x = date, y = value)) + geom_col()

The default plot is not particularly attractive, but you can modify the style to your heart's content:
Answer: You may want to calculate the mean before calling ggplot.
Using dplyr:
df <- df %>%
    group_by(ID, times) %>%
    summarize(mean = mean(value))

Then call ggplot plot with mapping aes(y = median) and whatever aesthetics you want to map ID and times to.
Comment: this doesn't produce the output described above. Not clear whether the example data or description is flawed though.
Comment: Sorry, I made a mistake. The answer I want is above, thanks tho!


UseExceptionHandler is not working with ExceptionHandlingPath

Question: In an Asp.Net Core Mvc app using .Net Core 3.0, I am trying to set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.
If I use:
public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler("/Error/Show");
    ...
}

The Error controller show Action never gets hit, neither does the Error controller constructor.
If I change the code to:
public void Configure(
        IApplicationBuilder app,
        IWebHostEnvironment env,
        ILoggerFactory loggerFactory,
        IDataAccess dataAccess,
        IHttpContextAccessor httpContextAccessor)
{
    app.UseExceptionHandler(new ExceptionHandlerOptions
    {
        ExceptionHandler = async context =>
        {
            await context.Response.WriteAsync(Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                title = "An Error Occurred",
                message = "The error was caught by UseExceptionHandler"
            }));
        }
    });
    ...
}

The expected response is returned, but I'd really like to use the ExceptionHandlingPath so that I can return json if the request was made using ajax and a razor view if the request was a standard Get.
I also tried using:
app.UseExceptionHandler(new ExceptionHandlerOptions
{
    ExceptionHandlingPath = "/Error/Show"
});

but this behaves the same as app.UseExceptionHandler("/Error/Show")
Any ideas why ExceptionHandlingPath wouldn't work, but ExceptionHandler would work as expected?
Answer:
set up global exception handling using app.UseExceptionHandler("/Error/Show"), but the Error controller is never hit.

I did a test with using same code to configure a custom error handling page, like below, which works as expected.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseExceptionHandler("/Error/Show");

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");

    });
}

Error controller and Show action
public class ErrorController : Controller
{
    public IActionResult Show()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Test Result

To troubleshot the issue, please try:
1) make sure you create corresponding "/Error/Show" controller action and view
2) check if you enabled the Developer Exception Page app.UseDeveloperExceptionPage();
3) check if you add other middlewares/filters, which cause the issue.
Comment: I have verified all of those things, I'll try upgrading to the latest .net core and see if that has any effect.
Comment: @FeiHan, for step #2 listed above, should the developer exception page be enabled or disabled?  You may want to clarify this for readers.
Answer: It turns out the issue was that attempting to inject the IExceptionHandlerPathFeature into the Error Controller caused the ExceptionHandler to fail silently. After removing the IExceptionHandlerPathFeature parameter from the Error Controller constructor, the handler started working as expected.
public async Task<IActionResult> Show()
{
  var exceptionHandlerPathFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
}

Comment: I ended up having the same issue, Controller with the endpoints for UseExceptionHandler was failing silently trying to inject an object.


C programming, variable changing value when it shouldn't

Question: I'm using Code-blocks and I found one of the variables is changing to a different variable's value, when I don't expect it to. If I declare goal on a different line it fixes the issue. But would like to understand how these addresses overlap.
Is this a common bug in C language? Or problem with my device?
#include <stdio.h>

int main() {
    int i, n, goal, num[2], sum;
    printf("Input n: "); scanf("%d", &n);

    for (i = 1; i <= n; i++) {
        scanf("%d %d %d %d", &goal, &num[0], &num[1], &num[2]); //obtain integers
        if (num[0] != num[1] && num[1] != num[2] && num[2] != num[0]) { //check if all are unique.
            sum = num[0] + num[1] + num[2];
            if (goal == sum)
                printf("Proper triplet");
            else
                printf("Not a good triplet");
        } else
            printf("Not a good triplet");
        printf("\n");
    }
}

I then printf at every opportunity and goal takes on num[2] value. Declaring goal with another int fixes it. Bring goal behind num[2] also fixes it. Is there some obvious reason that I should know causing this?
#include <stdio.h>

int main() {
    int i, n, goal, sum, num[2];

    printf("Input n: "); scanf("%d", &n);

    for (i = 1; i <= n; i++) {
        scanf("%d %d %d %d", &goal, &num[0], &num[1], &num[2]); //obtain integers
        printf("%d %d %d", num[0], num[1], num[2]); printf("\n\n");

        printf("%d", goal); printf("\n\n");

        if (num[0] != num[1] && num[1] != num[2] && num[2] != num[0]) { //check if all are unique.
            sum = num[0] + num[1] + num[2];
            if (goal == sum)
                printf("Proper triplet");
            else
                printf("Not b good triplet %d %d", goal, sum);
        } else
            printf("Not a good triplet");
        printf("\n");
    }
}

Comment: `int num[2]` allocates an array of size 2, but you are using it like it has a size of 3.
Comment: Enable higher warning level. GCC produces a warning about `#[2]`
Answer: The code has undefined behavior because there is no entry num[2] in the array num defined as int num[2].  An array with a length of 2 only has 2 entries: num[0] and num[1].
When you write to num[2], you write beyond the end of the array and it happens that goal is at the memory location just after the end of the num array. This explains the aliasing side effect you observe.  Yet the behavior is undefined so anything else can happen and if you just move the definition of goal in the source code, the behavior does change.  All this is circumstantial and unpredictable, and not necessarily reproducible.
Define num with a length of 3 to fix the problem.
Answer:
it will not work even though logic is correct

The logic is not correct; it has undefined behavior. 2 is not a valid index for num, so you are indexing outside the bounds of the array.
Answer: Looks like your issue is that declaring an array in C declares the size, not the max index.
int num[2];
declares an array of size 2, which only allows access via num[0] and num[1], num[2] is "undefined", and is writing to memory outside of the num declared space.
this error should go away if you using int num[3], which has 3 entries, so you can use num[2].