Can I manually switch off booster fans that are coupled with HVAC blower?

Question: Could not get upstairs in 1900 craftsman bungalow cooled with HVAC system until the contractor inserted a booster fan in each of the two ducts. Fans are coupled to the blower of the HVAC. Now in fall and probably throughout winter it gets way too hot upstairs. Is there a safe (and easy) DIY way to disconnect the fans from the blower to just have normal air flow going upstairs or would the fans block the airflow if not powered?
Thanks in advance!
Pictures show how the fans were hooked up to the blower control board.
Tom
Comment: I'm voting to close this question because it's been abandoned.
Comment: Both fans are wired to the hvac blower by a single cable. Unfortunately, they did not wire it to only switch on with cooling which would have been nice. It is a brand new American Standard Silver unit. Can I just put a wireless switch on the line going out to the fans? I found one but it is restricted to 10 A - I guess the two fans should not drag more than that?
Comment: Assuming the heat isn't already on the high speed terminal, which is where the AC should be, if you wired it there it'd only come on when it calls for AC. How is *the blower* wired? (can't really tell from the picture). *'Both fans are wired to the hvac blower'* - what color wire or terminal? And what's the model number to find the manual so we know what should be wired where. They either arbitrarily did it wrong, or did it wrong for a reason (e.g., they put the heat on the high speed terminal).
Comment: How are the fans coupled to the HVAC blower?
Comment: can you reach the fan?
Comment: It depends on your HVAC unit but my booster fans for upstairs bedrooms are wired such that they kick on when the unit is calling for cooling, but not when calling for heat. They don't significantly affect the already poor flow (hence the need for a booster) through those ducts when they are not operating during the winter.
Comment: Can you post the wiring diagram for the air handler?
Comment: I added pictures of the wiring diagram.
Comment: They might have put the blowers on the high speed because that was the only way to get AC really work upstairs but I really do not want the fans in winter as it is 90 degrees upstairs and 63 downstairs...
Comment: Can you post the exact model number of the furnace please? It looks like they're using the control board's EAC function for the auxiliary blower, which seems sensible enough, but we'll need to make certain of the behavior of that function before we start bolting stuff onto this.
Comment: AUH2B060A9V3VBA
Comment: Do you want the boosters to run when the system has its fan forced ON manually at the thermostat, or do you want them to *only* run when air conditioning is being called for?
Comment: Heat was sufficient upstairs before putting booster fans into the two ducts. I hope the air flow with turned off booster fans will still be enough. Is it easy to try how it works to just have them come on with AC - and if that does not work out - then put them on forced fans? Alternatively, can I just add a WiFi switch on the line connecting the fans to the furnace?
Comment: @Tom -- yeah, we can try it with AC only first, and then switch it to run them on a call for fan later (the switcheroo will just be a matter of moving a wire)
Comment: @ThreePhaseEel - how do I do it? Do I move both contacts and how are they fixed to the board. I have never done this before...
Comment: Is the heat currently on high blower settings? Can this be returned to variable and then only when the air is needed fix it to high blower speed?
Comment: @ThreePhaseEel please help me with my last question.
Comment: @Mazura please help me with my last question.
Answer: You'll need to add an extra fan relay to your system to accomplish this
Your existing setup controls the booster fans via the EAC terminals on the furnace control board, which appear to be energized whenever the furnace blower is running.  In order to change this, you'll need to stick a fan relay in line with the control wiring to the fans, so that the fan only comes on during the correct conditions (cooling, in your case).  For this, you'll need:

A SPST-NO HVAC relay (these have 24VAC coils, quick-connect terminals, and flange mounting means)
Two short lengths of 18/2 thermostat cable (enough to get from the control board to the relay, and another shorter length to serve as a pigtail)
A length of 14AWG stranded THHN wire (about the same length as the thermostat wire, can be any color save for white, grey, or green)
Four female quick-connect terminals (two red ones for 18AWG wire, two blue ones for the 14AWG wire), as well as two wirenuts suitable for 4x18AWG wires
A couple of self-drilling sheet metal screws, suitable for attaching the flanges on the relay to the inside of the furnace wiring compartment
And a screwdriver + wire-cutter/stripper (of course) and a ratchet-type crimper with an insulated terminal die (these are the way to go for crimping things, the cheap crimp pliers are not a good way to get uniformly reliable crimps)

The installation goes as follows (if you aren't comfortable with this, any HVAC tech or electrician should be able to do this on your behalf):

Turn power to the furnace off (the service switch will suffice), and open up the wiring compartment of the furnace
Find an empty spot near the control board to mount the control relay at, and use the mounting screws to attach it to the inside of the wiring compartment there
Crimp the red quick-connects onto the wires on one end after stripping the wires on both ends of the longer length of thermostat cable
Strip both ends of both wires on the shorter length of thermostat cable
Crimp the blue quick-connects onto the ends of the 14AWG wire after stripping them as well
Remove the black wire with the quick-connect terminal on it from the EAC-H terminal on the control board, and move it to one of the contact terminals on the new relay
Use the 14AWG jumper you made in step 5 to connect the other contact terminal on the relay to the EAC-H terminal on the control board
Remove both wires from the Y terminal on the control board, and connect one wire in the short length of thermostat cable to the Y terminal.  Take the matching wire in other end of the short length of thermostat cable, and nut it to the existing Y wires as well as to one wire in the long length of thermostat cable
Repeat the process of step 8 with the wires connected to the C terminal on the control board and the free wires in the two lengths of thermostat cable you added. If there's only one wire connected to C, that's no big deal -- this will set you up properly later if you need to run a C wire to a thermostat down the road.
Connect the quick-connects on the other end of the thermostat cable to the coil terminals on the new relay
Button the wiring compartment back up and turn the service-switch back on

Now, the booster fans should only work if the thermostat is calling for air conditioning.  If you want them to run during a call for fan, you'll need to rewire things so that the fan relay's coil is wired between G and C on the control board, instead of between Y and C as it is at the moment.
Comment: Is the heat currently on high blower settings? Can this be returned to variable and then only when the air is needed fix it to high blower speed?
Comment: @Tom -- the blower setting the heat is using doesn't matter, since we're using the EAC terminals on the furnace board instead of tapping the fan motor leads directly
Comment: Thanks. Just to make sure - I think the HVAC guy who did this job set the blower to always high because the AC did not cool enough upstairs. When following your solution will this be reversed but when AC is triggered go back to high settings?
Comment: @Tom -- this will not impact the setting of the main blower
Comment: Is this an appropriate relay?
https://www.amazon.com/Emerson-380-Relay-Volt-Coil/dp/B000LDCPQS
Comment: @Tom -- there's no sense in  trying to order this stuff from Amazon.  You should be able to find a suitable one at the big-box stores, or through a local HVAC or electrical supply house for that matter
Comment: after talking to a local HVAC supply store owner, I decided to go for an inline switch cutting the control cable to the booster fans. Seems to work and I was told it will not harm the HVAC system. Is this correct?
Comment: @Tom -- it's basically the manual version of what the relay I propose does, so yeah, it'll be fine if you want to go the manual route


How to apply background color to checkbox using CSS3?

Question: I've been searching for a solution to this problem for a few hours now without any luck. Seems like everyone uses a background image to solve their problem, and I only want to use a color so the solution scales better without extra CSS needed for mobile devices.
I almost have a working solution, but 1) the "checkbox" is not clickable like the rest of the label; 2) I just can't seem to find any way to add space between the label and the "checkbox" without altering the HTML (something that I prefer not to do, but will try if there's no workable CSS-only or JQuery solution).
Here's the HTML:

        <input type="checkbox" id="edit-field-school-education-und-28" name="field_school_education[und][28]" value="28" checked="checked" class="form-checkbox">
        Evening Classes & Distance Learning

     ......  Repeated for several checkboxes   .......

