Type error with ArrayCollection / OneToMany relationship in Symfony 3.4

Question: For the past couple of days I have been trying to create a bidirectionnal ManyToOne-OneToMany relationship in Symfony 3.4
I have two entities. One is Contribution and the other is Source. A Contribution can have several sources. So the relationship should be

Contribution – ManyToOne – Source – OneToMany – Contribution

But I keep getting the following error during $em→flush(); in my controller:

Type error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given, called in /var/www/html/Edebate/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 605

I do not have any set method related to the Array Collection in my Entity Contribution as I could see in other posts here:
Type error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given
Symfony-Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, object given
And the annotations are ok as mentionned here:
Doctrine OneToMany relationship error
Any help would be appreciate ! :)
Here is my Entity Contribution
use Doctrine\Common\Collections\ArrayCollection;

//annotations

  abstract class Contribution
    {

    /**
    * @ORM\OneToMany(targetEntity="Shaker\DebateBundle\Entity\Source", mappedBy="parent")
    */
    protected $sources;

//Other attributes and methods

    public function __construct() {
       $this->sources = new ArrayCollection();
    }

    /**
     * Add source
     *
     * @param \Shaker\DebateBundle\Entity\Source $source
     *
     * @return Contribution
     */
    public function addSource(\Shaker\DebateBundle\Entity\Source $source)
    {
        $this->sources[] = $source;
        return $this;
    }

    /**
     * Remove source
     *
     * @param \Shaker\DebateBundle\Entity\Source $source
     */
    public function removeSource(\Shaker\DebateBundle\Entity\Source $source)
    {
        $this->sources->removeElement($source);
    }

    /**
     * Get sources
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSources()
    {
        return $this->sources;
    }
}

And this is in my Entity Source:
/**
* @ORM\ManyToOne(targetEntity="Shaker\DebateBundle\Entity\Contribution", inversedBy="sources")
*/
protected $parent;

   /**
     * Set parent
     *
     * @param \Shaker\DebateBundle\Entity\Contribution $parent
     *
     * @return Contribution
     */
    public function setParent(\Shaker\DebateBundle\Entity\Contribution $parent = null)
    {
        $this->parent = $parent;
        $parent->addSource($this);
        return $this;
    }

    /**
     * Get parent
     *
     * @return \Shaker\JRQBundle\Entity\Contribution
     */
    public function getParent()
    {
        return $this->parent;
    }

And in my Controller, the problem arises with flush:
        $formsourcebook->handleRequest($request);
        $contributionid=$formsourcebook->get('ContributionId')->getData();

        if ($formsourcebook->isValid()) {
            $topicargtarget=$this->getContribution($contributionid);
            $sourcebook->setUser($user);
            $sourcebook->setContribution($topicargtarget);
            $em->persist($sourcebook);
            $em->flush();
        }

Comment: Has anybody any idea what the error means ? I'm still stuck with this problem and it seems to be a very general error log.
Answer: I don't know your question very well. However, did you try with this syntax in the Source entity?
private $parent;
// ...

public function __construct() {
    $this->parent = new ArrayCollection();
    // or new \Doctrine\Common\Collections\ArrayCollection();
}

I think you're forgetting the constructor in the class.
Comment: Yes I have a constructor but in the Entity "Contribution" for the attribute "Sources" as one contribution can have several sources. It did not appear in my first post so I edited it.
Answer: I think you "switched" some logic when working with collections. Here's how I think your "add" method should look like:
public function addSource(\Shaker\DebateBundle\Entity\Source $source)
{
    $this->sources[] = $source;
    $source->setParent($this);

    return $this;
}

And in the other entity:
public function setParent(\Shaker\DebateBundle\Entity\Contribution $parent = null)
{
    $this->parent = $parent;

    return $this;
}

There are missing variables in your controller snippet, together with the form fields definitions, so you shouldn't work that much after submitting the form. Try to directly map as many fields as you can (even via autoguessing), and even if it looks ugly, but works, but then you can beautify later. Just my two cents with several months of delay.


If $f(1+x)=(1-x)^2$ then how to find $f(1-x)$?

Question: I don't understand the process. Also, I don't understand why can't the same method be used as for $f(x+1)=\frac{x+2}{x-3}$ to find $f(x-1)$, where I put
$$y-1=x+1$$
$$x=y-2$$
$$f(x+1)=\frac{x+2}{x-3}$$
$$f(y-1)=\frac{y-2+2}{y-2+3}=\frac y{y-5}$$
So in the title question I can't put $x+1=-y+1$, but first need to find $f(x)$? Please explain, and thanks in advance.
Comment: The method you wish to apply is unclear, why put $y-1=x+1$ in the first place?
Comment: If you put $x+1=-y+1$ you get $x=-y$ so replacing every $x$ with $y$ you get $f(1-y)=(1+y)^2$ if you change $y$ to $x$ that is exactly what you're asking for $f(1-x)=(1+x)^2$
Answer: Hint:
$$f(x-1) = f(0+(x-1)) = f((1-1) + (x-1)) = f(1+x-2) = f(1+(x-2))$$
Now define $x'=x-2$ and use the fact that $f(1+x')=(1-x')^2$.
Answer: We know that $f(1+x) = (1-x)^2$. Lets define $u=1+x$ which implies that $x=u-1$. Now we can put $u-1$ instead of $x$ to obtain $$ f(u) = (1-(u-1))^2 = (2-u)^2. $$  Therefore, $f(1-x) = (2-(1-x))^2 = (1+x)^2.$
Answer: $f(1+x)=(1-x)^2=(2-(1+x))^2 $
$f(1+(t-1))=f(t)=(1-(t-1))^2=(2-t)^2$
$f(t)=(2-t)^2$
$f(1-x)=(2-(1-x))^2=(x+1)^2$


EXC_BAD_ACCESS when using UIPageControl in navigation bar

Question: When i first click on the UITabBarItem "Tabeller" this view is presented:

And after selecting any of the rows this view is presented:

What i am trying to achieve is to display the PageControl in the Navigationbar. It works and all BUT i am getting a weird crash in this scenario:
1) i click on the UITabBarItem "Tabeller"
2) Choose any row
3) PageControl is presented, i swipe right left (this part dont matter)
4) I switch to another UITabBarItem
5) Switch BACK to "Tabeller"
6) The application crashes

I do not know where this crash is happening. Tried putting some breakpoints in viewDidLoad for the first view when "Tabeller" is clicked but nothing happened.
Something to note is that this started happening after i implemented the code to show the PageControl, this is the code i used in the datasource delegate:
<code>self.navigationController.delegate = self;
CGSize navBarSize = self.navigationController.navigationBar.bounds.size;
CGPoint origin = CGPointMake( navBarSize.width/2, navBarSize.height/2 );
self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(origin.x, origin.y+16,
                                                                   0, 0)]; //Here added 45 to Y and it did the trick

self.pageControl.pageIndicatorTintColor = navbarColor;
self.pageControl.currentPageIndicatorTintColor = [UIColor lightGrayColor];

[self.pageControl setNumberOfPages:2];
[self.navigationController.navigationBar addSubview:self.pageControl];
</code>
If you need additional information please let me know and i will update the question. Thanks!
Comment: Add Exception break point to find the crash ....
Comment: I just added it "All Execeptions" came up and i tried running the simulator again but did not get the exact line where the crash happened? @ChandanSingh
Answer: Looks like you are trying to access a deallocated object. Try enabling zombie objects:

Edit your Target Scheme
Select 'Run' on the left menu
Check the checkbox 'Enable Zombie Objects'

This will not release any objects, so make sure to disable it after debugging.


paypal order summary missing

Question: For checking out process while redirecting the user  https://www.sandbox.paypal.com the paypal does not show more than one type item and only the last (with its quantity) i.e, if user add two types product in his cart and click for checking out process the paypal show only the second type with its quantity but not the first type in billing process. how can i solve the problem?
here is my api code in view file
     <form style=" padding:0px;margin:0px;" name="frmOrderAutoSubmit" method="post" >

        <input type="hidden" name="upload" value="1">
            <input type="hidden" name="cmd" value="_xclick">
                <input type="hidden" name="business" value="firstname.lastname@example.com">
                    <?php $cdata = $this->cart->contents() ?>
                    <?php foreach ($cdata as $items) { ?>
                    <input type="hidden" name="quantity" value="<?php echo $items['qty']; ?>" />
                    <input type="hidden" name="item_name" value=" <?php echo $items['name']; ?>"/>
                    <input type="hidden" name="amount" value="<?php echo $items['price']; ?>"/>

                    <input type="hidden" name="rm" value="2" />
                    <input TYPE="hidden" name="address_override" value="0">

                         <?php } ?>
    </form>

Answer: You only have one name attribute submitted name="quantity" for example.  PayPal uses a format of name="quantity_1".

paypal order summary missing


When I click on "Brightness And Lock" icon, system settings disappears

Question: I did fix the appearances but the brightness and lock is now broken. After installing gnome classic and gnome. I then uninstall gnome classic and gnome but it was still broken.
Answer: If you're problem is with the Icon then by changing the system theme to its default you can reset the icon. To do that I can suggest you Ubuntu tweak tool.Open your terminal and type as
<code>wget https://launchpad.net/ubuntu-tweak/0.8.x/0.8.5/+download/ubuntu-tweak_0.8.5-1_all.deb
sudo dpkg -i ubuntu-tweak_0.8.5-1_all.deb
</code>
Then open your unity dash and there type as Ubuntu tweak. Then in Ubuntu tweak reset your system theme to its defaults.


Need to change the layout of a Sharepoint Document Library

