java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CardView.setVisibility(int)' on a null object reference

Question: I am trying to animate a Cardview when FAB is pressed. I want to get circular animation. Initially Cardview is set to Invisible. But, it is trowing null object reference on CardView.setVisibility.
public class FeedFragment extends Fragment {

private FloatingActionButton floatingBtn;
private CardView cardView;
boolean flag = true;
public FeedFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_feed, container, false);

    floatingBtn = view.findViewById(R.id.floatBtn);
    cardView = view.findViewById(R.id.cardView);

    floatingBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(flag) {

                // Check if the runtime version is at least Lollipop
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                    // get the center for the clipping circle
                    int cx = cardView.getWidth() / 2;
                    int cy = cardView.getHeight() / 2;

                    // get the final radius for the clipping circle
                    float finalRadius = (float) Math.hypot(cx, cy);

                    // create the animator for this view (the start radius is zero)
                    Animator anim =
                            ViewAnimationUtils.createCircularReveal(cardView, cx, cy, 0, finalRadius);

                    // make the view visible and start the animation
                    cardView.setVisibility(View.VISIBLE);
                    anim.start();
                } else {
                    // set the view to visible without a circular reveal animation below Lollipop
                    cardView.setVisibility(View.VISIBLE);
                }

                flag = false;
            } else {

                // Check if the runtime version is at least Lollipop
                if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                    // get the center for the clipping circle
                    int cx = cardView.getWidth() / 2;
                    int cy = cardView.getHeight() / 2;

                    // get the initial radius for the clipping circle
                    float initialRadius = (float) Math.hypot(cx, cy);

                     // create the animation (the final radius is zero)
                    Animator anim =
                            ViewAnimationUtils.createCircularReveal(cardView, cx, cy, initialRadius, 0);

                   // make the view invisible when the animation is done
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            cardView.setVisibility(View.INVISIBLE);
                        }
                    });

                 // start the animation
                    anim.start();
                } else {
                    // set the view to visible without a circular reveal animation below Lollipop
                    cardView.setVisibility(View.VISIBLE);
                }
                flag = true;
            }

        }
    });

    return view;
   }
  }

Here is the XML code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.authent.authentication.FeedFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="bottom">

    <android.support.v7.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="208dp"
        android:layout_gravity="bottom"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        app:cardCornerRadius="20dp"
        android:visibility="gone">

        <LinearLayout
            android:id="@+id/linearReveal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:visibility="gone">

            <Button
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:background="@color/white"
                android:text="Ask a Query"
                android:textSize="24dp"
                android:textAllCaps="false"
                android:textColor="#00ccff"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/darker_gray"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:background="@color/white"
                android:text="Share Something"
                android:textSize="24dp"
                android:textAllCaps="false"
                android:textColor="#ff3300"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:background="@android:color/darker_gray"/>

            <Button
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:background="@color/white"
                android:text="Post an MCQ"
                android:textSize="24dp"
                android:textAllCaps="false"
                android:textColor="#cc9900"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatBtn"
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:layout_gravity="end"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="16dp"
        android:layout_marginRight="16dp"
        android:src="@drawable/edit_nick_name" />

</LinearLayout>

Somebody help how to achieve circular animation. I am new to programming.
I also tried making LinearLayout INVISIBLE, it is also throwing NullPointerException on LinearLayout.setVisibility on a null object reference.
Thanks in advance.
Comment: Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it)
Comment: In your `onclick(View view)` you have used `cardView = view.findViewById(R.id.cardView);`. here the view is local object that is **onclick view object**
Answer: Intilaize cardview outside of the "clickListener".
Comment: It is working. But Buttons are not visible. how to do that
Answer: Your CardView is null. Based on your code, you are trying to get the CardView from the View that received the onClick which is the FloatingButton.
Try calling the initialization outside just before the listener. Ideally on the same level as where you initialized the FloatingButton.
Comment: yes. worked but Buttons are not appearing on cardview. How to do that
Comment: @ThrinadhReddy how about instead of making the CardView GONE, how about you hide the Cardview's container instead, which is the LinearLayout? Then you show it, then still apply the animation on the CardView.
Comment: But, I want to hide cardview too.
Comment: @ThrinadhReddy doesn't hiding the LinearLayout that hides the CardView hide it also?
Comment: Thank You. solved. But, when I click again the FAB button, it is not going to invisible state. I have posted the full code. please tell me where it went wrong
Comment: @ThrinadhReddy your code didn't have any code that makes it back to invisible state. Basically a simple approach to that is to do boolean visibility = cardView.getVisibility(); then cardView.setVisibility(!visibility); or somethign like that. Or just keep a flag for the state of visibility for your cardView within the Fragment class.
Comment: I have added the full code.. tell me where i went wrong
Comment: @ThrinadhReddy can you add a breakpoint and see if this was called. cardView.setVisibility(View.INVISIBLE);
Comment: I have edited the code.. have a look at it and please tell me. why it is not working
Comment: You can easily check it with the debug feature of the Android Studio, to see if the code where you set it to INVISIBLE was actually called. Or even via Log.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/167458/discussion-between-jojo-narte-and-thrinadh-reddy).
Answer: You just need to remove this line cardView = view.findViewById(R.id.cardView);
and paste it before
    floatingBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

       return view;
 }

Comment: @ThrinadhReddy because your visibility of linear layout is set to "Gone" in xml..change it to "visible"
Comment: I have posted the full java code. I want that cardView to be invisible, when the user pressed FAB button again, but it is not working. where i went wrong
Comment: change your xml to this :
Comment: im posting a xml file just copy paste that and on click on fab button just set the visiblity of linear layout (whose id is main_linear)


satellite map view not show in fragment

Question: @EFragment(R.layout.main_map)
public class MapActivity extends Fragment {
      private GoogleMap map;
      static final LatLng DURG = new LatLng(21.1900,81.2800);

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_map, container, false);
        map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        return view;
    }

}

Null pointer exception error occure at map.setMapType(GoogleMap.MAP_TYPE_SATELLITE).

R.layout.main_map:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <fragment
        android:id="@+id/map_fragment_id"
        android:name="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

Comment: Please share your `R.layout.main_map`. You need to initialise your `map` variable, it is null.
Comment:
Comment: First call `map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map_fragment_id)).getMap()`, then `map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);`
Answer: You need to add MapFragment Dynamically when you want to inflate a MapFragment inside a Fragment.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.main_map, container, false);
    SupportMapFragmentmf = SupportMapFragment.newInstance();
    FragmentManager fm = getChildFragmentManager();
    fm.beginTransaction().replace(R.id.mapView, mf, "normal_map").commit();
    mf.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap arg0) {
            map = arg0;
            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        }
    });
    return view;
}

where your main_map should be like below
 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

I hope that helps. Please let me know if you have any doubts.
Comment: my mistake, i edited it.please try the edited one and let me know.
Comment: replace() in FragmentTransaction can not be applied to android.support.v4.app.Fragment mf (com.google.android.gms.maps.MapFragment)
Comment: i have edited it again. I did not  know that you are using supportFragments. Try the updated answer.
Comment: this = {sjain.ventures.nanotaxi.fragment.MapActivity$1@830038993760}
this$0 = {sjain.ventures.nanotaxi.fragment.MapActivity_@830038916328}"MapActivity_{422cbce8 #0 id=0x7f0a006b HOME}"
contentView_ = {android.widget.RelativeLayout@830038985592}"android.widget.RelativeLayout{422dcb78 V.E..... ......I. 0,0-600,887}"
onViewChangedNotifier_ = {org.androidannotations.api.view.OnViewChangedNotifier@830038916560}
map = null
mActivity = {sjain.ventures.nanotaxi.MainActivity@830037052512}
mWho = {java.lang.String@830038928096}"android:fragment:0"
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/78082/discussion-between-dora-and-roshan-bharti).
Comment: on   map.setMapType(GoogleMap.MAP_TYPE_SATELLITE); it crashes
Answer: you should use
getMapAsync(OnMapReadyCallback callback)

then in the callback you can set the map to satellite view

satellite map view not show in fragment


where to addObserver in iOS

Question: I use Objective-C to develop an iOS tabBar app. When users open the app, it is in tab1. When users click a picture in tab1, the app will jump to tab3 with the picture's name.
The problem is where to call addObserver in tab3 since tab3 never opens?
Comment: It is unclear what method you mean by `addObserver` (there are at least two distinct groups of methods with that name) or why you want to do so. In general, if a view controller needs observe something when it is not on screen, you're probably violating MVC. https://developer.apple.com/library/mac/documentation/General/Conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html If you just need to observe when you're onscreen, use `viewDidAppear` and `viewWillDisappear`.
Answer: If I get your question correctly you just want to open tab3 when you click a photo from tab 1
IMO, it should have something like window->mainController->tabController [tabs]
In your tab1Controller you can setup a delegate lets call it "Tab1ControllerDelegate" having a method named "tab1DidSelectSomething:(NSString *)something". then in your mainController you can assign the delegate to self.
 i.e.
  tab1Controller.delegate = self;

In your tab1Controller picker action you can do something like:
if(_delegate){
  [_delegate tab1DidSelectSomething:<whatEverheSelected>];
}
Then in your mainController:

-(void)tab1DidSelectSomething:(NSString *)something{
   // get the viewController here
   UIViewController  *controller = _tabController.viewControllers[2];
   [controller updateselected:something];
   _tabController.selectedIndex = 2;
}

where to addObserver in iOS


Limit Values for Properties in .NET

Question: I know this may be a noob question, but it's bugging the heck out of me.
Let's say I have a user control that I reference in my .aspx page:
<uc:somecontrol runat="server" id="uc1" property1="red" />

how do I make it so when in VS05 the intellisense will show options like "red", "green", "blue" for property1? Similar to how when you want to choose between "text", "multiline", and "password" for the modes on a textbox. I'm using VB.
Thanks!
Answer: Make your property an enum instead of a string.
Enum ControlColor
Red = 1
Blue = 2
Green = 3
End Enum