Here's my CSS so far:
.form-checkbox {display:none}
.form-checkbox + label:before {content: "\00a0\00a0\00a0\00a0"; height: 19px; width: 19px; border: 1px  solid black; cursor:pointer; }
input[type="checkbox"]:checked + label:before {background-color: #34c1ce;}

I prefer a CSS3 solution, but would be okay with a generic HTML or JS solution. I can't have a solution based on IDs etc. since the checkbox list may grow at any time. However, I could probably figure out a way to output a div with the same label text.
Comment: The checkbox element, as well as many other input types, are controlled by the browser's own stylesheet. They are set with the !important declaration and cannot be changed by any other CSS.
http://www.w3.org/TR/CSS21/cascade.html#cascade

You will probably have to use JS.

@spy-killer's link looks cool too.
Answer: You cant set a background color to a checkbox it is rendered depending on the browser not the css, But you could set a background image here is a handy tutorial
http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Comment: This solution uses images, which I said I'm not looking to use.
Answer: Best option is to create your own checkboxes with buttons and JavaScript or use a JavaScript UI. This however means that it doesn't work if JavaScript isn't enabled so you may wish to create a fallback (have a checkbox shown by default and use JS to switch it out with the custom one).
Comment: That sounds interesting...do you have an example you can link to?
Comment: This http://jqueryui.com/ is an easy way to implement stylable checkboxes but requires JS to be enabled. I don't currently have an example of custom UI though.
Comment: Okay thanks...I'll research this some more. I assume the JS will need to also check the checkbox when the button is clicked.
Comment: Yes. Just put a checkbox in the button element then set `visibility:hidden` so it isn't shown. You can then use JavaScript to check and uncheck the input behind the scenes while changing the class/styles of the button element. The checkbox should correctly pass the data when the form is submitted.

You should also consider alternate styles to allow the checkbox to be shown if JS is disabled.
Comment: Thanks I will check this out as a possibility.


Can std::thread by used in an constructor initializer list?

Question: I'm currently reading through the C++ Concurrency in Action book. I can't seem to get the following code to compile. I keep hitting the error
error: field of type 'std::thread' has private copy constructor

Is the copy constructor for std::thread being called?
class scoped_thread
{
    std::thread t;
public:
    explicit scoped_thread(std::thread t_):
        t(std::move(t_))
    {
        if(!t.joinable())
            throw std::logic_error("No thread");
    }
    ~scoped_thread()
    {
        t.join();
    }
    scoped_thread(scoped_thread const&)=delete;
    scoped_thread& operator=(scoped_thread const&)=delete;
};

int main() {
    int some_local_state = 0;
    scoped_thread t(std::thread(func(some_local_state)));
}

Comment: g++ 5.1.0: 0 error(s), 0 warning(s) (0 minute(s), 3 second(s))
Comment: Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Comment: Was it exactly the above code with an empty `main` ?
Answer:

Is the copy constructor for std::thread being called?

It is totally up to the code which uses scoped_thread.
Note, that std::thread is movable, but noncopyable type.
It means, that the next code works correctly:
scoped_thread st(std::thread{});

as t_ is created via move constructor.
But if you create an instance of std::thread and then try to wrap it into the scoped_thread like so:
std::thread t;
scoped_thread st(t);

then the attempt to call copy constructor happens and you get a compile error.
As scoped_thread seems to implement RAII the right way to use it is to wrap an unnamed instance of std::thread as in the very first example of the answer.
Comment: The example shows it being called with:

`scoped_thread t(std::thread(func(some_local_state)));`
Comment: @NeuralSandwich the example is correct as `t` is created from rvalue.
Comment: Turns out I didn't have -std=c++11 set. So Clang wasn't using move semantics and fell back on copy constructor
Answer: The listed code is correct. However -std was not set to c++11 for the compiler. This probably left the compiler using the copy constructor as move semantics is not available in older C++ versions.
Comment: Most probably, move constructor is conditionally enabled by macro which depends on the standard used. If there is no move constructor, then copy constructor is used in order to construct the class from rvalue and the error happens.


Customize catch block in Java and enable smart insert in Eclipse

Question: In Eclipse when we select code statements and right click on it, it gives us an option for surrounding with try/catch block, after selecting this option our code looks like.
try {
    //selected code lines
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Now I want to define a custom catch block which should look like below after selecting surround with try/catch block from eclipse smart insert:
try {
    //selected code lines
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    myCustomLogger.LogMe(Log.getStackTraceString(e));
}

Is it possible?
Does Eclipse allow us to customize some properties for specific project in smart insert?
Answer: Yes it's possible, open Eclipse Preference and then Java > Code Style > Code Templates. There you select Code > Catch block body. Here you can edit your try/catch block.
Add myCustomLogger.LogMe(Log.getStackTraceString(${exception_var}));


is log_in(user) the same as log_in user?

Question: Doing Hartl's Rails tutorial, chapter 8.2.1.
We define:
def log_in(user)
   session[:user_id] = user_id
end

And then we invoke the log_in method in the controller:
def create
   user = User.find_by(email: params[:session][:email].downcase)
   if user && user.authenticate(params[:session][:password])
     log_in user
     redirect_to user
   else
     flash.now[:danger] = 'Invalid email/password combination'
     render 'new'
   end
 end

Why we write log_in user instead of log_in(user) in the controller? Are they equivalent syntaxes? Thanks
Answer: Yes.
As a part of ruby's syntactic sugar, you can drop the parentheses on method calls
For example lets say you have a method that takes in a hash
You can call it any of these ways:
method_name({param1: 1, param2: 2})
method_name(param1: 1, param2: 2)
method_name param1: 1, param2: 2

When do use which? Depends.
If you want to nest method calls, its best to be verbose. If you need to pass multiple hashes, then you need to tell ruby their boundaries, by using the {} brackets.


Insert new user to firebase

Question: I have the following snippet which is currently located inside the create account button.
  self.ref.child("Users").child(user!.uid).setValue(["fb_id": fb_id, "first_name": f_name, "last_name": l_name, "email": email])

I currently receive the error type user! has no member uid which I understand because I haven't created a user for this new person yet, I have gone through all documentation on here however I can't find the solution I'm looking for.
Can someone please share their knowledge on how I go about inserting a new user.
Comment: whats the problem with this. .. looks ok to me
Comment: @EICaptainv2.0 apologies, managed to get this resolved I had to change user! to my variable name auth which inside contained the uid of the user,
Comment: ok .. no problem :)
Answer: You can access the uid with .child("\(FIRAuth.auth().currentUser.uid)"), if you haven't stored a value in user variable child(user!.uid) has no sense.

Insert new user to firebase


Vertical scroll animation 'jumps' on iOS

Question: I'm working on a site that uses CSS3 animations.
I've noticed on iOS the comic captions 'jump' which I believe is caused by the address bar changing one of the window properties used to calculate the caption position.
Source code is available here: https://gitlab.com/ashleyconnor/adventurersclubcomic
If I'm correct in my assumption. Is there an accurate way to offset the iOS address bar so there is no jump (sudden increase) in any of these values?
Comment: Not sure if this will help your debugging but if you scroll using page up and page down in Edge you also have a significant jumping issue. I'm going to guess it's likely the same issue. Probably a bug in your parallax code.
Comment: PgUp/Down works on Chrome and Safari on OSX but good to know. I've filed an issue on the project for this. Thanks.
Comment: Mind if I get a link to the issue you filed?
Comment: Filed on my project for now: https://gitlab.com/ashleyconnor/adventurersclubcomic/issues/1 - I'll add a pull request to the parent JS library once I figure out what is wrong.
Answer: I cloned your repo, and was able to reproduce the jitter on window resize in both Firefox and Chrome. After a few minutes of debuggine, I think the problem is actually in your index.js file.
You are completely refreshing the enllax plugin every time the windows resizes. This appears to be unnecessary.
If you remove the excess calls to the enllax function like this:
$(document).ready(function() {
// function enllax() {
    $('#start').enllax({
        type: 'foreground',
        ratio: 0.5,
        direction: 'vertical'
    });
//  $(window).scroll();
// };

    $('#begin').click(function() {
        $('html, body').animate({
            scrollTop: $("#panel1").offset().top
        }, 1000);
    });

//  enllax();

    // And trigger the scroll event on resize to deal with changes
    // in the responsive layout
    $(window).on('resize', $(window).trigger('scroll'));
});

With that update, the jitter stops on resize in all the browsers I have installed. It remains to be tested in iOS because I don't have any Apple hardware to test it on, but I suspect it should fix the problem there as well.
Comment: Looks like that's fixed it. Thank you!
Comment: Happy to help :)


Multiple Interface injection with castle windsor

Question: How can you get castle Windsor to choose the right implantation of a interface at run time when you have multiple implementations in the container.
For example lets say i have a simple interface called IExamCalc that does calculations to work out how someone did in that exam.
No we have several implementation of this like bellow for example,
public interface IExamCalc
{
    int CalculateMark(ExamAnswers examAnswers)
}

public class WritenExam : IExamCalc
{
    public int CalculateMark(ExamAnswers examAnswers)
    {
         return 4;
    }
}

public class OralExam : IExamCalc
{
    public int CalculateMark(ExamAnswers examAnswers)
    {
         return 8;
    }
}

public class ExamMarkService
{
    private IExamCalc _examCalc;
    public ExamMarkService(IExamCalc examCalc)
    {
        _examCalc = examCalc;
    }

    public int[] CalculateExamMarks(ExamAnswers[] examAnswers)
    {
        IList<int> marks = new List<int>;
        foreach(ExamAnswers examanswer in examaAnswers)
        {
            marks.Add(_examCalc.CalculateMark);
        }
    }
}

Say the ExamMarkService is being resloved through Windor how can i make sure that the correct implementation is injected in the constructor and is this an example of a multi-tenancy problem?
Hope that all makes sence
Colin G
Answer: As David said, you can't, but IHandlerSelector will let you take control.  Check out the tests to get an idea of how to use them: https://svn.castleproject.org/svn/castle/trunk/InversionOfControl/Castle.Windsor.Tests/HandlerSelectorsTestCase.cs
Basically, you would do something like:
public class WritenExamHandler : IHandlerSelector
    {
        public bool HasOpinionAbout(string key, Type service)
        {
            // Decision logic here
            return somethingThatWouldBeTrueToSelectWritenExam && service == typeof(IExamCalc);
        }

        public IHandler SelectHandler(string key, Type service, IHandler[] handlers)
        {
            return handlers.Where(handler => handler.ComponentModel.Implementation == typeof (WritenExam)).First();
        }
    }

and then you register it with:
container.Kernel.AddHandlerSelector(new WritenExamHandler());

This will allow you to easily deal with multi-tenency issues :)
Answer: Multi-tenancy is defined as being able to run your software on one instance, serving multiple tenants/customers/clients. I guess you could run into problems like yours more often in a multi-tenancy setup.
All your components have keys which are unique strings, so you may always so a container.Resolve("someKey") to get a specific implementation.
If you want to have a specific implementation automatically injected, you may configure your component like this (off my memory, may not be 100% precise):
<component id="someService.customer1" service="ISomeService" type="Customer1SomeService" />

<component id="anotherId" service="IAnotherService" type="AnotherService">
    <parameters>
        <parameterName>
           ${someService.customer1}
        </parameterName>
    </parameters>
</component>

Answer: The short answer is, you can't. This kind of choice is dependent on application code, so if you just did container.Resolve<IExamCalc>, then Windsor couldn't know which one you wanted.
The question to ask is how do you know which type to use?


Attaching multiple gizmos

Question: I'm trying to attach multiple gizmos to one object and have them all perform together.
Such as attaching,
Piston+piston
Piston+rotator
Is this possible?
Answer: You can attach the black body(!) of multiple gizmos to one object - in that case all the gizmos will move with the object. You can attach an object only to the axle (the metal top) of a single gizmo - in that case the object will move with the gizmo. (If you could attach it to the axles of two gizmos, it wouldn't be clear which gizmo controls the movement of the object.)
If you want an object to be influenced by multiple gizmos, you have to make a chain of gizmos, e.g. wire the axle of the first piston to the body of a second piston and then the axle of the second piston to an object. Same with rotators and other gizmos (except for the animation gizmo, which is a special case).
Comment: Might be worth noting the animation gizmo as an exception to this rule.

Attaching multiple gizmos


Cannot get to GUI

Question: I installed pytorch in the morning and then my laptop started working weird so when I restarted I got into the screen attached. I uninstalled pytorch, but I still have the same issue. Ctrl-Alt-F(1-6) does not work, all packages are up to date, firmware updates are also done, I tried to switch Dynamic to Discrete as suggested in BIOS, but there is no such setting.I also reinstalled lightdm, but it didn't work. Does anyone have any other ideas?
Final opening screen:
Answer: The next to last line suggests it is a gpu driver issue. Pytorch interacts and can modify the gpu driver/settings, I would suggest reinstalling the gpu drivers.  If it is a nvida based card, are you using the open source or proprietary driver?
If reinstalling the driver does not work, try changing the driver to/from open source.
You do have a number of other errors releting to firmware/drivers for devices, but I do not believe they would stop the gui from loading.
Comment: Thank you for the answer. My laptop uses Intel iRIS xe graphics. So I dont know how can I reinstall the drivers.
Comment: I believe the Intel iRIS drivers are part of the xserver-xorg-video-intel package.

Cannot get to GUI


How do I store data in class that is globally accessible file

Question: I am trying to make a basic app that allows a user to create an account and sign in. How do I save this information in a file that is globally accessible to all classes?
I tried using SharedPreferences, and was able to store the information but could not figure out how to retrieve it:
public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText username = (EditText)findViewById(R.id.editText1);
                EditText password = (EditText)findViewById(R.id.editText2);
                EditText email = (EditText)findViewById(R.id.editText3);

                String usernameData = username.toString();
                String passwordData = password.toString();
                String emailData = email.toString();

                //How do I store data in java?

                if (username != null && password != null && email != null){
                    savePreferences("usernameKey", usernameData);
                    savePreferences("passwordKey", passwordData);
                    savePreferences("emailKey", emailData);
                    Intent nextpage =new Intent(accountcreation.this,    information.class);
                    startActivity(nextpage);

                }

Comment: Have you looked at the documentation for `SharedPrefetences`? It makes it very clear how to retrieve values. Also, show us your `savePreferences(...)` method.
Answer: To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);

