Clone just the stable and one other branch in git?

Question: I'm just getting started with git and I have a question. My app has 10 other developers working on it, each one having their own branch like dev_XXXXX. So if I do a clone of the repository, do all of their code gets copied to my machine? In that case I dont want that. Suppose my branch is dev_swamy, how do I then clone just the stable branch and dev_swamy? Thanks.
Answer: By default git clone would fetch all branches, but those branches would be stored as remote-tracking branches: for example branch 'dev_XXXXX' would be stored as 'origin/dev_XXXXX' (with 'refs/remotes/origin/dev_XXXXX' as full name).  Those remote-tracking branches wouldn't be visible in git branch output: you would need git branch -r to list remote-tracking branches (or git branch -a to list all branches).  If those branches do not diverge too much from mainline, they wouldn't take too much disk space in repository.  Therefore I don't see why you want to clone only selected branches.
Nevertheless if you want to have a clone with only two selected branches, you can do it like this:

First, create new empty repository
$ mkdir repoclone
$ cd repoclone/
$ git init
Initialized empty Git repository in /home/user/repoclone/.git/

Then add your repository under the name 'origin' (just like "git clone" would name it), requesting tracking of only two branches: 'master' and 'dev_swamy', using "git remote" command.  Check that it was added correctly.
$ git remote add -t master -t dev_swamy origin email@example.com:repo.git
$ git remote
origin
$ git remote show origin
* remote origin
  Fetch URL: email@example.com:repo.git
  Push  URL: email@example.com:repo.git
  HEAD branch: master
  Remote branches:
    master          new (next fetch will store in remotes/origin)
    dev_swamy new (next fetch will store in remotes/origin)

If the stable branch is called 'stable' rather than 'master', you would have of course to modify above example.  Also there is -m <branch> option if you want specified branch to be default branch in remote.
Fetch from 'origin' (you could do this also by using -f option to "git remote add" above):
$ git fetch
remote: Counting objects: 282, done.
remote: Compressing objects: 100% (193/193), done.
remote: Total 282 (delta 82), reused 0 (delta 0)
Receiving objects: 100% (282/282), 81.30 KiB | 135 KiB/s, done.
Resolving deltas: 100% (82/82), done.
From email@example.com:repo.git
 * [new branch]      master     -> origin/master
 * [new branch]      dev_swamy -> origin/dev_swamy
From firstname.lastname@example.com:repo.git
 * [new tag]         v1.0       -> v1.0
 * [new tag]         v1.0.1    -> v1.0.1
 * [new tag]         v1.1       -> v1.1

Set up local branch 'master' (where you would do your work) to follow 'origin/master' (to have 'origin/master' as upstream), just like "git clone" would do:
$ git checkout -t origin/master
Branch master set up to track remote branch master from origin.
Already on 'master'

You can repeat this for branch 'dev_swamy'.
Now you can see how config file looks like.  You can get exactly the same result by editing .git/config file to look like the following, and then doing "git fetch".
$ cat .git/config  # or just open this file in your editor
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true
[remote "origin"]
        url = email@example.com:repo.git
        fetch = +refs/heads/master:refs/remotes/origin/master
        fetch = +refs/heads/dev_swamy:refs/remotes/origin/dev_swamy
[branch "master"]
        remote = origin
        merge = refs/heads/master

Don't forget to introduce yourself to Git before starting work on repository (i.e. set 'user.name' and 'user.email' config variables; usually in per-user config file)!
Answer: If you clone, all revisions in all branches are cloned along, but the cloned repository will check out master by default.
Just taking selected branches is trickier since git does not really think you should work that way. You have to pull down the branches manually:
mkdir repoclone
cd repoclone
git init
git remote add origin git://remote/url
git fetch origin master:master
git fetch origin dev_XXX:dev_XXX

Above is what I knew worked. However, if you want to set up a git repo that works as normal, just has a more narrow view of its remote branches? You can do that pretty easily:

mkdir repoclone
cd repoclone
git init
git remote add origin git://remote/url