and
Public Property MyProperty As ControlColor

Answer: Define an enum in a new file as Rex said:
Public Enum ControlColor
    Red = 1
    Blue = 2
    Green = 3
End Enum

And then in your control, define your property like this (my VB syntax is rusty, but I think this is right):
Private _color As ControlColor

Public Property [Color] As ControlColor
    Get
        Return _color
    End Get
    Set (ByVal value As ControlColor)
        _color = value
    End Set
End Property

Limit Values for Properties in .NET


How much of an underground area must be removed and rebuilt to stop mobs from spawning?

Question: So im trying to build an underground fortress as my bank world. I've built an area big enough so that if i stand in the middle of the fortress I can only see the outlining walls of what i have built. The problem stems from having enemies that are able to teleport past walls or just go right through them entirely. In hardmode if I go towards the outer walls enemies attack me through the walls and i have to constantly be on my gaurd. I want a place where I dont have to worry about being attacked specially in a bank world where I am organizing and finding stuff or creating stuff.
How much of an underground area must be removed and rebuilt to stop mobs from spawning?
Comment: The easiest option would be to not start hardmode in your "bank world", kill the Eye of Cthulhu once, and build a floating fortress instead. Nothing can get to you that way.
Comment: bleh hardmode is the only way to go.
Answer: Just get all the NPC's houses around your bank. Every NPC increases the area that mobs won't spawn. When you have all the NPC's around the bank you won't have any mobs bothering you.
Comment: Unless there's a Blood Moon, Solar Eclipse or invasion in progress... town safety goes poof under those conditions.


Changing the email address linked to my Steam account

Question: I found myself in kind of a big problem today as I tried logging on Steam on another computer.
The usual verification code popped up -- no problem -- the thing is that I only have access to the email address linked to my steam account from my own PC at home (I am currently using a yahoo mail address and intend to change to a gmail address).
Is there a way to change the email address that my Steam account is linked to?
Comment: I hope that you cannot change your email without logging in...
Answer: You can change your contact email address via the steam client. Menubar -> Steam -> Settings -> Change Contact Email Address.
For security reasons you will need to log in to steam and have access to the old email address.
Comment: Just a heads up: IIRC you won't be able to use Steam trading and the marketplace for a few days after changing your email.
Answer: You can only change your Steam email account while logged in.
However, it is possible to access Yahoo mail from any computer using the web interface at https://mail.yahoo.com/. I hope you remember your Yahoo mail password!


Spring data jpa search filter by foreign key and type

Question: Model Class Vehicle
@Column(name="type",nullable=false)
private String type;

@Column(name="last_service_date",nullable=false)
private String lastServiceDate;

@Column(name="seats",nullable=false)
private Long seats;

@Column(name="bags_capacity",nullable=false)
private Long bagsCapacity;

@Column(name="milage",nullable=false)
private Long milage;

//for Franchise object id
private transient Long fId;

@ManyToOne
 @JoinColumn(name="franchise_id")
 private Franchise fkFranchiseId;

@Repository
public interface VehicleRepository extends JpaRepository<Vehicle,Long>
{

 }

I am using spring data jpa repositories and want to search Vehicle by type and foreignKey=>(zipcode) how can i find
Comment: please add the code how you are interacting with database like using JpaRepository  or something else
Comment: i am using JpaRepository
Answer: Just add a method in your Vehicle JPA repository interface as follow:
findAllByTypeAndFkFranchiseIdZipCode(String type, String zipCode);

And also you are welcome to check docs of Spring Data Jpa
Answer: You can use JPA repo method name query  documented here    https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
public interface VehicleRepo extends JpaRepository<Vehicle, String> {

  List<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode);

  Page<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode,Pageable page);

 }

Answer:  List<Vehicle> findAllByTypeAndFkFranchiseId_ZipCode(String type, String zipCode);

Answer: for those who have a more complex object and want to keep their code, u can also use @Query for fetching data.
u just need to do this like this:
@Repository
public interface VehicleRepo extends JpaRepository<Vehicle, String> {
  @Query("from Vehicle v where v.type = :type and v.fkFranchise.zipCode = :zipCode")
  List<Vehicle> findAllByTypeAndZipCode(String type, String zipCode);
 }


JQuery Css Formatting leaks to other document elements

Question: As the title says i am new to Web Development and i tried out JQuery and i came across this issue. I am specifying on my code that the element with id #btn1 enables the specific characteristic i write it to and it does that only to elements with id #p1,#p2,#p3. Why do the changes leak to other elements of p?
I expected this to format only the elements with ids(p1,p2,p3) but it formats the other p elements too.

This is a heading

This is a paragraph.

This is a paragraph.

This is a paragraph.

This is a paragraph.

<button>Set background-color of p</button>

This is a heading

This is a paragraph.

This is a paragraph.

This is a paragraph.

This is a paragraph.

<button id="btn1">Set multiple styles for p</button>

Answer: Its because of this line here:
$("button").click(function(){
  $("p").css("background-color", "yellow");
});

This line adds a click event listener to every button on the page.
So when you click any button, every "p" element on the page gets the background-color set to yellow
Comment: Thank you so much! I have changed the button id to btn2 and it has solved my problem the above text is not being formatted! :)


Apt debug-symbols package empty

Question: I am trying to install debug symbols for gcc. Searching around I have:
gcc-4.7-dbgsym/xenial,now 4.7.4-3ubuntu12 amd64 [installed]
debug symbols for package gcc-4.7

gcc-4.7-multilib-dbgsym/xenial,now 4.7.4-3ubuntu12 amd64 [installed]
debug symbols for package gcc-4.7-multilib

gdb does not find the debug symbols when I load gcc-4.7 into the debugger. So I checked to see which files these packages had installed:
$>  dpkg-query -L gcc-4.7-multilib-dbgsym
/.
$>  dpkg-query -L gcc-4.7-dbgsym
/.