To read preferences:
String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());

To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();

Take from: How to use SharedPreferences in Android to store, fetch and edit values


Redgate Source Control commit changes throws trace filename exception

Question: Whenever I try to commit changes to source control I get this error message. Trace file name '' is invalid. The statement has been terminated.
Answer: Try disabling and re-enabling the default trace.
<code>EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'default trace enabled', 0;
GO
RECONFIGURE;
GO
EXEC sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO

EXEC sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'default trace enabled', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO
</code>


Java UTF-8 URLEncoder encoding special characters that it shouldn't

Question: I am trying to encode the username and password when logging in my mobile app. I am connecting to an existing API and am supposed to send an encoded username and password. I am using URLEncoder using UTF_8 but it seems to be encoding most special characters. I am comparing the encoded string to the one encoded by Postman (which is the correct version).
Here is my code:
URLEncoder.encode(value, StandardCharsets.UTF_8.toString());

For the string ~!@#$%^&*()_+{}|:<>?"`[]\;',./
In postman it is being encoded as
~!%40%23%24%25%5E%26*()_%2B%7B%7D%7C%3A%3C%3E%3F%22%60%5B%5D%5C%3B'%2C.%2F

while in my app, it is being encoded as
%7E%21%40%23%24%25%5E%26*%28%29_%2B%7B%7D%7C%3A%3C%3E%3F%22%60%5B%5D%5C%3B%27%2C.%2F

As you can see, it is encoding most special characters (The exceptions being ._*)
Answer: Using the static constant UTF_8's toString() method as the character encoding scheme throws java.nio.charset.IllegalCharsetNameException: java.nio.charset.CharsetICU[UTF-8] as the toString() returns "java.nio.charset.CharsetICU[UTF-8]". To get the desired "UTF-8" use displayName() method instead.
After that change your code work's like you wanted in my environment.
Comment: Hi. My code is not throwing an exception like that. I just tried the displayName() method and it the result is still the same


Will walls need re-plastering after removal of painted wallpaper?

Question: Getting ready to buy for the first time and so I'm trying to prepare myself for renovation projects. I'm mostly looking at old Scottish Victorian tenement flats.
The one I viewed earlier today is a second one where all the walls are covered by a semi-gloss beige paint spread over some kind of strips stuck to the wall. You can tell the places where one strip joins with the next, in some places they come off a bit (see the photo). There are also places where the wall isn't smooth i.e. there are lines and patches of wall being indented or protruding a few millimetres in contrast with the surrounding surface.
Needless to say, I'd probably want to make the walls nicer, but I have a few questions:

Presumably I'd need to remove the wallpaper-like thing from the walls. What kind of treatment would the walls need after that and before I apply a new paint or wallpaper? Would I need to re-plaster? I know that sometimes it's a game of chance but in general how common it is to mess up the underlying lime plaster when redoing the wall surfaces?
Is the only way to get rid of the unevenness of the walls re-plastering?

Thanks!
Answer: You won't need to re-plaster regardless. If anything, a light skim coat will flatten things out after paper removal.
My approach would be to peel and scrape away as much of the paper as is practical using common techniques--putty knives, steam, paper adhesive solvent. Once that's done and the wall has dried, seal it with a good primer to lock down all the paper fibers. Now skim with joint compound and texture if desired. Prime again and paint.
I would not add wallboard. That creates problems with drim, door jambs, etc.
Answer: To me that looks like a tape line (unless there are multiples evenly spaced).
Getting rid of lines is tough, I have seen diy patch repairs that would have been perfect but they taped outside the area to block any overspray with the cans of spray texture so there were lines.
In this case my advice would be to sand down the line get rid of the ridge. Then  retexture. If these lines are on ~4' spaces it may be the tape that hides the seams in the wallboard (sheetrock) coming loose, or possible cracking from the property being vacant and un heated for a while this can cause cracks at tape lines.
Hiding cracks can be difficult, sanding then using a spray texture and blending it will look worse until painted. But you can hide cracks without a large investment, just a little elbow grease sandpaper texture and paint.
Comment: There are multiple ones of them and evenly spaced by about 70cm so I think it is a wallpaper. Also in that place I could actually poke it as it was kinda detatched from the wall and see two distinct layers move independently.
Comment: If it is wallpaper that is lifting steaming off can be done, but this is a pain. With a commercial steamer it still takes time, I was think the strips were the tape more than wall paper but 70cm is a strange spacing. So it may be wallpaper. I don't like overlays as they require all the receptacles, switches and ceiling boxes to have extensions. So if it is wall paper, the choices are steaming, overlay, or complete replacement. I have not seen glue white glue injected under the edge of paper do well but have heard of it working.
Answer: Looks like pretty normal "someone decided to paint over wallpaper" - not anything all that unusual or special - but a right pain to fix.
If you can stand the loss of interior space from the extra thickness, wallboard/drywall right over that is generally less work than getting it off the wall, much less getting the wall covered in wallpaper paste ready to take paint reasonably. You get a new, smooth, reasonably flat paintable surface with comparatively minimal effort.
If considering purchase, price your offer on the assumption that you'll have to replaster.
Comment: A skim coat isn't anything like re-plastering. Let's be clear about that.
Comment: I was under the impression that wallboard/drywall solutions should be avoided in Victorian tenements because of the kind of breathing the walls require to not get damp and moldy?


Using Checksum to finddistinct rows

Question: Please see the DDL below:
create table #dbNames (reference int identity not null, name1 varchar(30),
                       name2 varchar(30), dateadded datetime, primary key (reference))
insert into #dbNames ('Bert', 'Claire', '2010-01-01')
insert into #dbNames ('Claire', 'Bert', '2015-01-01')

I want the output of the query to be:
Claire Bert 2015-01-01

2015-01-01 is more recent than 2010-01-01.  Claire and Bert only have to be displayed on row once i.e. the most recent row.
I was thinking about creating Checksum column.  However, Checksum produces two distinct values:
declare @checksum int
declare @checksum2 int

set @Checksum = checksum('Claire,Bert')
set @Checksum2 = checksum('Bert,Claire')

print @checksum
print @checksum2

Is there an algorithm I can use so the values are the same i.e. in the above, @Checksum and @Checksum2 produce different results.
Comment: CHECKSUM computes a hash value, called the checksum, over its list of arguments. The hash value is intended for use in building hash indexes. If the arguments to CHECKSUM are columns, and an index is built over the computed CHECKSUM value, the result is a hash index. This can be used for equality searches over the columns.
Comment: Are you returning "Claire Bert" simply based on the date being most recent?  Or are you wanting SQL to know the name is potentially transposed, and to treat them as the same person and then evaluate the date?  I'm confused at your question.
Comment: Do you only need a query that returns one row?    Or one row for every pair of names?
Comment: You could try thinking about a solution that employs a split function and compares the contents of the derived tables produced by fn_Split('Claire,Bert') and fn_Split('Bert,Claire')
Comment: @ Tab Alleman, there are millions of row sin the table.  There should only be one row for each combination i.e. one row would cater for: Claire,Bert and Bert,Claire.
Answer: Try this:
insert into #dbNames
            (
                name1
            ,   name2
            ,   dateadded
            )
    VALUES  ('Bert', 'Claire', '2010-01-01')
        ,   ('Claire', 'Bert', '2015-01-01')
        ,   ('John', 'Smith', '2015-01-02')
        ,   ('Smith', 'John', '2015-02-01')
        ,   ('Joe', 'Blow', '2015-03-01')

;WITH
    cte1 AS
    (
        SELECT      *,
                    full_name = name1 + ' ' + name2,
                    alt_name  = name2 + ' ' + name1
        FROM        #dbNames
    ),
    cte2 AS
    (
        SELECT      c1.*,
                    final_name =
                        CASE
                            WHEN c2.reference IS NULL THEN c1.full_name
                            WHEN c1.dateadded >= c2.dateadded THEN c1.full_name
                            ELSE c2.full_name
                        END
        FROM        cte1    c1
        LEFT JOIN   cte1    c2  ON (c1.full_name = c2.full_name OR c1.full_name = c2.alt_name)
                                AND c1.reference <> c2.reference
    ),
    cte3 AS
    (
        SELECT      *,
                    rownumber = ROW_NUMBER() OVER (PARTITION BY final_name ORDER BY dateadded)
        FROM        cte2
    )

SELECT *
FROM cte3
WHERE rownumber = 1

I haven't tested it on millions of rows though.

Using Checksum to finddistinct rows


why is my recursion not returning the desired output?

Question: I am writing a recursion function that simply returns x^n:
def myPow(x,n) -> float:
    def recurs_n(x,n):
        if n==1:
            return x

        if n>1:
            result = myPow(x,n-1)

        return result

    return recurs_n(x,n)

print(myPow(2,5))

The output that I am getting for the above is 2, which isn't correct obviously. Any idea where I am going wrong?
Comment: Don't you mean `result = x * recurs_n(x,n-1)`?
Comment: ahh yes, that's right
Comment: I would recommend reading https://ericlippert.com/2014/03/05/how-to-debug-small-programs/.
Answer: Your inner function calls the outer function, that should not be allowed. Furthermore, there is no logic applied anywhere for the multiplication when going to the n-1 step. So when n>1 you need to return x*myPow(x,n-1)
I should also mention, that in your case there is no real need to have an inner and outer function, one function should be enough. Like so;
def myPow(x,n) -> float:
    if n == 1:
        return x
    if n > 1:
        return x*myPow(x,n-1)

print(myPow(2,5))

Comment: Thanks oskros, it makes sense. One question, in what instance would it be necessary to have both the inner and outer loop as I have in my code?
Comment: @dhsdnfdsfn that would be relevant in the case where you wish to do some kind of recursive operation, and then afterwards apply some other operation. So for your example, in case you first wanted to recursively calculate a power, and then afterwards translate the result into a string saying `The result of myPow(2, 5) is 32`
Comment: I see, that makes sense too. Thank you
Answer: Your code runs until power n=5 reaches 1, where it activates the first if condition where x is returned (here x=2) without continuing onwards.
An alternative is presented below:
def power(N, P):

    # if power is 0 then return 1
    if P == 0:
        return 1

    # if power is 1 then number is
    # returned
    elif P == 1:
        return N

    else:
        return (N*power(N, P-1))