# now open .git/config for editing in your editor
# replace the following line (grab all remote branches)
fetch = +refs/heads/*:refs/remotes/origin/*

# replace with lines listing exactly which branches you want
fetch = +refs/heads/master:refs/remotes/origin/master
fetch = +refs/heads/dev_XXX:refs/remotes/origin/dev_XXX

# save the file, now run

git fetch

Comment: Aha! This is something I've been thinking about for a while - is there a way to clone only one branch. An interesting idea to turn it on it's head and fetch only what you need. But the first fetch generates this error: "fatal: Refusing to fetch into current branch refs/heads/master of non-bare repository"
Comment: BTW with modern git you can use `git init repoclone`
Comment: @Steve: Ah, you are right. You can replace with "`git fetch origin master; git reset --hard FETCH_HEAD`" to setup master.
Comment: @Jakub: "modern"? Not even 1.6.4 supports that. So more like absolutely latest git.
Comment: It's easier (in the long run) to add a fetch config for the remote which doesn't contain the default wildcard. Then you can keep the local and remote branches separate in the same way as you would for a normal clone and just use a simple `git fetch` for incremental updates.
Comment: @charles: You are right and I realized at the same time you wrote your comment.
Answer: Possibly a more uptodate way (using a small random repo found online):
Do a clean checkout of  the specific branch, and only that branch.
$ git clone https://github.com/martinmimigames/little-music-player --single-branch --branch=main
Cloning into 'little-music-player'...
remote: Enumerating objects: 1187, done.
remote: Counting objects: 100% (292/292), done.
remote: Compressing objects: 100% (142/142), done.
remote: Total 1187 (delta 114), reused 243 (delta 82), pack-reused 895
Receiving objects: 100% (1187/1187), 1.61 MiB | 9.38 MiB/s, done.
Resolving deltas: 100% (487/487), done.

Go into the checkout:
$ cd little-music-player

Show what branches are known (confirming only the 1 required branch is known):
$ git branch --all
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main

Fetch another branch:
$ git fetch origin m3u:m3u
From https://github.com/martinmimigames/little-music-player
 * [new branch]      m3u        -> m3u

List the known branches again:
$ git branch --all
  m3u
* main
  remotes/origin/HEAD -> origin/main
  remotes/origin/main

To improve performance on large repos, you can add a --depth nnn option to the checkouts if you're planning to do some work between the 2 branches and you know that there is only recent deviation between them (the value of the depth is upto you).
If you are only intending to operate on specific files within the repo, then the use of sparse checkouts is another option (setup more along the lines of git init and config changes before doing the fetch - a very different way of doing things).
Hope this helps.
Comment: git fetch origin develop throw this error `error: ssh://git-foo/bar/v1/repos/hello-world did not send all necessary objects`
Comment: This works, but `git pull` gives: _Remote origin did not advertise Ref for branch m3u. This Ref may not exist in the remote or may be hidden by permission settings._
I guess a command is missing.
Answer: Another way to do this is to avoid a direct clone, but instead manually add a remote with a custom set of fetch refspecs.
e.g.
mkdir myclone
cd myclone
git init

git remote add origin url://origin.repo

# Add fetch rules for the branches that we want to track
git config remote.origin.fetch +refs/heads/master:+refs/remotes/origin/master
git config --add remote.origin.fetch +refs/heads/dev_swamy:+refs/remotes/origin/dev_swamy

# fetch now fetches just what we need, subsequently it will do incremental fetches
git fetch

# Creating local branches tracking the remote branches
git checkout -b master origin/master
git branch dev_swamy origin/dev/swamy

Answer: I think the more important question here is what others will be pushing, not what you will be cloning or pulling. Since each developer is working on his own branch, another question is how you end up with a common code base. Are the developers merging their branches to master? And are they then pushing their changed master branch to a central repository? If that is the case, there is no way for you to pull the other developers' branches anyway.
If that is not the case, I fail to see how you can form a functioning team.
And as I final thought: I'd be curious to know why you wouldn't want to clone the other developers' branches to your repository?


A one-word synonym for "someone who wears his heart on his sleeve"?

Question: While there's an antonym "composed" which is an antonym, I couldn't find a short synonym to describe someone who wears his heart on his sleeve. Can you think of one?
Comment: I don't think "composed" is an antonym of that. Such a person is emotionally candid, not erratic.
Comment: Authentic? Vulnerable? An open book? Transparent? Drama Queen?
Answer: Such a person (and their behaviour) is unrestrained.
From Collins Cobuild Advanced English Dictionary:

unrestrained adj
If you describe someone's behaviour as unrestrained, you mean that it
  is extreme or intense, for example because they are expressing their
  feelings strongly or loudly.

Via WFMT`S Audio Library, via Chicago Tribune.com:

'Drury obviously enjoys his job ... and he is unrestrained in his
  enthusiasm.'

And from France 24:

Speaking to AFP on condition of anonymity, a former associate called Matovic "a phenomenon". "He is an extremely proficient communicator.
  He is unrestrained and sincere – sometimes too sincere," they said.

'Abandoned' and 'uninhibited' are other possibilities.

uninhibited adj
1 Expressing one's feelings or thoughts unselfconsciously and without
  restraint.
'a lively and uninhibited girl'

[Lexico]
'Abandoned' may convey too much wildness, impropriety.
Answer: How about "overly sensitive" or "touchy"?
If you are looking for a more neutral rather than negative connotation, "open" or "transparent" might work.
Comment: I'm not sure it means that [at all](https://www.merriam-webster.com/words-at-play/origin-of-wear-heart-on-sleeve). On the contrary such a person may be emotionally stable.
Comment: thanks for the suggestion, but I think both of them have a somewhat negative meaning, don't they? Which the sleeve idiom doesn't
Comment: Someone who has their heart on their sleeve has their emotions on display to everyone. They're often incapable of hiding their emotions. If they're happy, you know it. If they're sad, you know it.
Answer: Someone who expresses their emotions freely and openly is generally said to be emotional.


How to compile C++ under Ubuntu Linux?

Question: I cut&pasted the below code from a previous question into a file called "avishay.cpp" and then ran
gcc avishay.cpp

only to get the following error messages from the linker. What went wrong, what should I have done?
carl@carl-ubuntu:~/Projects/StackOverflow$ gcc -static avishay.cpp
/tmp/cccRNW34.o: In function `__static_initialization_and_destruction_0(int, int)':
avishay.cpp:(.text+0x41): undefined reference to `std::ios_base::Init::Init()'
avishay.cpp:(.text+0x46): undefined reference to `std::ios_base::Init::~Init()'
/tmp/cccRNW34.o: In function `A::func()':
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x11): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x16): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x26): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x36): undefined reference to `std::cout'
avishay.cpp:(.text._ZN1A4funcEv[A::func()]+0x3b): undefined reference to `std::basic_ostream<char, std::char_traits<char> >::operator<<(int)'
/tmp/cccRNW34.o:(.eh_frame+0x12): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status

The C++ code (not my code, I was just trying to run it):
#include <iostream>
using namespace std;

class A
{
private:
   int _dmember;

public:
   void func()
   {
     cout<<"Inside A!! "<<endl;
     cout<<_dmember; // crash when reach here.
   }
};

int main ()

{

    A* a= NULL;

    a->func(); // prints "Inside A!!!"

    return 1;
}

Comment: Duplicate of http://stackoverflow.com/q/203548/981959
Answer: You should use g++, not gcc, to compile C++ programs.
For this particular program, I just typed
make avishay

and let make figure out the rest. Gives your executable a decent name, too, instead of a.out.
Comment: Another +1 (if I could) for the "make" tip. I never knew make could/would do that!
Comment: the reason why `make serial-rob.c` doesn't work, is because that file is already made, it's there already.  on the other hand, when make looks for a file named serial-rob, it's not there, but it has an implicit rule for making *.c into *.o and that into just *
Comment: The trick, I think, is to let it use its implicit rules. If it works for you like it did for me, then "make serial-rob" (without the .c) should do it.
Comment: How does 'make' work here? I tried "make serial-rob.c" and it says "Nothing to be done for.."
Answer: You probably should use g++ rather than gcc.
Comment: Thanks. Just yesterday I didn't know how to spell "C++ programmer" and today I are one!
Answer: Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.
g++ source.cpp -o source

If you omit the -o parameter, the resultant executable will be named a.out. In any case, executable permissions have already been set, so no need to chmod anything.
Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.
Comment: Yeah, the code was part of another question (linked) and got its due thrashing there. For just a quick test, I don't mind the program being called a.out, and I knew about -o. My main problem was with the compiler name, thanks!
Answer: Update your apt-get:
$ sudo apt-get update
$ sudo apt-get install g++

Run your program.cpp:
$ g++ program.cpp
$ ./a.out

Comment: Out of the other answers , this one is more clear and to the point . Thanks a lot .
Answer: g++ is the C++ compiler under linux. The code looks right. It is possible that you are missing a library reference which is used as such:
g++ -l{library name here (math fns use "m")} codefile.cpp
Answer: Use

g++

space followed by the program name.
e.g:

g++ prog.cpp

if the filename was "prog.cpp" in this case.
if you want to run the program write:
./prog

so i used

"prog"

because it was my filename.
Comment: The output file will be "a.out" unless you use the `-o` flag
Answer: even you can compile your c++ code by gcc
Sounds funny ?? Yes it is.
try it
$  gcc avishay.cpp -lstdc++

enjoy
Answer: Use g++. And make sure you have the relevant libraries installed.
Comment: I paid good money for Ubuntu... oh wait, I didn't! But yeah, it turns out the problem was just in how I called the compiler.
Answer: you can use g++ --std=c++0x example.cpp -o example
Answer: To compile source.cpp, run
g++ source.cpp

This command will compile source.cpp to file a.out in the same directory.
To run the compiled file, run
./a.out

If you compile another source file, with g++ source2.cpp, the new compiled file a.out will overwrite the a.out generated with source.cpp
If you want to compile source.cpp to a specific file, say compiledfile,
run
g++ source.cpp -o compiledfile

or
g++ -o compiledfile source.cpp

This will create the compiledfile which is the compiled binary file. to run the compiledfile, run
./compiledfile

If g++ is not in your $PATH, replace g++ with /usr/bin/g++.
Answer: Install gcc and try the video below.
Try this:
https://www.youtube.com/watch?v=A6v2Ceqy4Tk
Hope it will works for you.

How to compile C++ under Ubuntu Linux?


Problems with read a file using fstream inside DLL

Question: I have the following problem, that should be well-known, but I have failed to google anything relevant.
I have a C# project, some of its performance-critical parts are supposed to be inside C++ DLL. In DLL I am trying to read some file using std::fstream. The problem is that it fails to read this file and pretends that there is no file at all (though I'm using the full path to it).
The question is the following: is this problem well-known? Probably I'm doing something wrong, in the other case what are possible workarounds?
This is the extract of my code:
fstream input("c:\\path\\file.txt");
if (!input) throw runtime_error("file not found");

UPD: FILE* seems to work. It is very weird.
Comment: How about posting some code showing how you're using the `ifstream`?
Answer: Did you forget to properly quote backslashes?
Shouldn't it be:
fstream input("c:\\path\\file.txt");
if (!input) throw runtime_error("file not found");

on top of that, I would avoid using ifstream if that code is performance sensitive.
Comment: I actually pass a string with correct backslashes. It is a typo in my initial post. File reading is not performance-sensitive.


How to sync songs in Rhythmbox with an iPod

Question: I can sync them with Banshee but in Rhythmbox (Am starting again to use it since it will be the default in 12.04) I can see that Rhythmbox can detect the ipod and see the songs but when I try to drag one to the ipod how can I tell it to sync it so I can remove the iPod and listen to it.
Answer: If you are using iOS 5.x, the library that Rhythmbox (and others) use to do this does not yet support the newer database version. If your iOS device has recently been updated, then you simply need to wait for libimobiledevice to be updated (watch the website under Music/Video Synchronization Status for updates).
[edit: 3/11/13 e.m.fields - It seems that the libimobiledevices is supporting up to iOS 6.12 as of this release. ]
from www.libimobiledevice.org:

Latest Release: 1.0.7
  Development/Unstable Release: 1.1.4
Tested with iPod Touch 1G/2G/3G/4G, iPhone 1G/2G/3G/3GS/4/4S/5, iPad 1/2/3rd Gen and Apple TV running up to firmware 6.1.2 on Linux, Mac OS X and Windows.
Comment: Thanks rwrw. For the moment I found this tool gtkpod which basically works. It detects the shuffle 4th gen I have and I can just drag, drop, sync and then listen to them with no problem.
Comment: It seems that the libimobiledevices is supporting up to iOS 6.12 as of this moment. However I have't been able to get it working with my rhythmbox installation, so YMMV.
Answer: Maybe you can take a look on the official documentation here:
https://help.ubuntu.com/community/PortableDevices/iPhone#Syncing_with_Rhythmbox
This is a grafical hint on how to do this:
http://www.simplehelp.net/2007/07/03/how-to-manage-your-ipod-using-rhythmbox-in-ubuntu/
If this doesn't work, you can try as described in this guide:
http://ubuntu-install.blogspot.com/2011/04/connect-ipad-and-ipod-with-ubuntu.html
Comment: Yes I already dragged the song to the ipod and yes that works. I can see the song there but I can not sync it to the ipod and if I remove the ipod the song is not there. It only "shows" that is there, is not actually synced to the device. That is the problem.
Answer: I'm using a Toshiba NB505 with Ubuntu 12.10 and an iPod Nano 8GB 4th Gen.  I restored the iPod using iTunes on a separate windows computer for a clean slate.  I set up my playlists and podcasts in Rhythmbox, connected the iPod, and synced with library.  When trying to sync again the following day after downloading fresh podcast episodes, Rhythmbox would crash again, send an error report and I was back at square one.  After looking at many forum entries and deleting config files that were hidden, trying banshee, trying gtkpod, I could not fix the problem.  However if I restored the iPod in iTunes and synced with Rhythmbox back on my Ubuntu netbook, it would sync fine, but only once.  Here's my lame attempt at a fix.  I eventually used gtkpod to remove the songs and podcasts (right-click on the iPod in gtkpod and remove all songs, click "i'm sure"), then once the iPod is empty, close gtkpod, open Rhythmbox and sync with library or drop podcasts or music directly on to the iPod.  It has worked so far for me.  I hope this helps.
Answer: Ah, I think I see the problem:

Ubuntu libimobiledevice version: 1.1.4
Version that supports iOS 6.1.3: 1.1.5.

Edit: the above might not appear to make much sense, but it has been merged out of context from this question: sync - iPhone 4s + Rhythmbox = Fail (12.10, ios 6.1.3) - Ask Ubuntu. In short, at time of writing, Ubuntu's version of libimobiledevice does not support the latest iOS.
Comment: I installed libimobiledevice 1.1.5 on ubuntu 12.10. I still could not sync my iphone 4s with 6.1.3 with rhythmbox.


How to make a simple collection view with Swift

Question: I'm trying to learn how to use UICollectionView. The documentation is a little hard to understand and the tutorials that I found were either in Objective C or long complicated projects.
When I was learning how to use UITableView, We ❤ Swift's How to make a simple tableview with iOS 8 and Swift had a very basic setup and explanation to get me going. Is there anything like this for UICollectionView?
The answer below is my attempt to learn to do this.
Answer: This project has been tested with Xcode 10 and Swift 4.2.
Create a new project
It can be just a Single View App.
Add the code
Create a new Cocoa Touch Class file (File > New > File... > iOS > Cocoa Touch Class). Name it MyCollectionViewCell. This class will hold the outlets for the views that you add to your cell in the storyboard.
import UIKit
class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var myLabel: UILabel!
}

We will connect this outlet later.
Open ViewController.swift and make sure you have the following content:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
    var items = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"]

    // MARK: - UICollectionViewDataSource protocol

    // tell the collection view how many cells to make
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    // make a cell for each cell index path
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        // get a reference to our storyboard cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! MyCollectionViewCell

        // Use the outlet in our custom class to get a reference to the UILabel in the cell
        cell.myLabel.text = self.items[indexPath.row] // The row value is the same as the index of the desired text within the array.
        cell.backgroundColor = UIColor.cyan // make cell more visible in our example project

        return cell
    }

    // MARK: - UICollectionViewDelegate protocol

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // handle tap events
        print("You selected cell #\(indexPath.item)!")
    }
}

Notes

UICollectionViewDataSource and UICollectionViewDelegate are the protocols that the collection view follows. You could also add the UICollectionViewFlowLayout protocol to change the size of the views programmatically, but it isn't necessary.
We are just putting simple strings in our grid, but you could certainly do images later.

Set up the storyboard
Drag a Collection View to the View Controller in your storyboard. You can add constraints to make it fill the parent view if you like.

Make sure that your defaults in the Attribute Inspector are also

Items: 1
Layout: Flow

The little box in the top left of the Collection View is a Collection View Cell. We will use it as our prototype cell. Drag a Label into the cell and center it. You can resize the cell borders and add constraints to center the Label if you like.

Write "cell" (without quotes) in the Identifier box of the Attributes Inspector for the Collection View Cell. Note that this is the same value as let reuseIdentifier = "cell" in ViewController.swift.

And in the Identity Inspector for the cell, set the class name to MyCollectionViewCell, our custom class that we made.

Hook up the outlets

Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class. (You can Control-drag.)
Hook the Collection View delegate and dataSource to the View Controller. (Right click Collection View in the Document Outline. Then click and drag the plus arrow up to the View Controller.)

Finished
Here is what it looks like after adding constraints to center the Label in the cell and pinning the Collection View to the walls of the parent.

Making Improvements
The example above works but it is rather ugly. Here are a few things you can play with:
Background color
In the Interface Builder, go to your Collection View > Attributes Inspector > View > Background.
Cell spacing
Changing the minimum spacing between cells to a smaller value makes it look better. In the Interface Builder, go to your Collection View > Size Inspector > Min Spacing and make the values smaller. "For cells" is the horizontal distance and "For lines" is the vertical distance.
Cell shape
If you want rounded corners, a border, and the like, you can play around with the cell layer. Here is some sample code. You would put it directly after cell.backgroundColor = UIColor.cyan in code above.
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 8

See this answer for other things you can do with the layer (shadow, for example).
Changing the color when tapped
It makes for a better user experience when the cells respond visually to taps. One way to achieve this is to change the background color while the cell is being touched. To do that, add the following two methods to your ViewController class:
// change background color when user touches cell
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.red
}

// change background color back when user releases touch
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.cyan
}

Here is the updated look:

Further study

A Simple UICollectionView Tutorial
UICollectionView Tutorial Part 1: Getting Started
UICollectionView Tutorial Part 2: Reusable Views and Cell Selection

UITableView version of this Q&A

UITableView example for Swift
Comment: I wish Apple's documentation was as easy to read as this explanation
Comment: If you didn't hook up the outlet by control-dragging from the label in the storyboard to the `@IBOutlet` for `myLabel` in code, you would get a crash like this.
Comment: if you are using interface builder and reference the cell using an outlet, do not register the custom cell class in your controller. see [this](http://stackoverflow.com/questions/35239543/nil-label-for-custom-uicollectioncell)
Comment: if UICollectionViewCell outlet is nil then you have to remove `self.collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")`. If you still have the problem check wether `reuseIdentifier` is same in `dequeueReusableCellWithReuseIdentifier` and in storyboard
Comment: im getting cell.myLabel as nil and it's crashing. any idea why? Im using a custom layout
Comment: @IlyaVinogradov, I've never done this and a survey of other SO questions seems to indicate that it is not possible (see [here](http://stackoverflow.com/q/28524691) and [here](http://stackoverflow.com/q/24341833)).
Comment: @Suragch you say: "Hook the Label in the collection cell to myLabel in the MyCollectionViewCell class" how do I add that as a hook up to another class? I am working on the ViewController and I cannot see where to drag the connection
Comment: @JamesG, Don't use the View Controller. Select the `MyCollectionViewCell` class code. Control drag from the label in the Interface builder to the `myLabel` outlet in the code.
Comment: Remember that the default `backgroundColor` of `UICollectionView` is black.
Comment: @AnnabelleSykes, the default background color for me used to be black when I was making this project in Xcode 7, but most recently when I retested the project in Xcode 8, the default was white. Anyway, whatever the default is for you, it can be changed in the Interface Builder or in code.
Comment: Is it possible to build a static collection view entirely in the Storyboard, similar to how you can build a table view with static content? With static content table view you can completely avoid using cellForRowAtIndexPath:, I was wondering it it's possible to get away without implementing cellForItemAtIndexPath: for my collection view.
Comment: @suragch thank you so much for this! Question - I have a function dynamically creating the data array... how can I call reloadData() for the uicollectionview from my data function?
Comment: @andehlu, I haven't been working with this for a while so I can't remember very well. Off hand I would say load the data in a background thread and when it completes then update the UI with `reloadData()`. It that doesn't work try asking a new question.
Comment: Thanks @Suragch > https://stackoverflow.com/questions/44261236/reloading-uicollection-view-after-data-parse
Comment: Cells will repeat if we add more than visible cells. E.g., if I add 1000 in array and try to load in the collection view. While scrolling the collection view, the cells will be repeated. I know its because of reusable identifier, if we want to keep dynamic reuse identifier, then we need to register all reuse identifiers in viewDidLoad and also we have to separate customer cell XIB from storyboard. That look little odd and I feel its not a standard. Do we have any alternate to that solution?
Comment: @SrinivasG, You mean that you made the `items` array go from 1 to 1000 (`["1", "2", ... "999", "1000"]`) but it repeated the first screen of numbers (1~70 or so)? I'll make a note to retest this, but if you want a quicker answer you might ask a new question on Stack Overflow.
Comment: @Suragch Thanks for checking it out. Yes, the cells will be repeating if custom cell of collection view embedded in storyboard. We were able to get it working properly if the custom cell separated from storyboard as new UICollectionViewCell xib and register dynamic reuse identifiers in viewDidLoad, but that looks odd in registering all identifiers.
Comment: Thanks for this. Its a great tutorial. It's working perfectly but I'm a tiny bit confused on how it works? The same function "func collectionView" exists 3 times. How does it know which function to run?
Comment: Sorry, I was looking at it more and think I get it now. When you, for example, link the collection views data source to the file then it looks in there and expects to find at least its mandatory methods (which it tells apart by the parameters)?
Comment: @GeorgeKendros, that is correct. Those are the mandatory methods for the data source and delegate protocols. It tells them apart by the parameters.
Comment: @SrinivasG, I finally got around to testing this. I made the array `["1", "2", ... "99", "100"]` so that it scrolled off screen. Everything seemed to work fine. The cells didn't repeat for me. I didn't change anything else about the project besides the data array.
Comment: @Suragch please help me... I really don't get how, but on first attempt I was able to ctrl-drag the label because I had the class in the "Automatic" section of the "Assitant Editor" but now I only got the viewcontroller class I'm having a burnout
Comment: Don't forget to attach your dataSource and delegate (apologies if this has already been mentioned) - this was the last thing that I hadn't done...
Comment: Swift 5: `cell` was not working as an identifier. It worked after giving it a different identifier.
Comment: I don't have any cell underneath my collectionview in the storyboard, and no way to add one. Anyone knows how to?
Comment: @agirault attribute inspector first option is "Items". Are you sure you dragged a collection view and not something else?
Comment: how did you drag drop the label to the UIViewCell Class. My assistant editor doesn't open the UIViewCell class, but always opens the ViewController class that has the Collection.
Comment: 'cell.myLabel.text = self.items[indexPath.item]' should be   'cell.myLabel.text = self.items[indexPath.row]'
Comment: Can I just say thank you @AlexZavatone for this really simple guide. As a noob this has saved my ass each time I forget an element of the process to set a collection view up
Answer: For swift 4.2 --
//MARK: UICollectionViewDataSource

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    configureCell(cell: cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.black

    //Customise your cell

}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // When user selects the cell
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // When user deselects the cell
}

Answer: Delegates and Datasources of UICollectionView
//MARK: UICollectionViewDataSource

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath)
    configureCell(cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.blackColor()

    //Customise your cell

}

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", forIndexPath: indexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
      // When user selects the cell
}

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
     // When user deselects the cell
}

Answer: UICollectionView implementation is quite interesting.
You can use the simple source code and watch a video tutorial using these links :
https://github.com/Ady901/Demo02CollectionView.git
https://www.youtube.com/watch?v=5SrgvZF67Yw
extension ViewController : UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return nameArr.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
        cell.titleLabel.text = nameArr[indexPath.row]
        cell.userImageView.backgroundColor = .blue
        return cell
    }

}

extension ViewController : UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }

}

Answer: UICollectionView is same as UITableView but it gives us the additional functionality of simply creating a grid view, which is a bit problematic in UITableView. It will be a very long post I mention a link from where you will get everything in simple steps.


Install Arabic language on Android ICS

Question: I have Samsung Galaxy S2 running Android ICS. How can I install the Arabic language on my phone keyboard as it is not listed?
Answer: Step 1 :
Download and install Language Enabler.

' Need Root ACCESS '

Step 2 :
and, add Arabic language for Menu.
Then go to Language and Input from Settings.
Tap "Configure Input Methods."
Step 3 :
Uncheck the "Use System Language" check box. This unlocks the other active input methods for use.
Select the check boxes for the keyboards and/or voice input methods you wish to add. This adds them for use during text input, as long as you use the standard Android keyboard.
Step 4 :
then add Arabic Language, and enjoy.

Install Arabic language on Android ICS


Comparing objects using hamcrest and lambdaj based on multiple inputs

Question: I am trying to filter an array list to remove objects that do not match a set of criteria input by a user. The object has 3 lists. See below for example.
public class A {
    public String [] a={"a", "b", "c"};
    public String [] c={"a", "b", "c"};
    public String [] d={"a", "b", "c"};
}

I'm trying to write a way of search this object to see if it matches data input into a search dialog. For example, i want all objects that have "a" in array a, "c" in array b and * in array c.
    for(int i = 0; i < products.length; i++)
    {
        reactionData = select(reactionData, having(on(A.class).a,Every.everyItem(containsString(products[i]))));
    }

I thought of doing something like this for each array im searching through but it seems inefficient. Not to mention that the reactionData array would just be replaced on each search.
If some one could help me solve this or perhaps point me to some useful sites explaining how to utilise hamcrest with lambdaj that would be ideal.
EDIT
output = filter(having(on(Reaction.class).getChemicalProducts(), hasItems(products)), reactionData);

the above matcher has to match every item in products. I'm looking for it to match any item in products
Comment: output = filter(having(on(Reaction.class).getChemicalProducts(), hasItems(products)), reactionData);
Answer: The following line will retain all instances with at least one of the chemical products in the products list:
output = filter(having(on(Reaction.class).getChemicalProducts(), hasItem(isIn(products))), reactionData);


How to speed up backend of magento?

Question: my magento store backend is very slow, how can I speed up admin panel in magento?
I used items in below link but admin panel is still very slow:
https://suyati.com/blog/speed-up-magento-admin-backend/
Answer: 3 ways to speed up Magento backend:

Sign up for better hosting plan. More CPU, More RAM.
Audit your server. Make sure it is optimized. Upgrade OS. Upgrade web server (nginx or apache). Fine tune MySQL with the help of mysqltuner.
3rd party plugins audit. Some custom extensions might slow your backend. Disable 3rd party plugins one by one and benchmark speed.

Taken from here.
Bonus point: enable Magento profiler and study its trace. See what function calls take most time. Try to understand why they take that much time and what you can do about. (In most cases it is some custom plugin, just delete it or find an alternative)

How to speed up backend of magento?


Limit of $\lim_{x\rightarrow 1}\sqrt{x-\sqrt[3]{x-\sqrt[4]{x-\sqrt[5]{x-.....}}}}$

Question: I known how to find the limit of my last question which was Finding $\lim_{x\rightarrow 1}\sqrt{x-\sqrt{x-\sqrt{x-\sqrt{x....}}}}$, but I couldn't how to start to find the limit of $$\lim_{x\rightarrow 1}\sqrt{x-\sqrt[3]{x-\sqrt[4]{x-\sqrt[5]{x-.....}}}}$$     so I used  a program written in visual basic 6 to calculate it.I found the limit about equal to $29/30$ but I am not sure if this value is right because the accuracy of this language not enough to give me a trust value. Anyhow,I want to know how to find the limit analytically.
Comment: I get $L=0.5818805230597856271212893881\ldots$
Comment: If you try to calculate this with a program, the result depends on what initial value you have for the roots, if the initial value is $0$, the final result is $1$, if the initial value is $1$ the final result is $0$, if it's between $0$ and $1$ it converges to $0.581881$ and it fails otherwise. I'm guessing the actual answer is $0.581881$ but who knows.
Comment: I tried just evaluating it with $x=1$ and $100000$ nested roots. The initial value I was talking about is the value I assigned to the $1000001$ root since I cant evaluate all infinite roots.
Comment: However I get the same result with $x=1.0001$, with $x<1$ I get undefined and with $x=2$ I get $1$
Comment: Can you post the program you used to evaluate the limit?
Comment: That calculates $$\sqrt[100]{x-\sqrt[99]{x-\sqrt[98]{x-\cdots}}}$$ Also please use something like pastebin
Comment: This is the program that I used http://pastebin.com/7vJ3TYM7
Comment: @Lucian I think the problem in my programming language.
Answer: It is not proved that a limit exists.
The figure below will give a new view on this question of limit or no limit. We consider an infinite set of functions $y_1(x)$ , $y_2(x)$ , ... , $y_n(x)$ , ... where the index $n$ is the number of radicals :

In case of the functions with odd index, the limit for $x$ tending to $1$ is  $y(1)=1$
In case of the functions with even index, the limit for $x$ tending to $1$ is  $y(1)=0$
When the number of radicals tends to infinity without specified parity, the limit is not defined. So we could say that there is no limit for the expression given in the wording of the question.
But, what is interresting is not the set of functions and corresponding curves, but what is the boundary curve of the infinite set of curves. This curve is not included into the set itself. The corresponding function might be on the form $y_{boundary}(x)=f(x)H(x-1)$ where H is the symbol of the Heaviside step function. Looking for $f(x)$ is something else: This is a challenge.
IN ADDITION :
We can express the firsts terms of the series expansion around $x=1$.
Let $x=1+\epsilon$ ,  with $\epsilon$ close to $0$.
$y_1=1+\frac{\epsilon}{2}+O(\epsilon^2)$
$y_2=(\frac{2\epsilon}{3})^{1/2}+O(\epsilon^{2/2})$
$y_3=1-(\frac{3\epsilon}{32})^{1/3}+O(\epsilon^{2 /3})$
$y_4=(\frac{4\epsilon}{405})^{1/8}+O(\epsilon^{2/8})$
$y_5=1-(\frac{5\epsilon}{201326592})^{1/15}+O(\epsilon^{2/15})$
$y_6=(\frac{2\epsilon}{ 10296910184203125})^{1/48}+O(\epsilon^{2/48})$
etc.
For $\epsilon=0$, this confirms that $y_n$  is alternatively equal to $0$ and to $1$ when $n$ tends to infinity.
When $n$ tends to infinity, the curves corresponding to the functions $y_n(x)$ tend asymptotically to a curve $f(x)$ for $x>1$. For $x=1$, $y_n(1)$ tends to $1$ if $n$ is odd, or tends to $0$ if $n$ is even.
The bounding curve corresponding to $f(x)$ is drawn in red on the figures below, represented in various enlargements. Of course, the curve in red is the same for all the figures. It looks like a straight line if we consider a range of $x$ close to $x=1$, but it is a misleading impression : $f(x)$ is not a linear function. The computation for drawing $f(x)$ was made with an algorithm similar to that given by Han de Bruijn.
Comment: What are the curves you have plotted there? I don't get the same result for $x<1$, the function is complex for odd index $>1$ there, and neither real nor imaginary part resembles what you've plotted. Looks like you've plotted something like $\sqrt x+f_i(x)$ for $x<1$ and $i>1$, $i$ odd.
Comment: $y_3$ is real if $x>1$ because $x>x^{1/3}>(x-x^{1/4})^{1/3}$ and $x>x^{1/4}$ if x>1. OTOH, if $x<1$ then $x-x^{1/4}<0$ so $x-(x-x^{1/4})^{1/3}>x$ and it has a real square-root, so $y_3$ is real again.
Comment: @Ruslan: The seven curves ploted on the figure correspond to the seven equations written on the same figure : $y_1(x)$ , $y_2(x)$ , ..., $y_7(x)$. Of course, they are ploted in real domains for $x$ and $y$.
Comment: @Michael oh, indeed. Was basing my comment on Mathematica plot. It appears to take the wrong branch of cubic root, funny!..
Comment: @Ruslan, if you raise a negative number to 0.33333, it has to multiply the angle $\pi$ by 0.33333  Is there an nth-root command in Mathematica?
Comment: @Michael yeah, there's a command, but it transforms internally to `Power[x,1/3]`, where although `1/3` is an exact number $\frac13$ (not an approximation like $0.33333$), the principal branch is defined differently from specifically `CubeRoot[]` or `Surd[]`. I.e. you can enter $\sqrt[3]x$ via `Ctrl+2`$\to$`x`$\to$`Ctrl+5`$\to$`3`, and it'll be taken as $x^{1/3}$. Using `Surd[]` fixes the problem, so the plots in this answer are actually correct.
Answer: Disclaimer. Please read the
answer by JJacquelin . Without it, the answer you are reading now wouldn't even
come into existence - literally : the possibility of no-limit must not be rejected.
It must be admitted that the current answer rests upon the assumption that the limit does indeed exist.
But the question is: does it exist?
From a computational point of view , this question is related to :

Evaluating the sum $\lim_{n\to \infty}\sqrt[2]{2+\sqrt[3]{2+\sqrt[4]{2+\cdots+\sqrt[n]{2}}}}$ .

And via this reference it is related to at least three other questions.
The common denominator is that backward recursion may be employed here too.
For the problem at hand, this backward recursion goes as follows:
$$
a_{k-1} = \sqrt[k]{x - a_k} = e^{\ln(x - a_k)/k} \qquad ( x-a_k > 0 )
$$
Starting "from infinity" with $\,x=1\,$ (where $\,\infty = 100\,$ is large enough for our purpose) , but with arbitrary $\;0 < a_\infty < 1$ , the recursion invariably leads to the outcome in the comment by Lucian and Kristoffer Ryhl :
$$
L = 0.5818805230597856271212893881
$$
Here is the Pascal program snippet that does the job:

program Lucian;
procedure test;
const
  n : integer = 100; { = oo }
var
  k : integer;
  a,x,d : double;
begin
  while true do
  begin
    a := Random;
    x := 1; d := 1;
  { Backward recursion }
    for k := n downto 2 do
    begin
      a := exp(ln(x-a)/k);
    { Error analysis }
      d := d*a/(x-a)/k;
    end;
    Writeln(a,' +/-',d);
    Readln;
  end;
end;
begin
  test;
end.

Output:

 5.81880523059786E-0001 +/- 2.39470132977704E-0043
 5.81880523059786E-0001 +/- 6.60618483531661E-0045
 5.81880523059786E-0001 +/- 4.15120583976206E-0044

The generality of $\;0 < a_\infty < 1$ sounds more impressive than it is.
Because, apart from the first one, the iterations actually start with numbers
close to and somewhat smaller than $1$  ($0 < x-a_n < 1$) :
$$
\lim_{n\to\infty} \sqrt[n]{x - a_n} = 1
$$
An estimate for the errors may be obtained by differentiation:
$$
d a_{k-1} = d \sqrt[k]{x-a_k} = d a_k \frac{1}{k} \left(x-a_k\right)^{1/k-1}
= \frac{a_{k-1}}{k(x-a_k)}d a_k
$$
starting with $\,da_k = 1\,$ for some sufficiently large value $n$
of $k$ , in our case $\,n=100$ . It is observed that the error in $\;a_1\;$ can be
calculated (more or less) by backward recursion as well.  It may well be
conjectured that some reasonable bound goes like $\,1/n!$ ,
meaning that convergence is rather fast. Apart from the first iterations, though,
where there are large denominators, due to the fact that $a_{\infty-1}$ is close
to $x=1$ .
Notes.
If we change x := 1 in the program by a slightly different value below $1$ ,
say x := 0.99 , then the iterations quickly become unstable for some $\;a_\infty$ , even if reasonable precautions are taken.
So it seems that the limit should better be approached from above : $\;x \downarrow 1$ in the first place.
Furthermore, <quote>
it is supposed that $a\ne 0$ and $a\ne 1$ . This is a not proved assumption.Doing this is something like using the result
to be proved, to prove it. If $\,a=1\,$ or $\,a=0\,$ is the starting value for the recursion (case $\,x=1$ ), the result will be $\,0\,$ or $\,1\,$
(depending on the parity of $\,n\,$ in the program).</quote>
Killing the fly in the soup ?
It's the difference between a closed interval $\,0 \le a \le 1\,$
and an open interval $\,0 < a < 1$ . I know it's a distortion
of the original problem, but my proposal would be to replace all
radicals $\,\sqrt[n]{a}\,$ by exponents $\,\exp(\ln(a)/n)$ , like
I've done in the program ( thus simply obviating the special cases
$a \in \{0,1\}$ ) . Wonder if that's acceptable for the OP.
BONUS. Making a graph of the following more general function $f(x)$ might be interesting.
$$
f(x) = \lim_{n\to \infty}\sqrt[2]{x-\sqrt[3]{x-\sqrt[4]{x-\cdots-\sqrt[n]{x}}}}
$$
So here goes, for $\;1 < x < 10\;$ and $\;0 < y < 5\;$ :

It is conjectured that $f(2) = 1$ . Proof :Start with $a_n = 1$ , then
$\,a_{n-1} = \sqrt[n]{2 - 1} = 1$ and so on for all $\,a_k\,$ until $\,a_1$ .
Comment: The limit $L=0.581880523..$ obtained with this method of computation or other numerical method is the numerical approximation of $f(1)$ according to the definition of the function $f(x)$ in my answer. The equation of the bounding function is $f(x)H(x-1)$ where H is the Heaviside's step function. Of course, $f(x)$ has a limit for $x$ tending to $1$. But it is not a limit for the infinite nested radicals function which should be called an improper "limit" because it is an asymptotic limit to the step function $f(1)H(x-1)$ for $x$ tending to $1$.
Comment: @JJacquelin: my current interpretation (subject to change) is that you are using _forward recursion_, which is known to be (numerically) _unstable_. But  I do not deny beforehand that there may be a can of worms here.
Comment: @JJacquelin: I've updated my answer. Which doesn't mean that I don't listen, but I cannot pinpoint exactly where my reasoning could possibly go wrong. Is it perhaps in the denominators of the error estimates?
Comment: I think that your reasoning is correct, depending of what we are looking for. Your computer program is well adapted to the numerical computation of the so called $f(x)$ function : instead of starting with $x=1$ which leads to a good approximate of $f(1)$, we could start with other values of $x$ and draw the curve representing $f(x)$. So, your approach is in agreement with what I consider as the most interesting challenge: is there a closed form for this function ? . On the other hand, ... to be continued...
Comment: On the other hand, if we consider the question of the limit or no-limit of the infinite nested radicals function, by using the backward recursion, there is a fly in the soupe. The program starts with random values $0. I think that your algorithm is perfectly convenient with any $0<a<1$ and preferably with $a$ not too close to $0$ or $1$ if the goal is to find the limit $f(1)$. As you can observe, if $a$ is too close to $1$ or $0$, the deviations are increassing and stability decreassing. On pure theoritical viewpoint, we know what append for $a=0$ and $a=1$: the limit is $0$ or $1$ depending on the parity of $n$.
Comment: I suggest to compare the results obtained with a given value of $a$, but in cases of $n=99$ and $n=100$ for example. The difference will probably be negligible if $a$ is not close to $0$ or $1$. Probably a large discrepancy will occur if $a$ is very close to $0$ or $1$ because the theoretical limits are not the same: $0$ in a case, $1$ in the other case.


is it possible to store single linked list information in NSUserDefaults of iphone

Question: is it possible to store single linked list information in NSUserDefaults of iphone. If there is an another way to store the information please mention that also
Answer: NSUserDefaults can only store standard data types like NSNumber, NSString, NSDate, NSArray, NSDictionary. You can always implement NSCoding for your linked list class and use Cocoa's standard archiving method to save it to disk.


Is there a functional difference between the modern police station and classic police station?

Question: A villager requested that I create a police station as our next public works project, which I would be happy to oblige... but I've got some questions first.  That conversation unlocked the "modern police station" and "classic police station" and both will cost 264,000 to construct.  Is there any functional difference between the two?  Can I build both, or will I be restricted to one or the other?  Is one better to have than the other?
Answer: The Modern Police Station gives you Copper, and the Classic gives you Booker as your constable. So aesthetics aside, what you want to do really is choose which of the two you get in town.
More info: http://animalcrossing.wikia.com/wiki/Police_Station
Answer: The modern police station has Copper, and the classic police station has Booker. There's no functional difference.
Answer: No, exept that the classic police station has booker and is made of wood, and the modern one has copper and is made of some sort of metal...


Whats wrong with my triple DES wrapper?

Question: it seems that my code adds 6 bytes to the result file after encrypt decrypt is called..
i tries it on a mkv file..
please help
here is my code
<code>class TripleDESCryptoService : IEncryptor, IDecryptor
{
    public void Encrypt(string inputFileName, string outputFileName, string key)
    {
        EncryptFile(inputFileName, outputFileName, key);
    }

    public void Decrypt(string inputFileName, string outputFileName, string key)
    {
        DecryptFile(inputFileName, outputFileName, key);
    }

    static void EncryptFile(string inputFileName, string outputFileName, string sKey)
    {
        var outFile = new FileStream(outputFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);

        // The chryptographic service provider we're going to use
        var cryptoAlgorithm = new TripleDESCryptoServiceProvider();
        SetKeys(cryptoAlgorithm, sKey);

        // This object links data streams to cryptographic values
        var cryptoStream = new CryptoStream(outFile, cryptoAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);

        // This stream writer will write the new file
        var encryptionStream = new BinaryWriter(cryptoStream);

        // This stream reader will read the file to encrypt
        var inFile = new FileStream(inputFileName, FileMode.Open, FileAccess.Read);
        var readwe = new BinaryReader(inFile);

        // Loop through the file to encrypt, line by line
        var date = readwe.ReadBytes((int)readwe.BaseStream.Length);

        // Write to the encryption stream
        encryptionStream.Write(date);

        // Wrap things up
        inFile.Close();
        encryptionStream.Flush();
        encryptionStream.Close();
    }

    private static void SetKeys(SymmetricAlgorithm algorithm, string key)
    {
        var keyAsBytes = Encoding.ASCII.GetBytes(key);
        algorithm.IV = keyAsBytes.Take(algorithm.IV.Length).ToArray();
        algorithm.Key = keyAsBytes.Take(algorithm.Key.Length).ToArray();
    }

    static void DecryptFile(string inputFilename, string outputFilename, string sKey)
    {
        // The encrypted file
        var inFile = File.OpenRead(inputFilename);

        // The decrypted file
        var outFile = new FileStream(outputFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite);

        // Prepare the encryption algorithm and read the key from the key file
        var cryptAlgorithm = new TripleDESCryptoServiceProvider();

        SetKeys(cryptAlgorithm, sKey);

        // The cryptographic stream takes in the encrypted file
        var encryptionStream = new CryptoStream(inFile, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read);

        // Write the new unecrypted file
        var cleanStreamReader = new BinaryReader(encryptionStream);
        var cleanStreamWriter = new BinaryWriter(outFile);
        cleanStreamWriter.Write(cleanStreamReader.ReadBytes((int)inFile.Length));
        cleanStreamWriter.Close();
        outFile.Close();
        cleanStreamReader.Close();
    }
}
</code>
Answer: Your code is not adding six bytes, 3DES is rounding up to a full block size. This is how block ciphers work. You will see this only in the resulting ciphertext, but not in the decrypted plaintext.
Again there is no need to worry, block ciphers must pad your plaintext to the next block size before it can encrypt the plaintext. When you decrypt the ciphertext, the padding is removed.
Also, I did a quick code review, and you have an error in the code - you are using the same key for the IV and the key, and you really should use different data. So I would add another arg to DecryptFile(), EncryptFile() and SetKeys() to allow for a different IV.
Comment: what is this IV, and they are not the same cause the size is not the same, IV is 8 byte and key is 24 byte..
the decrypted file does have the extra 6 bytes, should i be worry and cut it?
Comment: Initialization Vector - it's used in some block cipher modes, such as Cipher Block Chaining (CBC) - don't worry too much about it! Just make sure it's not the same as the key - and that means totally different, use a separate random number than the key.

So the only change I made to test your code was to remove IEncryptor and IDecryptor because they are not in the .NET Framework - what are they?
Answer: I glanced over the code and found no problem, but I'm not very familiar with the classes you used so I may well be wrong. Instead, I'll give some general advice that applies to any bug:
Try to hunt down the problem. It's difficult to find a mistake in many lines of code. Create the shortest possible code that displays the faulty behavior.
For instance, try to write a string to the output stream. Is the size correct?

If no, you almost found the problem - something is wrong with file writing, the encryption stuff has nothing to do with the issue.
If yes, continue to add functionality in small steps until you discover the problem.

That's a standard debugging technique and extremely helpful, I suggest to use it every time you encounter a problem.
Aside from that, try to always have clean starting conditions, i.e. make sure the file written to was deleted. Try your code on different input and see if it fails with the exact same result every time or if there are differences.
Edit:
According to other responses, the 64 bit block is causing your trouble. With the ideas described earlier, you can easily exclude many other factors until only the encryption itself would be left.
Then you're able to ask "Why is TripeDES adding up to 7 bytes to the input?" which would a far more clear question than "What's wrong with my triple DES wrapper??" - and you would have gotten an answer to this simple question in less than a minute for sure!
Answer: Tiple-DES is a 64 bit block cipher. Without analyzing your code my guess is that your data isn't 64-bit aligned and that it has been padded with the default PKCS7 mode.
Answer: I don't know which encryption mode you use, but ECB and CBC mode add padding bits at the end of the last block to increase it's size to 64 bit. Maybe that's where your bytes come from?
Comment: if i'll use another mode it will not happen?

Whats wrong with my triple DES wrapper?


How to show additive subgroup of $R^n$ is not discrete?

Question: Suppose we have the additive subgroup of reals generated by $\sqrt{3}$ and $\sqrt{5}$. How would you show you that this subgroup does not form a lattice?
Comment: I'm voting to close this question because as asked it's a math question with no motivation
Comment: "More precisely it should contain a shortest vector"; the meaning of 'shortest' depends on the metric; for the traditional metric on $\mathbb{R}$ ($dist(A, B) = |A-B|$), it's straightforward to show there are arbitrary short vectors.  For another metric, say, $dist( A\sqrt{3}+B\sqrt{5}, C\sqrt{3}+D\sqrt{5}) = |A-C| + |B-D|$, there is a shortest nonzero vector
Comment: "How would you show you that this subgroup does not form a lattice?"; are you sure it's not?  Isn't the group $\{a\sqrt{3} + b\sqrt{5}\}$ trivially isomorphic to $\mathbb{Z}^2$?  Isn't the latter a lattice?
Comment: @poncho Okay but it should be discrete (this is the definition). More precisely it should contain a shortest vector. I think, without a proof, one can find arbitrarily small vectors in this group.
Comment: There's a frustrating divergence between the mathematics and cryptography communities around the meaning of "lattice". Cryptographers talk about lattices using the Euclidean metric, rather than the more general mathematical definition.
Comment: I have not migrated this question to math-SE because they have [similar](https://math.stackexchange.com/q/73262) [questions](https://math.stackexchange.com/q/852210).
Answer: It suffices to show that there exists a sequence of arbitrarily short vectors, i.e. integer sequences $a_n, b_n$, such that
$$|a_n\sqrt{3}+b_n\sqrt{5}| \to 0$$
For this explicit example, note that an obvious choice of $a_n$, $b_n$ is
$$a_n\sqrt{3} = -b_n\sqrt{5}\iff -\frac{a_n}{b_n} = \sqrt{5/3}.$$
One can't exactly choose $a_n, b_n$ to satisfy this inequality ($\sqrt{5/3}$ is irrational).
Instead, we choose sequences $a_n/b_n$ of increasingly good rational approximations of $-\sqrt{5/3}$.
One can do this explicitly via continued fractions.
For example, wolfram alpha states the relevant continued fraction is $[1, 3, 2, 3, 2,\dots]$, meaning $1 + \frac{1}{3 + \frac{1}{2+\frac{1}{3+\dots}}}$.
Anyway, the various finite truncations of this continued fraction will be a sequence of increasingly good rational approximations to $\sqrt{5/3}$.
As the continued fraction is infinite, we can keep repeating this process, leading to $a_n, b_n$ such that $|a_n\sqrt{3}+b_n\sqrt{5}|\to 0$.
If $-\sqrt{5/3}$ were rational, its continued fraction would be finite, and the above argument would eventually fail.
Note that this means that something like the subgroup generated by $\sqrt{3}$ and $5\sqrt{3}$ is a lattice --- it is the lattice $\sqrt{3}\mathbb{Z}$.
It is important that we didn't consider the subgroup generated by $\sqrt{3}, 5\sqrt{3}$ and 1 here --- this is no longer a lattice, by (roughly) the same argument.


The specified type member is not supported in LINQ to Entities occurs when a new property is added in the partial class

Question: I'm having an entity framework's EDMX generated class having two properties
public partial class Contact : EntityBase
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I require additional property that should return FullName by joining FirstName and LastName. So I created a partial class for this.
public partial class Contact
{
    public string FullName
    {
        get { return string.Format("{0}{1}", FirstName, !string.IsNullOrEmpty(LastName) ? " " + LastName : String.Empty); }
    }
}

Now, I created a LINQ expression to search records matching "Steeve John" against FullName.
Expression<Func<Contact, bool>> cntExpression = p =>
                p.FullName.ToLower().Trim().Contains("Steeve John");

I passed this expression to the business logic to retrieve an IQueryable instance.
            IQueryable<Contact> qryContact = _cntMgr.GetFiltered(cntExpression);

The code fails at this line of code:
            var contactLeads = qryContact.Select(
                  s => s.Leads.Where(a => a.IsActive).GroupBy(a => a.ContactId).Select(a => a.FirstOrDefault())).ToList();

and the error that I get is this:
The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

Please help me in fixing this issue.
Thanks in advance.
Comment: Firstly,You are comparing FullName.ToLower() to "Steeve John", will never return any records. Whan does GetFiltered() contains?
Answer: Linq to entities does not know about string.Format which you used in FullName. You could try something like that:
Expression<Func<Contact, bool>> cntExpression = p =>
(p.FirstName + " " + p.LastName).ToLower().Trim().Contains("Steeve John");

or
Expression<Func<Contact, bool>> cntExpression = p =>
(p.FirstName == "Steeve" && p.LastName == "John");

You could also get Leads as a list first. Then your original code should work as well:
s.Leads.ToList().Where [...]

Comment: You're welcome. If you use ToList keep in mind that this can take a long time if you have many datasets...
Comment: I agree Norman, therefore I am not using ToList before filtering the records.
Answer: Any custom properties cannot be used in query expressions; basically that error is saying there is no "Name" (or I think this is supposed to be "FullName"?  If not, where did "Name" come from) field in the database, at least BEFORE the query has ran against the database.  AFTER, you can use it fine.  The query is failing there because ToList() executes it against the database, and that is when the validation happens.
Query the record first, then use FullName after the call to ToList, and it will work fine.


How to boot directly into Windows 10 from grub on Windows8.1-Windows10-Ubuntu15.04 tripleboot system?

Question: I have a tripleboot system having Windows8.1, Windows 10 and Ubuntu 15.04. When I choose Windows from grub menu, it takes me to Windows bootloader giving choice between Windows 10 and Windows 8.1. How can I configure grub such that it gives options for WIndows 8.1 and Windows 10 separately on grub menu and each option boots respective Windows directly bypassing the Windows bootloader completely? I would like to keep the Windows bootloader option also there in case I need to troubleshoot my Windows installations. The system uses BIOS.
Comment: Can you expand your answer with details on how to do this using BIOS?
Comment: UEFI or BIOS. Not sure if possible with UEFI. But with BIOS if both Windows are in primary partitions, you can repair the second install by adding bootmgr & BCD. With UEFI you may be able to create a second Windows efi folder with the Windows files & edit BCD for second install,  but that is theorical as I have never seen it done. Updates may then be an issue.
Comment: The system uses BIOS.
Answer: If both Windows are in primary partitions, you can repair install to be directly bootable from grub. But not possible if an install is in a logical partition as Windows only boots from primary partitions. Second installs of Windows normally overwrite the boot files in the existing NTFS primary partition with the boot flag. And it adds both installs to its BCD. You may just be able to copy bootmgr & /boot/BCD to second install and edit BCDs in both installs. But best to have repairCD or flash drive for each install and run its repairs. You have to move boot flag first and then repair an install. You may have to specify not to find other installs. Then move boot flag to other install and do same thing.
Be sure to have good backups first. And repair tools.
To get each MS to have its own boot loader make a second primary NTFS partition and set its boot flag on, then install the 2nd product in it. Multibooters, Pictures here worth 1000+ words - Vista but all Windows with BIOS/MBR
http://www.multibooters.co.uk/multiboot.html


Is next day funeral a requirement?

Question: In Turkish culture here in the UK, Turks generally get the body sent to Turkey for burial there. As far as I know we need to be buried the next day, but this delays that usually for at least one more day, sometimes more. Is the next day rule a strict requirement?
Comment: AFAIK neither of both are correct the body should be washed and prepared for funeral and buried as soon as possible this might mean in the same day if possible, however this can delay for reasons such as darkness (at night) for the next day!
Comment: Salam and welcome to Islam SE the Q&A site about Islam. I recommend you to take our 2 min. [tour] and check our [help] to learn more about the our site and model.
Answer: There is no strict law as to when the body should be buried. But according to Islamic law i.e; The Shariah, a body should be buried as soon as possible from the time of death, which means that funeral planning and preparations begin immediately.

Is next day funeral a requirement?


WCF RIA Entity Using Load Operation; How to Get Latest Database changes

Question: this is a follow up from the following question
WCF RIA : LoadOperation Not Refreshing Data
<code>LoadOperation<Clarifications> ClarificationsLP = context.Load(context.GetClarificationsQuery().Where(o => o.ProjectID == ((App)Application.Current).Project.ProjectID).OrderBy(o => o.RaisedOn), LoadBehavior.RefreshCurrent, false); ClarificationsLP.Completed += delegate
        {};
</code>
The code above works fine, it will return me any changes that may occur in the database outside of my application. Great! However it only returns me the new changes...what if an Item was deleted? How can I deal with this? This is an issue for me.
Any help is appreciated.
Thanks
Answer: if other application is deleting registrys, and you want to refresh it, so you need to clear the cache entitys and do the load operation.


CDN Tax Receipt issuance for more than 1 donor-auto process

Question: Can CDN tax receipts be emailed directly to the donors at once- auto process?
Answer: I'm not sure what you mean - the title implies "batch", but then the question body suggests you mean at the time the donor makes a contribution.
If you mean "automatically at the time the donor makes a contribution", then there is the "Attach receipts to automated workflow messages" setting in the CDN tax settings under Administer - CiviContribute. If you turn that on the donor will receive a tax receipt as soon as they finish the donation.
If you mean batch to several donors at once, if you do a contribution search, then you can select some or all, and then in the Actions dropdown there are some choices for Issue Tax Receipts.


Linq to SharePoint 2013

Question: Is it recommended to use Linq to SharePoint while developing projects for SharePoint 2013? or this became an old trend?
Answer: Advantages:

As is mentioned often, it provides strongly typed objects, which when using we get intellisense while coding. So, our code will be more bug free unlike the CAML Queries where the result will be known only in the run time.
One advantage not mentioned generally is that we can compare two columns (fields) of a SharePoint list in LINQ queries which is not possible in CAML queries.
We can also use LINQ to SharePoint to generate some complex CAML queries as shown in this blog

Disadvantages:

During the run time the LINQ query itself gets converted into a CAML query, which is an extra step ahead that takes more time . This can be avoided if we write a CAML query itself straight away.
Also, we generate a DataContext class using the SPMetal.exe. This class is the one which we use in our project to generate LINQ queries. This class is not generated dynamically. So, if we do any changes in any of the lists or libraries in our site it is not reflected in the DataContext class. We have to generate a new class whenever we make any changes in the site.
Unlike CAML queries, LINQ to SharePoint has no use if we are going to access SharePoint data in Silverlight using Client Object Model.
Fields like Created, CreatedBy, Modified and ModifiedBy of a SharePoint list are not created by SPMetal to be used in the LINQ queries.
LINQ to SharePoint cannot be implemented for an External list.
Comment: So guys, do you recommend it for 2013? or just 2010 projects?
Comment: i would prefer CAML. Here is the link that you want to look regarding the performance http://www.sharepointblues.com/2010/09/08/linq-to-sharepoint-performance-pitfalls/
Answer: It is depend upon on your choice but on average LINQ is not recommend.
Good:
LINQ provides an easy way to manage data in SharePoint's lists without writing CAML code.
Bad:
LINQ relies on providers (or drivers) to access its data, as a developer you get many of the same problems that developers working against hardware get.
there's no way for you to control how the provider works either, unless you understand intimately how that specific provider handles queries. There's really no way to optimize a LINQ query without knowing both how the provider works and how the underlying data source works.
http://blog.furuknap.net/why-linq-to-sharepoint-is-a-bad-idea
http://www.sharepointblues.com/2010/09/08/linq-to-sharepoint-performance-pitfalls/
Conclusion:
Even though the LINQ interface to SharePoint seems lucratively easy-to-use, it should be used with caution, especially at performance-critical parts or when dealing with potentially large lists
Comment: So, do you recommend it for 2013? or just 2010 projects
Comment: i would prefer for 2010.

Linq to SharePoint 2013


Matlab plots with a very low resolution when using -nodesktop option

Question: I'm having trouble with the resolution of matlab plots when the function is run via a cronjob using the -nodesktop option. The function plots, and saves (using the print function) a number of figures. When run from the matlab desktop, they plot and save according to the specified resolutions with no problems. But when run via a cronjob with the -nodesktop option, the resolutions are very poor (low).
This is essentially what I'm currently doing:
fh = figure;

set(fh,'Position',[0 0 1360 470]);

plot(somedata);

print(fh,'-dpng',figpath,'-painters');

Note that I've also tried specifying a print resolution:
print(fh,'-dpng',figpath,'-r300');

But this ends up with corrupt files. I'm not sure why. I'm using -painters because I read somewhere that if the plot is somewhat complicated it can default to opengl which ruins prints but this doesn't seem to be the issue (with or without the option, the plots are the same).
I've also tried:
set(fh,'PaperPositionMode','auto')

which does not solve the problem.
The cronjob runs the following command:
/usr/local/bin/matlab -nodesktop -r "startup; perform_plots; exit"

Any help would be much appreciated!
Comment: Can you post the output of `get(fh)`?
Answer: I figured out the issue.
By running matlab as a cronjob, the DISPLAY environmental variable wasn't set. As a result there was no X display for matlab to utilise. I don't know how it still managed to plot anything at all but it did and did so with a very low resolution.
The solution is to set the appropriate display before hand. e.g.:
#!/bin/bash

export DISPLAY=:1.0

/usr/local/bin/matlab -nodesktop -r "startup; perform_plots; exit"

In case you want to run it on a box that doesn't have an X server, you can set up a dummy X server using Xvfb (X virtual frame buffer). This also has the advantage of using a display separate to the one you may be working on so jobs can run in the background without plots randomly appearing while you work.


Enabling CSRF for Django

Question: I have the following python code in my Django views.py, the code takes in a JSON body and send the extracted DATA to another API endpoint, I have simplified the code here.
How do I enable csrf such that it will send the token back to the caller for this method? I am calling this from postman.
@csrf_protect
def validate_booking(request):
  if request.method != "POST":
    return HttpResponseServerError("Invalid HTTP method")
  body = json.loads(request.body)
  booking_details = body["booking_details"]

    DATA = {
      "name": booking_details["name"],
      "nric": booking_details["nric"],
      "booking_id": booking_details["booking_id"]
    }

  return HttpResponse(status="200")

This site directs to put this piece of code in my method. But what is "a_template.html"?
https://docs.djangoproject.com/en/4.1/ref/csrf/
@csrf_protect
def my_view(request):
    c = {}
    # ...
    return render(request, "a_template.html", c)

Comment: Does this answer your question? [Sending CSRF Tokens via Postman](https://stackoverflow.com/questions/43196888/sending-csrf-tokens-via-postman)
Answer: Thanks for your reply. I managed to find a solution by doing the following:

Create a new GET method that will generate the session CSRF token using python
Instead of using render which expects a HTML template file, I used JsonResponse(data) to return in JSON format directly
In my postman app which I am making the POST request with the X-CSRFToken in the header, I will first make a GET request to the new method I created in step 1 to retrieve the token and store it as an environment variable

The following is the GET method sample:
from django.http import JsonResponse

def get_csrf_token(request):
    csrf_token = csrf(request)['csrf_token']
    data = {'csrf_token': csrf_token}
    return JsonResponse(data)

Answer: This isn't an easy thing to do as CSRF is 2 steps thing

There is a value that is passed to the client and it is saved to the session on the server.
When a POST request is received, the client shall send this as csrfmiddlewaretoken in the body and the server will check the value against the stored one in the server's session.

So this isn't feasible to be done in APIs as you require session Management which is not of REST API implementations.

Enabling CSRF for Django


How to make cgdb show assembly code?

Question: I can't find a way for cgdb to disassemble a binary and show the assembly code with the current instruction in the code window. Is this possible and what command should I use? I'm using Mac OS X and got cgdb from the homebrew repository.
Answer: A recent update (Feb 2017) to cgdb makes it possible to do this. You will need cgdb version 0.7.0 or newer. (At the time of writing this is the latest release). You may need to compile this from source yourself given how recent it is.
More details on adding disassembly support can be found here:
https://github.com/cgdb/cgdb/issues/44
To view the disassembly in cgdb hit esc and type :set disenter.
To go back to the source (if available), repeat this, except type :set nodis.
Answer: display/i $pc shows disassembly always for the current instruction, in the console window.
To show disassembly for more instructions, prefix i with the number of instructions.
For example,
display/5i $pc

shows disassembly always for the next 5 instructions.
Comment: This sorta defies the purpose of cgdb. Why would one use it instead of plain gdb to debug sourceless applications if this functionality is achieved only via a gdb command?
Comment: There is a way to do this now with `:set dis` (as of version 0.7.0). See my answer.
Answer: I am working on MacOS to defuse a binary bomb and find "gdb -tui" will be helpful. Than I found "cgdb" can make code colorful. But what we want to see is show disassembled code on the code window, the answer above only show the code line by line or only changeless lines.
Unfortunately, I find a post said that "the cgdb does not support assembly display (yet)."
https://groups.google.com/forum/#!topic/cgdb-users/E-jZCJiBAQQ
   Sorry guys, cgdb does not support assembly display (yet).  It's a
frequently requested feature, and when we get a little more time to
work on cgdb we will probably add this.
Starting cgdb with the -tui option is a bad idea -- the TUI (text user
interface) is an alternative curses interface to gdb, not a part of
cgdb.  It will not play nice with cgdb.
Mike
--
Mike Mueller

Well, it's 12/11/15, but it seems still couldn't show the assembly code on code window like gdb in tui mode.

How to make cgdb show assembly code?


How feasible is an artificial island in the center of the Atlantic ocean?

Question: In my mecha-action story, I wish to have an island in the midpoint between South America and Africa along the equator. Given the weather and seafaring conditions of the area, is this feasible? Or would it just be a tsunami and hurricane prone country?
Comment: Is there a reason existing islands don't work, or can't be expanded as needed? Does it HAVE to be an artificial island? St. Helena? Georgetown?
Comment: Is the middle of the Atlantic really halfway between hemispheres? There's good reasons for the meridian datum to run through Europe (although Florence would be even better than Greenwich) at which point the "least aligned" location would be where the dateline and Equator intersect in the Pacific.
Comment: Jules Verne, [*Propeller Island*](https://en.wikipedia.org/wiki/Propeller_Island), 1895. (But it's in the Pacific.)
Comment: The specific reason an artificial island is used is for narrative impact. In order to attempt a show of peace, the United Nations form a new country that exists directly between the East and West hemispheres.
Comment: Whatever "mecha-action" means, Worldbuilding SE doesn't allow either "story" or "real-world" Questions.

Worldbuilding SE does want you to do research before Asking, which IMHO would include asking a search engine about the weather and seafaring conditions, tsunamis and hurricanes.
Answer: It would not be particularly difficult, thanks to the Mid-Atlantic Ridge, an underwater mountain chain that separates the North and South American Plates from the Eurasian and African Plates. Despite the depth of the ocean around it, the ridge itself is so tall that it breaches the surface in a number of places to form islands, and with standard construction techniques you could easily anchor a platform to a submerged peak that wasn't too deep.
Weather would not be a major hazard, as it falls into the Intertropical Convergence Zone, which has erratic but not usually very threatening weather. There are occasionally large thunderstorms, but never hurricanes; the nature of hurricane formation is that they migrate away from the ITCZ.
If it suits your purposes, you might be able to talk Brazil into letting you use the Saint Peter and Saint Paul archipelago, located on the Mid-Atlantic Ridge about 1000km off the coast of Brazil and some 100km north of the equator.
Comment: This is perfect, thank you for your research. Now that you've brought it to my attention, I will be incorporating more Mid-Atlantic islands where possible in my world-building.
Answer: If by island you mean floating island as opposed to one physically connected to the seas floor then yes. The mid Atlantic reaches depths in excess of 7000 meters at some points.
A large floating structure could be built at one or more coastal facilities in segments then towed to virtually any location you desired in international waters.
Your 'island' would at least need station keeping thrusters to keep it in position although it might be possible to construct 7 kilometer long plus anchor chains and attach them  to massive weights dropped onto the sea floor (I don't know I'm not an engineer). But station keeping would certainly be the easier option as long as you have power.
If power is not an issue you could actual give it bigger engines (or its own fleet of tugs) and take it anywhere you want.
Keep it mind a large floating 'island' wont be a monolithic structure, parts will need to be able to flex and compress in response to wave pressure & other factors like differences in temperature etc.
Comment: Or, instead of constructing an island at the deepest point, it might make more sense to construct it at a shallow point.
Comment: Yes, but I only had the phrase used in the original question i.e  'the midpoint between South America and Africa along the equator' to go by. So I chose the worst/hardest possible location as the baseline.  After that it only gets easier in terms of engineering.
Answer: Yes, have your artificial island!  And the weather there sucks.
I looked for a picture on DeviantArt of a colossal colony ship many kilometers long, purposefully scuttled in the ocean to make your artificial island.   No luck.  If someone finds one or is inspired to draw one please add it!
The weather there is terrible.  But this is an artificial island and that comes with advantages.  The sides slope steeply up and there are not surge-scoured lowlands near the shore as is usually the case.  Buildings and other structures are planted firmly in the hull of the colony ship and are not easily blown away.
Having frequent storms and terrible weather will make for fun stories!
Comment: if they can decide with some freedom where to anchor the island, weather may be quite sweet: Azores take a lot of rain, but Canarias island have a very nice weather
Comment: There was an anime where a scuttled colony ship/Hypermecha was serving as the home base and core for an island...not Macross though...  I think the protagonists did fly jets?


ubuntu on lenovo idepad s210 touch

Question: I'd like to buy Lenovo IdeaPad S210 and install linux (ubuntu) on it. So I'd like to ask if any of you have som experencie with running ubuntu on this notebook. Getting touch screen work is not so important, I'm more interested in installation (is UEFI a problem?), if wifi, ethernet etc. work out of box and what is the battery life while running linux.
Answer: I just bought one, and it runs great. Everything seemed to work, even booting off the flash drive.
I'm pretty sure you can install it with UEFI, but for now I just went all legacy.
Just turn off all the UEFI stuff in the BIOS setup, and anything that says 'security', and turn on anything that says legacy.
The downside of going the legacy route, is that the Win8 option in the grub loader won't boot Win8. You have to hit F-12 when booting and select Win8 that way.
If you use legacy mode, the dual-boot option comes up during install. It wouldn't come up if I booted up in UEFI mode. But I know it can be done, I just recently did it with another laptop, but already forgot all the details.
It's good to shrink the Windows 8 partition (inside Windows) to <100GB, so that GRUB can make a partition under 100gb, or else GRUB doesn't work.
Ideally, I would've wanted to scrub the whole drive, and re-install Win8 and Ubuntu from scratch so I could have it exactly like I wanted it, but didn't want to spend the time or copying of the recovery partitions, etc.
The touchscreen works really well in Ubuntu.
The only problem I had was the brightness control didn't work. This fixed it and posted here: How do I get brightness working on a Lenovo IdeaPad Yoga?
<code>GRUB_CMDLINE_LINUX="acpi_osi=\"!Windows 2012\""
sudo update-grub
</code>
I'd suggest installing tlp for power saving. Battery life seems to be at about 3 - 3.5 hours from it's estimate. The only problem is that the auto-dimmer doesn't seem to work when unplugging power. I'm sure that's fixable.
I think if I can spin down the drive more (have not heard it spin down yet), it would work well.
I'll probably buy a second power adapter, so I can have one ready to plug in wall at home, and carry the other with me. Saw one for $25. I would definitely get a 6-cell battery for it, if Lenovo comes out with one.
Answer: I cannot boot from USB on Ideapad S10 Touch :(
What I have done:

updated BIOS already to newest version (up to today - version 16).
set "legacy" support in BIOS boot options set "legacy first" in BIOS
boot options tried to boot my USB stick on other computer -
successfully

Problem:
Whenever there is USB stick present, laptop just remains stuck with initial "lenovo" pre-BIOS screen. The only thing you may do is hard switch off (holding down the power button).
Any suggestions, please?!
Comment: I managed to boot it using UEFI boot media:
https://help.ubuntu.com/community/UEFI
http://askubuntu.com/questions/395879/how-to-create-uefi-only-bootable-usb-live-media/

ubuntu on lenovo idepad s210 touch


Is there a way to play Legend of Zelda: Majora's Mask on the PC?

Question: I remember starting Majora's Mask, loving every minute of it, then having to go off to college and leave the N64 at home with the family. Now that I'm done, and my younger siblings have long since broken our N64, is there a way for me to restart (and finish!) my adventures on the PC?
Comment: Or a legal copy of a cart you own, depending on your jurisdiction! :P
Comment: Not without an illegal copy of the n64 cart.
Comment: Shame. I was hoping there might be a site similar to GoodOldGames.com, but for old console games.
Comment: Project64 has proven very good. I recommend using the Saitek P2600 controller (or anything with 6 buttons on the right-hand grip... in the past, it was harder to find USB controllers modeled after the N64 layout).
Answer: The best (Legal) way to play it is with the Wii, where you can download a copy for 1000 Wii points (About $10)
Also, it has been released for the 3DS.
Comment: And also that there's no vibration even if you use the GC controller, so some hidden grottos will be impossible to find with in-game clues.
Comment: There is also a version for the 3DS
Comment: Awesome! My family has a Wii. That'll give me something to do during holidays!
Comment: Keep in mind you need a classic controller or Gamecube controller to play N64 games.
Answer: Majora's Mask has a remake for the Nintendo 3DS now.  MSRP is $39.99 USD.
Series producer Eiji Aonuma took the opportunity to fix a bunch of things he thought were problems in the original.  These include:

Discoverability of sidequests.  For a game based mainly on sidequests, it's difficult to actually FIND some of them unless you're in the right place at the right time.  Now, the Bombers will tell you "rumors" they've heard about quests, which will appears in a new section of the Bomber's Notebook.  Each of the 4 Bombers (not counting Jim) will tell you at most one rumor during each 3-day cycle.
Speaking of the Bomber's Notebook, it's had an overhaul.  The new default view shows quests rather than the timeline.  As you complete parts of a quest, it will complete in the notebook.  The old view can be accessed via the Schedule button, but it has a lot more entries on it as everyone who has a sidequest, important or not, is now on there.
Boss battles were unintuitive in the original. It's now much easier to figure out what you need to do to beat a boss... and some bosses even have multiple ways to beat them.
The song of Double Time has been revamped.  You can now go to any hour in the current day or to the Dawn of the next day.
The save system has been changed.  You no longer have to reset to day 1 to save.

On the flip side, the game no longer saves when you go back to day 1, so remember to save at an owl statue.

There's also a new fishing minigame, but I've not tried it yet.
Comment: As a side note to the Bomber's Notebook, it remembers specific things for you, such as where the frogs are that you've used Don Gero's mask on.  Not only does it store their location, but the quest log highlights when you've used the mask on one of them during the current 3-day cycle.
Comment: I've heard that some of the changes to the 3DS version affect the atmosphere/ambiance of the game (as well as 3DS OoT) negatively. Is there any truth to that?
Answer: Depending on where you live, the law might actually be on your side. In some jurisdictions, you can make backup copies of the ROM on your PC (or use any devices necessary to run your bought software, including cracks) legally.
Comment: If you own the cart and some kind of ROM dumper hardware.