It seems these packages are empty? Am I doing something wrong? Or how can I check if the debug symbols are actually installed.
Checking under /usr/lib/debug I didn't find anything.
Comment: Where did you get the package `gcc-4.7-dbgsym`? It doesn't seem to be in the standard Ubuntu repos
Comment: Hmm, I thought it came from the standard repo. I can see it listed [here](https://launchpad.net/ubuntu/+source/gcc-4.7).  Otherwise I followed this [guide](https://wiki.ubuntu.com/Debug%20Symbol%20Packages) for getting debug symbols.
Answer: I ended up getting the GCC source directly from apt:
apt get source gcc

This installs the gcc source into a local directory. From here, I compiled GCC with debug flags and no optimizations. The compilation takes a very long time, so you might consider loading the gcc binary through gdb and merely pointing to the source like this, basically using the dir command. This may lead to some unexpected behavior as GCC will still have optimizations on.

Apt debug-symbols package empty


Program opening up in the top edge of the screen, preventing it from being dragged

Question: I apologize if this is a duplicate, but I didn't really know what to Google. I'm using Ubuntu 15.04 and sometimes when I open up a specific application, it opens up on the top left corner of the screen. That's all good, but the portion that allows you to be able to drag a window around is stuck behind the black bar menu on top that has your wifi, battery, time stuff on it. Refer to the screenshot below:
EDIT: I need 10 rep points in order to post an image so I hope people understand my issue without needing a screenshot.
As you can see, the application is launching behind the menu bar making it unable to be moved. I have to exit the application and relaunch it a few times since its place on the screen seems to be random. Is there a way to fix this or is this completely the application's fault?
Comment: You can Alt-drag the window on any position on the window :)
Comment: Possible duplicate of [Why are windows going to top left of the screen?](http://askubuntu.com/questions/233135/why-are-windows-going-to-top-left-of-the-screen)
Answer: There are keyboard shortcuts which allow you to minimize, maximize, and move windows in Ubuntu. If you can click on the problematic application so that is active, you can use:
Alt+Space then N to Minimize,
Alt+Space then  X  to Maximize/Unmaximize, and:
Alt+Space then M to Move.
If you can only invoke a menu with this shortcut:
Alt+Sapce
you can use the pointer (or arrow key) to highlight then select the option you'd like.
Comment: Thank you! I'd vote up your answer, but I need 15 rep points in order to do so. For now, I have marked it as best answer.
Answer: That is one of the most annoying things ever!
The Unity is a compiz plugin and you are using a compiz desktop so first, install compizconfig-settings-manager. Open a terminal and execute the following commands:
<code>sudo apt-get update
sudo apt-get install compizconfig-settings-manager
ccsm &
</code>
Now, scroll down the screen to the Window Management category, enable the Move Window plugin and then exit ccsm.
By default, this plugin is set to initiate a window move when you press ALT + the Left Click Button on your mouse.
So, move your mouse over anywhere in the window, hold down ALT and press the left click mouse button to click and drag the offending window down from behind the panel.
Also, I seem to remember having a plugin enabled or disabled that would cause the behavior you are experiencing but can't remember what it was. Hopefully, once you close the window in a different area, it will not want to open in that awful place again.


Subsequences of convergent series

Question: We know that all subsequences $x_{\phi(n)}$ of a convergent sequences $x_n$ have the same limit :
$$\lim_{n \to \infty} x_n = \lim_{n \to \infty} x_{\phi(n)}$$
Now we consider $x_n=\frac{n^3}{n!}$, we have that $S_n = \sum_{k=0}^n x_k = \sum_{k=0}^n\frac{k^3}{k!}$.
Suppose we already know that $\sum_{n=0}^\infty \frac{n^3}{n!}= \lim_{n \to \infty} S_n=5e$.
My question is : as the series converges (absolutely), i.e. $S_n$ has a limit when $n \to \infty$, why does the subsequence $S_{2n} = \sum_{k=0}^n\frac{(2k)^3}{(2k)!}$ seem to have a different limit that is not $5e$ ? I thought we should have
$\lim_{n \to \infty} S_n = \lim_{n \to \infty} S_{2n}$ but I also see that $S_{2n}$ is missing half of the terms from the original sum so its limit "must" be lower. So how does subsequences work with series ?
I am sure there is something very stupid that I don't get.
Answer: You made a mistake:
$$S_{2n} = \sum_{k=0}^{2n} \frac{k^3}{k!}$$ and not:
$$S_{2n} = \sum_{k=0}^{n} \frac{(2k)^3}{(2k)!}$$
Answer: Because
$$S_{2n} = \sum_{k=1}^n \frac{(2k)^3}{(2k)!}$$
is false. The correct $S_{2n}$ is
$$S_{2n} = \sum_{k=1}^{2n} \frac{k^3}{k!}$$
Answer: You are wrong when you assert that$$S_{2n}=\sum_{k=0}^n\frac{(2k)^3}{(2k)!}.$$In fact,$$S_{2n}=\sum_{k=0}^{2n}\frac{k^3}{k!},$$which is a different thing. And there is no reason for you to assume that$$\lim_{n\to\infty}\sum_{k=0}^n\frac{(2k)^3}{(2k)!}=\lim_{n\to\infty}\sum_{k=0}^{2n}\frac{k^3}{k!}.$$

Subsequences of convergent series


Copy a Specific Row from one sheet to another based on few conditions

Question: I want to copy an entire row based on if one of the 4 columns that I am interested is greater than 0.  I am new to VBA and tried the following code and it does not seem to work.
Sub MyViewCopy()
    Set sh = Sheets("XyNewSheet")
    RowCount = 0
    lr2 = 0
    For Each rw In sh.Rows
        If (
       (Cells(rw.Row, 10).Value > 0) Or (Cells(rw.Row, 12).Value > 0)
        Or
       (Cells(rw.Row, 14).Value > 0) Or (Cells(rw.Row, 16).Value > 0)
       Or
       (Cells(rw.Row, 18).Value > 0)
       ) Then
       Rows(rw).Copy Destination:=Sheets("MyView").Range("A" & lr2 + 1)
       lr2 = Sheets("MyView").Cells(Rows.Count, "A").End(xlUp).Row

       RowCount = RowCount + 1
    End If
    Next rw
    MsgBox (RowCount)
End Sub

Comment: try putting `sh.` in front of all the `Cells(rw...`  and in front of `Rows(rw).copy`
Comment: You understand that you are checking every row all the way to the bottom of the worksheet...?
Comment: I have a worksheet XyNewSheet and if columns, J, L, N, P, R have a value of greater than 0 then I want to copy to a new sheet "MyView".  That is what I was intending to do.
Answer: Try cutting down the rows examined to the rows with actual values in columns J, L, N, P and R.
Option Explicit

Sub MyViewCopy()
    Dim r As Long, rc As Long, mxr As Long

    With Worksheets("XyNewSheet")
        mxr = Application.Max(.Cells(.Rows.Count, "J").End(xlUp).Row, _
                              .Cells(.Rows.Count, "L").End(xlUp).Row, _
                              .Cells(.Rows.Count, "N").End(xlUp).Row, _
                              .Cells(.Rows.Count, "P").End(xlUp).Row, _
                              .Cells(.Rows.Count, "R").End(xlUp).Row)
        For r = 1 To mxr
            If .Cells(r, "J").Value2 > 0 Or .Cells(r, "L").Value2 > 0 Or _
               .Cells(r, "N").Value2 > 0 Or .Cells(r, "P").Value2 > 0 Or _
               .Cells(r, "R").Value2 > 0 Then
                .Rows(r).Copy Destination:=Worksheets("MyView").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                rc = rc + 1
            End If
        Next r
    End With

    MsgBox (rc)
End Sub

Your bracketing on the Or statements was unnecessary. There are only necessary if you want to group combinations of And and Or together.
Comment: Thank you so much. This helped me !!


Why am I getting thread exiting with uncaught exception?

Question: I am trying to open another activity according to the sap number entered by the user. But even before the next activity gets opened I get an exception, illegal state exception and thread exiting with uncaught exception.
This is the java file from where I am calling the other activities-
package ai.app;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

public class homepage extends Activity {
    SQLiteDatabase db;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);
        String sap = getIntent().getExtras().getString("sapno");
        tv=(TextView)findViewById(R.id.textView1);
        db=openOrCreateDatabase("aidatabase.db",MODE_PRIVATE,null);
        Cursor c=db.rawQuery("select * from master where sapno='"+sap+"'", null);
        Boolean s;
        s=c.moveToFirst();
        String a=c.getString(c.getColumnIndex("department"));
        tv.setText("Welcome to "+a+" Department");

    }

    public void call (View v)
    {
        switch(v.getId())
        {
        case R.id.view:
        {
        Toast.makeText(this, "view done", Toast.LENGTH_LONG).show();

        Intent i=new Intent(this, viewdetails.class);
        startActivity(i);
        finish();
        break;
        }
        case R.id.enter:
        {
            Intent i = getIntent();
            String sap = i.getStringExtra("sapno");
            if(sap.equals("102"))
            {
                System.out.println("Inside cargo");
            Intent i1=new Intent(this, cargo.class);
            startActivity(i1);
            finish();
            }
            else if(sap.equals("103"))
            {
                System.out.println("Inside hcc");
            Intent i1=new Intent(this, hcc.class);
            startActivity(i1);
            finish();
            }
            else if(sap.equals("104"))
            {
                System.out.println("Inside trimmers");
            Intent i1=new Intent(this, trimmers.class);
            startActivity(i1);
            finish();
            }
            else if(sap.equals("105"))
            {
                System.out.println("Inside ops 1");
            Intent i1=new Intent(this, ops.class);
            System.out.println("Inside ops 2");
            startActivity(i1);
            finish();
            }
            else if(sap.equals("107"))
            {
                System.out.println("Inside routing");
            Intent i1=new Intent(this, routing.class);
            startActivity(i1);
            finish();
            }

        }
    }

}
}

For example if ops section gets selected, the exception is thrown.
Following is the java code of ops.java
 package ai.app;

    import android.os.Bundle;
import android.widget.Toast;
import android.app.Activity;

    public class ops extends Activity
{   @Override
protected void onCreate(Bundle savedInstanceState)
{       System.out.println("inside oncreate");
try         {           System.out.println("inside try1");
super.onCreate(savedInstanceState);
System.out.println("inside try2");
setContentView(R.layout.opssection);        }
catch(Exception e)
{           Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();       }
                    }
 }

The xml file for the same is -
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="3dp"
        android:text="Remarks" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="200dp"
        android:text="FOB Revised2" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="160dp"
        android:text="FOB Revised1" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="120dp"
        android:text="Fuel on Board" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_x="1dp"
        android:layout_y="0dp"
        android:background="#BD3112"
        android:text="   OPS Section   "
        android:textColor="#FFFFFF"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="110dp"
        android:ems="10" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="150dp"
        android:ems="10" />

    <EditText
        android:id="@+id/editText5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="190dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="40dp"
        android:text="Enter Trip Fuel" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="30dp"
        android:ems="10" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="154dp"
        android:layout_y="70dp"
        android:ems="10" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="10dp"
        android:layout_y="80dp"
        android:text="RTOW" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="102dp"
        android:layout_y="248dp"
        android:background="#BD3112"
        android:text="  Update  "
        android:textColor="#FFFFFF" />

</AbsoluteLayout>

Similar exception is being thrown on other activities as well, kindly let me know where I am going wrong... Thanks
Comment: Can you add the stack trace?
Comment: In your `catch` blocks, log the exception via `Log.e()` to LogCat, then examine the Java stack trace associated with the crash: https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this If you do not understand the stack traces, edit your question to include them.
Answer: Not all exceptions are under Exception class.change:
 catch(Exception e)

To catch more exceptions types using Throwable class:
 catch(Throwable e)

Comment: Check where the exception.maybe outside try catch
Comment: I changed the Exception to Throwable, still the app is Force Closing.
Comment: The entire onCreate function code is inside try block. Still I am not able to debug the code.


Long press action clue/indicator

Question: On a desktop and touch devices, I'd like to know is there is a way to tell the user that some control could be clicked (one action) and long pressed (another action)?
Real-world example:

We have column chart

Tap performed on column 2007 (single selection)

Tap performed on column 2009 (single selection)

Long press performed on column 2010 (single selection)

Current situation is that user doesn't know that chart has possibility to multi-select columns (perform long press). How to indicate that it is possible?
Comment: Is the long press possibility the only possibility of the button, or can the user also perform a short press?
Comment: @NGAFD yes, click is also possible (e.g on click items in a list behave like radio button group, but on long press we can select several items like checkbox group).
Comment: Take a look at [Material design - Selection Patterns](https://material.io/guidelines/patterns/selection.html#selection-item-selection).
Comment: @NGAFD example added to a question
Answer: Changing the color of the column may be too little for the user to know that he have selected something.
Along with the color change, you could display a top toolbar showing how many items the user selected along with the option to cancel selection and other specific actions.
Someting like that:

download bmml source – Wireframes created with Balsamiq Mockups
I hope it helps :)
Answer: Since the bars have both a click and a long press, i reckon there are a couple of ways to acheive this.

Write a small info note at the end informing the users about the long press
Give some visual feedback , like a small circle filling up as the user makes contact with the page/touches the page.
one more form of visual feedback : start 'filling' the bar with color when user makes contact. click will make the bar fill up instantly, when that is seen . i guess the user will make an attempt to fill it up slowly, i.e long press .

in the above scenario, once user has long pressed, i'd recommend elevating the selected bar above the others to make sure it was selected via long-press or use a different fill color.

We used the last scenario for an app where user had this same confusion , but then again those were cards and not bars. But i hope this helps :)

Long press action clue/indicator


model binding in mvc

Question: i'm having a textbox inside a form.
[View]
<%=html.textbox("name") %>

[Controller]
 Index(string name)
    {
    name = "something";
    return View();
    }