Comment: It seems that the indentation in your copied code is wrong
Comment: @oskros It's ok, I am new here. I try to figure out how this site works with trial and error. I fix the indentation.


Unity doesn't load ubuntu 14.04

Question: I installed ubuntu 14.04 LTS with wubi and after 2 days of use after the login screen unity doesn't seem to load. Notifications work so the cursor but only the backgroun appears and nothing else. What should i do?
Answer: Reinstall your unity or reset it.
Few sites here:
http://www.webupd8.org/2012/10/how-to-reset-compiz-and-unity-in-ubuntu.html
How can I remove and re-install Unity?

Unity doesn't load ubuntu 14.04


Replacement only between begin{document} and \end{document}

Question: I have got some of the code from the stack-overflow and it's working, But while changing that code into my requirement(Replacement only between begin{document} and \end{document}) it's not working
this is the code i got
put wordOffset("begin{document}",fld "MytextField") into tBegin
put wordOffset("end{document}",fld "MytextField") into tEnd
put replaceText(word tBegin to tEnd of fld "MytextField","bad","good") into word tBegin to tEnd of fld "MytextField"

I am using the following code. How i convert above code to my requirement.
  on mouseUp
       put the htmlText of field "MytextField" into myHtml
       set the caseSensitive to true
       put the field SRText into myArrayToBe
       split myArrayToBe by CR
       put the number of lines of (the keys of myArrayToBe) into myArraylength
       repeat with i = 1 to myArraylength
          put  myArrayToBe[i] into y
          split y by colon
          put y[1] into searchStr
          put y[2] into replaceStr
          if searchStr is empty then
             put the  0 into m
          else
          replace searchStr with  "" & searchStr & "" & replaceStr & "" in myHtml
        end if
     end repeat
     set the htmlText of fld "MytextField" to myHtml
      end mouseUP

Answer: Now I think I understand your problem, try this...
on mouseUp
   put the htmlText of field "MytextField" into myHtml

   ## First we need to break up myHTML into 3 parts so we can edit the "Document" part...
   -- Find the document "begin" marker and put it's position into the tBegin variable
   put wordOffset("begin{document}",myHtml) into tBegin

   -- Find the document "end" marker and put it's position into the tEnd variable
   put wordOffset("end{document}",myHtml) into tEnd

   put word 1 to tBegin of myHtml into tHeader -- Part 1
   put word (tBegin +1) to (tEnd -1) of myHtml into tDocument -- Part 2 = the Document to change
   put word tEnd to -1 of myHtml into tFooter -- Part 3

   set the caseSensitive to true
   put field "SRText" into myArrayToBe
   split myArrayToBe by CR
   put the number of lines of (the keys of myArrayToBe) into myArraylength
   repeat with i = 1 to myArraylength
      put  myArrayToBe[i] into y
      split y by colon
      put y[1] into searchStr
      put y[2] into replaceStr
      if searchStr is empty then
         put the  0 into m
      else
         replace searchStr with  "" & searchStr & "" & replaceStr & "" in tDocument
      end if
   end repeat

   ## Now we can rebuild the htmlText from the 3 parts and put it back in to the field...
   set the htmlText of fld "MytextField" to tHeader && tDocument && tFooter
end mouseUp


Route not showing in MKMapView?

Question: I have these method that adds routes for MKMapView between two CLLocation. i have both valid pickUpDistanceLocation & dropOffDistanceLocation
 func addRoutesOverLayForMapView(){

        var source:MKMapItem?
        var destination:MKMapItem?
        println("\(pickUpDistanceLocation)")
        println("\(dropOffDistanceLocation)")

        //i also tested with these locations
        //let sourcelocation = CLLocation(latitude:  40.7141667, longitude: -74.0063889)
        //let destinationLocation = CLLocation(latitude: 38.89, longitude: 77.03)

        CLGeocoder().reverseGeocodeLocation(pickUpDistanceLocation, completionHandler: {(placemarks,error)-> Void in

            if (error != nil) {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                if let placemark: MKPlacemark = placemarks![0] as? MKPlacemark {

                    source =  MKMapItem(placemark: placemark)
                    println("\(source)")

                }

            } else {
                println("Problem with the data received from geocoder")
            }
        })

        CLGeocoder().reverseGeocodeLocation(dropOffDistanceLocation, completionHandler: {(placemarks,error)-> Void in

            if (error != nil) {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }

            if placemarks.count > 0 {
                if let placemark: MKPlacemark = placemarks![0] as? MKPlacemark {

                    destination =  MKMapItem(placemark: placemark)
                    println("\(destination)")

                }

            } else {
                println("Problem with the data received from geocoder")
            }
        })

        let request:MKDirectionsRequest = MKDirectionsRequest()
        request.setSource(source)
        request.setDestination(destination)
        request.transportType = MKDirectionsTransportType.Automobile
        request.requestsAlternateRoutes = false

        let directions = MKDirections(request: request)
        directions.calculateDirectionsWithCompletionHandler ({
            (response: MKDirectionsResponse?, error: NSError?) in

            if error == nil {

                self.showRoute(response!)
            }
        })
     }

This is the method that adds the route overlay in the map
 func showRoute(response:MKDirectionsResponse){
        for route in response.routes as! [MKRoute]{

            mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)

        }

    }

I get this error as the response returned error: 400

On printing error it shows as

Optional("The operation couldn't be completed. (NSURLErrorDomain
  error -1011.)")
Comment: According to OSStatus, this looks to be a server error: http://www.osstatus.com/search/results?platform=all&framework=all&search=-1011
Comment: what should i do then? i have tried using different lat and long
Comment: If the error is server side, there's not much you can do until it's resolved by Apple.
Answer: Actually both source and destination variables were nil.. So i got bad response from the server.If you need just try the below code
func addRoutesOverLayForMapView(){

    var source:MKMapItem?
    var destination:MKMapItem?
    var sourcePlacemark = MKPlacemark(coordinate: pickUpDistanceLocation!.coordinate, addressDictionary: nil)
    source = MKMapItem(placemark: sourcePlacemark)

    var desitnationPlacemark = MKPlacemark(coordinate: dropOffDistanceLocation!.coordinate, addressDictionary: nil)
    destination = MKMapItem(placemark: desitnationPlacemark)
    let request:MKDirectionsRequest = MKDirectionsRequest()
    request.setSource(source)
    request.setDestination(destination)
    request.transportType = MKDirectionsTransportType.Walking

    let directions = MKDirections(request: request)
    directions.calculateDirectionsWithCompletionHandler ({
        (response: MKDirectionsResponse?, error: NSError?) in

        if error == nil {

            self.showRoute(response!)
        }
        else{

        println("trace the error \(error?.localizedDescription)")

        }
    })
 }

func showRoute(response:MKDirectionsResponse){
    for route in response.routes as! [MKRoute]{
        mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
        var routeSeconds = route.expectedTravelTime
        let routeDistance = route.distance
        println("distance between two points is \(routeSeconds) and \(routeDistance)")

    }

}

And you should implement this delegate method,dont forget to set the mapview delegate
  func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {

        if overlay is MKPolyline {
            var polylineRenderer = MKPolylineRenderer(overlay: overlay)
            polylineRenderer.lineDashPattern = [14,10,6,10,4,10]
            polylineRenderer.strokeColor = UIColor(red: 0.012, green: 0.012, blue: 0.012, alpha: 1.00)
            polylineRenderer.lineWidth = 2.5
            return polylineRenderer
        }
        return nil

    }

Answer: For Swift 2.1 :
func addRoutesOverLayForMapView(){

    var source:MKMapItem?
    var destination:MKMapItem?
    let Scoordinate = CLLocationCoordinate2D(latitude: passLat, longitude: passLong)
    var sourcePlacemark = MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: passLat, longitude: passLong), addressDictionary: nil)
    source = MKMapItem(placemark: sourcePlacemark)

    let DCoordinate = CLLocationCoordinate2D(latitude: lati, longitude: longi)
    var desitnationPlacemark = MKPlacemark(coordinate: DCoordinate, addressDictionary: nil)
    destination = MKMapItem(placemark: desitnationPlacemark)
    let request:MKDirectionsRequest = MKDirectionsRequest()
    request.source = source
    request.destination = destination
    request.transportType = MKDirectionsTransportType.Walking

    let directions = MKDirections(request: request)
    directions.calculateDirectionsWithCompletionHandler ({
        (response: MKDirectionsResponse?, error: NSError?) in

        if error == nil {

            self.showRoute(response!)
        }
        else{

            print("some error")

        }
    })
}

func showRoute(response:MKDirectionsResponse){
    for route in response.routes {
        mapView.addOverlay(route.polyline, level: MKOverlayLevel.AboveRoads)
        let routeSeconds = route.expectedTravelTime
        let routeDistance = route.distance
        print("distance between two points is \(routeSeconds) and \(routeDistance)")

    }

}

func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer {

     let polylineRenderer = MKPolylineRenderer(overlay: overlay)

    if overlay is MKPolyline {
        polylineRenderer.lineDashPattern = [14,10,6,10,4,10]
        polylineRenderer.strokeColor = UIColor(red: 0.012, green: 0.012, blue: 0.012, alpha: 1.00)
        polylineRenderer.lineWidth = 2.5
        return polylineRenderer
    }
    return polylineRenderer

}

Route not showing in MKMapView?


How can we avoid entering the path of every different file each time in a shell script?

Question: I have to submit a script for slurm. I should enter the directory path whenever I change the submit script path. for example if I am in folder1 I should write manually:
/home/job/folder1

if I want to use the script in folder2 I should write:
/home/job/folder2

Is there any command to avoid making this change manually?
PS: I know I can use $pwd but I did not find the right way.
Answer: With $PWD

PWD is an environment variable that is updated to contain the current directory,
$variable is replaced by the value of variable

This gives:
thescript $PWD

With $(pwd)

pwd is a command that prints the current directory
$(command) is replaced by the output of command

This gives:
thescript $(pwd)

Comment: @PRATAP No, as explained, they are two different things.


What is easy to perceive? Width or height?

Question: Let say I have to show the difference between two values then what will be the best to show the values horizontally or vertically.
Edit: I need to know in which graph it would be easier to compare the distance between two dots.
Comment: Can you please show images of what you mean by horizontal and vertical comparisons?
Comment: Looking at it from a biological point of view I'd argue that humans have a more fine tuned ability to compare sizes in a vertical orientation. And why is that? Well, we can quite easily move on a horizontal plane without difficulty, meaning that if we see food somewhere on a horizontal plane we simply have to move over there to get it, no cognitive registration what so ever. But when we see food somewhere up in a tree we have to judge whether we think we can make the climb or not. Therefore I'd assume that humans are more capable of judging vertical distances rather than horizontal.
Answer: We scan the pages left to right, so jumping quickly from two specific pairs of dots will be much easier on option A than option B.
But please do your users a favor and connect the dots in some way. If all that they do is compare the distances in individual pairs, just connect the top dots with the bottom dot, instead of forcing their brain to imagine the line.

