What cardinals do we actually need?

Question: I recently heard of a great variant of set theory called "Pocket Set Theory" in which the only two cardinalities are that of $\mathbb N$ and that of $\mathbb R$  (and the latter is a proper class). Now clearly this theory doesn't have anything close to the expressive power of full ZFC, and an attempt to formulate a large part of mainstream math on its terms would probably be somewhat impossible. However, this made me wonder how much we'd miss by restricting our attention to small cardinalities like this.
What are examples of constructions, objects, and theorems outside of set theory (and closely related fields) where cardinals other than these two (so even something that's provably $\aleph_1$ without appealing to CH) appear naturally?
Pocket Set Theory on Wikipedia.
Comment: We use $\omega_1$ to construct the Borel sets (or any other $\sigma$-algebra) internally, rather than just "smallest $\sigma$-algebra containing the intervals". The internal construction allows us to understand the structure of Borel sets better, and prove more theorems about it.
Comment: You [might also](http://math.stackexchange.com/q/154234/622) be [interested](http://math.stackexchange.com/q/10096/622) in these [links](http://math.stackexchange.com/q/79346/622) on the site. Also [this](http://math.stackexchange.com/q/407564/622).
Answer: Without $\aleph_1$ you will miss the internal construction of the Borel sets. This means that you will have a much harder time to prove that there are only continuum Borel sets; and you will not be able to construct a hierarchy of Borel functions which itself has similar structure which allows us to prove theorems about it.
You will also miss the construction of an Aronszajn tree, and Suslin trees which means that you will not be able to ask whether or not a dense linear order without endpoints which is c.c.c. and order complete is necessarily $\Bbb R$ or not.
You will have troubles understanding what are uncountable Whitehead groups, or use other theorems which are seemingly not about set theory, but their proofs employ deep set theoretical instruments.
Similarly you will not be able to prove Borel determinacy (which requires $\beth_{\omega_1}$ to exist), which again brings us to natural questions on Borel sets.
Another thing you might miss the the ability to compute the global dimension of a countable product of fields, since the value seems to have intrinsic connection to the value of the continuum as an $\aleph$ number. Similarly you won't be able to talk about outer automorphisms of the Calkin algebra, since their existence may also be depending on whether or not $2^{\aleph_0}=\aleph_1$ (meaning that we make use of an object of size $\aleph_1$ in the proofs).
There are many other surprising connections that pop up once you start talking about uncountable objects, and more specifically uncountably generated objects. But it is true, that $\aleph_1$ is not something that meet every day in "usual mathematics". And that's why people would be surprised to see it popping up here and there.
The question is what exactly do you want to do when you say "mathematics". If you just want to talk about classical analysis, sure you can probably go your whole life without seeing $\aleph_1$ being used explicitly. You can probably go most of your life without hearing the term "a well-ordering of the continuum" either. But both terms can appear a lot if you are willing to advance beyond 19th century and early 20th century mathematics. Since we have started talking about arbitrarily large objects (even when we are interested in smaller ones), we have involved set theoretical assumptions about the structure of sets, and more importantly their power sets, into the discussion.
Pocket set theory is very cute, and very nice. And sure it can probably talk about basic analysis and second-order number theory. But modern mathematics is a lot more, even if you don't peak behind the curtain to see where uncountable cardinals get into the picture.

Some links to read when you're bored:

Can we distinguish $\aleph_0$ from $\aleph_1$ in Nature?
Proofs given in undergrad degree that need Continuum hypothesis?
Examples of sets whose cardinalities are $\aleph_{n}$, or any large cardinal. (not assuming GCH)
What happens after the cardinality $\mathfrak{c}$?
Comment: [On global dimension](http://mathoverflow.net/questions/68436/what-the-heck-is-the-continuum-hypothesis-doing-in-weibels-homological-algebra); [Whitehead problem](http://en.wikipedia.org/wiki/Whitehead_problem); and [Calkin algebras](http://www.math.cmu.edu/~pmckenne/research/preprints/outer.pdf).
Comment: Thanks a lot for the great answer! I'm going to leave the question open to see if anyone else comes up with cool examples. I'm familiar with the descriptive set theory type examples you listed (trees and Borel sets), but I haven't heard much about Whitehead groups, the dimension of a countable product of fields or the Calkin algebra. Could you link me to a reference about any of these in the context of set theory? Ideally, I'm looking for examples away from things like abstract topology and descriptive set theory and more towards algebra, geometry, analysis, etc.

What cardinals do we actually need?


Needing guidance on making a simple daemon for unity notifications in a python app

Question: I am making an app using pygtk, glade, and quickly and want to make a daemon that runs in the background to provide unity notifications for alarms and events. I would like to find a way to not require root authentication after installing the *deb file. I have tried adding a script to the users crontab but it seems that would require the restart of crond. (which needs either root or a reboot) I was wondering if there was a project I should look at to see an example of a daemon in python or how I could go about this? Thank you in advance for any help and feel free to tell me I'm wrong!
Answer: Daemons are usually run by root (although they sometimes change the user under they run).
For a normal notification you don't need to create a daemon, just create a normal program and let it run at the start of a session. This way it will run with user privileges, and you will run a separate instance for each user.
I have done this program, it's a bit more complex than what you need, as it uses different libraries to run in different systems but it is quite simple and maybe a good example.
Comment: I want to clarify, you are using `gobject.timeout_add(interval, callback, ...)` to check the alarm at a regular interval, aren't you? Does this function do checking in the main loop (*busy waiting* rather than idle)?
Comment: Yes, the gtk version is using gobject.timeout. I don't understand what you mean with checking in the main loop, but anyway it doesn't do any kind of busy waiting.


Not able to write on ApplicationData folder

Question: I wrote a little Logger class that help me to create a log file with all application exception, actually I though to save this log inside the ApplicationData, so I've created a simple class:
public class Logger
{

    private static string _appDataPath =
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

    private static string _logPath = _appDataPath + "\\MyApp\\Log";

    public static void log(string lines)
    {
        if (!File.Exists(_logPath))
        {
            Directory.CreateDirectory(_logPath);
        }

        using (StreamWriter file = new StreamWriter(_logPath))
        {
            file.WriteLine(lines);
            file.Close();
        };
    }
}

So how you can see I'm using the Roaming folder inside user AppData, when I call: Logger.log("some exception message"); I get on this line:
using (StreamWriter file = new StreamWriter(_logPath))

this exception:

System.UnauthorizedAccessException

Maybe I need to set some permission to the folder? Or I can't access properly to this path? Thanks.
Comment: you want file inside log folder or you want log to be the name of your file?
Comment: I need a log folder inside MyApp folder
Answer: Your code creates a folder named
%APPDATA%\MyApp\Log
Of course, being this a folder and not a file, the StreamWriter cannot write to a folder
Change your code to add a filename to the folder
if (!Directory.Exists(_logPath))
{
    Directory.CreateDirectory(_logPath);
}
string logFile = Path.Combine(_logPath, "myApp.Log");
using (StreamWriter file = new StreamWriter(logFile, true))
{
    file.WriteLine(lines);
    file.Close();
};

Answer: Your _logPath variable points to the directory you want so you should be checking for its existence using Directory.Exists instead of File.Exists.
Also, you need to specify the path upto the file that you want to create and not just upto the directory. So, in my sample code, I've declared variable _logFileName which specifies the name of log file to be created.
This is what your class needs to look like:
public class Logger
{
    private static string _appDataPath =
    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

    private static string _logPath = _appDataPath + "\\MyApp\\Log";
    private static string _logFileName = "logfile.txt";

    public static void log(string lines)
    {
        if (!Directory.Exists(_logPath))
        {
            Directory.CreateDirectory(_logPath);
        }

        using (StreamWriter file = new StreamWriter(Path.Combine(_logPath, _logFileName)))
        {
            file.WriteLine(lines);
            file.Close();
        };
    }
}


order multiple rides with Lyft API?

Question: I have a client that needs to be able order multiple rides for their customers. Is there any component of the API that would allow their single business appID to order, and pay for, these types of rides? Sometimes they would need to order two or three rides at once or have rides overlap each other.
Using a single user/token (similar to the Lyft app itself) doesn't work because once a ride is in progress that token is not usable again until the 1st ride is over.
Answer: Lyft does have a set of APIs they call Concierge APIs. It's basically an API for booking rides on behalf of someone such as a call center agent getting a Lyft for a customer.
The APIs allow a single token to book multiple rides. It's worth noting that a given passenger name + phone number is considered a unique user and cannot have multiple rides booked, if that's what you're looking for.
You'll need to reach out to Lyft to get access to the APIs and documentation.

order multiple rides with Lyft API?


Is a new StringBuffer object created when the StringBuffer goes out of capacity or it remains still the old one?

Question: Is a new StringBuffer object created when the StringBuffer goes out of capacity or it remains still the old one?
class Test{
public static void main(String[] args) {
    StringBuffer sb = new StringBuffer();
    StringBuffer sb2 = sb;
    System.out.println(sb.capacity());
    sb.append("abcdefghijklmnop");
    System.out.println(sb.capacity());
    sb.append("q");
    System.out.println(sb.capacity());
    System.out.println(sb == sb2);
 }
}

input: deep (master *) LanguagePackageInJava $ javac Lecture7.java
deep (master *) LanguagePackageInJava $ java Test
output: 16
16
34
true
In the above piece of code, I have tried to create a StringBuffer object sb and copied its reference to another StringBuffer object sb2 when the StringBuffer sb was empty. I have tried to overflow the capacity of sb and then tried out whether a new object has been created or not by comparing sb2 with sb. But it returns true. I suppose no object has been created. But I am not pretty sure about it even after going through the documentation. Any help would be appreciated!
Answer: The line
StringBuffer sb2 = sb;

doesn't create a copy of the sb object.  It only creates another reference to the same object.  Now you have two StringBuffer references to the same StringBuffer object.
sb  -------> StringBuffer
          /
sb2 ------

If you overflow the capacity of a StringBuffer, it will reallocate an internal buffer for the contents.
sb  -------> StringBuffer ----XXXXXXX"abcdefghijklmnop"
          /                  \
sb2 ------                    ------>"abcdefghijklmnopq"

The internal array used as a buffer for the contents will be a new object created.  The old buffer will be garbage collected eventually.
However, the StringBuffer object itself is not replaced.  When you append something to a StringBuffer, it always returns a reference to itself.  You're ignoring it, but even if you reassigned the return value back to sb, it's still referring to the same object.
Also, you can replace StringBuffer with StringBuilder and the rest of the above would not change.
Comment: yes I should have stored the return of the append function and then compare it with sb..I did it ...still it gives the same object
Answer: Obviously, it remains the same. First, you compare sb and sb2, and they are the same, and second, you do not do any assignment to sb, so it only can be the same as before.


What is lambda functions type? C++

Question: See my code:
#include <iostream>
#include <typeinfo>

int main() {
    auto x = [](int a, int b) -> bool{return a<b;};
    std::cout<<typeid(decltype(x)).name()<<std::endl;
}

And this is printing Z4mainEUliiE_. Can anyone explain whay? And what is the actual type of x??
Comment: It's `decltype(x)`. Why do you need to know?
Comment: It *is* printing the type...
Comment: Note that if you make a second lambda taking `(int,int)`, its name will be `Z4mainEUliiE0_`, regardless of return type or body code (assuming Linux/gcc). Similarly, third will get `1` instead of `0`, ...
Answer: The actual type of a lambda is specified as a "unique closure type" that corresponds to the lambda expression.
Its name isn't specified. Its layout even isn't fully specified. It's almost entirely an implementation defined type, of a name one usually doesn't know nor care about.
And when you think about it, you (the developer) don't really need to know what its "actual name" is. You can refer to it just fine:
using my_lambda_type = decltype(x);

There's another aspect to your question, that beyond the closure type being implementation defined, the behavior of std::type_info::name is itself implementation defined. You are printing an implementation defined name for an implementation defined type via an entirely implementation defined mechanism.
There's very little you can glean (C++-wise) from it other than details about your current compiler implementation.

What is lambda functions type? C++


Python: Alternatives to pickling a module

Question: I am working on my program, GarlicSim, in which a user creates a simulation, then he is able to manipulate it as he desires, and then he can save it to file.
I recently tried implementing the saving feature. The natural thing that occured to me is to pickle the Project object, which contains the entire simulation.
Problem is, the Project object also includes a module-- That is the "simulation package", which is a package/module that contains several critical objects, mostly functions, that define the simulation. I need to save them together with the simulation, but it seems that it is impossible to pickle a module, as I witnessed when I tried to pickle the Project object and an exception was raised.
What would be a good way to work around that limitation?
(I should also note that the simulation package gets imported dynamically in the program.)
Answer: If the project somehow has a reference to a module with stuff you need, it sounds like you might want to refactor the use of that module into a class within the module. This is often better anyway, because the use of a module for stuff smells of a big fat global. In my experience, such an application structure will only lead to trouble.
(Of course the quick way out is to save the module's dict instead of the module itself.)
Comment: Modules aren't intended to have state.  Classes are intended to have state.  Saving an object saves the state of a class.  That's the way it's supposed to work.  You "wrap" your complex simulation in a **Facade** class that encapsulates the whole simulation and can be persisted as a "single" thing.  With lots of other objects inside it.
Comment: You mean, instead of referencing to the dynamically-imported module, to reference to a class defined inside the dynamically-imported module?
Comment: Yes; instantiating a class dynamically seems cleaner than importing a module dynamically.
Comment: That's interesting. But I think it's a bit problematic. The way my program works is that the user chooses which simulation package to import. That is, there are pre-written simulation packages for different types of simulation (e.g. one for Newtonian physics, one for game theory...). Do you suggest I just define one class inside these pre-written packages and have all the objects be attributes of it?
Comment: That sounds like one way to go, but it's hard to say without knowing more about how your package fits together exactly. If you want to change the least amount of code, you could just have a single class with a well-known name (e.g. the same name in each module) in the different packages and still do the dynamic import dance.
Answer: If you have the original code for the simulation package modules, which I presume are dynamically generated, then I would suggest serializing that and reconstructing the modules when loaded. You would do this in the Project.__getstate__() and Project.__setstate__() methods.


Detect Mousedown Event in Angularjs

Question: I know how to detect mousedown event on a directive that is clicked. However my directive also needs to become unforcused or deselected when mouse is down outside of my directive/ element. How can I do this?
Answer: Create a link function in the directive which binds a mousedown event handler on the document. Then, bind another mousedown event on the directive element itself. The latter handler should also call event.stopPropagation() to prevent the event from bubbling all of the way up to the document level:
link: function(scope, elem, attrs){
  angular.element(document).bind('mousedown', function(){
    console.log('clicked on document');
  });

  elem.bind('mousedown', function(e){
    e.stopPropagation();
    console.log('clicked on directive');
  });
}

Working Plunker
Comment: will this automatically $apply() as well?

Detect Mousedown Event in Angularjs


Protocol Buffer: How to define Date type?

Question: I'm trynig to write a proto file that has a Date field which is not defined as a type into Protocol buffer.
I have read the following post but I couldn't figure out a proper solution that suits me :
What the best ways to use decimals and datetimes with protocol buffers?.
I'm trying to convert the proto file to a java .
Answer: My answer in the linked post relates mainly to protobuf-net; however, since you are coming at this from java I would recommend: keep it simple.
For dates, I would suggest just using the time (perhaps milliseconds) into an epoch (1 Jan 1970 is traditional). For times, just the size in that same unit (milliseconds etc). For decimal, maybe use fixed point simply by scaling - so maybe treat 1.05 as the long 1050 and assert always exactly 3dp (hence fixed point).
This is simple and pragmatic, and covers most common scenarios without making things complicated.
Comment: @ticktock either should be fine
Comment: Thx ... I 've followed ur advice and make the Date fields to be represented as "int64" into proto file and I would convert it to Date into my java class.
Comment: That is what I normally do also, just store millis since unix epoch.
Comment: Do you recommend int64 or fixed64?
Answer: I'm not sold on this idea, but I'm really not sold on the idea of storing dates (which aren't instants in time) as a timestamp, so here's my suggestion.
Convert your date into a human-readable integer (e.g. 2014-11-3 becomes 20141103) and store this integer value.  It contains exactly the data you need, is simple to create and parse, and takes up minimal space.  Additionally, it is ordered and has a one-to-one mapping of dates to valid values (granted, invalid numbers are possible, such as 20149999, but these are easy to detect).  In contrast, there are approximately 86400 valid timestamps that represent each day.
NB: There is a discussion on DBA SE criticizing this method of date storage, but in that context a specialized date type exists, which obviously isn't the case here.
Comment: I created nimn data format when I was not aware with protobuf, thrift, or avro. And I created a separated lib to [compress dates](https://github.com/nimndata/nimnjs-date-parser) which is more similar to your suggestion.


Run local executable file on remote servers with Capistrano

Question: I have a pretty long .sh file in my Capistrano tools directory that is intended to be executed on servers, not locally. Is there a simple way to execute this file on servers inside a Capistrano task without manually copying it on each server?
Answer: Assuming that the script is in your repository, you can create a custom task which allows you to do exactly that. Something like:
namespace :deploy do

  desc 'Run custom command'
  task :run_custom_command do
    on roles(:app) do
      # Your restart mechanism here, for example:
      execute release_path.join('tools/command.sh')
    end
  end

  before :publishing, :run_custom_command

end


Lenovo X1 Thinkpad battery not charging in 17.04

Question: I have a 8 month old Lenovo X1 Carbon (5th generation) which was originally running 16.04LTS.
When I upgraded to 17.04 I noticed the battery is no longer charging. When the AC is plugged in battery indicator / upower / Power Statistics all show the battery as "charging".
However the battery doesn't charge - it just stays at it's current rate (38%). Using the laptop when it's not plugged into AC just depletes the battery further.
I have tried three different chargers with the same results. I doubt there is any physical issue with the battery as the laptop is relatively new & the issue has only just started after the upgrade to 17.04.
Any help appreciated.
Answer: Same situation here, but my battery died completely and I could not turn laptop on at all. Called Lenovo tech support and their awesome rep (Joshua) instructed me to do a "static reset." Steps are:

Unplug laptop;
insert end of paper clip in small hole on bottom of laptop;
hold for five seconds; let go; plug laptop back in;
hit power/start button.

Worked like a charm! Apparently, electricity builds up inside laptop with nowhere to go. Reset button on bottom releases it so battery can recharge as it should. Thank you, Joshua!
Comment: I'm confirming this approach worked on a five-month old Thinkpad X1 Carbon (6th gen) aka "X1C6".  Symptoms started 10 mins ago w Ubuntu's power notification alternating between "charging" & "not charging" while the LED charging light was dark indicating "not charging". Went from 10% to dead in a few mins. After doing a few rounds of 5-second paper-clip presses in that small hole on the back (could feel a smell "click") eventually I could get the LED light to turn red (indicating charging) and the notebook would boot up. Thank you Marta for sharing this - you spared me lots of time & stress :)
Comment: It worked on my X1 Carbon 7th gen. Thanks a ton!!
Comment: Electricity is not "building up". All modern battery packs contain both cells and control circuitry to manage how cells are charged and discharged  and to protect the cells from damage. What you are doing is resetting that circuitry (which can be thought of as a little computer) so that it allows the cells to be used again.
Comment: Worked on X1 1st. gen. too! Thanks!!
Comment: Worked on X1 carbon gen 7 too :)
Comment: Worked on my Lenovo X1 Carbon 4th Generation in 2021. ❤
Comment: This is also only a [temporary solution](https://askubuntu.com/questions/980490/lenovo-x1-thinkpad-battery-not-charging-in-17-04/1383023#1383023). You'll have to do it again in a few days/weeks.
Comment: Not necessarily, Dan D. I did the "paper-clip reset" over three years ago and haven't needed do it again. And I use my X1 nearly every day, for several hours a day.
Answer: This worked for me:

Shutdown computer
Pressed power button to turn it on & pressed F1 to enter BIOS
In BIOS go "Config" > "Power" > "Turn off Battery"
After computer has turned off I unplugged AC & plugged it back in again.

The laptop is now charging.
Comment: This is only a [temporary solution](https://askubuntu.com/questions/980490/lenovo-x1-thinkpad-battery-not-charging-in-17-04/1383023#1383023) unfortunately.
Comment: @DanDascalescu - I'm sorry to hear you're having issues. I only just retired that (gen 5) X1 after 5 years & never had any issues with the battery after doing this fix.
Answer: This is a long-standing problem that Lenovo hasn't solved in years, and basically ignored. I've been having it with my X1 Carbon 7th gen too. If the other methods don't work, there's a last resort, though temporary:

Open the bottom cover
Disconnect the battery cable
Connect it back.

The battery should resume charging.
This solution is temporary. The battery will get screwed up again within a few days or weeks at most (charge drops to zero, it becomes not detected, says "not charging" even when plugged in etc.).
This trick worked for a few months, but now if I perform it, it no longer helps at all. The battery is always at 0%.
Replacing the battery may help but only for a few months. BIOS updates 1.38 as of Aug 2021 haven't helped as of May 2022.
Another solution, with the same effect, was to let the battery drain completely (make sure to save your work), then reboot. This is useful if you can't unscrew the bottom cover.
One user claims they fixed the problem for a longer term by bending slightly with a fine needle the "3 (out of 7)" [that's wrong, there are 8 wires] inner contacts ("not the red/black power outer conductors") of the battery JST connector. It's not quite clear where you should "clamp"/press.

By slightly bending the metal clips on the connector, especially the inner ones, you are insuring electrical contact of all the wires to the board.  It's hard to say exactly what to do, just take a fine needle and push the metal so that when the connector attaches to the board, you are assured electrical contact.

Another user wrote,

The plastic component that the wires feed into has 2 parts (male / female plastic-y connector pieces). (Don't try to disconnect it).

I manually with my fingers grabbed the top and bottom of that piece (the bottom being the side the wires feed into) and squeezed them together. I also recall taking a very small metal tool and seeing if I could gently / firmly press down on the metal connectors that are exposed on the top of the plastic piece.

Another supports that claim and offers as an alternative fix cleaning the connectors with DeoxIT.
Other users reported that sending in the laptop for repair made the issue recur weekly rather than daily.
The consensus is that the cause is the poor connection of the battery cable to the motherboard.
Affected models:

X1C 4th, 7th and 8th Gen
X1 Yoga

Combined with a few other annoyances (occasionally not resuming from sleep, the touchpad not being detected 4 out of 5 times when booting), I'll never buy an X-series ThinkPad again.


identifier "a" is undefined in c++

Question: I am writing c++ code to implememt universal hash function, but it doesn't recognize the parameters, here is the code:
#include <math.h>
#include <cmath>
#include "hash.h"
#include <iostream>
using namespace std;
#include <string>

HASH::HASH(){
    a=23;
    b=88;
    n=100;
    p=997;
    products=new product[n];
    }

HASH::~HASH(){
    delete []products;

}

HASH::HASH(int aa,int bb,int nn, int pp){
    a=aa;
    b=bb;
    n=nn;
    p=pp;
    products=new product[n];

}

int HF(int key){

    int index;
    int h;

   h=((((a*key)+b)% p)% n);

}

in HF function,it tells me that the parameters a,b,n,p are undefined. I defined them in the header file like this:
class HASH {
private:
    int a,b,n,p;
    product* products;

public:

        HASH();
        HASH(int aa,int bb, int nn, int pp);
        ~HASH();
        bool insert(product s);
        bool retrieve(int id,product &product);
        bool updateName(int id);
        bool updateCost(int id);
        bool updateQuantity(int id);
        bool remove(product &d);
        int getNumberOfProducts();

};
int HF(int key);

Comment: `HF` isn't a part of the class. It has no knowledge of `a`.
Comment: @roa.tah: Did you move the function declaration inside the class, *and* change the name to `HASH::HF` in the definition? If you did all that, then please update your code  so we can see what's still wrong.
Comment: @chris I moved it inside the class and keep getting same error
Comment: @nos what could be wrong??
Comment: @MikeSeymour thnx, I totally forget to add HASH::HF
Answer: First, never define a variable with a single char, that you will use a lot, or in class. If you wanna find it in code, it will be impossible - you will stop one each "a" char. Name it something readable.
Second, HF is not a member of class HASH, it can't see private variables of other classes.

Add to public part of HASH class
int HF(int key);
change procedure to
int HASH::HF(int key){ ...
and it will work
Answer: Add int HF to the public section of your class and in the file hash.cpp use int HASH:HF instead of int hash.
I noticed a small bug: your function HF doesn't return value  - add return statement to HF function.

identifier "a" is undefined in c++


No code completion in EL for Facelets files

Question: I'm using the Eclipse Neon with Maven repos for JSF project with JPA, the controller that I've created is not showing in the auto complete for any tag attributes in Facelets.
For example:

On the "value" should show the autocomplete with the controller that I have, but for some reason is not showing.
But if I type it manually, it works fine when I run on the tomcat server, so its not a problem on the class itself.
I copied everything from my last JSF project, I mean the configurations and the pom.xml and it's working on this one, but not on the new project.
Comment: check if you have all the relevant plugins. Which ones can be found using google
Comment: Hello Kukeltje, thank you for your answer. i'm using exactly the same plugins from my last project that worked fine.
Comment: Ok, sorry, I thought you switched IDE from e.g. Mars to Neon. Then I have no clue other than that maybe some project facets are not enabled now
Comment: The most strange thing is: both projects (the old and the new) are set on my Eclipse workspace, one is working fine, the other one no..
Comment: Facets are turned on/off per project
Comment: Is this helpful? http://stackoverflow.com/q/27505264
Comment: Hello BalusC, thank you for you answer and for editing my question, helped alot. I tried also but still not working, i will create everything from scratch and see if it helps.
Comment: Is your file open with the roght JSF editor from Eclipse Java EE development tools? Try doing a right-click > open with to check that.
Answer: I discovered the reason already.
When you create by Maven like me, you need to go to your Eclipse, RIGHT CLICK on your project > Configure > ADD JSF Capabilities.
Eclipse will create all needed files for auto completition on the facelets files.
Thank you for the help guys!


How to get individual fields from JSON in PHP

Question: My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
 "status":1,
    "list":
        {
         "204216523":
            {"item_id":"204216523",
             "title":"title1",
             "url":"url1",
            },
        "203886655":
            {"item_id":"203886655",
             "title":"titl2",
             "url":"url2",
            }
        },"since":1344188496,
  "complete":1
 }

I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
Comment: [What have you tried?](http://www.whathaveyoutried.com)
Answer: json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
    echo $value['title'].','.$value['url'];
}

Answer: echo $result['list']['204216523']['item_id']; // prints 204216523

Answer: json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.


What is the best way to move this electrical box a few inches?

Question: I need to move an electrical box up about five inches from where it is to mount a light fixture. The wall is drywall covered in plaster. The original box was nailed to a stud. Originally I was going to patch the old location with drywall and install a new plastic electrical box in the correct location. What I'm running into is the old wiring, which isn't Romex but rather cloth wire run via flexible conduit screwed into the old junction box. It's about one inch too short to make the move.
I can get the original conduit installed into a new "old work" metal box, but it won't stretch to the new location. I understand there are couplers to extend the length of the conduit, but the length I need to extend it by is so short I feel it would make fitting it difficult. My initial thought is to simply rerun the wire from the outlet to the switch with Romex so I can clamp it into a new box and not worry about the conduit, but I'm no expert at this and don't know if there's an easier way.
Thanks for any advice!
EDIT: @ThreePhaseEel pointed out that this may actually be BX wire, not simple flex conduit, which I imagine changes things up.
Comment: Are you in Chicagoland, NYC, or a high-rise building?
Comment: Would using a **larger box** allow you to connect the wire but still have box at the new location? you can get covers to reduce the opening on a larger box to suit a smaller device, but without knowing the details of your move it's hard to say for sure what would work.
Comment: @ThreePhaseEel: No, this is a standalone home in Minneapolis.
Comment: @Ecnerwal: I like the thought but can't visualize a way to get it to work. The box needs to move upwards about five inches, the conduit comes in from the lower left of the box and is at its limit in the current location.
Comment: If it's in conduit, **it's for a reason**. How about sticking a 5" EMT extension on it? Obviously if you're moving it 5" away from where it was, a 5" extension will work fine.
Comment: Where does the conduit run lead to?  And are you sure it's an actual *conduit* and not a metal-armored cable? (pro tip: if there's paper around the wires, its BX, not a conduit job)
Comment: @ThreePhaseEel: as far as I know the conduit runs to the switch. There's no paper around the wires. I'm no electrician but I'm pretty sure it's not BX.
Comment: @ThreePhaseEel: Oh, I take that back! I've never thought it was BX because of how some of the house is wired, but checking out the lines from the basement and poking around the internet show that this might indeed be an armored sheath cable.
Comment: @RogerWilco if there's no paper fillers at either end, then it's not BX.  (It's very hard to tell AC/BX from MC from FMC without looking inside boxes, BTW.)
Comment: It's black and white wires (no specific ground) in rubber insulators covered in a cloth wrapping.
Comment: @RogerWilco -- no paper wrapping around those wires, though?
Comment: @ThreePhaseEel: I added a photo to show the wiring in the box. I've never seen paper wrapping in any of the original wiring, but after reading your comment I looked it up and BX wiring was common here around the time the house was built (1940).
Comment: Yeah, that looks like old-school cloth wiring in FMC, not BX/AC....
Answer: If you don't object to having a junction box cover below your new light fixture, consider leaving the original box right where it is. Install the new box above it, and connect the two boxes with a short conduit nipple in a pair of knockouts that line up (or if there's a bit more space than shown, use an offset nipple if that helps to line things up.)
Wire as needed, put a plain cover on the original box and the light fixture on the new box.
If going with the conduit extension approach, consider an FMC to EMT transition rather than FMC to rigid - a 90 degree EMT bend would do the job nicely from the new box to where the FMC ends, and in general EMT is a lot cheaper than rigid (or flex) even comparing a 4 inch nipple to having to buy a 10 foot stick (though by the time you put connectors on the ends you are closer to the same price, but you have more than 9 feet of EMT left for your next project...
If you don't have a bender or a friend you can borrow one from, you can find pre-bent EMT sweeps to purchase, though they may cost more than 10 feet of straight EMT.
Comment: FMC-EMT sounds like the way to go, thank you!
Answer: I know that it is frustrating to work with a wiring method of which you are unfamiliar, and the temptation is to "run home to momma". However, changing wiring methods midstream can open up a lot of complications, and force you to deal with even more unfamiliar things, and can also lead to really bad workmanship due to unexpected situations you don't know and don't have any prototype to model from.
So let's stick to conduit wiring method, and just cheat ourselves the 5".
I gather this uses a common 1/2" knockout?
Get two 1/2" rigid conduit nuts.  They're like a nickel.  And you'll already have one from the other fitting.

Get a 4" stick of Rigid conduit, pre-threaded (called a "nipple").

Now, get a coupling.

Remove the "nut" from the old fitting.  Screw the old fitting onto the coupler. Screw the 4" Rigid nipple into the coupler.   Now you have a ~5" extension on the flexible conduit.
Take one conduit nut, and run it down the Rigid thread as far as it will go.  Farther the better.
Stick it through the knockout hole in the junction box.   Use the other conduit nut to run down the threads.   Use a screwdriver and hammer to bap the castellations to tighten it.
Effectively the junction box will be clamped between the two conduit nuts.
Comment: I would use an actual FMC-to-rigid coupling (such things exist!) vs. threading a FMC fitting into a RMC-RMC coupling (nobody's paid UL to test FMC fittings for being threaded into couplings, for the most part)
Comment: @ThreePhaseEel Oh, even better... I just went with easiest to find.
Comment: I like this idea a lot but the conduit still wouldn't reach because of the geometry (I added a photo above which hopefully makes sense). That said, I could add a rigid conduit extension from the bottom of the new box and elbow it left toward the original flex? The only major thing from stopping me from trying this elbow with a few couplers and more flex is the cost of a reel of flex conduit.


How do I safely restart TortoiseSVN?

Question: It's not obvious to me..
Answer: If you do kill TSVNCache, you don't need to manually restart it, the shell-extension will do that next time it needs it.
If you're trying to restart the shell-extension, you might achieve it by killing all Explorer.exe processes, and anything else which has ended-up with TSVN in-process.  This is basically any app which has asked the shell about icons, or has used the common file/directory dialogs.   You may need to use something like "Process Explorer" (sysinternals) to find which processes have the TSVN DLLs loaded.
Answer: If you don't see the TortoiseSVN icons anymore you can restart TSVNCache.exe by navigating to TortoiseSVN's bin directory, e.g. C:\Program Files\TortoiseSVN\bin, and double clicking on it. Note that if you restart it in this way it will be killed when you logout. Otherwise follow the suggestions from the other answers.
Answer: The background process that watches your file system for SVN related files and folders is TSVNCache.exe. You can kill that process and start it again, or just reboot your machine :)

How do I safely restart TortoiseSVN?


Suppose that $d,\, m > 1$, and that $d|m$. Let $a,\,b \in\mathbb{ Z}$, prove that if $a \cong b (mod\,m)$ then $a \cong b (mod\,d)$.

Question: The only sense I can make of this question is that $m = dq$ and $a \cong b (mod\,m)$ is the same as $as+mt=b$, or $as+(dq)t=b$. I feel as though proving that this holds since $m$ is just a multiple of $d$ is not enough.
Any help is appreciated.
Comment: Why is it not enough?
Comment: $s$ doesn't happen to be 1 ?
Comment: My understanding of this is shaky at best, so maybe it is enough to prove this, but I don't see how $a \cong b$ for the modulo of some number still holds for a divisor of that number.
Answer: As $a \equiv b (\mod m)$, so $m$ divides $a-b$, by definition.
Now as $d$ divides $m$ and as $m$ divides $a-b$, so $d$ too divides $a-b$, and hence
$a \equiv b (\mod d)$, as required.
Answer: $$a\equiv b\bmod m\implies a=mx+b\implies a-b=mx$$
and
$$a-b=mx\land m=de\implies a-b=dex$$


Update Stripe Payment Amount

Question: I'm attempting to have two stripe payment amounts on a one page application. The user has 5 minutes to purchase the item at a sale price. I then need to be able to update the price to a different amount. I tried to simply create two stripe forms but you're not able to have more than one on a page per my understanding. How would I go about doing this?
My stripe set-up:
var token = req.body.stripeToken; // Using Express
var charge = stripe.charges.create({
  amount: 749,
  currency: "usd",
  description: "Example charge",
  source: token,

How would I change the "amount?"
Comment: You would create a Checkout experience where you supply the `amount`-argument to Checkout with an outside input, then pass that amount to your backend and replace your hardcoded `794` with the value you pass.
Answer: If you had a <input type="hidden" name="chosen_amount" id="chosen_amount" />
And use Javascript to change the value of the hidden field on click of the button then you can access the amount on the backend with var amount = req.body.chose_amount;

Update Stripe Payment Amount


How to get past the stone head in Karthspire?

Question: I'm in a room in Karthspire with this huge head. There aren't any obvious things to trigger except for several plates on the ground about the location where my character is located in the following figure.

Any ideas on how to get past this room?
Answer: The seal on the ground is bound to react to the Dragonborn blood.
It is automatically activated when you step on it if I remember. It is possible thought that you need a specific quest for it. You should be accompanied by Delphine and Esbern at this time. It's part a a quest series to defeat the main opponent. You are going to Sky Haven to learn about history.
Comment: Right, well I don't have either have either with me, so I guess I should go find the quest line to pick them up
Answer: For those that find themselves at this point, and 'guessed' their way through the first bridge puzzle, quickly reload as this creates a serious bug in the game later part of the main quest line.
You will find it to be a royal pain in the butt when the 2 people part of the quest get stuck and just stand there at the first bridge puzzle.
So reload prior to solving this puzzle if possible.
Answer: For most of the puzzles the guy accompanying you says most of the answers, so listen carefully. When you are with them in the room, I had to activate something on that stone tablet you stand on.
Comment: Welcome to Arqade! You are answering a question that already had an accepted answer two years ago. This question probably doesn't need another answer--perhaps look at some more recent questions or use the 'Unanswered' tab at the top of the page to find questions that haven't yet been answered.


AS3: ExternalInterface.addCallback return false

Question: This is my problem when working with flash - as3:
I have the code here and i want to known why it's value is FALSE?
ExternalInterface.call('console.log',"addCallback");
var wasSuccessful:Boolean = ExternalInterface.addCallback("playMusic", jsPlayMusic);
ExternalInterface.call('console.log',wasSuccessful.toString());

This is result in console:
addCallback
false

Thanks you for help!
Answer: ExternalInterface.addCallback() does not return a status, it returns void. So you are getting false, which is the default value of boolean data type. check this link for details on ExternalInterface.addCallBack method.


Spark submit in IntelliJ of project jar yields Class not found error

Question: I'm doing a basic program of implementing Drools and the program runs on an application configuration but when I try to run the JAR, I face an error.
The error I get on the terminal:
    `Suhita-MacBookPro:Drool-CreditScore-Sample sgoswami$ spark-submit --class main.scala.suhita.Sample --master local[*] target/DroolsMaven-1.0-SNAPSHOT.jar
java.lang.ClassNotFoundException: main.scala.suhita.Sample
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.util.Utils$.classForName(Utils.scala:230)
    at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:712)
    at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:180)
    at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:205)
    at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:119)
    at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)`

Drools-Project
  >src
   >main
    >scala
     >suhita
      - Sample
      - Applicant
   >META-INF
    -kmodule.xml
    -manifest.MF
   >resources.rules
    -rules

Comment: A class is not found in the classpath. Who knows what is going on because you did not provide a [mcve]. Please read [ask].
Answer: Looking at the tree structure of your project
Drools-Project
  >src
   >main
    >scala
     >suhita
      - Sample
      - Applicant

You don't need to provide class name from main as main.scala.suhita.Sample
Simply use suhita.Simple for class name as
spark-submit --class suhita.Sample --master local[*] target/DroolsMaven-1.0-SNAPSHOT.jar

and it should work
Answer: This happens sometime when your classes are not loaded property. I have seen a few times recently. So there are two ways to fix this issue:

Refresh classes that may include sbt clean compile
or you can try reloading idea classes from top menu. It's  very vague to say but sometimes restarting intellij  also works as it reloads all the classes again.

I am sure one the method will work. Let me know if it persists.


Dropdown year list in Laravel not displaying

Question: I want to generate a dropdown list that displays years and so far, here's what I've done. I created a method in my controller below.
namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class RUMSModel extends Model
{
    protected $primaryKey = 'id';
    protected $fillable = [];
    protected $dateFields = [];
    protected $dropdownFields = [];

    public $module_dir = '';
    public $module = '';
    public $importFields = [];

    public static $months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    public function selectYear($name, $startYear, $endYear, $selected = null, $options = array())
    {
        $years = range($startYear, $endYear);
        $years = array_combine($years, $years); // [2013 => 2013]

        return $this->select($name, $years, $selected, $options);
    }
?>

Use it to display in a Blade template:

     Latest Estimate Year:
      <select id="validation-latest_estimate_year" class="form-control" name="latest_estimate_year">
      <option value="">-Select Year-</option>
         @foreach($model->selectYear('year') as $year)
           <option value="{{$year}}" {{$year == $model->latest_estimate_year ? 'selected': ''}}>{{$year}}</option>
         @endforeach
      </select>

However, the dropdown list doesn't display the years. I'm trying to figure out why but I ran out of ideas. Any guidance from the experts would help.
Comment: Show us the full code, where is your `$model` come from? What is `$this->select`?
Comment: hello thanks for taking your time replying. here's the code and ive updated my post.
Comment: where is your controller codes?
Answer: Hello guys thanks for taking your time to answer this post. I found a way to make it work but i dont know if its the most efficient way to do this.
here's what ive done to make it work:

       Latest Estimate Year:
       <select id="validation-latest_estimate_year" class="form-control"
        name="latest_estimate_year">
       <option value="">{{$model->latest_estimate_year}}</option>
         @for ($year = date('Y') + 2; $year < date('Y') + 100; $year++)
            <option value="{{$year}}" {{$year == $model->latest_estimate_year ? 'selected': ''}}>{{$year}}</option>
         @endfor
       </select>

Answer: Why not use selectYear() from the laravelcollective/html package?
Install:
composer require laravelcollective/html

View/Blade:
{!! Form::selectYear('year', 1900, 2019) !!}


Including related data in controller

Question: I have a Details page that displays a report, I now need an index page that displays more than one report. I have set this up with some sucess (I can select checkboxes on a page of users and display some of the information on a 'Print page' but I can't figure out how to display related info.
My details takes in a userid like this -
 public ViewResult Details(string id)
        {
User user = db.Users
                .Include(i => i.UserDetails)
                .Include(i => i.TRS)
                .Include(i => i.Pension)
                .Include(i => i.LifeAssurance)
                .Include(i => i.IncomeProtection)
                .Where(i => i.UserName == id)
                .Single();

string pensionProviderName = providerRepository.GetProviderByID(user.Pension.PensionProviderID).ProviderName;

TRSViewModel viewModel = new TRSViewModel
            {
                UserName = user.UserName,
                FirstName = user.UserDetails.FirstName,
                LastName = user.UserDetails.LastName,
                Salary = user.UserDetails.Salary,
                PensionSchemeName = pensionSchemeName

but in my index I have
public ViewResult Index(FormCollection form)
        {
          string[] UserIDs = form["TRSIDs"].Split(',');

var trs = db.Users
                .Include(t => t.UserDetails)
                .Include(t => t.TRS)
                .Include(t => t.Pension)
                .Where(g => UserIDs.Contains(g.UserName))
                .Select(user => new TRSViewModel
            {
                UserName = user.UserName,
                FirstName = user.UserDetails.FirstName,
                LastName = user.UserDetails.LastName,
                Salary = user.UserDetails.Salary

but I can't figure out how to include the 'PensionSchemeName' details in teh view model. I tried mapping directly using -
PensionSchemeName = db.SchemeNames.Find(user.Pension.PensionSchemeNameID).Name,

but i get an error with that. Any ideas how I can include this?
Answer: You can try to join Users and SchemeNames  manually:
public ViewResult Index(FormCollection form)
{
    string[] UserIDs = form["TRSIDs"].Split(',');

    var trs = db.Users
        .Join(db.SchemeNames,
            user => user.Pension.PensionSchemeNameID,
            schemeName => schemeName.SchemeNameID,
            (user, schemeName) => new { User = user, SchemeName = schemeName })
        .Where(a => UserIDs.Contains(a.User.UserName))
        .Select(a => new TRSViewModel
        {
            UserName = a.User.UserName,
            FirstName = a.User.UserDetails.FirstName,
            LastName = a.User.UserDetails.LastName,
            Salary = a.User.UserDetails.Salary,
            PensionSchemeName = a.SchemeName.Name
        }
    //...
}

I assume that Pension doesn't have a PensionSchemeName navigation property, otherwise it would be more straight-forward:
    var trs = db.Users
        .Where(u => UserIDs.Contains(u.UserName))
        .Select(u => new TRSViewModel
        {
            UserName = u.UserName,
            FirstName = u.UserDetails.FirstName,
            LastName = u.UserDetails.LastName,
            Salary = u.UserDetails.Salary,
            PensionSchemeName = u.Pension.PensionSchemeName.Name
        }

(I have removed the Includes. They are ignored anyway when you use a projection (Select).)

Including related data in controller


Cargo run / start not working, missing Ant dependency?

Question: I've been trying to set up the cargo-maven2 plugin (although I am using Maven 3; and this is supposed to be ok) so that I can start a container during the pre-integration-test phase and shut it down in the post-integration test phase.
I'm having no luck.  I keep getting this error message:
Failed to execute goal org.codehaus.cargo:cargo-maven2-plugin:1.2.4:start (start-container) on project microgivr.web: Execution start-container of goal org.codehaus.cargo:cargo-maven2-plugin:1.2.4:start failed: Unable to load the mojo 'start' in the plugin 'org.codehaus.cargo:cargo-maven2-plugin:1.2.4'. A required class is missing: org/apache/tools/ant/BuildException

Easy fix, right?  Add Ant as a dependency.  So I add:
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.4</version>
</dependency>

(And lord only know why this should need Ant in the first place.)
I can now find org.apache.tools.ant.BuildException on my classpath, but I STILL get this error.
So, thinking this is surely some issue with my own build, I decided to start fresh, using the maven2-cargo-plugin archetype documented here: http://cargo.codehaus.org/Maven2+Archetypes
You know what?  Same problem!
I've tried different versions of the plugin.  I've tried different versions of Ant.  No luck.
Someone MUST have run into this before.  I see mentions of this issue online, but don't see any solutions.
Any insight is appreciated!
Answer: Damnit.  I guess I put the Ant dependency in the wrong spot.  That dependency needs to be expressed in the plugin's OWN  stanza; NOT with the rest of the dependencies.
So... moving it did the trick.
Comment: But still, you'd expect (or at least hope) that this dependency would be documented and that the archetype from the authors of the plugin would get it right.


org.hibernate.MappingException: Could not determine type for: java.util.Set version issue?

Question: Tough i see lot of matching suggestion question, None of the suggestions seem to answer my question. I am newbie to Hibernate and just started with annotation. Slightly comfrtable with XML configuration. I was going through "Harnessing hibernate" and was trying a annotation sample. And when try to run this i am stuck with this exception. My code is here
hibernate.cfg.xml
    <?xml version='1.0' encoding='UTF-8'?>
    <!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

    <hibernate-configuration>

` <session-factory>
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

      <property name="connection.url">jdbc:mysql://localhost:3306/HibernateTest</property>
      <property name="connection.username">root</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.password">root</property>`

    <property name="current_session_context_class">thread</property>

    <property name="connection.pool_size">1</property>
    <property name="hibernate.show_sql">false</property>

    <mapping class="com.home.hibernate.bean.Track"/>
    <mapping class="com.home.hibernate.bean.Album"/>
    <mapping class="com.home.hibernate.bean.AlbumTrack"/>
    <mapping class="com.home.hibernate.bean.Artist"/>
  </session-factory>

</hibernate-configuration>

Track.java
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;

    import org.hibernate.annotations.CollectionOfElements;
    import org.hibernate.annotations.Index;

    @Entity
    @Table(name="TRACK")
    @NamedQueries({
        @NamedQuery(name="queryTest.tracksNoLongerThan",
                query="from Track as track where track.playTime <= :length")
    })
    public class Track  implements java.io.Serializable {

    @Id
    @Column(name="TRACK_ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
     private int id;

    @Column(name="TITLE",nullable=false)
    @Index(name="TRACK_TITLE",columnNames={"TITLE"})
     private String title;

    @Column(nullable=false)
     private String filePath;

    @Temporal(TemporalType.TIME)
     private Date playTime;

    @Temporal(TemporalType.DATE)
     private Date added;

    @ManyToMany
    @JoinTable(name="TRACK_ARTISTS",
            joinColumns={@JoinColumn(name="ARTIST_ID")},
            inverseJoinColumns={@JoinColumn(name="TRACK_ID")})
     private Set<Artist> artists = new HashSet<Artist>(0);
     /**
      * Media on which track was obtained
     */
    @Enumerated(EnumType.STRING)
     private SourceMedia sourceMedia;

     @CollectionOfElements
     @JoinTable(name="TRACK_COMMENTS",
            joinColumns={@JoinColumn(name="TRACK_ID")})
    @Column(name="COMMENT")
     private Set<String> comments = new HashSet<String>(0);
     /**
      * How loud to play
     */
     @Embedded
     @AttributeOverrides({
         @AttributeOverride(name="left", column=@Column(name="VOL_LEFT")),
         @AttributeOverride(name="right", column=@Column(name="VOL_RIGHT"))
     })
     private StereoVolume volume;

    public Track() {
    }

    public Track(String title, String filePath) {
        this.title = title;
        this.filePath = filePath;
    }
    public Track(String title, String filePath, Date playTime, Date added, Set<Artist> artists, SourceMedia sourceMedia, Set<String> comments, StereoVolume volume) {
       this.title = title;
       this.filePath = filePath;
       this.playTime = playTime;
       this.added = added;
       this.artists = artists;
       this.sourceMedia = sourceMedia;
       this.comments = comments;
       this.volume = volume;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }
    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
    public String getFilePath() {
        return this.filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }
    public Date getPlayTime() {
        return this.playTime;
    }

    public void setPlayTime(Date playTime) {
        this.playTime = playTime;
    }
    public Date getAdded() {
        return this.added;
    }

    public void setAdded(Date added) {
        this.added = added;
    }
    public Set<Artist> getArtists() {
        return this.artists;
    }

    public void setArtists(Set<Artist> artists) {
        this.artists = artists;
    }
    /**
     *      * Media on which track was obtained
     */
    public SourceMedia getSourceMedia() {
        return this.sourceMedia;
    }

    public void setSourceMedia(SourceMedia sourceMedia) {
        this.sourceMedia = sourceMedia;
    }
    public Set<String> getComments() {
        return this.comments;
    }

    public void setComments(Set<String> comments) {
        this.comments = comments;
    }
    /**
     *      * How loud to play
     */
    public StereoVolume getVolume() {
        return this.volume;
    }

    public void setVolume(StereoVolume volume) {
        this.volume = volume;
    }

    /**
     * toString
     * @return String
     */
     public String toString() {
      StringBuffer buffer = new StringBuffer();

      buffer.append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).append(" [");
      buffer.append("title").append("='").append(getTitle()).append("' ");
      buffer.append("sourceMedia").append("='").append(getSourceMedia()).append("' ");
      buffer.append("volume").append("='").append(getVolume()).append("' ");
      buffer.append("]");

      return buffer.toString();
     }

}

Build.xml
    <artifact:dependencies pathId="dependency.classpath">
        <dependency groupId="mysql" artifactId="mysql-connector-java"
            version="5.0.5" />

        <dependency groupId="org.hibernate" artifactId="hibernate"
            version="3.2.5.ga">
            <exclusion groupId="javax.transaction" artifactId="jta"></exclusion>
        </dependency>

        <dependency groupId="org.hibernate" artifactId="hibernate-annotations"
                version="3.3.0.ga">
        </dependency>

        <dependency groupId="org.hibernate" artifactId="hibernate-commons-annotations"
                version="3.3.0.ga">
        </dependency>

        <dependency groupId="org.hibernate" artifactId="hibernate-tools"
            version="3.2.0.beta9a" />

        <dependency groupId="org.apache.geronimo.specs" artifactId="geronimo-jta_1.1_spec"
            version="1.1" />
        <dependency groupId="log4j" artifactId="log4j" version="1.2.14" />

    </artifact:dependencies>

This is all the dependencies i have used in the application
And my error trace is
    BUILD FAILED
    D:\Hibernate-SelfStudy\Workspace\HibernateTutorial\build.xml:19: org.hibernate.MappingException: Could not determine type for: java.util.Set, for colu
    mns: [org.hibernate.mapping.Column(comments)]
            at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:266)
            at org.hibernate.mapping.Column.getSqlTypeCode(Column.java:138)
            at org.hibernate.mapping.Column.getSqlType(Column.java:182)
            at org.hibernate.mapping.Table.sqlCreateString(Table.java:394)
            at org.hibernate.cfg.Configuration.generateSchemaCreationScript(Configuration.java:848)
            at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:94)
            at org.hibernate.tool.hbm2ddl.SchemaExport.<init>(SchemaExport.java:61)
            at org.hibernate.tool.ant.Hbm2DDLExporterTask.execute(Hbm2DDLExporterTask.java:45)
            at org.hibernate.tool.ant.HibernateToolTask.execute(HibernateToolTask.java:183)
            at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:601)
            at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
            at org.apache.tools.ant.Task.perform(Task.java:348)
            at org.apache.tools.ant.Target.execute(Target.java:392)
            at org.apache.tools.ant.Target.performTasks(Target.java:413)
            at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
            at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
            at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
            at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
            at org.apache.tools.ant.Main.runBuild(Main.java:811)
            at org.apache.tools.ant.Main.startAnt(Main.java:217)
            at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
            at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

    Total time: 3 seconds

Can anybody please help me out with this
Thanks in advance
Kiran
Answer: Use @ElementCollection  instead of @CollectionOfElements. Its depricated.
Hope it helped :)
Comment: Thanks for the quick response Biman. To get the @ElementAnnotation i changed my refrence in ant to point to the following jar

`
org.apache.geronimo.specs
geronimo-jpa_2.0_spec
1.1

            `

But error i get is still the same :(

Can you please cross check the jars i am using. If everything is fine.
Answer: Sorry For the question. The error was thrown in other class. Where annotation for comments collection was given wrongly.


Fetch line starting with a specific string in powershell

Question: I am executing a command for which I am getting output like below
Identifier:  3    SFP
Connector:   7    LC
Transceiver: 7004404000000000 4,8,16_Gbps M5 sw Short_dist
Encoding:    6    64B66B
Baud Rate:   140  (units 100 megabaud)
Length 9u:   0    (units km)
Length 9u:   0    (units 100 meters)
Length 50u (OM2):  3    (units 10 meters)
Length 50u (OM3):  10   (units 10 meters)
Length 62.5u:0    (units 10 meters)
Length Cu:   0    (units 1 meter)
Vendor OUI:  00:05:1e
Vendor PN:   57-0000088-01
Vendor Rev:  A
Wavelength:  850  (units nm)
Options:     003a Loss_of_Sig,Tx_Fault,Tx_Disable
BR Max:      0
BR Min:      0
Date Code:   180316
DD Type:     0x68
Enh Options: 0xfa
Status/Ctrl: 0xb2
Pwr On Time: 3.52 years (30822 hours)
E-Wrap Control: 0
O-Wrap Control: 0
Alarm flags[0,1] = 0x5, 0x40
Warn Flags[0,1] = 0x5, 0x40
Temperature: 32      Centigrade
Current:     8.082   mAmps
Voltage:     3311.6  mVolts
RX Power:    -5.5    dBm (280.4uW)
TX Power:    -2.8    dBm (523.1 uW)

I need to fetch the last 2 lines only, that is starting with RX and TX out of it.
I was trying like
#$streamOut | Select-String -Pattern "^RX" | select -ExpandProperty line
$streamOut | Select-String -Pattern "RX" | select -ExpandProperty line

This is by code
$session = New-SSHSession -ComputerName $SAN_IP -Credential $cred
$Strem = New-SSHShellStream -SSHSession $Session
$streamOut=@()
$SystemView = $Strem.WriteLine("sfpshow $port_Num")
sleep -Seconds 5
$streamOut = @($Strem.read())
sleep -Seconds 5
$RXTX_Data = @($streamOut | ? { $_ -match "^RX" -or  $_ -match "^TX"})

$RXTX_Data

When I use the below solution in above code, it is returning blank. the $streamOut is array
PS C:\Windows\system32> $streamOut.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

But it is returning the entire output.
Please let me know on this
Comment: `$streamOut | Select-String -Pattern "^(RX|TX)" | Select-Object -ExpandProperty Line` works for me, provided that `$streamOut` is an array of lines, such as from a call to `Get-Content`. Please add the code where you assign `$streamOut`.
Comment: @zett42: I m using Strem to execute the commands and $streamOut is a string. so is there any way to convert that to array or any other approch
Answer: As you clarified, the $streamOut variable contains a single, multiline string.
In this case you can use Select-String with -AllMatches like this:
$RXTX_Data = ($streamOut | Select-String -Pattern '(?m)^(RX|TX).*$' -AllMatches).Matches.Value
$RXTX_Data  # Output array of matching lines

Output:
RX Power:    -5.5    dBm (280.4uW)
TX Power:    -2.8    dBm (523.1 uW)

Note that it is important to use the (?m) inline modifier for multiline mode, which changes behaviour of ^ to anchor beginning of line and $ to anchor end of line, instead of beginning and end of whole input string.
An easier alternative is to split the string into lines first, so you can use the -match operator to filter for matching lines:
$streamLines = $streamOut -split '\r?\n'
$RXTX_Data = $streamLines -match '^(RX|TX)'

This works because -match and other comparison operators act as a filter when the LHS operand is a collection like an array. We don't need multiline mode, because the RegEx gets applied to each array element (line) individually.
The above two lines could even be condensed into a one-liner:
$RXTX_Data = ($streamOut -split '\r?\n') -match '^(RX|TX)'

Comment: Thanks for the response. I am getting the data of RX and TX. need one more help. how to get the numeric value out of it. like from `RX Power:    -5.5    dBm (280.4uW)`  extract `-5.5`
Comment: @EmptyCoder `$rxValue = if('RX Power:    -5.5    dBm (280.4uW)' -match ':\s*(\S+)') { $matches[1] }`
Answer: try this :
$streamOut = Get-Content -Path "Your_Output_FilePath"
$streamOut | ? { $_ -match "^RX" -or  $_ -match "^TX"}

Comment: Nice! Even shorter one: `$streamOut -match '^(RX|TX)'`. This works because `-match` and other [comparison operators](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.2) act as a filter when the LHS operand is an array.
Comment: @Romylussone: one more thing. this solution is working only for object[], not for String.
Comment: @zett42:  one more thing. this solution is working only for object[], not for String.


Get number of days between two Dates excluding weekends

Question: I subtract two dates using below code
Dim OpenDate, ClosedDate As DateTime
dim Result as String
OpenDate = Convert.ToDateTime(some string contain date and time)
ClosedDate = Convert.ToDateTime(some string contain date and time)
Result = ClosedDate.Subtract(OpenDate).ToString

it works fine with correct result in format (day.hour:minute:second )
what i need is
if period between closed and opened date contain Friday or Saturday subtract from result
Ex. if result 9.03:02:10  contain 2 Saturday and Friday it must be 6.03:02:10  and so on
Comment: What are the normal operating hours?
Answer: A naive but readable approach:
Public Shared Function GetBusinessDays(startDay As DateTime, endDay As DateTime) As Integer
    Dim today = Date.Today
    Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday}
    Dim businessDays =
        From d In Enumerable.Range(0, (endDay.Date - startDay.Date).Days + 1)
        Select day = today.AddDays(d)
        Where Not weekend.Contains(day.DayOfWeek)
    Return businessDays.Count()
End Function

Test:
Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9))
Console.Write(days) ' 7

The LINQ query first creates a range of integers from 0 to days (+1 because including last day). Then it creates Date objects via today.AddDays(days). Since weekend is an array of DayOfWeek you can use Enumerable.Contains to take only dates which are not weekend-dates. The last step is to execute the query by using Enumerable.Count to get the number of business days.
You could improve it by providing a ParamArray for the banking-holidays:
Public Shared Function GetBusinessDays(startDay As DateTime, endDay As DateTime, ParamArray bankHoliday As Date()) As Integer
    Dim today = Date.Today
    Dim nonWorkingDays = New HashSet(Of Date)(bankHoliday)
    Dim weekend = {DayOfWeek.Saturday, DayOfWeek.Sunday}
    Dim businessDays =
        From d In Enumerable.Range(0, (endDay - startDay).Days + 1)
        Select day = today.AddDays(d)
        Where Not weekend.Contains(day.DayOfWeek) AndAlso Not nonWorkingDays.Contains(day)
    Return businessDays.Count()
End Function

That works as it is even if you don't have bank holiday days. If you have one or multiple you can either pass a real array as argument or single objects like here for christmas:
Dim christmas = New Date(2014, 12, 25)
Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9), christmas)

or few single objects:
Dim christmasEve = New Date(2014, 12, 24)
Dim days As Int32 = GetBusinessDays(Date.Now, Date.Now.AddDays(9), christmasEve, christmas)

Answer: It should really be:
Select day = startDay.AddDays(d)

As the startday of the range specified may not always be today.
Comment: For everybody who is confused by this answer, this should be more like a comment on the answer by @tim-schmelter


Can I access a variable's type for generic programming?

Question: If I have code such as:
std::wstring s(L"...");
bool allCharsEqual =
        std::find_if(s.begin(),
                     s.end(),
                     std::bind1st(std::not_equal_to<std::wstring::value_type>(),
                                  mystring[0]))  // ^^^^^^^^^^^^^^^^^^^^^^^^
        == s.end();

I would like to have a generic expression in the marked location which would also work if I changed the variable type to std::string. Is this possible?
I realize I could put this in an extra function and template it with the string type, but is there another way?
Answer: You can use decltype in C++11:
std::not_equal_to<decltype(s)::value_type>()

Or in C++14 you can use transparent comparators and just skip the template argument entirely:
std::not_equal_to<>()

If you're stuck with C++03, you could make a typedef so that you only have a single place you need to update to change types. This is good practice in general if you can't use auto and have types which you forsee changing.
typedef std::wstring str_t

Answer: I think decltype is what your are looking for.
Since decltype is only available in C++11, maybe making your code a template would help if you have to code pre-11
template <typename STRING_TYPE>
bool allCharsEqual(STRING_TYPE s){
    /* ... */
}


How to install this cheap metal curtain rod?

Question: I bought one of these cheap curtain rods for my home theatre blackout curtains:

But it doesn't appear to have come with any instructions. I mean it appears that I'm supposed to just screw those little hook ends into the wall and then set the rod upon the hooks. But this strikes me as odd for a couple reasons:

The hook itself is pretty long, and the end of the rod (as you can see in the picture) is curved anyway, so it seems the rod will hang way far out from the window when installed. I could perhaps find some shorter hooks.
It doesn't look like it can hold a lot of weight. In fact it doesn't even look like it can hold even the weight of the curtains (which are pretty heavyweight being blackout curtains).

To further complicate things, my apartment uses metal studs, not wooden ones, and they're a major pain to drill through. Moreover, there is basically a 4-inch section of wall on either side of the window where the rod pretty much needs to attach to, and I don't know if there's a stud there or if it's just drywall (haven't checked with my studfinder yet).
The window takes up pretty much the entire wall, and is about 10' across, minus the few inches on either side already mentioned. So in theory I could install the curtain rod onto the side walls, though I don't think this particular model would work very well (perhaps a tension rod would have been a better idea--do they come in 120" long versions?).
In short, is there any way I can install this in such a way that it will support the weight of my curtains? Will I need to buy some different hardware (if so, what kind of things will I need)?
Comment: I would expect there to be brackets to hold the ends of the rod, and they hooks are to be used periodically along the length of the rod for extra support in the middle.  But that's a guess.
Comment: Ah, that makes a heck of a lot more sense!
Answer: You're not showing all the pieces. What we see is a curtain rod and the center support.
There are brackets for the end that the rod hooks over.
Pictured is a dual curtain rod hanger bracket. The hole in the rod catches on the tang and it drops down onto the bracket.
The answer to your problem might be shown in the picture, use a nice board that spans across the window opening about six inches above. Use screws to hold it to the studs and then mount the curtain to that using stronger screws than came in the hardware pack. Graininess of the cellphone picture doesn't do the spar varnish finish on the hemlock board any justice.
For spanning that window (10') there are heavy-duty three piece curtain rods constructed exactly like these but with two of the screw-in supports available in addition to the end brackets.
Comment: You're right. I went back and noticed the two small brackets I had missed before. They quite clearly attach the the ends after all. Thanks!


How to build CMake documentation with Sphinx?

Question: After checking out the CMake sources, I configured and build CMake successfully. But how do I build CMake's documentation? I have Sphinx installed.
There is no target like make doc and it is not obvious where I have to call which Sphinx command. I didn't find any hint in the CMake Wiki or their mailinglist archives.
Comment: If you are using CMake to build CMake you need to set the `BUILD_DOCUMENTATION` variable to `TRUE`. Check `cmake-gui` or `ccmake`. Also, I will vote to close this question since it is very narrow and should rather be asked on the CMake mailing list.
Comment: This question appears to be off-topic because it is about the build system of the CMake project and too narrow for StackOverflow
Answer: Recently I found the answer [1]

Configure CMake with -DSPHINX_HTML=ON.  Be sure you have python-sphinx
  installed.  Point SPHINX_EXECUTABLE at the sphinx-build command if
  needed.

Run make. The documentation is built in directory Utilities/Sphinx/html.
[1] Written by the CMake developer Brad King at the CMake developer mailing list, https://cmake.org/pipermail/cmake-developers/2015-September/026567.html.
Comment: Thanks. Just wanted to add that the resulting/new build target that is added is named `documentation` and the result is outputted to `Utilities/Sphinx/html` directory relative to your binary output directory.


Ubuntu 14.04 workspace switch hotkeys

Question: I upgraded my Ubuntu from 12.04 to 14.04 and hotkeys for switching workspaces (Ctrl + Alt + arrow keys) are not working anymore.
I checked in System Settings > Keyboard > Shortcuts to make sure that they're assigned and they are, but why they are not working? How can I fix this problem?
Comment: possible duplicate of [How do I turn on workspaces? (Why do I only have one workspace?)](http://askubuntu.com/questions/260510/how-do-i-turn-on-workspaces-why-do-i-only-have-one-workspace)
Comment: nope, workspaces are already enabled, just hotkeys are not working.
Comment: If this was an upgrade the number of workspaces should have remained the same, I believe.
Answer: I found the solution myself. It seems that I needed to enable Desktop Wall plugin in Compiz; just apt-get install compizconfig-settings-manager, run ccsm and search for "wall" to find the option.
Comment: [This answer](http://askubuntu.com/questions/26628/cant-switch-workspaces/26671#26671) provides additional details which eventually helped me resolve this.
Comment: how do you do that exactly can you please share details?
Comment: same happened to me in ubuntu 16.04 and this solution solved it. thanks
Answer: This has broken for me a couple times now in Ubuntu; most recently after going from 12.04LTS to 14.04LTS (in place upgrade).

System Settings... (gear at top of screen)
Appearance
Behavior Tab
Check box for Enable workspaces

Screen grab of configuration setting for workspaces:
Answer: Run these two commands:
sudo apt-get install ubuntu-desktop
sudo apt-get install unity

Reboot your system
And after than try Ctrl + Alt + arrow keys.
You will able to switch between workspaces.
Comment: unfortunately doesn't work for me :( I'm able to switch between 1 and 2 while cannot go to 3 and 4 via 1 and 2. In other words I'm able to switch horizontal between 1 and 2, 3 and 4 while I'm not able to switch between 1 and 3, 2 and 4 :(

Ubuntu 14.04 workspace switch hotkeys


Display base64 image with Deno's Oak package

Question: I've got a base64 encoded image stored in my database, so the start looks like this data:image/png;base64,iVB.. and I return it from the database at my 'image' endpoint.
I could of course just fetch the content using JavaScript and include the base64 string as img source and it would render just fine, but I also want to be able to view the image when I go to the endpoint with my browser. I've tried a combination of different headers but couldn't get it too work.
How do I render a base64 image using Oak?
EDIT:
This is the code I ended up using, for anyone interested!
const getImage = async (
  { params, response }: { params: { id: string }; response: Response },
) => {
  // Get the image using the ID from the URL
  const image = await imageDatabase.findOne({ _id: ObjectId(params.id) });

  // If there is no image found
  if (!image) {
    response.status = 404;
    return;
  }

  // Return the image to the user
  const semicolonIndex = image.base64!.indexOf(';')
  const colonIndex = image.base64!.indexOf(':')
  const commaIndex = image.base64!.indexOf(',')

  const imageSize = image.base64!.slice(colonIndex + 1, semicolonIndex);
  const imageData = image.base64!.slice(commaIndex + 1);

  response.headers.set('Content-Type', imageSize)
  response.body = base64.toUint8Array(imageData)
};

Answer: HTTP doesn't support base64 image content. You should decode it and return with content type.
const images: any = {
  beam: 'data:image/png;base64,<base64-string>',
  google: 'data:image/png;base64,<base64-string>',
}

router.get('/image/:id', ctx => {
  if (ctx.params && ctx.params.id && ctx.params.id in images) {
    const image: string = images[ctx.params.id]
    const colonIdx = image.indexOf(':')
    const semicolonIdx = image.indexOf(';')
    const commaIdx = image.indexOf(',')
    // extract image content type
    ctx.response.headers.set('Content-Type', image.slice(colonIdx + 1, semicolonIdx))
    // encode base64
    ctx.response.body = base64.toUint8Array(image.slice(commaIdx + 1))
  }
})

To find full code, see code on github
Or you can run my sample directly
deno run -A https://raw.githubusercontent.com/XDean/StackOverflow/master/src/main/deno/Q66697683.ts


What to use to fill a 2" x 12" gap in a dark walnut hardwood floor

Question: I need to replace a 12" x 10" supply register grill with a 12" x 8" supply grill (because I need a booster fan grill and the largest size they come in is 12" x 8") leaving me with a 2" gap along the bottom of the register grill.
What's the easiest way to fill that 2" gap in the hardwood floor opening in a way that doesn't stand out?  If I can find a nice reducer frame, that would be nice but I can also take suggestions for other simple suggestions as well.
The smaller size doesn't matter with the supply duct since the duct below is a round oval about 10x4... with the supply duct before the elbow being a larger rectangle.
Here is the original supply grill before I will replace it with a shorter grill.

Here it is after

Maybe there is a way to add a frame or something to surround it?
Comment: You are putting a grill with push buttons on the floor?  Aren't the cracks around those buttons going to fill with schmutz?
Comment: Matching to the wood floor would hard, suggest using two 1 inch pieces of light colour wood to frame it.  Too bad duct is oval, or a duct booster could have been used.  Maybe get some duct adapters to change oval to round duct.
Comment: Rather than match a filler piece to the colour of the flooring you could match the colour to the grill using spray paint or a custom mix.
Comment: Picture added with original grill, imagine new grill is 2" shorter leaving a gap
Comment: @crip659 I might be able to swap out the elbow since it goes from rectangular duct to a round oval elbow for some reason... would the duct booster fit in the elbow?  the duct underneath is actually rectangular so maybe there is a rectangular booster as well?
Comment: Do know that there rectangular to round adapters.  Most duct boosters are just short round duct with a fan in it.
Comment: Matching stained wood is as much art (if not more) as it is science. I'd suggest taking a look at the `finishing` tagged items at [woodworking.se] to see what you can learn there.
Comment: Also, that looks a lot more like stained oak than walnut, at least to my eye.
Comment: Now that you've [cross-posted](https://woodworking.stackexchange.com/questions/13249/how-to-fill-2-x12-gap-in-hardwood-floor-with-something-that-looks-nice) this to woodworking, want to delete it from here?
Answer: Why make this hard? Trying to patch wood strips into your existing floor will look "patched".  Find an alternate sized floor register.
If you can't find the size in your existing design, use a totally different design so it doesn't look like a mistake. Try this site:
https://ventcoversunlimited.com/cast-iron-scroll-grilles/?gclid=Cj0KCQjwrJOMBhCZARIsAGEd4VFJ6qhzdlgssxstAKxfXe5Gp-qF2GGwemEM6tuNWS31nCEvQMfKUusaAopzEALw_wcB
Or try a custom register:
https://www.pacificregister.com/product/custom-aluminum-laser-cut-vent-covers/?lv=LCA-Various&gclid=Cj0KCQjwrJOMBhCZARIsAGEd4VHTno6tjhMD6Cz692rGhExapdzzYqVhUBCMKCl_MJpMFNtix0mvz6UaAjn5EALw_wcB
You didn't mention if the size was id or od.
Comment: I needed to put the booster fan in and it doesn't come in the larger size registers
Answer: You could build and stain a little frame that goes around the existing cut out that the fan would sit inside. That flooring looks like oak that's been stained dark brown.


What kind of transformation when the aspect is changed for a rotated shape?

Question: I have a geometric shape (assuming that is a rectangle). I want to rotate it about it geometric center by an angle of 45° and plot the result using matplotlib with an equal aspect ratio, I get something like this:

However for some reason, I want to plot the result in a figure with a non-equal aspect, I am getting this result:

As you can see, the rotated shape is deformed (skewed). But the original shape seems to be scaled only in the y direction.
I am trying to understand what kind of transformation is occuring to the orange shape from a linear algebra perspective: Is it a shear? a combination of scaling and shear (Affine transformation)? if not what kind of transformation is that?
My goal is to identify the type of transformation, then finding it's inverse to get the following result:

I appreciate any help.
Answer: Let's talk about linear geometric transformations in homogeneous coordinates.  In your question there are mainly two kind of geometric transformations involved: planar rotation and planar scaling, the computation-friendly analytical re-definitions of which are found hereUnified frameworks of elementary geometric transformations.
The 2D homogenous rotation matrix that rotates 2D objects clockwise by $\theta$ radians is as below:
$$R=\left[
\begin{array}{ccc}
 \cos \theta & \sin \theta& 0 \\
 -\sin\theta & \cos\theta & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]$$
A 2D scaling due to unequal aspect ratio $\rho$ in this case is a stereohomology with $x$ axis $(0,1,0)^T$ as the stereohomology interface (a line of invariant points), and the normal direction $(0,1,0)^T$ as its stereohomology center per definition 3.9 in page 12 and line No. 5 in Table 1, page 9 of the article Unified frameworks of elementary geometric transformations. Then its scaling matrix can be obtained as below:
$$S=\color{gray}{\left[
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & 1 & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]+\left(\rho-1\right)\dfrac{\left[
\begin{array}{c}
 0 \\
 1 \\
 0 \\
\end{array}
\right]\cdot \left[
\begin{array}{ccc}
 0 & 1 & 0 \\
\end{array}
\right]}{\left[
\begin{array}{ccc}
 0 & 1 & 0 \\
\end{array}
\right]\cdot \left[
\begin{array}{c}
 0 \\
 1 \\
 0 \\
\end{array}
\right]}=}\left[
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & \rho  & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]$$
When aspect ratio normally is $\rho=1$, suppose under this circumstance the original object has the homogeneous coordinates of $n$ points in $3\times n$ matrix $X$, and the transformed object in $3\times n$ matrix $Y$, then the geometric transformation between them is the rotation you have mentioned:
$$Y=R\cdot X$$
When the aspect ratio abnormally is $\rho\ne 1$, both $X$ and the $Y$ after rotation are as a matter of fact scaled along the $y$ axis:
$$X'=S\cdot X$$
$$Y'=S\cdot Y$$
Now you want to find the geometric transformation $T$  which satisfies $Y'=T\cdot X'$. Since:
$$Y'=S\cdot Y=S\cdot R\cdot X =S\cdot R\cdot S^{-1}\cdot X'$$
then
$$T=S\cdot R\cdot S^{-1}$$
$$=\color{gray}{\left[
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & \rho  & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]
\cdot
\left[
\begin{array}{ccc}
 \cos \theta & \sin \theta& 0 \\
 -\sin\theta & \cos\theta & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]\cdot
\left[
\begin{array}{ccc}
 1 & 0 & 0 \\
 0 & \dfrac{1}\rho  & 0 \\
 0 & 0 & 1 \\
\end{array}
\right]=}\left[
\begin{array}{ccc}
 \cos \theta & \dfrac{\sin \theta}{\rho } & 0 \\
 -\rho  \sin\theta & \cos \theta& 0 \\
 0 & 0 & 1 \\
\end{array}
\right]$$
It is a rotation under the generalized meaning.
Answer: The transformation is non-uniform scale - it does not preserve angles. The only reason the angles for the other shape were preserved was because the scaling was in the same direction as the edge. To get the result that you want, you either have to scale by the same amount in each direction, or just rescale the "viewing window" and not the shapes.
Comment: Can we describe that in terms of matrices?
Comment: Yes, a diagonal matrix with non-equal elements: $a_{ii} \ne a_{jj}, i \ne j$.
Comment: @I tried that but it dodn't seem to work. it looks like the eigenvalues are the stretching factors and the eigenvectors are (1, 0), (0, 1) by using diagonalization of a matrix we have $P^{-1} D P$
Comment: You tried what? The normalized eigenvectors of a 2x2 diagonal matrix are indeed $(1,0), (0,1)$, what's the issue there? And the scaling factors are the eigenvalues. I don't get what your issue with that is, it's a non-uniform matrix as I said. The initial image didn't have its angles changed, because the rectangle's edges are parallel to the eigenvectors. If you had a circle initially, you would have gotten an ellipse stretched along the $Y$ axis.
Comment: I mean I tried to multiply the rotated shape with multiple scaling matrices but that didn't seems to work at all. What do you mean exactly the matrix is not uniform?
Comment: Non-uniform scale matrix $a_{ii} \ne a_{jj}, i \ne j$, zero everywhere else. Assume that your image was stretched along $Y$ by a factor of $2$, then you have to rescale your rectangle by a factor of $0.5$ along $Y$ if you want it to keep its size, but this will change to which $Y$ it corresponds to on the measure bar on the left. Example matrix:
$$M(1,0; 0, 0.5)$$
Note, you have to know what the image was rescaled with, in order to put the correct value in $a_{22}$.
Comment: Could we find the stretching factors from the image sizes? I mean by cropping the image to the outer black rectangle of the figure.
Comment: @Navaro Not necessarily - the margins and scaling may be different. If this was generated by matplotlib then there's probably a way to retrieve that information from it, or even make it work like you want through some option. I cannot help you further though, since I am not that well-versed in matplotlib anyways.
Comment: Are you familiar with Matlab?
Comment: @Navaro Not enough to help you with that.
Comment: Thank you. I have asked this question several times but didn't get an answer.
Comment: @Navaro A simple solution is rather than stretch your image, allow different bounds for your axes.


three-uniform hypergraph on $n$ vertices with at least $n/3$ edges contains an independent set of size at least $\frac{2n^{3/2}}{3\sqrt{3m}}$

Question: Here is question 3 from chapter 3 Part 1 of The Probabilistic Method, 4th edition.

Prove that every three-uniform hypergraph with $n$ vertices and $m \ge n∕3$ edges contains an independent set (i.e., a set of vertices containing no edges) of size at
least $\frac{2n^{3/2}}{3\sqrt{3m}}$.

I'm trying to solve this using a probabilistic approach. I've only been able to get $\frac{n^{3/2}-mn^{1/2}}{\sqrt{3m}}$ as a bound by defining $S\subset [n]$ by randomly including a vertex in $S$ with probability $p$. We call the resulting induced graph $G':=G[S]$ and denote its vertex set and edge set by $V'$ and $E'$. Then $\mathbb E[|V'|]-\mathbb E[|E'|]=np-mp^3$ because for each edge to be inside $S$ we need all three of its vertices to be chosen. Also, removing one vertex per edge in $G'$ results in an edge-less graph, so $\alpha(G)\ge\alpha(G')\ge np-mp^3$, where $\alpha$ is the size of the largest independent set. The inequality comes from taking the expectation on $\alpha(G')\ge \mathbb E[|V'|]-\mathbb E[|E'|]$.
Then the idea is to optimize over $p$, so make the 1st derivative w.r.t. $p$ equal to zero and get $p=\frac{n^{1/2}}{\sqrt{3m}}$ and the optimized RHS of the equality is $\frac{n^{3/2}-mn^{1/2}}{\sqrt{3m}}$.
Now the problem is that there is a minus there and the hypothesis is that $m\ge n/3$ so $-mn^{1/2}\le-\frac{-n^{3/2}}{3}$ and so $\alpha(G)\ge f(m,n)$ with $f(m,n)\le \frac{2n^{3/2}}{3\sqrt{3m}}=:B$, which does't prove anything. I think I must have made a mistake somewhere...
I only showed that the largest independent set is bounded from below by something which is below $B$. If I had showed that it is bounded by $B$ then that would probably be enough to say that there exists an independent set of size at least $B$.
Answer: Your algebra is fine. I think you just misunderstand what optimizing over $p$ does.
The inequality
$$
   \alpha(G) \ge np - mp^3
$$
holds for any $m, n$ and any $p \in [0,1]$, because the random process you've described works for any $m, n$ and any $p \in [0,1]$. It will produce a random independent set $S$, with $\mathbb E[|S|] \ge np - mp^3$; therefore, with positive probability, it will produce an $S$ with $|S| \ge np - mp^3$; therefore, the largest independent set has size at least $np - mp^3$.
At this point, if all you want to do is to write a proof, you can just write:

For no particular reason, we are inspired to take $p = \sqrt{\frac{n}{3m}}$, which satisfies $0 \le p \le 1$ provided that $m \ge n/3$. With this value of $p$, we conclude that $\alpha(G) \ge \frac{2n^{3/2}}{3\sqrt{3m}}$, which was what we wanted.

If we want to actually find a good value of $p$ to pick, so that we can come up with the proof, then optimizing over $p$ is a good idea. When $m \ge n/3$, we conclude that $p = \sqrt{\frac{n}{3m}}$ is the best probability to use. In other words, we deduce the inequality $$np - mp^3 \le \frac{2n^{3/2}}{3\sqrt{3m}}.$$ You're right that sticking this inequality into our proof would produce nonsense! But this inequality doesn't belong in our proof to begin with. It is part of our outside-the-proof reasoning for picking $p$.
All we actually need to know is that the right-hand side $\frac{2n^{3/2}}{3\sqrt{3m}}$ is achievable by some choice of $p$. We don't, strictly speaking, need to know that it's the largest possible value of $np - mp^3$. (But if it weren't, we could have written a better proof.)
In more complicated problems, it is common to skip taking the derivative, because we wouldn't get a closed form for the answer. Even here, we could be lazy and think "hmm... we want $np$ and $mp^3$ to be about the same size. Let's try setting $mp^3 = \frac12 np$. This gives us $p^2 = \frac{n}{2m}$, which gives some answer of the form $O(n^{3/2}/m^{1/2})$. Good enough!" Then, we could write a proof using $p = \sqrt{\frac{n}{2m}}$. That proof would work equally well, even though it no longer proves the best lower bound that this method can prove.
Comment: Awesome answer, thanks. I didn't see the usefulness of $m\ge n/3$ so I kept trying to use it and coming up with inequalities but it's just a technical constraint to have the optimized $p$ be in $[0,1]$.


Phonegap with node.js

Question: I'm developing an IOS app using phone gap and I'd like to use node.js for part of it. Is it feasable to get phonegap to run an instance of node.js along side the rest of the app?
Comment: @JasonSperske: Yes, exactly. The client wants a nodejs back end to handle outgoing smtp.
Comment: If you elaborate on your design idea you'll probably get better feedback.
Comment: Do you mean you want to run a node.js server on the phone and point PhoneGap at it?
Comment: I don't know about phonegap, but there are efforts to bring node.js onto phones: https://github.com/paddybyers/anode and http://mitchtech.net/node-js-on-android-linux/. (Taken from http://stackoverflow.com/questions/11392590/how-to-run-my-node-js-project-on-android)
Comment: This was essentially a yes/no question and no one gave a straight answer. Can you or can you not use node.js functions such as base64 encoding with your Cordova apps?
Answer: Phonegap is a client-side solution only with JavaScript/CSS/HTML running on the browser-app of the phone. The JavaScript Phonegap API talks to the native phone interface and browser interface which gives you options to work natively and as a normal web page would with enhanced permissions. Node.js would only serve you as a data connection for JSON or whatever else you would need to pull/push with a network call.

UPDATE:  @Turion had a great comment and made me look a little deeper. Here's what the stack and google came up with:
Native IOS app and node.js
and direct YouTube link to neu.Node (Node runnning on iphone!!!) http://www.youtube.com/watch?v=xzFH80-HYTo
Comment: There are usecases where you'd like your phone to be a server, though. For example when connecting other phones to it or when communicating with other devices (roboters, drones). I was actually hoping to be able to develop a node.js application running on a phone, controlling a Parrot AR Drone using this node.js library: https://github.com/felixge/node-ar-drone
Comment: I actually agree with you that there should be. I removed the "nor should it (BS)" I wrote. Not sure what smug train I was on to write that but we all have our moods I guess. Since ios has Unix flavored and I am absolutly in love with node.js, I thought yah why not? I put a reference on this to another post about this. Thanks for the comment. Got me thinking.
Comment: That's what I figured. Just making sure because that was what the client wanted.
Comment: couldn't you build a restful api with node.js and have your phonegap app make requests to that? I'm trying to figure out how to use a database with cordova
Comment: yes, any web server tech can do that. you could consider socket.io for doing quicker real time communication.
Answer: This might be helpful:
http://phonegap.com/blog/build/phonegap-build-api-for-node/
phonegap-build-api-js is a published NPM module for accessing the PhoneGap Build API with node.js. It abstracts the HTTP communication, deals with the API quirks, and leaves the rest untouched. In other words, it simplifies accessing the PhoneGap Build API, so that you can focus on integrating it with your product.

Phonegap with node.js