On Form Submit
In this case without sending any ViewData the textbox value is maintained.But the value "something" is not setting up.
But whn i change the Action to
[Controller]
Index()
{
string name="something";
return view();
}

the value is not maintained.
Really wat happening on that parameter.
Comment: This code will not compile, nor does it make any sense to me as pseudocode. It would help if you showed the actual code you are using.
Answer: If you want to set data for html.textbox("name") in the Controller use ViewData["name"] = "something"
Answer: Your question is not very clear and your code example is not actually adding anything to ViewData or the view Model - here's a shot at what i think your trying to do...
Assuming you want to re-populate the form and your View is Strongly Typed, You would do something like this:
public ActionResult Index(String name)
{
    MyModel model = new MyModel;
    model.Name = name;
    ViewData.Model = model;
    return View();
}

A textbox in your view with the same name would then have the value auto populated from the Model
<%= html.textbox("Name") %>

Posting the form would then post the model object to your controller like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(MyModel model)
{
    // do something with the model
    ViewData.Model = model;
    return View();
}

and then re-populate the form with the model data.
Answer: string name in your Index action in the controller, is mapped to the FormValue, if you change this, MVC understands that it needs to add the value from the FormValueCollection to the textbox, and you have changed that in your Index action. If you declare a variable by yourself this doesn't work because there is no binding to the formvalues.
Comment: but whn i change the value inside the action i doesn't reflect in the view.

in the case

Index(string name)
{
name = "somethng";
return view();
}

but the string "somethng" doesn't reflect in view..

model binding in mvc


Biopython not able to work in UNIX Ubuntu or Mac OS

Question: I am currently struggling to be able to import the Bio module in a python script which is in a different directory.
The error I keep receiving is as follow:
from Bio import SeqIO

ImportError: No module named 'Bio'