If the overall trend is also important (or more important), then draw lines connecting dots of the same type.

You can also do both, with or without filling the area between the top and bottom line.

This will have a much greater effect than horizontal vs vertical layout.
Comment: There are formal conventions on how to graph data - so users will be used to the formats shown above.
Comment: Okay here if I add no data is related to its next or previous data  then what would you suggest?  I think connecting lines the dots with the line is givig the sense of increment which is not the case here.
Comment: Then I suggest going for the first option (vertical lines). You're afraid that drawing them with create an illusion of a trend and you're right, but from what I understand, your users are supposed to be familiar with the nature of the data and shouldn't be confused. Not connecting them for this reason is making the users work much harder just to avoid a vague possibility of them making a small and inconsequential one-time mistake.
Answer: Without some sort of context, I doubt you'll get an entirely useful answer...
That said, when stats are being compared on webpages using graphs (especially when comparing more than just two things), vertically presented horizontal bar graphs seem to work well and be most popular.
As a semi-random example: http://www.cpubenchmark.net/common_cpus.html
Imagine all that info arranged with vertical bars, listed across the page horizontally...


iPhone SDK : UIBarButtonItem not refreshing after Memory warning

Question: I'm facing a very strange behavior of UIBarButtonItem.
I have been able to reproduce the bug in a test app whose code has been pasted below.
On my first view I have a label displaying a GUID, a button to go to an empty second view, and a UIBarButtonItem. If I click it its color changes from green to red and vice versa and the GUID updates.
Here is how to reproduce it:

go to the second view
raise a memory warning (in the Simulator Hardware menu, but works the same with a real memory warning on the device)
go back to the first one
click the UIBarButtonItem

The UIBarButtonItem is not refreshing even if it was before and logs show everything seems correct.
ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController {
    @private
    BOOL _isGreenNotRed;
}

@property (weak, nonatomic) IBOutlet UIBarButtonItem *aButton;
@property (weak, nonatomic) IBOutlet UILabel *aGUID;
@end

ViewController.m
#import "ViewController.h"
#import "AFHTTPClient.h"
#import "AFHTTPRequestOperation.h"

@interface ViewController ()
- (NSString *)generateUUID;
- (void)refreshView;
@end

@implementation ViewController
@synthesize aButton;
@synthesize aGUID;

- (NSString *)generateUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return (__bridge_transfer NSString *)string;
}

-(void)refreshView {
    NSLog(@"Refreshing first view");

    if(self->_isGreenNotRed) {
        [self.aButton setTintColor:[UIColor colorWithRed:0. green:0.8 blue:0. alpha:1.]];
        NSLog(@"Button should be green");
    }
    else {
        [self.aButton setTintColor:[UIColor colorWithRed:0.8 green:0. blue:0. alpha:1.]];
        NSLog(@"Button should be red");
    }

    self->_isGreenNotRed = !self->_isGreenNotRed;

    NSString *guid = [self generateUUID];

    [self.aGUID setText:guid];
    NSLog(@"GUID should be %@", guid);
}

- (IBAction)aButtonClick:(id)sender {
    [self refreshView];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self->_isGreenNotRed = YES;
    [self refreshView];
}

- (void)viewDidUnload
{
    [self setAButton:nil];
    [self setAGUID:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NSLog(@"Going to second view");
}

@end

And the storyboard :

It affects Simulator 5.0 and 5.1, and Device on 5.1.1
EDIT : by logging the value of self.aButton I saw it became nil after the memory warning, due to the weak keyword. But how can I reassign it ? Shouldn't the SDK do it by itself ? And why is aGUID still available ?
EDIT : here is a log. we can see aButton becomes nil.
2012-07-19 14:39:14.716 test[934:f803] Refreshing first view
2012-07-19 14:39:14.718 test[934:f803] Button <UIBarButtonItem: 0x68b89d0> should be green
2012-07-19 14:39:14.719 test[934:f803] GUID label <UILabel: 0x6dbe580; frame = (49 291; 222 48); text = '08960AFD-F98A-4FBA-9A6E-C...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x6dbe5f0>> should be 08960AFD-F98A-4FBA-9A6E-C548E753F259
2012-07-19 14:39:18.690 test[934:f803] Refreshing first view
2012-07-19 14:39:18.692 test[934:f803] Button <UIBarButtonItem: 0x68b89d0> should be red
2012-07-19 14:39:18.692 test[934:f803] GUID label <UILabel: 0x6dbe580; frame = (49 291; 222 48); text = 'EBB41B52-46D1-4CAE-BF0E-B...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x6dbe5f0>> should be EBB41B52-46D1-4CAE-BF0E-B0679BC1F0EE
2012-07-19 14:39:19.946 test[934:f803] Refreshing first view
2012-07-19 14:39:19.949 test[934:f803] Button <UIBarButtonItem: 0x68b89d0> should be green
2012-07-19 14:39:19.949 test[934:f803] GUID label <UILabel: 0x6dbe580; frame = (49 291; 222 48); text = '8E802026-E825-4219-9CCA-5...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x6dbe5f0>> should be 8E802026-E825-4219-9CCA-5106BF65BDA0
2012-07-19 14:39:33.353 test[934:f803] Going to second view
2012-07-19 14:39:40.811 test[934:f803] Received memory warning.
2012-07-19 14:39:43.471 test[934:f803] Refreshing first view
2012-07-19 14:39:43.472 test[934:f803] Button (null) should be green
2012-07-19 14:39:43.473 test[934:f803] GUID label <UILabel: 0x6896570; frame = (49 291; 222 48); text = '3D4933A8-908B-4570-BD55-6...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x68b0130>> should be 3D4933A8-908B-4570-BD55-68C298F6E621
2012-07-19 14:39:48.649 test[934:f803] Refreshing first view
2012-07-19 14:39:48.650 test[934:f803] Button (null) should be red
2012-07-19 14:39:48.651 test[934:f803] GUID label <UILabel: 0x6896570; frame = (49 291; 222 48); text = '9CDCF065-12C2-4F16-9464-A...'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x68b0130>> should be 9CDCF065-12C2-4F16-9464-A5CE202BE7CA

Answer: Is refreshView getting called after the memory warning?
Try removing the code that sets the views to nil in viewDidUnload? Does it solve the problem?
Comment: refreshView gets called. I added a log in my question. and indeed removing the line from viewDidUnload did the trick, but this is weird isn't it ? Why does aGUID is always working but not aButton ? If the button were on the actual view it would be ok, so why is their a difference ? Isn't some kind of bug ?
Comment: I have no idea. It's not the same label though. After popping out from the second controller, it seems like the label gets recreated but not the bar button.


Axis2 1.5.1 connections management

Question: HttpConnections where not being used efficiently by our code using Axis2 1.5.1 project. By setting a certain limit of max connections per host and stressing the application, responsiveness was not the good I expected according the intentional limits and sometimes connections got stucked indefinitly, so the available connections were each time less till reaching the point that none request was attended by the application.
Configuration:
MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams connectionManagerParams = connManager.getParams();
connectionManagerParams.setMaxTotalConnections(httpMaxConnections);
connectionManagerParams.setDefaultMaxConnectionsPerHost(httpMaxConnectionsPerHost);

HttpClient httpClient = new HttpClient(connManager);

ConfigurationContext axisContext;
try {
    axisContext = ConfigurationContextFactory.createDefaultConfigurationContext();
} catch (Exception e) {
    throw new AxisFault(e.getMessage());
}

axisContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);

service = new MyStub(axisContext, url);

ServiceClient serviceClient = service._getServiceClient();

serviceClient.getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, httpConnectionTimeout);
serviceClient.getOptions().setProperty(HTTPConstants.SO_TIMEOUT, httpReadTimeout);
serviceClient.getOptions().setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);

So, as you can see, we're defining max. connections and timeouts.
I have a workaround I will share, hoping to help somebody under hurries as I was. I'll mark my answer as the good one a few days later if there isn't any better answer from experts.
Answer: 1) PoolTimeout to prevent the connections that got stucked (for any reason)
Next line helped us to prevent Axis2 to lose connections that got stucked forever:
httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 1000L);

Let's call it PoolTimeout in this entry. Make sure it's a Long, since an Integer (or int) would raise a ClassCastException that will prevent your service to even be triggered outside your client.
The system you're developing, and that is using Axis, could be in turn a client for another system. And that other system will have for sure an specific ConnectionTimeout. So I suggest
PoolTimeout <= ConnectionTimeout

Example:
serviceClient.getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, httpConnectionTimeout);
httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, Long.valueOf(httpConnectionTimeout) );

2) Connections release
I was using Amila's suggestion for connection management, but actually the connections were not released as fast as in advance I expected they would be (because I prepared consciously the delay times mocked external system would respond to fit limits accordingly my tunning configuration).
So I found that next lines, in method org.apache.axis2.client.OperationClient.executeImpl(boolean), helped to mark as available the connection in the pool as soon as it's been used:
HttpMethod method = (HttpMethod) getOperationContext().getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)
        .getProperty(HTTPConstants.HTTP_METHOD);
method.releaseConnection();

That's what Axis is trying to do when calling serviceClient.cleanupTransport() but it seems the context is not correct.
Now, performance tunning is working in a predictable way, so it's in hands of our integrators to select the tunning configuration that best suits production needs.
A better answer will be highly appreciated.
Comment: Note: To "override" *OperationClient.executeImpl(boolean)* standard behavior I created a copy of **ServiceClient**, **Options** and **OperationClient** and set them into my stub like these:

    stub._setServiceClient( serviceClient = new MyServiceClient(stub._getServiceClient()) );

These three classes are just delegating method calls to Axis original classes but overriding executeImpl to release the connection.

Axis2 1.5.1 connections management


Statements equivalent to the Axiom of Choice

Question: The Axiom of Choice reads:

The product of a collection of non-empty sets is non-empty.

As you know well, this axiom is equivalent to many other statements. A few examples (probably the most known) are the following:

Zorn's lemma: Let $(P,\ge)$ be a poset in which every chain has an upper bound. Then $P$ has a maximal element.

This is used in a number of different places to prove very powerful theorems. A couple of examples I can think of right now are: the proof that every ring has a maximal ideal (commutative algebra) and the Hahn-Banach theorem (functional analysis).

Well ordering theorem: Every set can be well-ordered (i.e. it admits a total order such that every subset has a least element).
Tychonoff's theorem: Every product of compact topological spaces is compact.

This is used for example in the proof of Alaoglu's theorem (again functional analysis).
Wikipedia gives various more. Among them:

Tarski's theorem: If $A$ is an infinite set, then there is a bijection $A\to A\times A$.

(As @Wicht dutifully commented, Tarski's theorem is the name given to the implication $|A|=A\times A \Rightarrow$ Axiom of Choice, while the other implication was known before the proof of this fact by Tarski.)

Every vector space has a basis.

My question is: what are other useful statements which are equivalent to the axiom of choice? Where are they used, and to prove what?
P.s.: By "useful statements" I mean either statements which are important theorems by themselves (as Tychonoff's theorem) or that are directly used in (simple versions of) the proof of important theorems (as Zorn's lemma).
Comment: There's like... a huge book of statements equivalent to the axiom of choice. Do you want them all, or just a few?
Comment: @Wicht Ok, thanks. I will add a note to the post.
Comment: There is a website dedicated to collect all this. Have you tried Google?
Comment: (As it stands, I am tempted to close as too broad. If you can narrow it down, then perhaps this can be reasonably answered.)
Comment: @AsafKaragila I am interested mainly in statements equivalent to the axiom of choice which are either kind of "big theorems" by themselves (like Tychonoff's theorem) or are directly used in the proof of such "big theorems" (an obvious example of this is Zorn's lemma). I will edit my question to make this clear.
Comment: Also see: http://www.orianhealth.com/mediawiki/images/7/72/Equivalents_of_the_Axiom_of_Choice._Part_I.pdf
Comment: This is not Tarski's theorem.
Comment: @Wicht On Wikipedia it's called Tarski's theorem: http://en.wikipedia.org/wiki/Tarski%27s_theorem
Comment: The statement there is different from yours, substantially different. Tarki's theorem is the assertion that $|A\times A|=|A|$ implies AC, whereas you present Tarski's theorem as claiming that AC implies $|A\times A|=|A|$.
Comment: @Wicht Are you sure the inverse implication is not true? It is listed in the page of "statements equivalent to AC" http://en.wikipedia.org/wiki/Axiom_of_choice#Equivalents
Comment: The inverse implication is true, but is not called Tarski's theorem. As stated on Wikipedia, the opposite direction was already known; but its just Wikipedia.
Answer: From the top of my head, some "big" equivalents to the axiom of choice.

Every commutative ring with a unity has a maximal ideal.
Every surjection has an injective inverse.
Every free abelian group is projective.
Every divisible abelian group is injective.
Skolem-Lowenheim theorems in model theory.
Every two cardinals are comparable. This is used often in "hiding" where we have two sets and we know that one necessarily injects into the other.
Every spanning set includes a basis (which is stronger than just the existence of a basis).
Every set is included in $L[A]$ for some $A$. Where $L[A]$ is a model of $\sf ZFC$. This can be used to prove certain things in set theory.

There are many many many more, and one can scrounge through Rubin & Rubin Equivalents of the Axiom of Choice II to find many of them including proofs.
Comment: @user170039: Not even remotely. It's a local statement about the real numbers. It also follows from the Hahn–Banach theorem, which is much weaker than the ultrafilter lemma, which doesn't even imply countable choice.
Comment: I suppose 2. means that every surjective $f:A\to B$ allows a $g:B\to A$ such that $f\circ g$ is the identity mapping on $B$. That is kind of a right-inverse to $f$. There will surely not be a left-inverse in general.
Comment: Clearly. Yes...
Comment: Isn't the Banach-Tarski Paradox also equivalent to AC?


Assemble - page titles in Pages collection

Question: On the Pages bit of the assemble.io docs, under Using YFM with the page variable, it has this:

    {{#each pages}}

{{../page.title}}

    {{/each}}

suggesting this will output the title (from each page's YFM) - if I paste that code into the top of example.hbs from the examples project it just outputs this (and I see the same thing in my own project):

Examples

Examples

Examples

Examples

Examples

Answer: It looks like the documentation has been updated since you posted this question. The correct handlebars code should be...

  {{#each pages}}

{{title}}

  {{/each}}

This is saying that for each page in the pages collection, write out an anchor tag that uses the title property on the current page within the loop.
I hope this helps.
Comment: Weirdly that doesn't work for me, it outputs nothing? Should I update anything?
Comment: I downloaded assemble-bootstrap and dropped your code into index.hbs and it outputs empty anchor tabs
Comment: I meant tags, not tabs
Comment: @jonschlinkert or I will take a look and see what's wrong.... Also... just to make sure, do the pages have a `title` property in the yaml front matter?
Comment: Yes - using assemble-bootstrap, all pages seem to have titles. Does this (bootstrap) work as described above for you? I just pasted in doowb's code
Comment: See here: https://github.com/assemble/assemble-bootstrap/blob/3.0.0-wip/docs/components.hbs#L2-L4. Then here: http://assemble.github.io/assemble-bootstrap/components.html. The subhead is where the title and lead render, and they work correctly there. Are you wrapping the page in another tag by any chance? Or are you using this as a partial?
Answer: The data for each page is exposed via the data object. Updated code below.

  {{#each pages}}

{{ data.title }}

  {{/each}}


Setup for OURLINK USB Wireless stopped working - Again

Question: I have one of these and it stopped working again.  It seems to be the latest Ubuntu update that got it.  Neither of the earlier solutions work so I have to go back to the earlier version of Ubuntu.  Are there any recommendations to fix or maybe a recommendation for a wireless adapter for desktop more compatible with updates?
see for earlier experience
Setup for OURLINK USB Wireless stopped working
More detail from the non working version. 4.13.0-45 works.  I'm also getting a system error but it seem unrelated.  See pics.enter image description here
dan@Pavilion:~$ sudo dkms status
[sudo] password for dan:
rtl8812au, 4.2.2, 4.13.0-45-generic, x86_64: installed
dan@Pavilion:~$
dan@Pavilion:~$ uname -r
4.15.0-24-generic
dan@Pavilion:~$
Comment: Please edit your question to show the result of: `sudo dkms status` and also: `uname -r`
Answer: I found a solution here:
https://github.com/gnab/rtl8812au/issues/144
1: git clone https://github.com/gnab/rtl8812au
2: cd rtl8812au
3: wget https://github.com/msharov/rtl8812au/commit/296fb88cf466fe07fffd1b9d2f42a33c420ceb1d.patch
4: patch -p1 < *.patch
5: sudo make && sudo make install


Continuity of distance function and its generalization

Question: The starting is an easy undergraduate problem. The distance function $d: X \times X \rightarrow \mathbb{R}$ in a metric space $(X,d)$ is continuous. Please check if my proof is correct. If it is wrong please give some hint for the accurate proof.
From the triangular inequality we can say $d(x,y) \le d(x,z) + d(y,z)$ i.e. $d(x,y) - d(z,y) \le d(x,z)$
Interchanging the role of $x$ and $y$ we shall get $|d(x,y) - d(z,y)| \le d(x,z)$.
Now for any $\epsilon > 0$ $|d(x,y) - d(z,y)| < \epsilon$ when $d(x,z) < \delta$ where $\epsilon = \delta$.
Thus $d$ is uniformly continuous and hence continuous.
The main problem is here.

I am thinking to prove it by using the open set definition of continuous function in a general topological space. Basis open sets of $\mathbb{R}$ with usual metric is open intervals $(a,b)$. Its inverse in the metric space will be an open set. How to prove it?
Can we generalize the concept of distance function to an arbitrary order topology? I want to say if we can replace the range $\mathbb{R}$ of the distance function $d$ by a linear continuum or an arbitrary order topology.

Thank you very much for your help.
Comment: If you show that $|d(x,y)-d(z,y)|<ϵ$ when $d(x,z)<ϵ$, then this tells you that the function
$$X\to \Bbb R\\
x\mapsto d(x,y)$$
is uniformly continuous. However, you want to show that the function
$$d:X\times X\to\Bbb R\\
(x,y)\to d(x,y)$$
is continuous. To do that, show continuity at a point $(x_1,y_1)$. For an $ϵ>0$ find a $δ$ s.t. $|d(x_1,y_1)-d(x_2,y_2)|<ϵ$ whenever $D((x_1,y_2),(x_2,y_2))<δ$, where $D$ is the distance function on $X\times X$ which is defined as
$$D((x_1,y_2),(x_2,y_2))=d(x_1,x_2)+d(y_1,y_2)$$
**Hint:** Use the equation $|d(x_1,y_1)-d(y_1,x_2)|<d(x_1,x_2)$ and a similar one.
Comment: On occasion, metrics are [generalized to arbitrary ordered fields](http://en.wikipedia.org/wiki/Generalised_metric) other than $\Bbb R,$ and sometimes [to other directed sets](http://en.wikipedia.org/wiki/Metric_(mathematics)#Extended_metrics).
Comment: @StefanH Thank you for your reply. Whatever you have written is clear to me. What for other two questions?
Comment: @Cameron Buie. Thank you for your links. It was unknown to me.
Answer: In general,if $X,Y$ are any spaces, a function $f:X\times X\to Y$ may have the property that the functions  $f^{(1)}_a:X\to Y$ and $f^{(2)}_a:X\to Y$ are continuous for every $a\in X,$ where $f^{(1)}_a(x)=f(a,x)$ and $f^{(2)}_a(x)=f(x,a),$ and yet $f$ may still not be continuous.
What you need to show is that when $u,v\in \mathbb R$ with $u<v$ then $d^{-1}(u,v)=\{(a,b)\in X:u <d(a,b)<v\}$ is open in the space $X\times X.$
An open set in $X\times X$ is a union of a family of sets of the form  $C\times D$ where $C,D$ are open balls in $X.$ So it suffices to show that if $(a,b)\in d^{-1}(u,v)$ then $C\times D\subset d^{-1}(u,v)$ for some open balls $C,D$ of $X$ with $(a,b)\in C\times D.$ That is, with $a\in C$ and $b\in D.$
For $d(a,b)\in (u,v),$ let $w=\min (d(a,b)-u,\; v-d(a,b)).$ We have $w>0$ so $a\in B_d(a,w/2)$ and $b\in B_d(b,w/2)$.
For $a'\in B_d(a,w/2)$ and $b'\in B_d(b,w/2)$ we have $$\text {(i)} \quad d(a',b')\leq d(a',a)+d(a,b)+d(b,b')<w/2+d(a,b)+w/2\leq v$$  and  we have $$\text {(ii) }\quad  d(a,a')+d(a',b')+d(b',b)\geq d(a,b)$$  which implies $$\text {(ii') }\quad  d(a',b')\geq d(a,b)-d(a,a')-d(b',b)>d(a,b)-w/2-w/2\geq  u.$$ Therefore $$(a,b)\in d^{-1}(u,v)\implies (a,b)\in B_d(a,w/2)\times B_d(b,w/2)\subset d^{-1}(u,v).$$
Remark: For an example of an $f$ of my first paragraph, let $X=Y=\mathbb R,$ let $f(0,0)=0$ and let $f(x,y)=xy/(x^2+y^2)$ when $x^2+y^2\ne 0.$ If $x\ne 0$ then $f(x,x)=1/2$ so $\lim_{x\to 0^+}f(x,x)=1/2\ne f(0,0)$. So $f$ is not continuous at $(0,0).$
Answer: Let $\{(a_n,b_n)\}_n\subseteq X\times X, (a,b)\in X\times X, (a_n,b_n)\to(a,b)$. We claim that $d(a_n,b_n)\to d(a,b)$.
First observe that $\forall n:d(a_n,b_n)\leq d(a_n,a)+d(a,b)+d(b,b_n)$
$\implies \limsup d(a_n,b_n)\leq \limsup (d(a_n,a)+d(a,b)+d(b,b_n)) $
$=\limsup d(a_n,a)+\limsup d(a,b)+\limsup d(b,b_n)= d(a,b)$ (equality holds when distributing limit superior over two sequences when one of them is convergent and the other one is bounded $(*)$). Hence $\limsup d(a_n,b_n)\leq d(a,b)$.
Conversely, $\forall n: d(a,b)\leq d(a,a_n)+d(a_n,b_n)+d(b_n,b)$
$ \implies d(a,b)\leq \liminf (d(a,a_n)+d(a_n,b_n)+d(b_n,b))=\liminf d(a_n,b_n)$
by an analogue of $(*)$. Thus $\limsup d(a_n,b_n)\leq d(a,b)\leq \liminf d(a_n,b_n)$, so that $d$ is continuous.
Answer: Take any open ball $B=(d(x,y)-\epsilon,d(x,y)+\epsilon)$ in $\Bbb{R}$. Then the inverse image $d^{-1}(B)\supseteq B_d(x,\epsilon/2)\times B_d(y,\epsilon/2)=U$, since for any $(z,t)\in U$, $d(z,t)\leq d(z,x)+d(x,t)<\epsilon/2+d(x,y)+d(y,t)<\epsilon+d(x,y)$. Similarly $d(x,y)<\epsilon+d(z,t)$.   So, $|d(x,y)-d(z,t)|<\epsilon$ as desired!


What determines the rate at which I recover stamina?

Question: During my trip through the tutorial dungeon, I noticed my stamina seemed to recover more slowly with the more weight my character carried. Since I plan on specializing in two-handed weapons, it's important for me to understand what factors increase or decrease stamina regeneration so I can prevent myself from running out of stamina at crucial moments in epic battles. What other factors affect the rate at which I recover stamina?
Answer: I don't know about the weight thing. I tested it and I didn't notice any difference. I can't guarantee it though, maybe it has something to do with armor worn, perks etc.
What I can tell you is that there are the following ways of recovering stamina, apart from letting stamina restore over time:

Drink stamina potions
Choosing the "Respite" perk in the Restoration tree will make it so healing spells also recover stamina
Some types of food restore stamina.
Stamina is fully restored on level up.
Sleeping and waiting fully restores stamina (regardless of the length)

This is mostly from http://www.uesp.net/wiki/Skyrim:Restoration.
Also, as a neat bonus: When you sprint, don't let stamina drain completely, since it will take a couple of seconds before it starts recharging again. If you sprint until you have just a little bit of stamina left, the stamina will start recharging immediately.
source: http://www.reddit.com/r/skyrim/comments/m9wfo/tip_when_sprinting_dont_let_stamina_completely/
Comment: There are also enchantments that increase stamina regeneration speed.


toggle element by numerical value of data attribute in django template

Question: I have a list of group names and for each group name i have a list of students names.
I want to show the list of names under each group on the click of group name.
for eg.
group 1(#clicked)
    A
    B
    C
group 2(#not clicked)
group 3(#clicked)
    F
    E
    R

I have two models
1: Groups(id,name)
2: Students(id,name,group_id)
HTML:-
{% for group in groups%}
{{group.name}}Click To ExpandGroup created Date:{{group.update_date}}

    {% for stu in group.students_set.all %}
    {{stu.name}}
{%endfor%}

{%endfor%}

I want to send group id as attribute and use it to dispaly only those names which match the group_id.
My Html gives me correct names under each group. All i want is to toggle them on click of group name.Right now it toggles all the names under all the groups.
EDIT:
JAVASCRIPT:
nameDisplay = function () {
    $(".clickSpan").click(function () {
        $(".group-list").next('.name-list').toggle()
    });
}

clickSpan is the class of the span that i added against each group name which says "click to exapnd". How will i be able to achieve the same target with this?
Also it will be better if i can get "click to collapse" here when it is expanded.
Comment: Where is elements with these `students-list`, `class-list` and `name-list` CSS class?
Answer: You can simply use .next(), or other methods to traverse using the element for which event is triggered then can use .toggle() method

Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

$(".group-list").click(function(){
    $(this).next(".name-list").toggle();
});

There is no need for additional attribute.
Answer: In your markup the group-list element and the name-list that has to be toggled are sibling elements so you can make use of that relationship to toggle the correct element.
There is no need to have another attribute to do that.
nameDisplay = function () {
    $(".name-list").hide();
    $(".group-list").click(function () {
        $(this).next('.name-list').toggle()
    });
}

Also it will be better to use a css rule to set the default hidden state of name-list like
.name-list {
    display: none;
}

then use the click handler to make it visible
nameDisplay = function () {
    $(".group-list").click(function () {
        $(this).next('.name-list').toggle()
    });
}

Comment: @FullOfQuestions `$(this).parent().next('.name-list').toggle()`
Comment: great.thnx for the help sir.
Comment: I have edited my question. regarding click to expand and click to collapse span. can you please help me with this.
Comment: @FullOfQuestions can you share the html for `clickSpan`


Make Jade (Pug) fail if variable cannot be resolved

Question: It seems that if Jade (Pug) cannot resolve a variable it treats it as not set.
Is there a possibility to make it fail during rendering of the template?
Controller code:
exports.index = function (req, res) {
    res.render('index', {})
};

Template code:
extends layout
block content
    p Value is "#{val}"

Result:

Value is ""

This does not detect bugs early and thus I would like Jade to throw an exception when something like this happens. Is it possible ?
Comment: show the code please.
Answer: You should be able to use conditionals for this like so:
block content
  if val
    p Value is "#{val}"
  else
    p Value is undefined

or
block content
  if val !== ""
    p Value is "#{val}"
  else
    p Value is undefined


I don´t know how to add a search function within this app in React

Question: I am coding a small app in React as part of a bootcamp assignment. The app should be able to do the following:
-An app with a list of workers, to be displayed: OK
-To be able to add more workers (email and name) and have them added to the list: OK
-Clear the form after submission: OK
-Use encapsulated components for the different functions: OK
-Use some boostrap: OK
-Create a search engine to find the workers in the list, either the old ones or the new ones: Thi is NOT OK.
The employees data base is a JSON file included in the .src folder.
I am doubtful about how to create the filter and how the function should be if the same must be in the App.js or maybe another component.
Link to github repository:
https://github.com/guslopezr/desafio_renderizacion_listaempleados
App published on Vercel (Search function not yet working).
https://desafio-renderizacion-listaempleados.vercel.app/
Any help will be much apprecciated.
Best,
Gustavo
Answer: You need to use useCallback hook at buscarEmpleado method and add datosTabla state as follow:
function App() {
  const [empleados, setEmpleados] = useState(trabajadoresDB);
  const [empleado, setEmpleado] = useState({});
  const [datosTabla, setDatosTabla] = useState(trabajadoresDB);
  //console.log(empleados);

  // to update datosTabla on any empleados changes
  useEffect(() => {
    setDatosTabla(empleados);
  }, [empleados]);

  const guardarEmpleado = (empleado) => {
    setEmpleados([...empleados, empleado]);
  };

  const buscarEmpleado = useCallback(
    (e) => {
      e.preventDefault();
      const search = empleados.filter((empleado) =>
        empleado.name.toLowerCase().includes(e.target.value.toLowerCase())
      );
      console.log(search);
      setDatosTabla(search);
    },
    [empleados]
  );

  return (

      <Buscador buscarEmpleado={buscarEmpleado} />

      <FormularioApp guardarEmpleado={guardarEmpleado} />

      <TablaEmpleados key={empleado.id} empleados={datosTabla} />

  );
}

export default App;

Comment: This is amazing, thanks a lot for your support. I will give this a try at the earliest.


Ubuntu bq Aquaris 3g always showing roaming is on

Question: I have a bq aquaris E4.5 Ubuntu edition. If I connect to the 2g service, all is well. I can speak on the phone, use my mobile internet connection, no problem.
If instead I try to use the 2g/3g service, I always get the roaming text in the notification bar, even though I never had active roaming on my prepaid card and the roaming setting in Ubuntu phone is set to off.
How can I fix this?
Comment: Where do you live and which is your ISP?

It might be that it uses external services to provide 3G access. As an example, my gf lives in France and she has Free, who does something similar. She has to enable roaming to use the internet. Does the net work when you see the roaming notification?
Comment: I live in Romania, and the ISP is Telekom Romania, the phone found it nad selected it as active ISP, so it should not have any roaming active.
Comment: Fill the bug as suggested, that's the best thing to do :)
Answer: Can you report a bug about that on https://bugs.launchpad.net/ubuntu/+source/indicator-network/+filebug ?
Answer: After all kind of searching the web for solutions I found out that my carrier (Telekom Romania) is transmitting 3G over the network of another carrier that was bought by the company some time ago.
It appears that their infrastructure is based on a kind of roaming between the 2G and 3G services and will only work on Ubuntu phones if you enable both 3G cellular data AND data roaming.
This way it works juns fine, and the roaming service that the system is detecting is correct AND free inside the Telekom Romania network.
Maby this will help someone when using Ubuntu phones inside Romania using Telekom.


How to check if any rows exists and rerurn boolean POSTGRES

Question: Two simple table
table a (id bigint, name varchar)

table b (id bigint, a_id bigint, notice varchar)

how to get id from a and boolean exist_notice if any rows exists in table B for this id
without subselect and without count
Answer: you can use a left join and a case when:
create table a (
  id bigint,
  name varchar
  );

create table b (
  id bigint,
  a_id bigint,
  notice varchar
  );

insert into a values(1,'a1'), (2,'a2'), (3,'a3');
insert into b values(1,1,'b1'), (2,2,'b2');

select
a.id as a_id,
  case when b.a_id is null then false else true end as in_b
from a
left join b on b.a_id = a.id

a_id
in_b

1
t

2
t

3
f

fiddle
edit:
to remove duplicates:
select
a.id as a_id,
  case when b.a_id is null then false else true end as in_a
from a
left join b on b.a_id = a.id
group by 1,2

edit 2:
select
a.id as a_id,
b.a_id is not null
from a
left join b on b.a_id = a.id
group by 1,2

Comment: i remove CASE WHEN with a_id is NOT NULL
Comment: Your CASE expression can be simplified to `b.a_id is not null`
Comment: yes it works but it return duplicates and i do not want to use distinct.
Comment: https://dbfiddle.uk/5oEbjiAF
Comment: then use a group by 1,2 at the end, see edit
Comment: yes its that i need , thx Freddy


JavaScript time compare

Question: I have now the following code:
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + ":" + curr_minute;

var open_time = "17:00";

if(Date.parse ( curr_time ) > Date.parse ( open_time )){
   alert("Webshop is open");
} else {
   alert("Webshop is closed.");
}

What the code should do is.. if the current time is greater then 17:00 send the alert and if not, send the other alert.. All i get now is that it is closed.
Comment: For one, you're missing an `else`
Comment: Ahh.. yeah I fixed that, still not working.. (stupid lol)
Answer: You don't need all that parsing, you already know getHours() method!
if(new Date().getHours() >= 17)

...that's it!
Comment: Very simple, and very usefull. Thanks Tomasz!
Comment: Ya, note however that this also picks up when the time is 17:00. You need to only get the time greater than 17:00. So, check the seconds and minutes as well. I posted the code in one of the answers
Answer: You can't just parse time in hh:mm format. Give it an arbitrary date (Jan 1, 2012 in this case) to make it a full date object. The date doesn't matter as long as it's the same for both.
if(Date.parse('01/01/2012 ' + curr_time) > Date.parse ('01/01/2012 ' +  open_time)){
   console.log("open");
}else{
   console.log("closed");
}

A simpler approach would be to just compare the hours and minutes since that's what you have.
curr_hour > open_hour && curr_minute > open_minute

Answer: Why create date objects? Just use basic math.
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_time = curr_hour + curr_minute/60;

var open_time = 17;
var openClosed = curr_time > open_time ? "Open" : "Closed";

alert("Webshop is " + openClosed + ".");

Answer: Try this:
var d = new Date();
var curr_hour = d.getHours();
var curr_minute = d.getMinutes();
var curr_second = d.getSeconds();

if((curr_hour > 17) || (curr_hour == 17 && curr_minute == 0 && curr_second == 0 )){
   alert("Webshop is open");
} else {
   alert("Webshop is closed.");
}

Comment: Ah ya... we will need to check the == 17:00:00 condition separately. Just amended

JavaScript time compare


TestNG tests not running in parallel

Question: I am frustrated with this issue. I have 3 nodes running with multiple browsers and grid starts nicely. Then I have a test suite that has 3 tests in it with multiple tests in each test. When I execute the tests, three browsers get occupied but after some time only one browser in first node stays occupied and the other two nodes just stay idle. Here is my setup code
public void setUpEagle() throws Exception {
        DesiredCapabilities cap = DesiredCapabilities.firefox();
        cap.setBrowserName("firefox");
        cap.setPlatform(Platform.ANY);
        ffdriver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), cap);

        eagleLogin = new EagleLogin();
        LaunchEagle launchEagle = new LaunchEagle();
        driver = launchEagle.setUp(eagleLogin, LP1_GeneralManager, NonProductionPassword);

        // Print the Class Name
        System.out.println("Test Starting: " + this.getClass().getName());

        menuItem = new MenuItems();
        menu = new Menu();

        verify = new Verify();
    }

//testng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="MRS_TestNGSuites1" verbose="10" parallel="tests" thread-count="30">

<test name="mrs_testsuite1" junit="true">
    <classes>
        <class    name="com.squaretwo.eagle.smoketests.noninvasive.AccountAssignmentTestNI"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountCommentPODDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountDebtorPODAddressDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountDebtorPODEmailDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountDebtorPODPhoneDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountDebtorPODPInfoDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountDebtorTearOffTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountFinancialPODDataVerifyTest"/>
    </classes>
 </test>

 <test name="mrs_testsuite2" junit="true">
    <classes>

        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountHeaderViewTest"/>
        <class name="com.squaretwo.eagle.test.accounts.AccountID_CTC_US5211Test"></class>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountNotelineDataVerifyTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountNotelineTearOffTest"/>
        <class name="com.squaretwo.eagle.test.accounts.Account_ReOpen_And_CancelTimTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.PerformanceLegalAccountSearchTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AdvDebtorsLifecycleCancelledTest"/>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AdvSearchAcctNumberTest"/>
    </classes>
 </test>
 <test name="mrs_testsuite3" junit="true">
    <classes>
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AdvSearchLifecycleCancelledTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AdvSearchMultipleCriteriaTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AdvSearchSaveCriteriaTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountPODDataVerifyTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountPODMediDataVerifyTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountStatusPODDataVerifyTest" />
        <class name="com.squaretwo.eagle.smoketests.noninvasive.AccountsTouchedReportTest" />
        <class name="com.squaretwo.eagle.test.accounts.AddPaymentPlanArrangement" />
    </classes>
 </test>

Comment: whats ur suite file like?
Comment: Here is my testng.xml. All my classes have the same setUpEagle()
Answer: You have parallel=tests in your suite xml and only 3 tests in it (<test>). So you actually running no more than 3 browsers at a time. One of your <test>'s runs longer than other two thats why "after some time only one browser in first node stays occupied and the other two nodes just stay idle".

TestNG tests not running in parallel


Fix "Type 'CMTime' has no member 'zero'" error in Xcode, for 16.2?

Question: It seems that currently (14.2 (14C18)) if you use CMTime.zero
self.player?.seek(to: .zero, toleranceBefore: .zero, toleranceAfter: .zero)

or
self.player?.seek(to: .zero)

you'll see the error

However, the project does compile and run perfectly.
For the file, I import
import UIKit
import CoreMedia
import AVFoundation
import MediaPlayer
import AVKit

(And if I try removing some/all of those it makes no difference; I can't find a fix anyway.)
It seems that if you wind back to minimum deployment 16.0 (rather than current 16.2) the warnings do go away, but the behavior is a bit erratic.
Is anyone familiar with this and/or has a solution?
Comment: BTW for anyone reading here, a handy way to find the derived data folder is, just tap command-comma, Locations tab, and you'll see the current location is given (tap the small circle arrow to bring it up in finder, quit xcode, then just trash the whole derived data folder).  thanks @HangarRash !!
Comment: Not advertising. Not my app. :)
I use the free DevCleaner app for convenience. It cleans up Derived Data, support files for outdated OS versions, logs, and so on, at the user's option.
https://itunes.apple.com/app/devcleaner/id1388020431
Comment: Weird stuff like this can usually be resolved by quitting Xcode, deleting the `~/Library/Developer/Xcode/DerivedData` folder, restarting Xcode, a loading the project again.
Comment: It's a great point @HangarRash .. and indeed .. that fixes it!  I can repro the problem even after doing that, but, that seems to be the only solution.  perhaps U should put it in as an answer to help googlers...
Answer: I had the same issue and tried to delete ~/Library/Developer/Xcode/DerivedData as suggested by the comments, but they didn't work. I was able to fix it by changing the Swift Language Version to Swift 5 in Build Settings. I was using Swift 4 previously.

My setup is Xcode 14.2, trying to build to an iPhone with iOS16.1.


Does cancelling the operation while copying a .mkv file split it into 2 parts?

Question: I was copying a movie (.mkv) file from pen drive to PC (Ubuntu) and it showed error while copying, so I had to cancel it. The file size was 3.2 GB. Now the file on Pen drive still shows size 3.2 GB but there's also a file on my PC of 311 MB. Did cancelling it destroyed that 311 MB data from 3.2 GB?
In simple words, is my file on pen drive is still same as before copying and cancelling?
Answer: No, canceling a copy or a move of a file does not modify the original file.
Your 3.2 GB file is still intact as it was before the move/copy.
In fact, when you copy a file from one location to another, the original file is not modified in any way whether the copy was finished, canceled or interrupted.
And when you move a file to a different filesystem (for example, in your case from your pen drive to your PC's internal drive), the file will be copied first (as if you are doing a normal copy), and only then is the original deleted. So in this case, the original file doesn't get modified either if the move was canceled or interrupted.
Comment: Are you sure about the second point? Moving a (huge) file *within* a filesystem is usually a matter of < 1 second, so I doubt it'll be actually copied. But you are probably right for moving files *between* filesystems. And since the OP used a pen, the file is moved between filesystems here.
Comment: @Jost he is correct. topic is about moving from/to a stick to/from ubuntu. On the same partitions what changes is not the file but the directory content (and that is flipping a node so almost instant)
Comment: @Jost yeah, I only meant moving them between file systems, I'll clarify it in my answer. Thanks for the note.
Comment: @Jost The answer is correct. Within the same filesystem, `mv` just calls `rename()` whereas while `mv`-ing between filesystems, the content is first copied by `read()`s-`write()`s, only after these become successful, the file is `unlink()`-ed from source directory.


LLhood for t-dis

Question: What is the mistake in the following code for the loglikelihood function of the t-distribution:
loglike <- function(p,x){
  mu <- p[1]
  sgm <- p[2]
  df <- p[3}
 ll <- dt((x-mu)/sgm, df=d)
 sum(log(ll)
}

Answer: You just missed dividing by sigma because of the cdf:
loglike <- function(p,x){
  mu <- p[1]
  sgm <- p[2]
  df <- p[3}
 ll <- dt((x-mu)/sgm, df=d)\sgm
 sum(log(ll)
}

Same if you want to calculate the LL for the normal distribution:
loglike <- function(p,x){
  mu <- p[1]
  sgm <- p[2]
 ll <- dnorm((x-mu)/sgm)/sgm
sum(log(ll)
}

You again divide by sigma

LLhood for t-dis


When Dolphin lists the results of a search, how can you display the full path of a result?

Question: I'm running Kubuntu 20.04. When Dolphin lists the results of a search, how can I find the full path to one of the results?
Comment: Don't you have `Copy Location` in the right-click-menu?
Comment: Copy Location simply isn't in the menu that I get after right-clicking an item (eithr
Comment: Copy Location is not in the menu that I get after right-clicking either a file or a folder.  Is there something I'm missing?
Comment: What exactly would the (nonexistent) Copy Location action do anyway? I can get the effect of Move by dragging the files to the place I want them to be, but that is only reliable if the dragging distance is small.  If it's not small, it's too easy for the mouse to slip a bit and make the file(s) land in the wrong place.
Comment: It would be very nice if Shift-righticlick
Comment: I was starting to say that it would be very nice if shifting would change Copy into Move.
Answer: In the search result, do a right-click on the result headers (e.g. Name, Size, etc.). In the submenu that pops up, you'll find "path" under "other" category.
This at least works for me on KDE Neon 5.24.