Question: So I have created a Custom library for a Sharepoint 2010 site. Changed the file look using css, Here is the hard part I can not change the positioning of the of the files(client wants a 4x4 grid) because they all have the same Class Name so when I change the positioning on the tag and open in Designer they are all stacked on top of eachother. Does anyone know any way other than hard coding it to change the layout of the folders in a Document library. I have removed everything from the out of the box Library through CSS just want the files positioned like below instead of the typical Column view. Hope this makes sense.
Where I am now
http://img593.imageshack.us/img593/9226/foldernow.png
What I need it to look like
http://img10.imageshack.us/img10/8097/folderpic.png
Comment: A screenshot would help to understand what you want to achieve.
Comment: Some source code would even be better.
Comment: Put a pic up to show what im trying to accomplish
Comment: why not float them left?
Comment: Floating doesnt work. The easy solution would be to build a custom web part, problem is I dont have access to the server so this is going to have to be done through CSS or XSLT and my XSLT is sub-par. Went so far as to try and change it in designer. but the Class issue persists there and your stuck using the out of thebox styles in designer. Really thought SP would have thought of this issue when giving option in library layouts.
Answer: I'm using the Yahoo User Interface library Grids http://yuilibrary.com/yui/docs/cssgrids/ for all my positioning needs.
Takes half a minute to set up, and as long as you're familiar with elementary school fractions it takes two minutes to master.
Seriously.
Basically what you want to achieve is something like this,
and keep in mind you need to set a pixel width on your outermost container, ms-bodyareacell for instance, if you're using a vanilla v4.master.

 //the yui3-g is a grid container

 // yui3-1-4 fills 1/4 of the avaliable width
        //document 1 goes here

        //document 2 goes here

        //document 3 goes here

        //document 4 goes here

This way all the document instances can have the same class name (yui3-1-4), and will wrap if there's more than 4.
YUI grids have seriously taken a lot of pain out of gridding and positioning items on web pages in general, and for me SharePoint in particular. I've used it on several public facing web sites, as well as numerous intra- and extranet implementations.
Hope it works out for you.


How to read GET data from a URL using JavaScript?

Question: I'm trying to pass data from one page to another.

www.mints.com?name=something

How to read name using JavaScript?
Answer: Please see this, more current solution before using a custom parsing function like below, or a 3rd party library.
The a code below works and is still useful in situations where URLSearchParams is not available, but it was written in a time when there was no native solution available in JavaScript. In modern browsers or Node.js, prefer to use the built-in functionality.

function parseURLParams(url) {
    var queryStart = url.indexOf("?") + 1,
        queryEnd   = url.indexOf("#") + 1 || url.length + 1,
        query = url.slice(queryStart, queryEnd - 1),
        pairs = query.replace(/\+/g, " ").split("&"),
        parms = {}, i, n, v, nv;

    if (query === url || query === "") return;

    for (i = 0; i < pairs.length; i++) {
        nv = pairs[i].split("=", 2);
        n = decodeURIComponent(nv[0]);
        v = decodeURIComponent(nv[1]);

        if (!parms.hasOwnProperty(n)) parms[n] = [];
        parms[n].push(nv.length === 2 ? v : null);
    }
    return parms;
}

Use as follows:
var urlString = "http://www.example.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";
    urlParams = parseURLParams(urlString);

which returns a an object like this:
{
  "a"  : ["a a"],     /* param values are always returned as arrays */
  "b b": ["b"],       /* param names can have special chars as well */
  "c"  : ["1", "2"]   /* an URL param can occur multiple times!     */
  "d"  : [null]       /* parameters without values are set to null  */
}

So
parseURLParams("www.mints.com?name=something")

gives
{name: ["something"]}

EDIT: The original version of this answer used a regex-based approach to URL-parsing. It used a shorter function, but the approach was flawed and I replaced it with a proper parser.
Comment: If anyone was still wondering how to get the data from `urlParams` the syntax is: `urlParams["name"][0]` which would return: `"something"`
Comment: Well getting only the key is actually very easy, I did - `for(var a in parms) { console.log(a); }` This only returned the key.
Comment: @Tomalak can you please tell me the way to print the value of name?

i am trying to use this script and when i use document.write(urlParams);
it gives me [object Object]
but i dont get the actual value..
Can you help me with this please?
Comment: @KiranVemuri: Try `console.log(JSON.stringify(urlParams))`
Comment: How to only get the key and not the value? For example - if url is like `example.php?name`, in this case it doesn't contain `name=something`, I only want to get `name` because my url is dynamic so that value can change so I need a way to get that value.
Comment: @Chinmay Keys without values will be set to null by my  solution. You can look for that in your code.
Comment: @Garrett Yes, or `urlParams.name[1]` and so on for the subsequent values with the same key. That's regular JS array syntax, nothing special.
Comment: This doesn't account well for the fragment identifier and a couple other things.. the link below has worked very well for me.

https://www.sitepoint.com/get-url-parameters-with-javascript/
Answer: It's 2019 and there is no need for any hand-written solution or third-party library. If you want to parse the URL of current page in browser:
# running on https://www.example.com?name=n1&name=n2
let params = new URLSearchParams(location.search);
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

If you want to parse a random URL, either in browser or in Node.js:
let url = 'https://www.example.com?name=n1&name=n2';
let params = (new URL(url)).searchParams;
params.get('name') # => "n1"
params.getAll('name') # => ["n1", "n2"]

It's making use of the URLSearchParams interface that comes with modern browsers.
Comment: What is that location.search ? I am getting an error there.
Comment: @ShashankAC Which browser are you using?
Comment: I am using Google Chrome
Comment: @ShashankAC That's really weird. It works on my Chrome. On which page are you testing this? For example, does `location.search` gives you anything on https://www.example.com/?foo=bar?
Comment: Oh sorry, I am using react so I should put this.props.location.search
Answer: You can easily do this
const shopId =  new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);

Answer: try this way
var url_string = window.location;
var url = new URL(url_string);
var name = url.searchParams.get("name");
var tvid = url.searchParams.get("id");

Comment: Simplest answer
Answer: I think this should also work:
function $_GET(q,s) {
    s = (s) ? s : window.location.search;
    var re = new RegExp('&'+q+'=([^&]*)','i');
    return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}

Just call it like this:
var value = $_GET('myvariable');

Answer: Here's one solution. Of course, this function doesn't need to load into a "window.params" option -- that can be customized.
window.params = function(){
    var params = {};
    var param_array = window.location.href.split('?')[1].split('&');
    for(var i in param_array){
        x = param_array[i].split('=');
        params[x[0]] = x[1];
    }
    return params;
}();

Example API call on http://www.mints.com/myurl.html?name=something&goal=true:
if(window.params.name == 'something') doStuff();
else if( window.params.goal == 'true') shoutGOOOOOAAALLL();

Answer: location.search
https://developer.mozilla.org/en/DOM/window.location
although most use some kind of parsing routine to read query string parameters.
here's one http://safalra.com/web-design/javascript/parsing-query-strings/
Answer: I also made a fairly simple function.
You call on it by:
get("yourgetname");
and get whatever there was.
(now that i wrote it i noticed it will give you %26 if you had a & in your value..)
function get(name){
  var url = window.location.search;
  var num = url.search(name);
  var namel = name.length;
  var frontlength = namel+num+1; //length of everything before the value
  var front = url.substring(0, frontlength);
  url = url.replace(front, "");
  num = url.search("&");

 if(num>=0) return url.substr(0,num);
 if(num<0)  return url;
}

Answer: The currently selected answer did not work well at all in my case, which I feel is a fairly typical one. I found the below function here and it works great!
function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

Comment: Hi! Thanks for that function. Can you give the same function, but in TypeScript?
Answer: Iv'e fixed/improved Tomalak's answer with:

Make an Array only if needed.
If there's another equation symbol in the value it gets inside the value
It now uses the location.search value instead of a url.
Empty search string results in an empty object.

Code:
function getSearchObject() {
    if (location.search === "") return {};

    var o = {},
        nvPairs = location.search.substr(1).replace(/\+/g, " ").split("&");

    nvPairs.forEach( function (pair) {
        var e = pair.indexOf('=');
        var n = decodeURIComponent(e < 0 ? pair : pair.substr(0,e)),
            v = (e < 0 || e + 1 == pair.length)
                ? null :
                decodeURIComponent(pair.substr(e + 1,pair.length - e));
        if (!(n in o))
            o[n] = v;
        else if (o[n] instanceof Array)
            o[n].push(v);
        else
            o[n] = [o[n] , v];
    });
    return o;
}

Answer: Try like this..
Eg : www.example.com?id=1
$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.search);
    return (results !== null) ? results[1] || 0 : false;
}
console.log($.urlParam('id'));

Hope it helps. :)
Answer:
You can do like this

function parseURLParams(url) {
        var queryStart = url.indexOf("?") + 1,
            queryEnd   = url.indexOf("#") + 1 || url.length + 1,
            query = url.slice(queryStart, queryEnd - 1),
            pairs = query.replace(/\+/g, " ").split("&"),
            parms = {}, i, n, v, nv;

        if (query === url || query === "") return;

        for (i = 0; i < pairs.length; i++) {
            nv = pairs[i].split("=", 2);
            n = decodeURIComponent(nv[0]);
            v = decodeURIComponent(nv[1]);

            if (!parms.hasOwnProperty(n)) parms[n] = [];
            parms[n].push(nv.length === 2 ? v : null);
        }
        return parms;
    }

    //enter code here

    var urlString = "http://www.examle.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";

    urlParams = parseURLParams(urlString);
    console.log(urlParams)


What is the Powershell equivalent of export PATH=$PATH:$HOME/dotnet

Question: Couldn't find powershell equivalent for the below commands in the Dotnet SDK installation page.
I need to add these lines to the Powershell Profile file C:\Program Files\PowerShell\7\profile.ps1
export PATH=$PATH:$HOME/dotnet
export DOTNET_ROOT=$HOME/dotnet

TIA
Answer: $Env:PATH = $PATH,(Join-Path -Path $HOME -ChildPath 'dotnet') | Join-String -Separator $([Io.Path]::PathSeparator)
$Env:DOTNET_ROOT = Join-Path -Path $HOME -ChildPath 'dotnet'