I have tried reinstalling Biopython, rebuilding it and also changing the paths (as all recommended on Stackoverflow, but still I get this error message.
I built Biopython according to the pypi.python.org site instructions:
python setup.py build
python setup.py test
sudo python setup.py install

I am still quite new to how Python and BioPython works. Is there a possible solution to this?
Comment: Even better, use this command to install it: `pip install biopython`. This will automatically put the module in the default python site-package.
Comment: Try `import site; site.getsitepackages()` in python consolle. This will show you the site-package directory that contains all the modules. Put the Bio module directory under the site-package directory.
Comment: If you are new to Python, please use Python 3 instead of Python 2 - i.e., run `python3` on the command line instead of `python`.
Comment: Thank you Terence and Matt.
Comment: I tried installing with pip but it still gives the same issue. I also tried it with python3. I'm running the test again to see if I can find the problem.
Comment: Try the distribution package: sudo apt-get install python-biopython
Comment: Did you tried to import the full Bio module: `import Bio`. If the installation with pip was successful then I cannot see why python cannot find the module. Wait, on OSX the default is python2.7 if you installed python 3 then you also have pip3.X, to install modules for python3.X use pip3.X.
Comment: BTW You can use @name syntax anywhere in your comment to reply to a specific user (so that the user will be notified of your reply, see this [post](http://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) on comments.
Comment: @terencehill I'm reading "UNIX Ubuntu" in the title.
Comment: @xbello yeah! My apology.  Sometimes I'm so dumb that I can't belive it
Comment: Any success so far?
Answer: What worked for me was:
First uninstall all trace of biopython
In the terminal:

pip uninstall biopython
pip3 uninstall biopython
pip3.X uninstall biopython

Note: If you have python3.7 is pip3.7, python3.7.6 will still be pip3.7
Then see which python do you use, in the terminal:

which python
which python3

Then, the main process is:

dowload manually biopython-1.74.tar.gz 16Mb – Source Tarball from https://biopython.org/wiki/Download
decompress/unzip/tar biopython-1.74.tar.gz
in the terminal change directory to biopython-1.74 and:

python setup.py build
python setup.py test
sudo python setup.py install

or

python3 setup.py build
python3 setup.py test
sudo ython3 setup.py install

or

python3.X setup.py build
python3.X setup.py test
sudo python3.X setup.py install

DONE! https://pypi.org/project/biopython/


Rails: Returning a blank select option with observe_field?

Question: I have an observe_field call in my app like this:
  = observe_field "marketSelect", :update => "merchantSelect", :with => "id", :url => { :controller => "markets", :action => "get_merchants" }

That code activates the following action in my markets controller:
@merchants = @market.merchants.sort_by { |merchants| merchants.name }

That code returns a list of every merchant associated with the selected market, and populates them into another selection list.
How can I insert an empty "Select merchant..." along with the merchants?
Thank you
Answer: Thanks for the suggestion. I ended up just building a straight javascript solution.
Answer: Hmm.. I found this at http://joshhuckabee.com/rails-observe-field-function-and
observe_field 'text_field_id',
    {:function => "(value == '') ?
        $('email_preview').innerHTML =
             'not entered yet' :
        $('email_preview').innerHTML =
             value.replace(/\\n/g, '
');",
      :on => 'keyup'}

The author did this with prototype. He had added a little snippet that will replace carriage returns with HTML line breaks and also set a default value if no text is entered or the field gets cleared out.


What additional thumbnailers are available and how do I install them?

Question: Question:
Ubuntu's file manager, Nautilus, comes with a wide support for file previews. These thumbnails are handled by helper programs called thumbnailers.
The number of thumbnailers that come preinstalled with Ubuntu are limited and thus some more exotic file types aren't rendered by default.
What additional thumbnailers can I install to activate previews in these cases?

Related Q&As:
How can I instruct Nautilus to pre-generate thumbnails?

Note:
Feel free to contribute to this list by editing the community wiki answer. If you do so please follow the guidelines in this Meta discussion and use the preexisting pattern to keep the answer consistent.
Answer: General installation instructions

Thumbnailers in repositories and PPAs
A number of thumbnailers are pre-packaged and can be easily installed from the software center or the command line. These thumbnailers don't require any additional configuration and should work right after restarting nautilus. You can do so with:
nautilus -q

Please consider reading these Q&As before installing anything from a PPA:
What are PPAs and how do I use them?
Are PPA's safe to add to my system and what are some "red flags" to watch out for?
Custom thumbnailing scripts on Ubuntu 11.04 and above
Custom thumbnailers that aren't available in repositories have to be installed manually. These are the steps you will have to take to install them:
Check out whether the script has any dependecies listed. If so, install them first.
Download the script and make it executable with chmod a+x filethumbnailer or via Nautilus
Designate a folder in your file system for all future thumbnailers and move the script to it, e.g.
mkdir $HOME/.scripts/thumbnailers && mv filethumbnailer $HOME/.scripts/thumbnailers
Next you will have to register your script with Nautilus. To do so create a thumbnailer entry in /usr/share/thumbnailers. The entry should follow the naming scheme foo.thumbnailer where foo is an expression of your choice (here file):
gksudo gedit /usr/share/thumbnailers/file.thumbnailer

The thumbnailer specifications follow this scheme:
[Thumbnailer Entry]
Exec=$HOME/.scripts/thumbnailers/file.thumbnailer %i %o %s
MimeType=application/file;

The Exec entry points to your thumbnailer script while the MimeType field designates the related MimeTypes. Possible variables are:
%i Input file path
%u Input file URI
%o Output file path
%s Thumbnail size (vertical)

The specifications and variables will vary with each script. Simply copy and paste the content of the respective text box into the file and save it.
The thumbnailers should be up and running after restarting nautilus (nautilus -q).
Custom thumbnailing scripts on Ubuntu 11.04 and below
Earlier versions of Ubuntu rely on GConf for thumbnailer associations. See here for more information.

Sources:
https://live.gnome.org/ThumbnailerSpec
https://bugzilla.redhat.com/show_bug.cgi?id=636819#c29
https://bugs.launchpad.net/ubuntu/+source/gnome-exe-thumbnailer/+bug/752578
http://ubuntuforums.org/showthread.php?t=1881360

Thumbnailers by file type

CHM files
Overview

Description: With this script you'll get thumbnails of your chm files
  in the nautilus file manager. The script uses the largest image from
  the homepage of the chm file to generate the thumbnail, usually this
  will be an image of the front cover.
Creator: monraaf
  (http://ubuntuforums.org/showthread.php?t=1159569)
Dependencies: sudo apt-get install python-beautifulsoup python-chm imagemagick

Thumbnailer entry
[Thumbnailer Entry]
Exec=$HOME/.scripts/thumbnailers/chmthumbnailer %i %o %s
MimeType=application/vnd.ms-htmlhelp;application/x-chm;

Script
#!/usr/bin/env python

import sys, os
from chm import chm
from BeautifulSoup import BeautifulSoup

class ChmThumbNailer(object):
    def __init__(self):
        self.chm = chm.CHMFile()

    def thumbnail(self, ifile, ofile, sz):

        if self.chm.LoadCHM(ifile) == 0:
            return 1

        bestname    = None
        bestsize    = 0
        base        = self.chm.home.rpartition('/')[0] + '/'
        size, data  = self.getfile(self.chm.home)

        if size > 0:
            if self.chm.home.endswith(('jpg','gif','bmp')):
                self.write(ofile, sz, data)
            else:
                soup = BeautifulSoup(data)
                imgs = soup.findAll('img')
                for img in imgs:
                    name = base + img.get("src","")
                    size, data = self.getfile(name)
                    if size > bestsize:
                        bestsize = size
                        bestname = name
                if bestname != None:
                    size, data = self.getfile(bestname)
                    if size > 0:
                        self.write(ofile, sz, data)
        self.chm.CloseCHM()

    def write(self, ofile, sz, data):
        fd = os.popen('convert - -resize %sx%s "%s"' % (sz, sz, ofile), "w")
        fd.write(data)
        fd.close()

    def getfile(self,name):
        (ret, ui) = self.chm.ResolveObject(name)
        if ret == 1:
            return (0, '')
        return self.chm.RetrieveObject(ui)

if len(sys.argv) > 3:
    chm = ChmThumbNailer()
    chm.thumbnail(sys.argv[1], sys.argv[2], sys.argv[3])

EPUB files
Overview

Description: epub-thumbnailer is a simple script that tries to find a cover in an epub file and creates a thumbnail for it.
Creator: Mariano Simone
  (https://github.com/marianosimone/epub-thumbnailer)
Dependencies: none listed, worked fine right away

Thumbnailer Entry
[Thumbnailer Entry]
Exec=$HOME/.scripts/thumbnailers/epubthumbnailer %i %o %s
MimeType=application/epub+zip;

Script
#!/usr/bin/python

#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Author: Mariano Simone (email@example.com)
# Version: 1.0
# Name: epub-thumbnailer
# Description: An implementation of a cover thumbnailer for epub files
# Installation: see README

import zipfile
import sys
import Image
import os
import re
from xml.dom import minidom
from StringIO import StringIO

def get_cover_from_manifest(epub):
    img_ext_regex = re.compile("^.*\.(jpg|jpeg|png)$")

    # open the main container
    container = epub.open("META-INF/container.xml")
    container_root = minidom.parseString(container.read())

    # locate the rootfile
    elem = container_root.getElementsByTagName("rootfile")[0]
    rootfile_path = elem.getAttribute("full-path")

    # open the rootfile
    rootfile = epub.open(rootfile_path)
    rootfile_root = minidom.parseString(rootfile.read())

    # find the manifest element
    manifest = rootfile_root.getElementsByTagName("manifest")[0]
    for item in manifest.getElementsByTagName("item"):
        item_id = item.getAttribute("id")
        item_href = item.getAttribute("href")
        if "cover" in item_id and img_ext_regex.match(item_href.lower()):
            cover_path = os.path.join(os.path.dirname(rootfile_path),
                                      item_href)
            return cover_path

    return None

def get_cover_by_filename(epub):
    cover_regex = re.compile(".*cover.*\.(jpg|jpeg|png)")

    for fileinfo in epub.filelist:
        if cover_regex.match(os.path.basename(fileinfo.filename).lower()):
            return fileinfo.filename

    return None

def extract_cover(cover_path):
    if cover_path:
        cover = epub.open(cover_path)
        im = Image.open(StringIO(cover.read()))
        im.thumbnail((size, size), Image.ANTIALIAS)
        im.save(output_file, "PNG")
        return True
    return False

# Which file are we working with?
input_file = sys.argv[1]
# Where do does the file have to be saved?
output_file = sys.argv[2]
# Required size?
size = int(sys.argv[3])

# An epub is just a zip
epub = zipfile.ZipFile(input_file, "r")

extraction_strategies = [get_cover_from_manifest, get_cover_by_filename]

for strategy in extraction_strategies:
    try:
        cover_path = strategy(epub)
        if extract_cover(cover_path):
            exit(0)
    except Exception as ex:
        print "Error getting cover using %s: " % strategy.__name__, ex

exit(1)

EXE files
Overview

Description: gnome-exe-thumbnailer is a thumbnailer for Gnome that will give Windows .exe files an icon based on their embedded icon and
  a generic "Wine program" icon. If the program has normal execute
  permissions, then the standard embedded icon will be shown.  This
  thumbnailer will also give a thumbnail icon for .jar, .py, and similar
  executable programs.
Availability: official repositories

Installation
sudo apt-get install gnome-exe-thumbnailer

ODP/ODS/ODT and other LibreOffice and Open Office files
Overview

Description: ooo-thumbnailer is a LibreOffice, OpenOffice.org and Microsoft Office document thumbnailer that can be used by Nautilus to
  create thumbnails for your documents, spreadsheets, presentations and
  drawings.
Availability: developer's PPA (most recent version that's compatible with LibreOffice in Ubuntu 12.04 and up)

Installation
sudo add-apt-repository ppa:flimm/ooo-thumbnailer && apt-get update && apt-get install ooo-thumbnailer

Comment: nevermind, i've found out it can't handle files with comments before the `/* XPM */` header, even if `eog` displays them fine
Comment: What about `.xpm` images? I assumed they were as "standard" as `png`, `jpg` and `bmp`, but Nautilus does not generate previews for them.
Comment: XPM image files render fine for me on Nautilus 3.4: http://i.imgur.com/XYUZonV.png
Comment: I think you can find the mimetype of the file using `file -i FILE`
Answer: ICNS files (Mac OSX Icons)
Overview
Nautilus does not generate thumbnails for Mac OSX icons due to some bugs, but support is built in GdkPixbuf.
Script
This is a basic script to generate thumbnails for .icns files. A more robust version can be found at https://github.com/MestreLion/icns-thumbnailer
#!/usr/bin/env python
import sys
from gi.repository import GdkPixbuf
inputname, outputname, size = sys.argv[1:]
pixbuf = GdkPixbuf.Pixbuf.new_from_file(inputname)
scaled = GdkPixbuf.Pixbuf.scale_simple(pixbuf, int(size), int(size),
                                       GdkPixbuf.InterpType.BILINEAR)
scaled.savev(outputname, 'png', [], [])

Install
An install script, along with the .thumbnailer file for Nautilus, are available at the icns-thumbnailer project repository


ATI radeon mobility 3650 overheats and shuts down computer in Xubuntu and not Windows. Why?

Question: I have recently installed Xubuntu 12.04 alongside Windows Vista on my Acer Aspire 6920G laptop. I installed the latest proprietary fglrx drivers for the ATI radeon mobility 3650.
In Xubuntu I felt significant heat coming from the area in which the graphics card is situated, even when the system is idle. After about 10 minutes of playing Quake Live the system shut down suddenly. I opened up the laptop and found that the reason for the emergency shut down was most likely the graphics card, as the heat sink was extremely hot. The heat sink for the CPU wasn't hot and I vacuumed it recently (and temperatures are within normal range) So I have assumed it isn't the CPU.
I vacuumed the laptop again and booted into Windows. When the system is idle the laptop feels warmish but significantly cooler where the graphics card is situated. After playing UT2004 and Quake Live for a good while I found that even though the graphics card got warmer, the computer never shut down.
Has anyone else had this problem and does anyone know why the graphics card overheats in Xubuntu and not Windows (if that is indeed the cause)? How can I find out what exactly is causing this problem? is it a power-management issue or graphics drivers issue? I installed Xubuntu to have a less resource intensive system but I might have to go back to Windows for fear of overheating and emergency shut downs.
Additional Info:
One thing I also noticed was that UT2004 runs with lower frame rate and has to have less demanding graphics settings to run more smoothly in Xubuntu. In Windows I can have very high graphics settings and it runs very smoothly. So perhaps the route of the problem is the drivers. However, the fan/system-in-general seems much noisier in Xubuntu, even when idle, although the CPU usage doesn't seem any higher.
Answer: Right it seems that the command aticonfig --initial initialized the /etc/X11/xorg.conf file and filled it with the correct configuration for my graphics card. Before I did this the file had almost no information in it so if anyone has a similar problem check that  /etc/X11/xorg.conf is set up correctly (might be in a different folder for others). I played UT2004 after doing this and the frame rate issue is gone, even on higher settings. Although the graphics card got hotter there was no emergency shut down and I played it for a while.
If you want a way to check if the file is set up correctly run aticonfig --odgc --odgt --adapter=all (this was suggested in Bill's answer so credit goes to him). This command normally returns performance information about your graphics card. If /etc/X11/xorg.conf isn't set up correctly it will return an error that asks you to run aticonfig --initial.
Comment: Following your advice, I'm stuck with the error message
ERROR - Get temperature failed for Adapter 0 - ATI Mobility Radeon HD 3650
Comment: I also get this error and I never figured out why. UT2004 runs fine despite the fact that this error is given. But I honestly don't know what causes it. Perhaps this issue alone would make for a good question to ask.
Comment: I've read somewhere that the Thinkpad T500 does not have a temperature sensor for the GPU, which explains the error message.
Answer:
Have you installed the most recent drivers on card?
Does this happen when the battery is plugged in? or out?
Have you checked how stressed the GPU is?

aticonfig --odgc --odgt --adapter=all

This command should display the stress being put on GPU. The memory and GPU usage will appear in percentage. Also it will give you your fan speed to see if that is changing while the GPU is being heavily stressed.
Try running that as you play Quake on linux machine and compare results with what its doing while on Windows. It may well just be that your linux machine is not controlling the fan as it becomes more stressed. But more likely this is a drivers problem.
Bill
Comment: Hi, thanks for the reply, when I type that command in I get this message - No layout section was found in the file: '/etc/X11/xorg.conf'.
Please run 'aticonfig --initial' first or modify your configuration file manually and run aticonfig again.
aticonfig: parsing the command-line failed.
Comment: I then tried "aticonfig --initial" but got this - Uninitialised file found, configuring.
Using /etc/X11/xorg.conf
Saving back-up to /etc/X11/xorg.conf.original-0. Is there something else I need installed to run this program?
Comment: After trying that a couple of times it started working now! However it says GPU load is 0% and it also says Get temperature failed for Adapter 0 - ATI Mobility Radeon HD 3650.
Comment: Have you made sure you are on the new driver for ATI? Install that then, Once you have done that run the "aticonfig --initial" again. I think the problem is that the wrong drivers are installed and that it wont pick up the temperature or have control of the fans. And the GPU is just overheating under load.. If its not that then im out of answers mate sorry.
Comment: Hey see my answer. Your answer lead me to it but I can't upvote yet. But thanks a lot for your help!


How can I re-enter "Fragile Existence" (level 9) after I changed it into Baba?

Question: While playing level 9 ("Fragile Existence") I accidentally spelled Level Is Baba and got back to the world map with said level replaced by Baba:

Now I cannot enter the level again, as Baba moves away as soon as I try to enter the level:

But I haven't solved the level yet! How can I re-enter the level?
Answer: In order to reenter "Fragile Existence" (level 9), you have to satisfy two conditions:

the cursor must be on top of the level (in this case Baba)
the cursor must not be on top of another map element, e.g. another level or the path

At first, this seems like an impossible condition. However, the cursor can move on-top of Baba off the path. Or to use game terms:

CURSOR ON BABA AND NOT ON PATH IS ENTER.
CURSOR ON BABA IS WALKABLE

So in order to play the level, you have to move Baba to the cursor and then move away from the path. The easiest way is to go into level 8 ("Slideshow") and then back to the map. Afterwards, move down, right and then left:
Comment: @StevenM.Vascellaro True, but that's a hen and egg problem: to be able to change it into a stationary map icon, you first need to enter the level :). (Also, you really want a Baba on that screen later in the game).
Comment: You can change the level back into a stationary map icon by spelling `LEVEL IS KEY`.


Why golang slices internal designed like this?

Question: Code:
func main() {

    a := []int{1, 2}
    printSlice("a", a)

    b := a[0:1]
    printSlice("b origin", b)

    b = append(b, 9)
    printSlice("b after append b without growing capacity", b)
    printSlice("a after append b without growing capacity", a)

    b = append(b, 5, 7, 8)
    printSlice("a after append b with grown capacity", a)
    printSlice("b after append b with grown capacity", b)

    b[0] = 1000
    printSlice("b", b)
    printSlice("a", a)

}

func printSlice(s string, x []int) {
    fmt.Printf("%s len=%d cap=%d %v\n",
        s, len(x), cap(x), x)
}

Output:
a len=2 cap=2 [1 2]
b origin len=1 cap=2 [1]
b after append b without growing capacity len=2 cap=2 [1 9]
a after append b without growing capacity len=2 cap=2 [1 9]
a after append b with grown capacity len=2 cap=2 [1 9]
b after append b with grown capacity len=5 cap=6 [1 9 5 7 8]
b len=5 cap=6 [1000 9 5 7 8]
a len=2 cap=2 [1 9]

The interesting thing is at the last two printed lines. I already know that a slice is just a window of underlying array. When reslicing it within is capacity, then the two slices share the same underlying array, but When I reslice it to grow beyond its capaccity, the two slices have distinct underlying array. But why golang designers choose not to change the underlying array of the origin slice to the underlying array of the new slice, so as to make both slices still have the same underlying array? In current state when I changed the value of some elements of newly resliced slice I have to check if I changed the underlying array to decide if this operation have side effects on other slices backed up by it(see the last two lines of Output). I think it's awkward.
Comment: I don't understand the downvotes. The question is a) perfectly valid b)  well prepared (input code, almost runnable, output) c) clearly formulated and d) There is a simple answer to the question. To those who downvote: plase write why the downvote. It would help the OP.
Comment: If you're worried about "I have to check if […] this operation having side effects on other slices" then you're doing it wrong.
Answer:
But why golang designers choose not to change the underlying array of the origin slice to the underlying array of the new slice, so as to make both slices still have the same underlying array?

Mainly, slices of the same array can appear absolutely anywhere in the program--completely different functions, packages, and so on. Given how slices are laid out in memory, Go would have to "find" all slices sharing the array to update them; it has no way to.
The approach of some other array-list implementations (like Python lists) is that what you pass around is really a pointer to something like a Go slice, and if two variables hold "the same list", an append using one variable will also show up when you look at the other. That also has some efficiency cost--another pointer lookup to do a[0]. In those circumstances where you really need an append over here to act as an append over there, you can use pointers to slices.
Pointers to slices give you aliasing if you want it but don't provide subslicing--to get everything you ask for, you'd need a different arrangement that I can't think of an example of from in the wild (offset, length, and pointer to struct { capacity int; firstElem *type }).


repair hole in hardwood floor near garage door

Question: One weekend after a gathering, I noticed that there was a hole in my hardwood floor. The hole is about half an inch in  depth and about the size of penny, maybe a bit larger. I know sometimes hardwood has pin knots, but this looks to be caused by a heavy step of a woman's high-heeled shoe.
What's the best way to fix this without having to tear up the floor?
Comment: I think you have more to worry about than repairing the hole. If you have a craw space, go under the house and inspect the sub floor. From the picture, it seems you have some rot going on. For someones high heel to collapse your floor, most of the hardwood must be rotted and the sub floor gone in that place.
Comment: If indeed the floor is sound and this was just a factory void under the laminate, just plug it with a good solvent base wood putty that comes close in color. I would not go chopping up that floor for a penny sized hole.
Comment: How new?  There may be a warranty claim here.
Comment: @diceless well, I checked and there's no rot. I don't have a crawlspace. This is is the first floor, I have a basement, and there's no issues underneat there at all. The wood around the hole is pretty dry and actually sturdy. It's actually pretty hard to "make the hole larger" as the wood seems pretty solid around
Comment: @Bryce The house was built I believe around 2006-2007. We're the original owners. How long are hardwood floor warranties for? Is the hardwood manufacturer liable or is it the builder?
Comment: @CesarDV ten plus years is a normal warranty for such a floor.  Note: it may be less hassle just to fill this hole rather than complain.  As others have said this is not "normal".
Comment: The only reason I brought that up is because it looks like a small collapse in the floor.  For that to happen, the floor had to be missing a lot of wood and only the top finish about 1/4 of a inch thick (at the thickest).  Since the sub floor looks good (sorry for assuming craw space, where I live that's the best people have) you can assume a defective board was used.  If you have extra planks search google for "how to replace one hardwood board"
Answer: A solid healthy piece of oak would never collapse like that. You need to figure out what is going on before you fix it. Look at the underside if you can, break away any of the edges of the hole that come out easily (preferably without getting into the surrounding pieces) and try to figure out what you're dealing with. Look hard for moisture or evidence of insects. If you find anything suspicious, those problems must be dealt with first.
If ,however, the hole is pretty localized and the rest of the floor feels dry and solid, you can reasonably assume that it was an isolated defect in that piece and proceed with a patch. Here's a pretty decent tutorial on patching hardwood flooring:
https://www.youtube.com/watch?v=ez0GSSVuTyk
Good Luck!
Comment: hmm well, like I mentioned in the comments above, the floor around there seems fine (no insects, etc) and pretty dry and sturdy. Maybe this was a manufacturing defect in the wood? There was a hollow areas and by some bad luck a high-heel shoe just happened to put pressure and break the thinner wood surface there?
Comment: Yeah it's not inconceivable that it was just a weird spot. Was Lana Kane clomping around your house?:)
Comment: Lana Kane? I wish lol


Interactive drop down list django with option to add new entry

Question: I am relatively new to django.  I have made a simple app which enable a user to record   details regarding a run (Activity).  The user enters data such as: distance, time, route name, date ran..etc using a django ModelForm.
I have a ModelForm which enables the logged on user to add an Activity to the model database.
How do I get the form to add a drop down list of all the routes which are already in the model database AND add a new one if the Person is entering data about a route they haven't ran before.?
class Person(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    fName = models.CharField(max_length =100)
    lName = models.CharField(max_length =100)
    weight = models.FloatField()
    sex = models.CharField(max_length=10)

    def __str__(self):
        return self.lName

class Activity(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    length = models.FloatField()
    runTime = models.DurationField()
    route = models.CharField(max_length=100)
    ave = models.DurationField()
    dateRun = models.DateField()
    marathon = models.DurationField()

    def __str__(self):
        return self.route ```

Answer: I would add model Route in models.py:
class Person(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    fName = models.CharField(max_length=100)
    lName = models.CharField(max_length=100)
    weight = models.FloatField()
    sex = models.CharField(max_length=10)

    def __str__(self):
        return self.lName

class Route(model.model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    length = models.FloatField()
    route = models.CharField(max_length=100)

class Activity(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    runTime = models.DurationField()
    route =  models.ForeignKey(Route, on_delete=models.CASCADE)
    ave = models.DurationField()
    dateRun = models.DateField()
    marathon = models.DurationField()

    def __str__(self):
        return self.route

When person wants to add activity he will have all routes that he enters before. That solution require additional job in modelform, and need of another form to add new route. I think the ActivityForm should look like:
class ActivityForm(forms.ModelForm):
    class Meta:
        model = Activity
        fields = '__all__'
        widgets = {'person': forms.HiddenInput}

and init it in views.py:
form = ActivityForm(initial={'person': request.user.id})
form.field['route'].queryset = Route.objects.filter(person=request.user)


Powershell script combine

Question: How can I combine these PowerShell cmdlets instead of running them separately? These commands are ran on our Exchange server for on premise and Office 365.
<code># General
New-DistributionGroup -Name dis_its3 -DisplayName dis_its3 -Alias dis_its3 -PrimarySmtpAddress firstname.lastname@example.com

# Ownership
Set-DistributionGroup -Identity "dis_its3" –ManagedBy Robinson Mykal -BypassSecurityGroupManagerCheck

# Membership approval
Get-DistributionGroup | Set-DistributionGroup -MemberJoinRestriction:closed -MemberDepartRestriction:closed

# Delivery Management
Set-DistributionGroup "dis_its3" -RequireSenderAuthenticationEnabled $False
</code>
In the picture shown is what the PowerShell script is automating:
Comment: What happens if you copy all the commands in a .ps1 file and run it ? Do you get any errors ?
Comment: What do you mean "combine"?
Comment: Combine as in put all scripts into one body of text so when i copy and paste it into powershell it will execute. The scripts are working because I have test them, but I have to copy and paste them one by one. I want to be able to copy all of them at once and paste it all then execute.
Comment: I don't know what characters or parameters to put between the scripts so that they'll execute without errors.
Comment: Normally you just put one after the other, each in a separate line. Do you get errors when you do that? If so, what do they say?
Answer: You could create a function like below and throw it into a .psm1 and it import it as a module or into a .ps1 and dot source it to your session. Then you can call this function like I have also shown below. Mind you that you will probably want to add some error handling.
<code> function Set-CustomDistributionGroup
 {
     [CmdletBinding()]
     param
     (
         [Parameter(
             Position = 0,
             Mandatory = $true
         )]
         [ValidateNotNullorEmpty()]
         [Alias('DistributionGroupName')]
         [String] $Name,

         [Parameter(
             Position = 1,
             Mandatory = $true
         )]
         [ValidateNotNullorEmpty()]
         [Alias('DistributionGroupDisplayName')]
         [String] $DisplayName,

         [Parameter(
             Position = 2,
             Mandatory = $true
         )]
         [ValidateNotNullorEmpty()]
         [Alias('DistributionGroupAlias')]
         [String] $Alias,

         [Parameter(
             Position = 3,
             Mandatory = $true
         )]
         [ValidateNotNullorEmpty()]
         [Alias('DistributionGroupPrimarySmtpAddress')]
         [String] $PrimarySmtpAddress,

         [Parameter(
             Position = 4,
             Mandatory = $true
         )]
         [ValidateNotNullorEmpty()]
         [Alias('DistributionGroupManagedBy')]
         [String] $ManagedBy
     )
     process
     {
         # General
         New-DistributionGroup -Name $Name -DisplayName $DisplayName -Alias $Alias -PrimarySmtpAddress $PrimarySmtpAddress

         # Ownership
         Set-DistributionGroup -Identity $Name –ManagedBy $ManagedBy -BypassSecurityGroupManagerCheck

         # Membership approval
         Get-DistributionGroup | Set-DistributionGroup -MemberJoinRestriction:closed -MemberDepartRestriction:closed

         # Delivery Management
         Set-DistributionGroup -Identity $Name -RequireSenderAuthenticationEnabled $False
     }
 }
</code>
And Then Call it like this:
<code> Set-CustomDistributionGroup -Name 'dis_its3' -DisplayName 'dis_its3' -Alias 'dis_its3' -PrimarySmtpAddress 'jackson.k12.ms.us' -ManagedBy 'Robinson Mykal'
</code>
However I Would be careful with this call because you are not specifying what to get. A lot of powershell cmdlets will just return everything and the net effect will be that you update all of them.
<code> # Membership approval
 Get-DistributionGroup | Set-DistributionGroup -MemberJoinRestriction:closed -MemberDepartRestriction:closed
</code>

Powershell script combine


What is the code approved way to cut and patch fire rated drywall hung on the ceiling of a basement?

Question: My new house is still under construction, and for code reasons the builder is required to hang fire rated drywall on the ceiling of the basement.
I am sure the situation will arise eventually where I will need access to wire or plumbing runs behind this, and to do this I will need to cut the drywall.
Are there are any restrictions or things to know about according to national US residential building codes regarding the proper repair of fire rated drywall?
EDIT:
In case you were curious, the reason this fire board is code required is because the house wasn't built with typical dimensional lumber for floor joists.  Instead they use these questionable looking Engineered I Joists

Because it is nothing but OSB in the middle, they don't quite as well in the event of a fire as dimensional lumber would.  This is why the fire rated drywall is required.
Comment: Interesting. The last time we used those engineered joists, I don't recall any requirement to use fire rated drywall. I guess that's a local code.
Comment: The code may be localized, but the question of working with fire rated drywall is a good one.
Comment: @BMitch Maybe you are right, if so then this question is probably too localized or off topic.
Comment: It might also be the combination of the engineered i beams and having a finished basement (I don't know if you are getting a finished basement). Pure speculation on my part.
Answer: I'm not aware of anything special for fire rating a joint in drywall, just use the same joint compound and tape you would use on the rest of your walls. Fire rated drywall will cut similar to normal drywall, but it will offer a lot more resistance because of the embedded fiberglass.
When sealing any gaps or cracks, they make special fire rated expanding foam and caulk. They tend to be orange in color. There's also fire rated insulation that can be used for any utility chases/bulkheads that connect to the ceiling.
For junction boxes, we've been required to box our in on common walls (2x4 above and below the junction and a piece of plywood behind everything) to ensure that any shorts in the electrical couldn't travel to another unit, but I doubt this would be a requirement for anyone in a single family home.
Comment: @maple_shaft You can caulk around the joint between the junction box and drywall. Between the drywall joints, just mud and tape like normal.
Comment: Ahh so thats what that dried orange foam is!  Wasn't aware but good to know that they guys are doing everything to code.  So to repair a rectangle hole, I would cut a piece of fire rated drywall and then seal it in place with this special foam and caulk?  And only then I can tape and mud it?
Comment: I see, in case I want to install overhead lighting some day.  It will not be finished, but that may be something I take on some day when I get more money.
Comment: @maple_shaft Pick your place and run the wiring and junction box for it now. You can cover it with a blank until you decide on the fixture.
Answer:
What is the code approved way to cut and patch fire rated drywall

There are several building codes that come into play for this question. You didn't specify your locality so I'll just assume you're in North America and that the most relevant code applicable to your question is National Fire Protection Association, NFPA 221.
In this case, I see no NFPA mentions for patching the drywall. That means following the code is, "per the manufacturers instructions." I checked the USG's installation instructions for normal and fire rated drywall and again see no difference in their patching instructions.
Drywall patching tips
Cut out a 2' square patch of drywall. It's so much easier to work with ample space. I usually center my cutout over a stud. You can use a magnet to find the fasteners in the studs. After cutting with a knife or drywall or oscillating saw, the 2' square patch can be pushed in on one side and the other side pops right out. Unless I'm trying to save the old drywall, I usually pull any fasteners through the old piece. Then remove the fasteners.
When finished working behind the drywall, find two pieces of scrap 1x3 or 2x4 furring that's a little longer than 2'. Center the furring inside the cut out hole so that half the wood is exposed and zap a few screws into that blocking. Now you've got a frame to set the new piece of drywall into.
Cut a new 2' square piece of drywall. You can cut the sheet of drywall into quarters at the store to make it easier to transport. Since your hole is 2' square, it's real easy to remember the exact dimensions. Slide the new square into place, fine tune the edge with a rasp if necessary, and zip a couple screws along the edges into that blocking and a couple more into the stud. Patch per the manufacturers instructions.


How to scan I2C slave address on STM32?

Question: I'm trying to communicate with an mpu9250 with STM32 via I2C, but I can't determine the slave address. (I am using a usb bootloader.)
Answer: According to the datasheet
(https://www.invensense.com/wp-content/uploads/2015/02/PS-MPU-9250A-01-v1.1.pdf)
page 12,
the default I²C slave address of the MPU9250 is 0b1101000(=0x68=104) or 0b1101001(=0x69=105) depending on the value of pin AD0.
If you use two MPU9250, you can differentiate them by using one with the first address and the other one with the other address by putting a logic LOW on the AD0 pin of the first MPU and a logic HIGH on the AD0 pin of the second MPU.

How to scan I2C slave address on STM32?


How bad is this quartz countertop seam (color mismatch)?

Question: Reality check here. The seam fits together quite well, but my wife and I were unpleasantly surprised by the degree of the color mismatch. Is that considered normal?
Comment: No good...........
Comment: This is likely to be closed as "opinion based", since that's what you're asking for. If it's unacceptable _to you_, ask the installer to fix it. If it's acceptable _to you_, move on with life. Whether I, a random stranger on the internet, would be willing to live with it or not is irrelevant in your decision making. That said, my opinion is no, that's totally unacceptable.
Comment: My opinion: unacceptable.
Comment: Not unusual.  I'm guessing the workman gets to the site and finds the pieces badly mismatched.  Rather than go back to the shop to find the right bits he just installs what he has and hopes the customer doesn't complain.  (Note that in some cases, with large counters, there may be several pieces, and it's hard to get everything matched, especially if a piece breaks on-site and a substitute piece is needed.)
Comment: Noting the risk that this question be closed as being subjective, I'd suggest that it could be recast along the lines of "how much difference in terms of RAL or Pantone colours is considered acceptable in this situation?".
Comment: (not a native speaker) are you talking about the color of the product that connects the two pieces (like a seam between two pieces of fabric), if so I do not even see it. If this is the rectangular piece of a completely different color I would never accept then yes, they are completely mismatched.
Comment: Do note that there appears to be a significant variation in the color across the larger piece.  The problem is that variation like this is fairly common.
Answer: That is, in my opinion at least, quite substandard.  It looks as though they put two pieces from different batches together.
Seams are almost inevitable but they should carefully match pieces so that they are nearly invisible.  I'll bet that if you were to go to their showroom and look at some seams you'd have a difficult time figuring out that there was a seam there.
I'd absolutely have a discussion with the company that sold and installed this.  It's UNACCEPTABLE!
Comment: Yeah, that's not a "seam" problem, that's One from color A, One from color B on either side of the seam.
Comment: Agreed, that's unacceptable.  Get it re-done or a discount if you are willing to live with it.
Comment: @GeorgeAnderson: Sometimes if one can't make things match perfectly, a good alternative (with the purchaser's permission) is to turn the mismatch into a design feature).  If the area is a breakfast bar, then although one would want a smooth top surface across the seam for ease of cleaning, having a deliberately contrasting color might look good.
Answer: No, it is COMPLETELY unacceptable, and whoever installed it knows that. Ask him if he would accept that level of workmanship in his own house. He wouldn't, and neither should you. If you haven't paid for it yet, I would arrange to put the money in escrow until it is remedied. A big hassle, but better than living with that inferior product.


Splitter using jQUery UI library

Question: I am trying to create resizable cells (Splitter) like the one below
http://methvin.com/splitter/3csplitter.html
But I need to do that using jQUery UI.
I am not sure how similar thing can be achieved using jQUery UI.
Is it possible using the jQuery UI Resiable(http://jqueryui.com/resizable/)
If yes, could you please provide any reference example for the same.
It should behave similar to the Methvin.com/splitter
Answer: This is the code I used one day:
<code>$(".resizable1").resizable({
    handles: 'e',
    minWidth: '50',
    maxWidth: '350',
    resize: function() {
        var remainingSpace = $(this).parent().width() - $(this).outerWidth(),
            divTwo = $(this).next(),
            divTwoWidth = remainingSpace - (divTwo.outerWidth() - divTwo.width());
        divTwo.width(divTwoWidth);
    }
});
</code>
http://jsfiddle.net/8qzTJ/
Comment: Source: http://www.codechewing.com/library/jquery-ui-resizable-splitter-function/
Comment: This example is great! How about to use $(".resizable2").resizable with handles: 'w'? I  try to rewrite the "resize: function()" but it couldn't work properly. Any idea?
Comment: Hi @dfsq ur example is great and its working, but i am trying this same idea with multiple number of columns. where we should deduct sum of  previous columns width also, for getting  `remainingSpace`. here i'm facing some pblms.. if u have some brilliant idea or reference, it will save my hours.
Answer: This is definitely possible with the jquery ui, check out the docs here http://jqueryui.com/resizable/#helper this is just a short hand example
<code>$(function() {
    $( "#resizable" ).resizable({
      handles: "n,e,s,w" // chose the handle you want
    });
  });
</code>

Splitter using jQUery UI library


Replace G24q-1 (4-pins) with a B22 Bayonet

Question: Having recently moved house, I've noticed that the majority of the lighting upstairs is running CFLs using a type of connection that I am unfamiliar with (research says it's a G24q-1 cap but see photos below).
I'm looking to replace these with standard B22 Bayonet caps. However, since I'm unfamiliar with the G24q-1 cap I wanted to make sure that my approach is sound.
Here is the current configuration of what I believe to be a G24q-1

and a closeup of what I believe to be a G24q-1 cap that is currently fitted

and here is the B22 Bayonet cap I have bought that I wish to fit

Now, my question is do I simply remove the existing base and fit the pendant in its place. Ensuring that all wires match up to where they are in the current arrangement (3/7 and 4/8) in the first picture?
Comment: Why B22 Bayonet ??  If it were me i would just buy new fixtures and led bulbs or just led fixtures.
Comment: The B22 Bayonet is the most common form of fixture in the UK. Which (although it does accept old incandescence) also provides the greatest choice for LED bulbs. I'm open to suggestions though, which LED fixture did you have in mind?
Answer: G24q-1 bulbs do not take mains voltage
I agree that the 8-terminal block is the standard UK mains splice. However, there must be a ballast or driver circuit between the mains connection and the G24q socket.
You must account for that before you can rewire.
My concern is that they may simply be using common UK wiring kit to extend from an external ballast to this location.  That would be reasonable to do if they use a ballast that can support 2+ lamps.
This is an incandescent socket. Be careful!
A basic tenet of design is that fixtures not made for incandescents must not have sockets which could possibly take incandescents.
Even if you are enlightened enough to use efficient LEDs, the person who comes after you may slap in an incandescent.   At that point, the bulb is making much more heat than the fixture was ever designed to accommodate, and you can start a fire.
The bayonet socket you want to install will take incandescents.
I can't see the rest of the fixture,  but make sure it is listed and rated for incandescents.
If it is not, and  you want to fit LED bulbs, choose a socket type that only supports LEDs and not incandescents.  Or change to a fixture that is appropriate for incandescents.
Answer: The ballast etc is inside the Eterna LEP13 lampholder and you can just change the lampholder or the pendant and leave the ceiling rose as it is.
This is a misguided attempt under Building Regs that require a certain proportion of lighting points in new build houses to be 'low energy'.
Similar product from MK
https://www.ebay.co.uk/c/1412633868


Windows Application: Switching to iframe window nested inside the same window

Question: Firstly, I have tried driver.switchTo().frame("framename"); but it does not switching to that.
driver.switchTo().frame("xxx");/// Throws an {"status":7,"value":{"error":"no such element","message":"An element could not be located on the page using the given search parameters."}}

After dig into deeper, I found that the particular frame locators were not even present inside the page source. Any idea on how to switch to that frame.
P.S. I'm using WinApp driver.
Note: Same scenario in web, I'm able to switch using switchTo iframe elements.
Answer: I think you have a mismatch here. What you need to input at frame(" ") is not a string. It should be:
driver.switchTo().frame(driver.find_element_by_xpath("xpath of the iframe"));

Comment: Even after giving a xpath, It doesn't switching to the frame. Because in page source iframe elements were not there. So it throws no such element in it.


Covariance of process $X(t) = \int_{t}^{t+1} W(s)\, ds$, where $(W(t))$ is a Wiener process

Question: Let $X(t)$ be the following time integral of a Wiener process $W(t)$
$$
X(t) = \int_{t}^{t+1} W(s)\, ds.
$$
This process is zero mean, and I want to compute its covariance $EX(t)X(s)$.
I am not sure that the following is correct. It is obvious that if $|t-s|>1$ then $EX(t)X(s) = 0$.
In the case when, for definiteness, $t \leq s \leq t+1$ we can consider the following partition
$$
\Delta_1: t=a_0<a_1<\ldots<a_n=s,
$$
$$
\Delta_2: s=b_0<b_1<\ldots<b_k=t+1,
$$
$$
\Delta_3: t+1=c_0<c_1<\ldots<c_l=s+1.
$$
Each corresponding Riemann sum can be represented in the following way
(here $a_{-1}=0$ by definition)
\begin{align*}
R_{\Delta_1} &= \sum_{i=0}^{n-1} W(a_i)(a_{i+1}-a_{i})\\
&= \sum_{i=0}^{n-1} (W(a_{i-1})-W(a_i))a_{i} + W(a_{n-1})a_n\\
&=\sum_{i=0}^{n-1} (W(a_{i-1})-W(a_i))(a_{i}-a_n).\\
\end{align*}
And now using the independence of increments we have
\begin{align*}
E (R_{\Delta_1}+R_{\Delta_2})(R_{\Delta_2}+R_{\Delta_3})
&= E (R_{\Delta_2})^2\\
&= \sum_{i=0}^k (b_i-b_k)^2 E(W(b_{i-1})-W(b_i))^2 \\
&= \sum_{i=0}^k (b_i-b_k)^2 (b_{i}-b_{i-1}).
\end{align*}
And
$$EX(t)X(s) = \lim_{k\to\infty} \sum_{i=0}^k (b_i-b_k)^2 (b_{i}-b_{i-1})
= \int_{s}^{t+1} (y-t-1)^2dy = \frac{(t+1-s)^3}{3}.$$
Am I right?
Answer: \begin{align}
\mathsf{E}[X(t)X(s)]&=\mathsf{E}\left[\int_t^{t+1}W(r)dr\int_s^{s+1}W(q)dq\right] \\ &=\mathsf{E}\left[\int_t^{t+1}\int_s^{s+1}W(r)W(q)dqdr\right] \\
&=\int_t^{t+1}\int_s^{s+1}\mathsf{E}[W(r)W(q)]dqdr \\
&=\int_t^{t+1}\int_s^{s+1}\min\{r,q\}dqdr.
\end{align}
If $s\ge t+1$, then
$$
\mathsf{E}[X(t)X(s)]=\int_t^{t+1}rdr=t+\frac{1}{2}.
$$
Comment: Thanks! So the rest is also wrong because $ER_{\Delta_1}R_{\Delta_2}\ne0$, right?


Generating set for $SL_2(F)$

Question: Let $F$ be a field and $G = SL_2(F)$. Let us define the following matrices
$$X(b) = \begin{pmatrix} 1 & b\\ 0 & 1 \end{pmatrix}, \quad Y(c) = \begin{pmatrix} 1 & 0\\ c & 1 \end{pmatrix},$$
where $b,c\in F$. It a well-known result that these matrices generate $G$ (Lemma 8.1, Ch. XIII in 3rd edition of Lang's Algebra).
After doing some short calculations, I noticed that the set consisting of all matrices $X(b)$ and the matrix $Y(c_0)$ (for some $c_0\in F^\times$) is already a generating set.
Is there some other way to obtain this result?
AYK

PS. These are the calculations that I mentioned above:
$$X(-1/x)Y(x)\cdot X(y)\cdot Y(-x)X(1/x) = Y(-x^2y).$$
Comment: Can we make any assumptions about $F$?  Can we say it has characteristic $0$?
Comment: The statement holds in every characteristic. But all arguments are welcome of course..
Comment: wouldn't have expected that.  Good to know.
Comment: By the way: I've added some more generic tags with the hopes of increasing your question's visibility
Comment: @AYK: Are you sure your result is correct. Can you outline the proof?
Comment: I am sorry, I forgot to include the inverse of $Y(c_0)$ which I've also used in the calculations.
Comment: @AYK: Suppose $F=\mathbb{Q}$. Using, as generators, the set of matrices of the form $X(b)$, together with $Y(2)$, how would you generate $Y(1)$?
Comment: @quasi I've edited the question.
Comment: But $Y(-c_0)$ is  just the inverse of $Y(c_0)$, hence if you have $Y(c_0)$, you get $Y(-c_0)$ for free. So my question remains: How can you generate $Y(1)$ from $Y(2)$ (and the matrices $X(b)$)?
Comment: Ok, I see the edited post -- no need to answer my question.
Comment: @quasi You are right on the 'inverse comment', my bad
Comment: @AYK: Your construction is very nice, and fully answers my question.
Answer: I think, doing "these short calculations" is the best method to obtain this result.
We may even use only two unipotent generators for finite fields, with a few exceptions. A precise statement is given in Dickson's Theorem. For a finite field $F$, and a generator $\lambda$ for $F$ over $\mathbb{F}_p$,
$$
L:=\langle \left( \begin{array}{clcr} 1 & 0\\1 &1 \end{array} \right),\left( \begin{array}{clcr} 1 & \lambda\\0 &1 \end{array} \right) \rangle
$$
is indeed $SL_2(F)$, except when $|F| =9$, in which case $L\cong SL_2(5)$.
For a reference see here.
Comment: I did not assume the field $F$ is finite...
Comment: Yes, but this is the only interesting case left, I think.

Generating set for $SL_2(F)$