Comment: for some reason, `$Home` is recognized by powershell. The below variation works for me. Thanks! `$Env:PATH = $Env:PATH,(Join-Path -Path $HOME -ChildPath 'dotnet') | Join-String -Separator $([Io.Path]::PathSeparator)`
`$Env:DOTNET_ROOT = "$HOME/dotnet"`
Comment: lit, @blogs4t: It is the [automatic `$HOME` variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Automatic_Variables#home), i.e. one automatically defined by PowerShell (but note that it is _not_ an environment variable).
Answer:
For Windows, specifically (restructured to avoid repetition):
$env:DOTNET_ROOT = "$HOME\dotnet"
$env:PATH += ";$env:DOTNET_ROOT"

Note:

The $env: namespace prefix refers to (process-level) environment variables and the need to specify the values in quotes; more specifically, due to to the need for string interpolation, double-quoted string literals ("...") are needed, so-called expandable strings.

$HOME is PowerShell's automatic $HOME variable, i.e. a variable automatically defined by PowerShell that refer's to the current user's home directory, analogous to the HOME environment variable on Unix-like platforms; note that it is not an environment variable, however.

Cross-platform formulation:
$env:DOTNET_ROOT = Join-Path $HOME dotnet
$env:PATH += [IO.Path]::PathSeparator + $env:DOTNET_ROOT

Join-Path implicitly uses the platform-appropriate file-system path separator (\ vs. /), and [IO.Path]::PathSeparator returns the platform-appropriate separator for the entries of the PATH environment variable (; vs. :)
See also:

The conceptual about_Environment_Variables help topic.

Join-Path

System.IO.Path.PathSeparator (and System.IO.Path.DirectorySeparatorChar)


How do I access mounted hard drive with a Snap application?

Question: I have a dual-boot set-up on my computer, Windows + Ubuntu. Additionally I have a secondary hard drive in my computer, formatted as NTFS. Both operating systems are able to access this drive. It's very convenient since I can put all my music, personal files and projects there and access them from both Windows and Ubuntu. On Ubuntu, this drive is mounted on ~/shared.
However Snap applications on Ubuntu are not allowed to access this drive. This includes things like Gimp, VLC, SubtitleEdit and such which access media files that I keep there.
These applications register themselves with the option to access removable drives. I'm giving them this permissions as per this post and they are indeed able to access things in /media such as USB sticks. But not this NTFS partition mounted in my home directory.
I have two workarounds:

Uninstall these applications and install them using Apt and such. This works for many applications (like Firefox). The problem is that not all applications are available from Apt or they are sometimes in a lower version.
Copy the files I need to access temporarily to my desktop and copy them back when I've edited them. Annoying.

This question is similar, but not quite the same as the following other questions: 1, 2, 3, 4. I wasn't able to find an answer there that worked for this case.
Comment: Does this answer your question? [How to get access to USB-storage from the application installed as Snap?](https://askubuntu.com/questions/1034030/how-to-get-access-to-usb-storage-from-the-application-installed-as-snap)
Comment: No. I did mention in my question that I've given these application permissions to access removable media as per all 3 answers in that link. I've linked that question in my original question twice, even. Most things I could find online linked to that question as it seems to be a common problem, but it did not work here I'm afraid. I tried mount-observe too but that made no difference (and indeed it shouldn't).
Answer: Inkscape was unable to access mounted drives at /mnt/* -- even after setting permissions in Snap Store.
This seemed to work:
sudo snap connect inkscape:removable-media

Ubuntu 20.04.2 LTS
Comment: worth mentioning this is not available for all apps, I believe when packaging [the specific permission must be defined](https://snapcraft.io/docs/removable-media-interface)


Deterministic finite automaton parity bit question

Question: for a university assignment ive been tasked with creating a DFA that accepts the regular language (00010 + 1101 + 1010)* and must contain a parity bit at the end to make sure there is an even amount of 0's
I understood this as creating a DFA that handles (00010 + 1101 + 1010)*(0+1)
but under further clarification from the teacher this means that the parity bit is only added on once!
My current diagram that i have attached fails this test. Ive spent the last 2 weeks trying to modify this to only add on one parity bit and accept the string but for the life of me i cant work out how.
Can anyone here help me understand how to do parity bits with DFA's? Am I way off the mark with my working out.
Thanks.
Comment: I am not sure to understand your question. Let $R = (00010 + 1101 + 1010)^*$. Are you trying to find a DFA for the set of words of $R$ with an even number of occurrences of $0$? That is, the language $R \cap (1 \cup 01^*0)^*$?
Answer: You essentially need two copies of the (00010 + 1101 + 1010) automaton to distinguish the parity, i.e., we need to keep track of the overall parity as well as the 0-1-sequence since the last completed $(00010+1101+1010)^\star$ (fortunately, there is always only one way to reach every valid string):
Thus create nodes carrying mnemonic labels: even, odd0, even00, odd000, odd0001; even1, even11, odd110; odd10, odd101; odd, even0, odd00, even000, even0001; odd1, odd11, even110; even10, even101. Create an arrow labelled 0 from $p\alpha$ to $q\beta$ (where $p,q\in\{\text{even},\text{odd}\}$ and $\alpha,\beta\in\{0,1\}^\star$)
if

$p\ne q$ and $\beta=\alpha0$ or
$p\ne q$, $\beta=\epsilon$, and $\alpha$ is $0001$ or $101$

Similarly, draw an arrow labelled 1 if

$p=q$ and $\beta=\alpha1$ or
$p=q$, $\beta=\epsilon$, and $\alpha=110$

The starting node is "even" and the accepting nodes are "even" and "even0".
Comment: The idea is that we are limited to 30 states (to keep it as reduced as possible) Sorry I should of clarified that earlier so I'm not sure I could implement what you're saying into a state transition table. Maybe if you could clarify a way of doing so that would be amazing. In saying that, I'm beyond thankful for the help you've already given me.


Show Webapi objects in view page by asp.net MVC

Question: I want to separate each variable from the web service separately into the view page
 there is a sample json string like my url resul
{"change":[{"object1": "value1", "object2": "value2", "object3": value3, "object4": value4},{"object1": "value1", "object2": "value2", "object3": value3, "object4": value4}]}

 public ActionResult Get_test(){WebClient webclient = new WebClient();
webclient.Headers[HttpRequestHeader.ContentType] = "application/json;charset=utf-8";
string url = "My URL";
webclient.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
webclient.Headers.Add("Request-type", "My Method");
string result = webclient.DownloadString(url);

}
how can i show the objects in a view.i have an empty view(Get_Test).
Comment: What "variables"?  What "view"?  It's not really clear what you're asking.  Please elaborate.
Comment: i edit my question.thank you lots..
Answer:  public ActionResult Get_test(){
  WebClient webclient = new WebClient();
  webclient.Headers[HttpRequestHeader.ContentType] =
   "application/json;charset=utf-8";
  string url = "My URL";
  webclient.Headers["Authorization"] = "Basic " +
  Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
  webclient.Headers.Add("Request-type", "My Method");
  string result = webclient.DownloadString(url);`
 List<SampleViewModel>
  userList = new List<SampleViewModel>();
        JObject jObject = JObject.Parse(result);
        JToken jUser = jObject["MyMethod"];
        foreach (var item in jUser)
        {
            SampleViewModel user = new SampleViewModel();
            user.object1 = (string)item["object1"];
            user.object2 = (string)item["object2"];
            user.object3 = (int)item["object3"];
            user.object4 = (int)item["object4"];
            userList.Add(user);
        }
    return view(userlist);
  }

at first i build a SampleViewModel with mt Objects.and then we have a foreach in view page
@model IEnumerable<WebApplication.Models.SampleViewModel>
@{ViewBag.Title = "Get_Test";}

        object1
        pobject2
        object3
        object4

@foreach (var item in Model)
{

        @item.object1
        @item.object2
        @item.object3
        @item.pobject4

}


How to grep whole manual?

Question: I can do for example

man cp | grep verbose

to findout if cp man has word "verbose", how can I do something like (pseudo-code)

man * | grep copy

to find out what command to use for coping?
Comment: man has its own man page ;)
Answer: You can use
man -K printf

(note the capital k)  to search in content of man all man pages. The first page will be shown, and when you quit you have the option to open or skip the next matching page or quit the whole search.
Comment: This is the correct answer.
Answer: man -k printf

Search the short descriptions and manual page names for the keyword printf  as regular  expression.  Print out any matches.  Equivalent to apropos -r printf.

Or as you can see you can also use
apropos -r printf
Example...
man -k "test"

Test (3perl)         - provides a simple framework for writing test scripts
cupstestdsc (1)      - test conformance of postscript files
cupstestppd (1)      - test conformance of ppd files
DBD::Gofer::Transport::null (3pm) - DBD::Gofer client transport for testing
DBD::Gofer::Transport::pipeone (3pm) - DBD::Gofer client transport for testing
dh_auto_test (1)     - automatically runs a package's test suites
dh_testdir (1)       - test directory before building debian package
dh_testroot (1)      - ensure that a package is built as root
dh_testversion (1)   - ensure that the correct version of debhelper is installed
ExtUtils::testlib (3perl) - add blib/* directories to @INC
feature_test_macros (7) - feature test macros
File::CheckTree (3perl) - run many filetest checks on a tree
filetest (3perl)     - Perl pragma to control the filetest permission operators
ftm (7)              - feature test macros
gcov-4.2 (1)         - coverage testing tool
make-memtest86+-boot-floppy (1) - (unknown subject)
Memoize::ExpireFile (3perl) - test for Memoize expiration semantics
Memoize::ExpireTest (3perl) - test for Memoize expiration semantics
mysql_client_test (1) - test client API
mysql_client_test_embedded (1) - test client API for embedded server
mysqlmanager-pwgen (1) - internal test-suite program
mysqlmanagerc (1)    - internal test-suite program
mysqltest (1)        - program to run test cases
mysqltest_embedded (1) - program to run embedded test cases
ndb_cpcd (1)         - automate testing of NDB (development use only)
Answer: You can use
  man -k copy

to search in the short descriptions and names of all manpages for copy
Comment: ovangle - that `cat` is superfluous.
Comment: That solves the second part of the question. For the first part, there are a couple of options. 'man cp | cat | grep verbose' will just get the particular lines containing the word *verbose*. You can also type /verbose when you're in the man page to do a pattern match for the word 'verbose'. After that, if you keep pressing 'n', it will cycle you through all the occurences of the word verbose in the file.
Comment: So it is. Stupid me, that's a whole 5 keystrokes I've wasted every time I've grepped a man page (never -- I prefer some context with my flags, so '/' is more useful).
Answer: You can also zgrep -r each location in manpath to search the raw manpage files.
for p in $(manpath | tr ":" " ");
do
    echo $p
    zgrep -r 'copy' $p
done

Comment: a) `manpath` is a command (it might also be a ENV, but I'm talking about the command) and b) good point, I'll swap it for `zgrep` which works on both the compressed and non-compressed files.
Comment: Ah, I did not know about `manpath` as a command. Learn something new every day. But zgrep doesn't support -r, so try this: `find $(manpath | tr ":" " ") -type f -print0 | xargs -0 zgrep 'copy'`
Comment: Except that a) MANPATH is upper case and often not set, and b) many man-pages are compressed and therefore not grep-able.
Answer: Try this:
man * | col -b | grep *

Comment: As the OP mentioned, `man *` does not do what he wants.
Comment: what's the difference of man command | grep "keyword" AND man command | col -b | grep "keyword" ? When I tried "man grep | grep -i "case" " AND "man grep | col -b | grep "case" ", I couldn't find any difference. When will piping through "col -b" make a difference ?
Comment: ANSWER : I did a hex compare of the output of both above commands (with and without "col -b" command pipe) and found that without "col -b", there's additional characters in the output, I presume coming from the man content. So, yes, it helps to do a "col -b"

How to grep whole manual?


My 5th (top) floor apartment is shaking; what might cause this?

Question: I live in a developing country (so don't have much faith in building codes), and have been experiencing increasingly noticeable and frequent "shaking" in my top fifth floor apartment. I'm seriously concerned.
My home has been shaking. I have felt small tremors from an earthquake before, and this is the best way to describe it, however, I do not currently live in an earthquake zone, so this is quite worrying.
The "shaking" bouts seem to last for about 5-10 seconds, by my estimate; I should also note that this country is not an earthquake zone. My home is the top floor of a five story building, that is rather "skinny" (in my judgement, something like a 2.5 - 3.5 : 1 X:Y ratio. When I first began experiencing this shaking a couple of months ago, I thought that it might have been the bed, or even just my imagination, and paid it little attention. However, over the past few weeks, the shaking has become markedly more noticeable, and I confirmed that my girlfriend also felt it. I made a query with the landlord, but I was told that there was no problem, or that it was "the wind". After some research on the internet, I found that buildings do indeed sway slightly with wind, and so felt at least somewhat placated in my perhaps overblown fears of building collapse.
However, today, I felt the most violent instance of shaking to date in the late evening, and confirmed that my girlfriend also felt it. This had me very concerned, so I took the step of also asking the tenants on the floor below, and they also confirmed that they had felt the shaking. Based on our positions at the time of the shaking, it was apparent that the shaking was felt at least on the 4th and 5th floors of the building, and at all locations, as I was in the middle, my girlfriend was on the "left", and the other tenants were on the "right" at the time of the occurrence of the shaking. There was absolutely no wind, and as it was late night, there was no construction going on that may have caused vibrations or such.
I should also note that since I moved into the apartment, there has been ongoing construction on the lower level floors; I obviously have no idea, but my fear is that they may have weakened a key supporting wall or some such.
I decided to leave the building immediately, and I'm currently in a hotel, and plan to cancel my lease and find a new place to live.
So, my question to you, in your opinion, am I overreacting, or is something reasonable likely to be seriously wrong with this building? What sort of tests would a structural engineer perform to determine the cause of the shaking / if a building like this is safe? I ask because it may be that the landlord says she will hire an engineer or some such to look into the problem, and in this case, I want to be sure that my fears are sufficiently placated, as right now I have absolutely no desire to move back into my apartment.
Hope you can help shed some light on this rather scary situation of mine!
Comment: Good move. Read about the collapse from a safe place rather than from under the pile of rubble. Shaking 5 story buildings are not "normal", regardless where they are.
Comment: Do you have a rail/subway near or below the house? Heavy truck traffic on poorly made roads can also cause building movement.
Comment: No subway / rail, so that's been ruled out. I've hired my own structural engineer, and I suppose we'll see what the results of the audit here. I'll be sure to post them here :)
Answer: Normal Vibrations in Buildings Have Identifiable Sources
I've encountered a vast range of vibrations in multi-dwelling buildings I have lived. Hear are the ones I can remember:

washing machine spin cycle (this happens often and, if it matches the resonance of the building can travel throughout multiple floors)
dishwasher valves and drain pump (not very strong, but once the sound filtered through floors and walls, the sound and feel was disconcerting)
nearby trains
nearby garbage trucks and other heavy vehicles
dancing at house parties
active construction work
elevators
earthquakes
explosion nearby

Note that all these sources are not the building structure itself, and are fairly easy to track down.  I can't remember encountering a source of vibration or shaking whose source I could not pinpoint with a small amount if work.
Find the Source or Move Out
The most likely explanation for the vibrations/shaking is that it is being caused by something in or near the building and not the building structure itself.  With a reasonable amount of effort by you, your neighbors and landlord, you should easily be able to pinpoint the source of the vibrations/shaking.
If you still cannot pinpoint the source after putting some earnest effort into finding the source, it may actually be the building structure itself.  This is not that far fetched if the building was not engineered (building inspectors usually defer to a professional engineer for structural issues).
If your only conclusion is that the vibration/shaking is originating from the building structure itself, then you should move out - it is a bad sign.  Even if the building doesn't collapse, you will have made the correct decision with the information you had at hand at the time.
Answer: "Normal" building movement would only be due to wind or earthquake. Movement due to normal wind would only be slightly apparent to very sensitive individuals in very tall buildings, as in dozens of floors. Most people would notice slight wind movement in very high winds or minor earthquakes, but nothing alarming. The only alarming movement anyone would notice would be during strong earthquakes.
How much a building moves due to a lateral force such as wind or earthquake depends partly on the buildings height to width ratio and the relative rigidity of the building's structural elements. The critical width when determining the height to width ration is the building's critical (narrowest) depth in the direction of the force. Since wind and earthquakes can come from any direction, we can simplify and say the least horizontal dimension.
Sometimes people in buildings will sense vibrations caused by passing trains, or even heavily loaded trucks. Some types of soils have a certain elasticity that transmits vibrations from heavy movement into the building's foundation and up into the structure. These movements are primarily vertical in direction and would typically not be threatening to the building, though repeated severe vibrations can cause brittle finish materials such as plaster work to crack or even fall out of position.
A similar movement can be caused just from people moving normally on a particular floor system, especially in smaller buildings, because the floor structure is overly elastic. This usually would not indicate any structural failure is imminent, rather that the structure was not built adequately from a usability standpoint.
Renovations to existing buildings must be carefully planned to avoid disturbing structural, load bearing elements. Not just bearing vertical loads, but lateral loads as well. If they must be disturbed, adequate temporary shoring must be in place until proper permanent structure is replaced. Even if shoring was not done, building movement would not be discernible unless structural failure was imminent. Imminent in building failure can be anywhere from within the next few minutes to happening over a period of several months.
Besides wind, earthquake, heavy vehicles, and compromised structure, the only other cause for building movement would be differential settlement due to foundation not being founded in stable soil materials. This is actually a subset of structural failure, as stable soils is a necessary part of a sound structure.
When an engineer assesses a structure for soundness, testing may or may not be done, depending on the situation. Structural testing often means testing to failure, which is often not feasible in an occupied structure. The engineer will make an assessment based mainly on inspection of existing conditions and comparing with the building's plans to see if it was built in accordance to the plans, if the plans have design errors, if there are signs of failure such as cracks of certain form in certain locations or sagging and deformation of structural elements.
Some small scale materials tests can be done to verify the installed material matches the design specifications by taking samples and testing in a laboratory. Only after considering all available evidence will the engineer make an assessment based on the evidence and his/her experience and knowledge. They would typically publish a report summarizing what they did, what they observed and their findings. While such reports are quite technical by nature, the main gist of it should be comprehensible to any reasonably intelligent person without an engineering background.
It's impossible to say if you overreacted since I was not there. While there is certainly cause for concern, imminent collapse World Trade Center style is highly unusual. I've seen many obviously failed buildings in developing countries in which squatters live without incident for years. Yet one would have to be truly desperate to spend time in such buildings, as sudden catastrophic collapse does remain a possibility.
Comment: Thank you very much for this detailed answer. I have hired a structural engineer to look into it. In addition to the "renovations", the landlord also built a "roof" structure on the top of the building. This is what the structural engineer suspects is causing the shaking. In any case, I suppose we'll find out, until then, hotel life :\ I'll let you know how it goes!
Comment: Please do stay in touch, I'd be very curious to hear a professional take on this. Certain roof structures, such as steel water tank supports, can amplify small lateral motions. But something needs to initiate a motion to begin with.
Comment: The structural engineer did some wind load tests, and said that the building should be safe, an should not be shaking. Unfortunately, the cost of checking the foundation of the building would have been too expensive relative to my deposit on the lease. However, the structural engineer did say that the building uses "plates" instead of pilings, and that due to the concrete construction, even if the foundation had issues, the building would not collapse "WTC" style, and thus I shouldn't worry. Fun fact: this country literally does not have building codes / regulations ;)
Comment: To add a bit more, he said that the issue was likely similar to the case of the leaning tower or pisa. Additionally, he said that the shaking would probably cause some issues with the building years down the road, but that I don't have anything to worry about for the duration of my stay, and in any case a problem of this kind would not be life threatening (which was my main concern). So... I guess I just deal with the shaking, sort of like a bad trip, it's scary, but you know it's harmless so you shrug it off :)
Comment: So the mystery remains. At least you can sleep well at night, that's worth a lot, and moving is such a big hassle. I LOL'd at your "Fun Fact" because it's not fun at all. Even having building codes does not always help much if they cannot be adequately enforced. This is the problem in some developing countries that actually have codes. Hopefully your country will not have this problem once it gets around to enacting codes to begin with. Cheers.
Answer: You will have to do a bit of investigation to decipher external causes (e.g. trains etc.).
Thereafter maintain a daily log with times, degree of movement and any other relevant information. Get your friend to stay and report on a cell phone the movement while you are outside checking the source.
If it still does not help a good engineer would be useful but very expensive. But if you are not having the peace of mind, leave the place and take action to get the deposit back and inform the owners and the authorities.
Cheers


How to check if any point (or part) of a line is inside or touches a rectangle

Question: I want to check if a line (or any point of a line) is within a rectangle or intersects  a rectangle.
I have (x0, y0) and (x1, y1) as starting and ending points of a line.
Also, (ax,ay) and (bx,by) as the top-left and bottom-right points of a rectangle
For example,
<code>     ____________
    |            |
 ---|-----       |    Result: true
    |            |
    |____________|

    /
  _/__________
 |/           |
 /            |      Result: true
/|            |
 |____________|

     ____________
    |            |
    |   -------- |   Result: true
    |            |
    |____________|    ----------     Result: false
</code>
Can anyone suggest how to do this? I dont want to know which point is that, i just want to know if its there or not.
Thanks a lot for help
Comment: +1 for clear ASCII art :)
Comment: A quick Google for "Cohen Sutherland" should get you started in the right direction.
Comment: Consider each edge as it's own line segment. Then it's just a matter of determining line-segment intersection *and* the case where it's entirely contained-in. Of course, this is just a quick observation and likely not the *ideal* way of solving this type of intersection (it's also a really common intersection -- I'd be really surprised if this is an original question ;-)
Answer: The first and third cases are trivial - simply return true if either endpoint of the line is within the box (i.e. > ax and ay, < bx and by).
The second presents a problem - we can't rely on the endpoints of our line anymore. In this case, we will have to test the line with each edge of the rectangle.
The equation for our line will be <code>(x1 - x0)*x + (y1 - y0)*y + x0*y0 - x1*y1 = 0</code> , and we can construct a similar equation for each side of the rectangle using the corners. Following that, substituting the equation for the sides of the rectangle into our line will give us the intersection.
Finally, we check to ensure that the point is within the bounds of the side of the rectangle, and likewise within the line segment we are considering.
There is a more detailed account of this in this discussion.
Comment: 2) doesn't seem right to me. take the case of the unit square (0,0 to 1,1) versus the segment (-1,0)-(1,3), for example.
Comment: You're right! That would produce a false positive. I will update my answer.


Not able to creat funtion in mariaDB 10.6.8, but was working in 10.2

Question: DELIMITER ;;
CREATE FUNCTION `substrCount`(s varchar(65530), ss VARCHAR(255)) RETURNS mediumint(8) unsigned
BEGIN
DECLARE count MEDIUMINT(4);
DECLARE offset MEDIUMINT(4);
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = NULL;
SET count = 0;
SET offset = 1;
REPEAT
    IF NOT ISNULL(s) AND offset > 0 THEN
        SET offset = LOCATE(ss, s, offset);
        IF offset > 0 THEN
            SET count = count + 1;
            SET offset = offset + 1;
        END IF;
    END IF;
UNTIL ISNULL(s) OR offset = 0 END REPEAT;
RETURN count;
END ;;
DELIMITER ;

It was working fine in 10.2 MariaDB but getting syntax error in 10.6.8
SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'offset MEDIUMINT(4);
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET s = N...' at line 4 */
Comment: Do not use reserved words and keywords for objects naming. Or at least quote them with backticks.
Answer: Offset became a reserved keyword in 10.6 and now needs to be quoted (or change your variable name).


How to open modal from anywhere in react

Question: I have a modal when opened, display auth user data, currently, I can only open the modal on the dashboard, but I want to be able to render it from anywhere in my application. How do I achieve this?
Dashboard
     const [visible, setVisible] = useState(false)

     const trigerModal = ()=>(
       <ModalCustom visible={visible} setVisible={setVisible}>
            <form>
                <>

Select an Account

                      {accounts && accounts.map((item, i) => (

{item.name}

{item.email}

 {item.phone}

                      ))}

                </>

            </form>
          </ModalCustom>

      )

return(

   {trigerModal()}
    <button onClick={()=> setVisible(true)}>Open modal</button

)

Profile
how do trigger the modal from this component
Answer: Two statements will answer virtually every react question:

Don't mutate state (not applicable here)
Lift state up (this is the answer to your question).

Create a context - wrap your application in it, and have any component useContext to open a modal with whatever components you want it in:

export const ModalContext = React.createContext();

const ModalProvider = ({children}) => {
  const [modalContent,setModalContent] = useState();

  return (
     <ModalContext.Provider value={
       useMemo(() => ({
        hide:() => setModalContent(),
        open:setModalContent
       }),[]
     }>
       {modalContent ? <Modal>{modalContent}</Modal> : null}
       {children}
     </ModalContext.Provider>
  )
}

Wrap you application in the ModalProvider component so the context will be available to all your components:
const AdminDashboard = () => (
   <ModalProvider>
    <OtherComponents/>
   </ModalProvider>
)

SomeLink, a component that is anywhere inside AdminDashboard can use React.useContext to access the state in ModalProvider
const SomeLink = () => {
   const { open } = React.useContext(ModalContext);

   return (
     <button onClick={() => open(<SomeModalContent/>)}>Click to Open!</button>
   )

}

Comment: Is it best practice to store jsx in the context?
Comment: @YedidyaRashi you can store whatever you want in context/state if it suits your needs. It's not directly serializable, so if your app requires you to persist this type of state to a storage then I guess it wouldn't work for you (if that's what you meant).
Comment: Is there a way to check if the modal is open or closed?
Comment: you shouldn't dispatch update the jsx element into useState because it can be affect to performance
Answer: If you want to access it from anywhere You need to use Global State (like Redux or Mobx)
If you want to control this  from parent component you can use useRef
Answer: Not the most "react"-like solution but I don't like to solve everything "react"-like so here is how I solved it for my specific usecase.

Create a class with static access.
Place the modal high / outside the dom tree
set the necessary access in the modal component

HelperClass
export class ModalHelper {
    private static openFunction: (state: boolean) => void;
    public static setOpenFunction(f: (state: boolean) => void) {
        ModalHelper.openFunction = f;
    }
    public static setOpen(state: boolean) {
        if (ModalHelper.openFunction) {
            ModalHelper.openFunction(state);
        } else {
            console.error("ModalHelper called before setOpenFunction")
        }
    }
}

Sample Modal component
export function ExplainerModal() {
    const [open, setOpen] = useState(false);

    useEffect(() => {
        ModalHelper.setOpenFunction(setOpen);
        return () => {
            ModalHelper.setOpenFunction(undefined);
        };
    }, []);

    return <>I'm a modal</>
}

Call from anywhere
ModalHelper.setOpen(true);

Now keep in mind this only works for one modal, but can of course be further adapted to handle multiple modals (e.g. by adding a dict for the functions etc.)


TinyMCE: how to center an image?

Question: In TinyMCE, I may insert an image and center it. And the code generated is as follows:

However, when I save the textarea, the display: block; style is removed.
I also tried the followings, but all in vain:

Set
:

The style of
 is removed when I save the content of the textarea.
In tinymce.init, set:
verify_html: false

Set valid_children: "+body[style]" in tiymce.init and add the following in textarea:

Set the following in tinymce.init:
valid_styles: {
    "img": "display"
}

So, how do I center an image in TinyMCE anyway?
Comment: I just tried your example and it works for me. The image is centered. Are you sure you are running the last version?
Comment: Is this really a tough question? In that case, maybe the question should be "how do I set TinyMCE not to parse the style settings"?
Comment: @devconcept same for me - what Version do you use?
Answer: Edit CSS
If you are able to insert css to your page, you could simply set the images property to display: block:
p img {
    display: block;
}

Edit TinyMCE
If you are not able to excess the css files , you can maybe somehow edit the TinyMCE editor, so that you are able to use its build in text-align: center button, which should do the same, as your code does?
You can set the toolbar of your TinyMCE like so:
$('#your_editor').tinymce({
    plugins: 'link,code,preview,autolink',
    height: 350,
    width: 750,
    toolbar: "undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist | link image | preview code"
});

Within toolbar: you can choose which buttons you want to add. Using aligncenter you can create a button, which you can use to align your image to the center.
Comment: Centering the image has no problem in the editor. The problem is that when I `save` the textarea, some of the styles will be removed, for example, `display: block;`.
Comment: Even if you do not use custom styles, that you have added, but use the build in tinymce functions?
Comment: Same. I have edited my question: tinymce will add `display: block;` automatically when I choose to center the image. But it will be remove when I save the content.
Comment: This is a noob guess, but just to be sure: Have you tried to apply `display: block` inside your `` using `!important`? So: `img {display: block !important;}`
Comment: @yltang52 although, maybe you are able to send a live link to your website? That would help looking for the error! All basic tinymce build ups work like a charm using only one of your tweaks you have tried.
Comment: The whole `
Comment: @yltang52 are you able to insert
Comment: I don't think this is a good solution. Because, it's a Mezzanine CMS, users may choose to align the image to the left, center, or right. Currently, left and right are OK; only center has problem.
Comment: You always can set the align to `left` or `right`, while "hardcode" a fix into the core files. This should not affect each other.
Answer: I came up with a work-around solution:
Modify tinymce.init:
(a) Add Formats: add the class center and necessary styles to every centered block element including img.
formats: {
    aligncenter: {selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', classes: 'center',
                  styles: {display: 'block', margin: '0px auto', textAlign: 'center'}},
}

(b) Add JavaScript to display centered elements correctly in the editing window: replace previously added margin: 0px auto; with margin: 0px auto; display:block; text-align: center;:
var value = $('textarea').val();
value = value.replace('margin: 0px auto;', 'margin: 0px auto; display:block; text-align: center;');
$('textarea').val(value);

And then add the following in our own CSS file to display centered element correctly in the HTML page:
.center {
    display: block;
    margin: 0 auto;
    text-align: center;
}

The above solution took me hours to figure it out, all because TinyMCE wouldn't want to save the style display: block; created by its own!

TinyMCE: how to center an image?


Can having a bad grounding situation destroy a circuit breaker?

Question: We moved into a home, built a while ago. there are wires hanging and covered in black tape on a chimney.
I bought 2 sconces and put them in place. i did not hook up the ground wire on one of them, the first in series and turned them , they worked, i saw the ground wire was broken, so i cut the wire back and fix it and re-wired it to use the ground wire.
after wiring them up, our circuit breaker on another circuit for the dryer starting popping. We had a dryer repair man come out and test the dryer, it never went over the 17amps to pop the 30 amps circuit breaker, he thinks the circuit breaker is bad.
I thought maybe the work I did for the sconces on ANOTHER circuit may had caused an issue? I have turned off that breaker for the sconces and still the dryer pops the 30 amp circuit breaker.
Answer: Sounds to me like a coincidence.
Grounds have nothing to do with the functionality of a circuit breaker. Meaning a circuit will work properly (albeit less safely) with or without a ground. The ground is a "safety backup" in case of a short circuit to metallic parts and pieces.
Hopefully all the work you did on the sconces is proper. Did you install and mount boxes for the wiring and to mount the lights?
Comment: Well, that is not a compliant or safe installation then. You must have a box for the splices and to mount the fixture to.
Comment: There was no boxes, just 2 holes in the bricks for the romax wires, and 2 screw holes. I wired up the 3 wires (hot,neu, ground). I have no idea where those wires go behind the bricks. It works, both lights work, and no funniness.
Comment: @ttomsen -- go back and ***put a box in*** -- bricks aren't waterproof, and water ingress could easily cause problems with your wiring down the road.
Answer: If you had a short from a hot to ground (screw through some wires) and an open ground (broken connection somewhere), then fixing the ground could result in a circuit breaker tripping. If that were the case, you'd see voltage on the ground.
But since you're fixing the ground at a fixture, and I'm assuming you didn't do anything like a bootleg ground to neutral connection, then the only possibility for it to be related to your work is disturbing the wiring (with perhaps a screw that missed the stud exactly where the dryer happens to be run).
All of this is highly unlikely and would show up with an amp meter when tested at the breaker. So if the amp meter shows the breaker is going bad, then replace it, they can go bad over time.


Boost CRC problem: different results with the same parameters

Question: I am using CRC for the first time (boost::crc_32_type), and I noticed that calling the process_bytes() method twice with the same parameters I get different results. Is it normal?
#include <boost/crc.hpp>
#include <ios>              // for std::ios_base, etc.
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string              data1, data2;
    boost::crc_32_type  result1, result2;

    data1 = "This is a test string";
    data2 = data1;

    result1.process_bytes(data1.c_str(), data1.length());

    cout << "result1: " << hex << uppercase << result1.checksum() << endl;

    result1.process_bytes(data1.c_str(), data1.length());

    cout << "result1: " << hex << uppercase << result1.checksum() << endl;

    result2.process_bytes(data1.c_str(), data1.length());

    cout << "result2: " << hex << uppercase << result2.checksum() << endl;

    return 0;
}

This is the output:
result1: 2DB69898
result1: E29C91
result2: 2DB69898

Answer: According to the manual, checksum() returns "the CRC checksum of the data passed in so far". So, the second checksum is the checksum of the concatenation of data1 with itself and thus naturally different from the checksum of data1.
Answer: I'll throw a random rock... You aren't resetting the state of result1, so the checksum you are calculating the second time is of "This is a test stringThis is a test string". Mmmh... Yes... There should be a crc_32_type.reset().


Can an expansion tank described as for a water heater be used for a boiler system?

Question: There is only one expansion tank we can find which states it is also a thermal expansion tank but it says it protects hot water heaters
Comment: Your question is very unclear.
Comment: Read the spec sheet, look for pressure and temperature ranges...
Answer: Can a expansion tank be used to protect a hot water heater? YES.
Dose it need to be thermally listed? Not really if on the cold water feed and a check valve in the input of the pressure tank.
The thermal cycling water really won't heat the expansion tank, as the water is not being used when the water heater continues to heat some hot water pushes back into the expansion tank the hot water in most cases only makes it back a few feet. The water heater tank is now hot and full. Slowly cooling, but the supply line rapidly cools. The water moved from the tans back to the water heater once the water heater tank cools the cycle starts over. I have installed several dozen small expansion tanks and have never used anything special. The closest my expansion tank has been is on the floor next to the water heater that did not have any problems many were 20' away. So I just use a small bladder tank nothing fancy.
Comment: Worth noting is that you can find both potable and non-potable varieties. The former being used on the supply of a DHWH and the latter in hydronic heating.
Comment: Yes good point for a boiler it won't matter but for drinking water potable is needed +


How to make user to believe that they have visited the best site?

Question: I've a website. But, my question is how to make a user believe that a user has visited the best site ever?
What could be added to a existing site that user might think that, this webisite is good.
Comment: This reads a bit like SPAM to me. But in case it isn't, the answer is: animated GIFs of kittens.
Comment: what about giving the user the best site ever instead of tricking him?. I think that you should rephrase your question and explain better what do you want, because right doesn't sound very good.
Comment: Subliminal messages, hypnosis, or just build the best site ever as Derek suggested. The "best" is subjective - some people may think *facebook* is the best - I hate it. Of course animated kittens never fail.
Comment: Animated wallpapers, animated flaming skulls, and a midi that automatically plays in the background when the page load all indicate that you are on the cutting edge of web design.  Also, frames indicate that you are a skilled developer who can grasp the more difficult concepts of HTML
Comment: Can confirm what @rotard. Made a site using those principles in '92, got all the girls.
Answer: Short answer: Build the best site ever.


How to setup bcache?

Question: I've tried to set up bcache in Ubuntu 14.04 with a fresh install and an empty /home partition (/dev/sdb2) as a backing device. I have a running system on my SSD and I'd like to use its /dev/sda2 partition to cache my /home
.
I've always managed to sort my ubuntu problems out from forums but I'm struggling to understand the basics here and need help:

What account do I need to be logged in when I set up bcache in the first place? Obviously the user created during install on /dev/sdb2 has to be logged out for /home to be unmounted, so I set up a temporary user account on a separate partition to do it. This seems too clumsy already.

make-bcache -B and -C both tell me that there are non-bcache superblocks on the device so I did sudo wipefs -a on both of the devices.
The partitions then appear as unformatted without an UUID in GParted. Is this normal?

If so, what happens to fstab and /home at boot? Do I need to use bcache's UUID in fstab? I did but the system didn't find the /home partition upon next boot.

Both echo /dev/sdb2 > /sys/fs/bcache/register and echo /dev/sda2 > /sys/fs/bcache/register return 'Permission denied' messages; as I understand /sys cannot be written to.
So  echo /dev/sdb2 | sudo tee /sys/fs/bcache/register seems to have worked.

Can someone verify this is the proper way to do it in Ubuntu?
I seem to have managed to create, register and attach the backing drive but according to the tail /sys/block/bcache0/bcache/stats_total/*  I only have bypassed data.
My whole setup is quite a mess now so any clarification would be greatly appreciated.
Comment: Have you tested it? Appears that you know the "how-to", what you need to know?
Comment: I tested it as above and I'm getting cache hits, misses and bypasses. Trouble is my backing device that is supposed to be my home partition is not mounted as home at startup but as a separate drive. So my /home is a folder on / at the moment and I'm testing bcache by copying files onto the backing device and accessing them.
I was messing with fstab which was probably a mistake and I don't have a valid UUID for my /home partition now if that makes any sense..
What I need is an idiot-proof walk-through specifically for ubuntu.
Comment: OK, I messed up fstab and /home had the wrong UUID.
It seems to work now.
I would still be interested in how exactly is bcache supposed to be set up: from temporary user account, live CD/USB, or other?
Answer: With Ubuntu 15.10, alex's answer is no longer correct. The initramfs image is locked in the installer and will not be automatically re-generated when the system is installed. Thus one will have a bcache installation, but it won't be able to boot. I've written a more verbose description of the following process elsewhere; however, here are the basics:
1. Partitioning
Boot into the Ubuntu live-cd and create the following partition scheme with fdisk or gparted. Assuming /dev/sda is your SSD and /dev/sdb is your HDD:
/dev/sda1 - 1024 MB, EXT4, used for /boot (grub/grub2 doesn't support bcache)
/dev/sda2 - any format, for cache
/dev/sdb1 - EFI partition (if your machine needs it)
/dev/sdb2 - swap
/dev/sdb3 - any format, backing partition

2. Create the bcache device
Open up the terminal, wipe the file systems on the backing and caching device:
sudo wipefs -a /dev/sda2
sudo wifefs -a /dev/sdb3

Install bcache-tools and create the bcache device:
sudo apt-get update
sudo apt-get install bcache-tools
sudo make-bcache -B /dev/sdb3 -C /dev/sda2
sudo mkfs.ext4 /dev/bcache0

3. Install Ubuntu
Install the operating system using the custom partitioner as follows:
/dev/bcache0 - format EXT4, use as /
/dev/sda1    - format EXT4, use as /boot
/dev/sdb1    - EFI partition (if your machine needs it)
/dev/sdb2    - swap

DO NOT REBOOT after the installer completes!
4. Install bcache on the new installation
Using a chroot we install bcache-tools on the new installation.
Setup the environment and enable DNS resolution
sudo mount /dev/bcache0 /mnt
sudo mount /dev/sda1 /mnt/boot
sudo mount --bind /dev /mnt/dev
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys

For Ubuntu 17.10 or newer you also need to copy over the resolv.conf file
so DNS resolution works within the chroot environment.
sudo mv /mnt/etc/resolv.conf /mnt/etc/resolv.conf.backup
sudo cp /etc/resolv.conf /mnt/etc/resolv.conf

Enter into the chroot and do the installation
sudo chroot /mnt
sudo apt-get update
sudo apt-get install bcache-tools

During the installation you should notice the initramfs is re-generated and installed to the (chroot-ed) /boot partition.
5. Cleanup
Cleanly dismount the filesystem and reboot.
exit
sudo mv /mnt/etc/resolv.conf.backup /mnt/etc/resolv.conf # for 17.10+ only
sudo umount /mnt/sys
sudo umount /mnt/proc
sudo umount /mnt/dev
sudo umount /mnt/boot
sudo umount /mnt
sudo reboot

Comment: Five years later and this still works well. Thanks @bklppenborg for updating the instructions for 20.04: https://www.kloppenborg.net/blog/2020/05/22/installing-ubuntu-20-04-with-bcache
Comment: Thanks for the reminder about this post. I updated it to include the resolv.conf instructions for Ubuntu 17.10+.
Answer: After some trial and error I've arrived at the following solution for a clean install:

Partition the HDD the way you like (assuming /dev/sdb2 is the space you want for your /home).
# apt-get install bcache-tools
# make-bcache -B /dev/sdb2 -C /dev/sda2  (This creates /dev/bcache0, but the UI installer can't use it yet.)
# mkfs.ext4 /dev/bcache0  (This makes the installer see a "partition /dev/bcache0" under "device /dev/bcache0" and allows you to use it as "/home" during installation.)
Run the installer as usual, be sure to select advanced disk partition options.
The installer creates initrd image with the bcache kernel module included and loaded due to that we've installed bcache-tools earlier, so after reboot it just works.
After booting the installed system, install bcache-tools once again, so that further updates don't cripple the boot process by omitting the necessary bcache kernel module from initrd image.
Comment: I went without bcache in the end because I needed cacheing for both Ubuntu and Windows in a double-boot configuration plus I access my drives from another system as well. So I decided cacheing is just not suitable for this PC. Thanks for your help anyway.
Answer: I too tried and failed many times till I found these instructions:
http://www.wdong.org/wordpress/blog/2014/05/28/installing-ubuntu-14-04-to-bcache/
They sound somewhat hairy but this is probably the only feasible way to get bcache going, at least until bcache becomes part of the ubuntu installer.
The only curious omission in the instructions is the very last stage.
After you've done everything, look up the UUID of the cache set in /sys/fs/bcache and do this:
echo <UUID> > /sys/block/bcache0/bcache/attach

If you'd like to enable writeback mode (which I'd strongly recommend):
echo writeback > /sys/block/bcache0/bcache/cache_mode

catting various files in /sys/block/bcache0/bcache/ will tell you all about how the cache is running. I set up my system using these instructions on July 26th this year and everything is running perfectly since. cat /sys/block/bcache0/bcache/stats_total/cache_hit_ratio shows a highly satisfactory 88 per cent and subjectively, the machine feels like an all-SSD setup.

How to setup bcache?


Is there a way to get both Sneaky Bastard aced and Bulletproof aced?

Question: I'm having trouble finding the points, especially since I'm not currently infamied enough to have point requirements lowered. Thanks in advance.
Comment: I haven't played in a while so I forget the point requirements for top-tier skills, but you should have 120 skill points at level 100. Is it 52 skill points minimum to ace a top tier skill? If so you can clear 2 paths, but you'll only have 18 skill points spare. Infamy cost reductions allow you to build more optimally (i.e. not waste as many points as a prerequisite to take the skills you want).
Comment: Thanks, I'll keep this in mind. If I have enough points like you say then I should be able to figure it out.
Comment: You could ace both if you wanted, but I wouldn't recommend it. Have you considered an Enforcer/Fugitive build instead? Technician/Fugitive is a niche build involving an LBV Crook or Grinder, but it's not very effective.
Answer: It's all going to depend on your own level, but it is possible.  If you're level 100 (and not infamous) I believe you should be able to get it, however it was a long time ago when I wasn't infamous.
Here is an example of what you can do to get there, please note this isn't optimal, as it doens't take into account a lot of soft skills (ones that you should pretty much always have), but it'll give you an idea:
Technical Tree

Unlocking The Technician - Basic
Demolition Man - Basic
Rifleman - Aced
Sharpshooter - Aced
Combat Engineer - Basic
Hardware Expert - Aced
Drill Sergeant - Aced
Sentry Gun - Basic
Jack of All Trades - Aced
Shaped Charge - Aced
Bulletproof - Aced

Fugitive Tree

Unlocking the Fugitive - Basic
Daredevil - Aced
Thick Skin - Aced
Duck and Cover - Aced
Run and Gun - Aced
Quick Fix - Aced
Uppers - Aced
Low Blow - Aced
Sneaky Bastard - Aced

I created this uysing PD2Skills:
http://pd2skills.com/#/v3/tSOLhJEGBcDa:fROMJEGBDa:::
From a personal stand point, I don't think you'd really want Bulletproof & Sneaky Bastard, as with Dodge you want to maximise your dodge with Mastermind / Ghost skills, as with max dodge you won't get hit a lot.
Comment: Thanks, I'll probably use this guide. I know it's not the most effective build but I like trying weird stuff.
Comment: No problem. If its helped please mark this as answer, then it will close the thread off.


android app craches after adding spinner

Question: I've added a spinner to my android app and when I run my app in the emulator it crashes.  Prior to that it ran fine.  Here is my code for the spinner...
This is in my class...
public void populateSpinners(){
    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.planets_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    return;
}

This is in my string.xml...
<string name="planet_prompt">Choose a planet</string>
<string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>

This is code I "borrowed" from here...
http://developer.android.com/resources/tutorials/views/hello-spinner.html
I added a break point after the spinner was initilazed and ran the app in debug mode.  The debugger runs fine and reaches the breakpoint with no errors.  However after the breakpoint, the debugger freezes and shows this...
myapp [Android Application]
myapp [Android Application]
    DalvikVM[localhost:8615]
        Thread [<1> main] (Suspended (exception Resources$NotFoundException))
            Resources.loadXmlResourceParser(int, String) line: 1877
            Resources.getLayout(int) line: 731
            PhoneLayoutInflater(LayoutInflater).inflate(int, ViewGroup, boolean) line: 318
            ArrayAdapter.createViewFromResource(int, View, ViewGroup, int) line: 332
            ArrayAdapter.getView(int, View, ViewGroup) line: 323
            Spinner(AbsSpinner).onMeasure(int, int) line: 192
            Spinner(View).measure(int, int) line: 8171
            TableRow.getColumnsWidths(int) line: 308
            TableLayout.findLargestCells(int) line: 497
            TableLayout.measureVertical(int, int) line: 462
            TableLayout.onMeasure(int, int) line: 428
            TableLayout(View).measure(int, int) line: 8171
            LinearLayout(ViewGroup).measureChildWithMargins(View, int, int, int, int) line: 3132
            LinearLayout.measureChildBeforeLayout(View, int, int, int, int, int) line: 1012
            LinearLayout.measureVertical(int, int) line: 381
            LinearLayout.onMeasure(int, int) line: 304
            LinearLayout(View).measure(int, int) line: 8171
            FrameLayout(ViewGroup).measureChildWithMargins(View, int, int, int, int) line: 3132
            FrameLayout.onMeasure(int, int) line: 245
            FrameLayout(View).measure(int, int) line: 8171
            LinearLayout.measureVertical(int, int) line: 526
            LinearLayout.onMeasure(int, int) line: 304
            LinearLayout(View).measure(int, int) line: 8171
            PhoneWindow$DecorView(ViewGroup).measureChildWithMargins(View, int, int, int, int) line: 3132
            PhoneWindow$DecorView(FrameLayout).onMeasure(int, int) line: 245
            PhoneWindow$DecorView(View).measure(int, int) line: 8171
            ViewRoot.performTraversals() line: 801
            ViewRoot.handleMessage(Message) line: 1727
            ViewRoot(Handler).dispatchMessage(Message) line: 99
            Looper.loop() line: 123
            ActivityThread.main(String[]) line: 4627
            Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
            Method.invoke(Object, Object...) line: 521
            ZygoteInit$MethodAndArgsCaller.run() line: 868
            ZygoteInit.main(String[]) line: 626
            NativeStart.main(String[]) line: not available [native method]
        Thread [<6> Binder Thread #2] (Running)
        Thread [<5> Binder Thread #1] (Running)

And I see this....

I read that it means I'm missing the Android source.  Is this correct?  Why do I need the Android source?  Isn't the Android SDK enough?  Or is there some other problem?  I'm new to Java/Android (been programming for about a week now) and I've been muddling my way through things so please excuse me if this is a "noob" question. :D  Thanks!
Here are the parts of my DDMS that show the error that is occurring...
07-04 16:57:19.063: DEBUG/dalvikvm(134): GC_EXPLICIT freed 4275 objects / 210048 bytes in 124ms
07-04 16:57:23.311: DEBUG/AndroidRuntime(309): Shutting down VM
07-04 16:57:23.311: WARN/dalvikvm(309): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
07-04 16:57:23.651: ERROR/AndroidRuntime(309): FATAL EXCEPTION: main
07-04 16:57:23.651: ERROR/AndroidRuntime(309): android.content.res.Resources$NotFoundException: File res/layout/simple_spinner_item.xml from xml type layout resource ID #0x1090008
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.content.res.Resources.loadXmlResourceParser(Resources.java:1916)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.content.res.Resources.loadXmlResourceParser(Resources.java:1871)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.content.res.Resources.getLayout(Resources.java:731)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.LayoutInflater.inflate(LayoutInflater.java:318)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:332)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.ArrayAdapter.getView(ArrayAdapter.java:323)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:192)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.TableRow.getColumnsWidths(TableRow.java:308)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.TableLayout.findLargestCells(TableLayout.java:497)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.TableLayout.measureVertical(TableLayout.java:462)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.TableLayout.onMeasure(TableLayout.java:428)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1012)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:381)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.View.measure(View.java:8171)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.os.Looper.loop(Looper.java:123)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.app.ActivityThread.main(ActivityThread.java:4627)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at java.lang.reflect.Method.invokeNative(Native Method)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at java.lang.reflect.Method.invoke(Method.java:521)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at dalvik.system.NativeStart.main(Native Method)
07-04 16:57:23.651: ERROR/AndroidRuntime(309): Caused by: java.lang.RuntimeException: Assetmanager has been closed
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.content.res.AssetManager.openXmlBlockAsset(AssetManager.java:483)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     at android.content.res.Resources.loadXmlResourceParser(Resources.java:1898)
07-04 16:57:23.651: ERROR/AndroidRuntime(309):     ... 36 more
07-04 16:57:23.912: WARN/ActivityManager(58):   Force finishing activity com.newapp.practice.app/.myappActivity
07-04 16:57:24.461: WARN/ActivityManager(58): Activity pause timeout for HistoryRecord{44f86260 com.newapp.practice.app/.myappActivity}
07-04 16:57:31.261: DEBUG/dalvikvm(187): GC_EXPLICIT freed 110 objects / 4680 bytes in 117ms
07-04 16:57:36.003: WARN/ActivityManager(58): Activity destroy timeout for HistoryRecord{44f86260 com.newapp.practice.app/.myappActivity}
07-04 16:57:36.422: DEBUG/dalvikvm(261): GC_EXPLICIT freed 755 objects / 54824 bytes in 209ms

Answer: Eclipse tries to access the Android source in order to help you debug the crash. There are some instructions online to attach the source to Eclipse, but they're quite long-winded, and best left as an exercise for elsewhere (I used http://android.opensourceror.org/2010/01/18/android-source/ at some point).
If you'd like some help with the crash itself, can you paste the stacktrace from DDMS? (With the breakpoints disabled).
Comment: Thanks for the reply.  The contents of the logCat of DDMS were HUGE sot I only included the parts that occurred when the error occurred.  It seems that I'm missing something in my XML layout.  Still trying to figure out what
Comment: I noticed that there is a line that says caused by: java.lang.RuntimeException: Assetmanager has been closed.  In a function I run prior to the populateSpinner function I open an Assetmanager and then close it.  If I don't close the Assetmanager my program never crashes.  Obviously I need to leave the Assetmanager open.  But why is this?  I though I was supposed to declare a class of Assetmanager when I needed it and then close it, right?
Comment: Frankly, I'm not too sure about the Asset manager stuff. But I'm wondering: what scope is the populateSpinners() function in? Is the `this` in `ArrayAdapter.createFromResource()` still going to be the activity context as it is in the source link?


How to add a list of integers into in a table in sqlite3

Question: I am writing a database which will be used for a game. So in this database I have a PLAYERS table which contains some information regarding the players of the game. For one of the columns of this table, I need to have a list which will contain the integers (IDs) of players which are friend with the current player. (like a friend list)
The problem is that first the size of this list is not defined and will change (by adding or removing a friend) and the second problem is that sqlite3 only lets use the primary values like INT, TEXT, etc.
So my question is that how I could add such column in my table and modify it accordingly ( meaning that adding or removing contents from it)?
I know by searching that I could add a second table and use it by I don't really know how to that and I would be appreciate it if someone could help and guide me throw it.
Here is some code:
  std::string sql = "CREATE TABLE IF NOT EXISTS PLAYERS("
                    "ID INTEGER PRIMARY KEY AUTOINCREMENT, "
                    "USERNAME               TEXT NOT NULL UNIQUE, "
                    "PASSWORD               TEXT NOT NULL, "
                    "SCORE                  REAL NOT NULL  );";
  // here I want to add the column that I am talking about with name of FRIENDS which contains the ID (a list of integers) of the other players
  int ret = 0;
  char* errMsg;

  ret = sqlite3_exec(DB, sql.c_str(), nullptr, 0, &errMsg);
  if (ret != SQLITE_OK) {
    std::cerr << "Table creation error: " << sqlite3_errmsg(DB) << std::endl;
    sqlite3_free(errMsg);
    return false;
  } else {
    std::cout << "Table created successfully." << std::endl;
  }

  std::ostringstream osql;
  osql << "INSERT INTO PLAYERS (USERNAME, PASSWORD, SCORE) VALUES('" << "mra" << "', '" << "12456" << "', " << 20.2 << ");";
  std::string sql = osql.str();

  int ret = 0;
  char* errMsg;

  ret = sqlite3_exec(DB, sql.c_str(), nullptr, 0, &errMsg);
  if (ret != SQLITE_OK) {
    std::cerr << "Insertion error: " << sqlite3_errmsg(DB) << std::endl;
    sqlite3_free(errMsg);
    return false;
  } else {
    std::cout << "Insertion was successfull." << std::endl;
  }

Thank you in advanced for your help.
Answer: What you are describing is a many-to-many relationship between Players. A junction table better serves this purpose than a column of a list of friends.
The junction table can have a structure like this:
| Player1 | Player2 |
| 1       | 2       |
| 1       | 3       |

With a CHECK constraint you can enforce Player1 < Player2 so that you eliminate the possibility of duplicate friendship relationships.
The sql to create such a table (FRIENDS) will be:
CREATE TABLE "FRIENDS" (
    "PLAYER1"   INTEGER,
    "PLAYER2"   INTEGER,
    CHECK(PLAYER1<PLAYER2),
    FOREIGN KEY("PLAYER1") REFERENCES "PLAYERS"("ID") ON DELETE CASCADE,
    PRIMARY KEY("PLAYER1","PLAYER2"),
    FOREIGN KEY("PLAYER2") REFERENCES "PLAYERS"("ID") ON DELETE CASCADE
);

ON DELETE CASCADE ensures that when a primary key in the PLAYERS table related rows in the FRIENDS table are deleted too.
So you just have to query the FRIENDS table to get a player's friends.
Comment: @DavidVasconcelos No, I did intend on `PLAYER1 < PLAYER2` so that there is only 1 variant of a pairing: 1,3 but not 3,1 for example.
Comment: @Mohammadreza To get all the friends for a particular persion (e.g. id=2) you can do a select union: `select PLAYER1 from FRIENDS where PLAYER2=2 union select PLAYER2 from FRIENDS where PLAYER1 = 2;`
Comment: @Mohammadreza Then extend the select to get username using the ids: `select USERNAME from PLAYERS where id in
(select PLAYER1 from FRIENDS where PLAYER2=2 union select PLAYER2 from FRIENDS where PLAYER1 = 2);`
Comment: Did you intend `CHECK(PLAYER1 <> PLAYER2)`?
Comment: Thank you for your answer. Could I also know how to add or delete some data in this table? For example what do I have to do if I wanted to make ID 1 and ID 2 friends?
Comment: Also I would like to know how I could search in this table? Thank you so much
Comment: @Mohammadreza To insert just do `INSERT INTO FRIENDS (PLAYER1, PLAYER2) VALUES(2,3);` Make sure Player1 < Player2.
Comment: @jignatius but my problem is that the select union gives me the id of each friend. i want to get username of the friend. So how can I get the username from the id obtained by the code that you gave in your reply? Thank you again for your response


jQuery event handlers - memory usage

Question: I've been doing this:
$('#id').on('click',function(e){myFunction(var1,var2);});

function myFunction(x,y){blah blah blah}

I'm wanting to change to this:
$('#id').on('click',function(e){blah blah blah});

If I do this with lots of different DOM elements, am I consuming more memory space because I'm multiplying the space taken up by myFunction with each closure? Or does it just use a pointer?
Comment: darn typo, i meant "how"
Comment: @Joseph - I see! :)  It's done by AJAX when a new DOM element is created. Each element of a certain type (and class, for that matter) has the handler attached on creation. I'm now wondering whether I can just attach a handler to the class, although I think it needs the element-specific variables present at the time of creation in the function that is making the closure.
Answer: The first code has the advantage of reuse, but has the disadvantage of defining an anonymous function just to call the real function. If it really matters, then the extra function is an overhead.
The second one will take much less memory since you are passing only one function. Functions are also passed by reference. Meaning this function could be stored once and called by many different callers.

However, the way you attach it also affects performance. If you do it like this:
$('#id1').on('click',function(e){myFunction(var1,var2);});
$('#id2').on('click',function(e){myFunction(var1,var2);});

this one calls jQuery 4 times (2 $() and 2 on()), creates 2 anonymous functions and calls an external function twice. count: 6 calls, 3 functions just to execute your operation (not including internal jQuery calls).
$('#id1').on('click',function(e){blah blah blah});
$('#id2').on('click',function(e){blah blah blah});

if you do it this way, the function isn't reusable anymore but you got 4 calls to jQuery, 2 functions but you are repeating the code. not good from a DRY perspective.
$('#id1, #id2').on('click',function(e){blah blah blah});

this one, you have 2 calls, and 1 function. this one is better.
$('#id1, #id2').on('click',function(e){myFunction(var1,var2);});

you could also do it this way, the function is reusable with a sacrifice of an additional anonymous function and call. count: 3 calls, 2 functions.

You could harness the power of .on by attaching the handler to the "nearest common parent", nearest so that the bubble won't travel up very far. in comparison, live() attaches events to the document, making handlers available even to new elements. But attaching to the document makes it very far for deeply nested elements.
$('nearest_common_parent').on('click','dynamic_element',function(){
    //do stuff
});

Answer: I believe your second method is correct by convention. Especially, since with the first, you lose access to $(this)
You'd have to pass it in as a var
$('#test').on('click', function(e) {myFunction($(this), e, other_vars)});

VS
$('test').on('click', function(e) {
  e.preventDefault();
  var $this = $(this);
  //yadda yadda
});

It really also makes your code more readable. I know I'm not answering the actual question, but I think these are some valid reasons to write your functions right in.
Answer: Joseph's answer is an excellent explanation when primarily using ids. But if you're classes or tag names for you selectors, you would do better to leverage the selector parameter of the on function. Example:
  $('#page-wrap').on('hover', 'a', function() {
    // do something
  });

That creates only one binding to #page-wrap element but will be fired on any a elements inside of it. Its better in terms of memory usage and setup speed, especially if you're binding to a lot of elements.

jQuery event handlers - memory usage