January 23, 2012

Passing arguments to a HMVC Module method using an array

Question by joomlearner

While using the HMVC Component in Codeignitors, we can render a particular actions like this

echo modules::run('site/news/view', 1);

Here the 1 is the parameter send to the view method.

Now I have an array of parameters, which i need to pass to the function

$params = array(1, "latest", "desc"); //suppose this are the parameters I received dynamically some how and dont knows its length

Now, I need to send these parameters seperately as

echo modules::run('site/news/view', 1, "latest", "desc");

Like in other functions call_user_func_array() will not work at this case(I think).

Answer by Starx

Well, its not possible to make an existing function work the way you need (unless modified). You should code, the way THE FUNCTION ALREADY WORKS. If it does not work the way you need, modify the source if allowed, or else write you own version of it, or extend the main class, to fit your needs.

I could answer this question easy, but this time I will want you to do the same. I have answered your question before & just viewed your profile, 6 Questions (1 accepted) 0 answers and on most of the questions no input from your side. You don’t seem to do anything on your own.

You relying on this community to get your job done, which is so unfair. So UNLESS you show me some of your work, I refuse to answer.

January 21, 2012

.htaccess for either redirecting to subdomain or applying certain rules

Question by mrN

I am hosting a zend framework project on a subdomain. Lets say, project.mydomain.com. This domain however can be accessed from mydomain.com/project as well. Now, to avoid the complexity of having to maintain two different cases, I am trying to minimize the complexity by redirecting the directly accessed path to the subdomain, i.e.

mydomain.com/project > project.mydomain.com

but, if the same direcoty is accessed using subdomain, then i want some rules to be applied to it as well.

Here is my currect .htaccess which is allowing me to use direct path i.e mydomain.com/project/

RewriteEngine On

# Exclude some directories from URI rewriting
#RewriteRule ^(dir1|dir2|dir3) - [L]

RewriteRule ^.htaccess$ - [F]

RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ /projects/myproject.com/public/index.php [NC,L]

RewriteCond %{REQUEST_URI} !^/public/.*$
RewriteRule ^(.*)$ /projects/myproject.com/public/$1

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]

RewriteRule ^public/.*$ /projects/myproject.com/public/index.php [NC,L]

Next, I will write a .htaccess for subdomain only. But, I want the directly accessed path to be redirected to the subdomain. How to do this redirection through .htaccess?

Please note, redirecting through a php file is not a option.

Answer by Starx

Robin, it looks like you are trying to redirect the path mydomain.com/projects to projects.mydomain.com. So, I dont think this is going to be combined .htaccess. As you would need, pretty much everything from /projects/your-anotherproject to has to be redirected to projects.mydomain.com/your-anotherproject. Rewriting htaccess for every projects is a BAD idea.

If this is the case, then i suggest having a simple .htaccess on projects/ root instead

RewriteEngine On
RedirectMatch 301 ^/projects/(.*)$ http://projects.mydomain.com/$1

This will solve you all cases, for all subdirectory, on that subdomain. Now write your project specific .htaccess in the project’s root, like you are doing above

January 17, 2012

What is the return type of a constructor in java?

Question by sonu thomas

As we know the we do not have to add any return type to a Java constructor.

class Sample{
  .....
  Sample(){
    ........
  }
}

In Objective C, if we create a constructor, it returns a pointer to its class. But it is not compulsory, I think.

AClass *anObject = [[AClass alloc] init];//init is the constructor with return type a pointer to AClass

Similarly, Is the constructor converted to a method which return a reference to its own class??

Like this:

class Sample{
    .....
    Sample Sample(){
      ........

      return this;
    }
}

Does the compiler add a return type a reference to same class to constructor?
What is happening to a constructor?
Any reference to study this?

EDIT:

Actually i want the answers to be at byte code level or JVM level or even below.

Answer by Peter Lawrey

Many have answered how constructors are define in Java.

At the JVM level, static initialisers and constructors are methods which return void. static initialisers are static methods, however constructors use this and don’t need to return anything. This is because the caller is responsible for creating the object (not the constructor)

If you try to only create an object in byte code without calling a constructor you get a VerifyError. However on the oracle JVM you can use Unsafe.allocateInstance() to create an object without calling a constructor,

The static initialiser is called <cinit> which takes no arguments and and the constructor is called <init>. Both have a void return type.

For the most part this is hidden from the Java developer (unless they are generating byte code) however the only time you see these “methods” in stack traces (though you can’t see a return type)

Answer by Starx

Is the constructor converted to a method which return a reference to its own class??

No but yes, if it is specified to do so.

Does compiler add a return type a reference to same class to constructor ??

No it does not

What is happening to a constructor??

It is the method, which runs when the object is created. Typically, by using “new” keyword. It Might perform some preliminary task, or return something or assign some values during construction.

Any reference to study this.??

January 14, 2012

Better way to select a child menu item selector in CSS

Question by CodeDevelopr

I found this amazing resource http://gtmetrix.com/ that you supply a URL to a website and it gives you a performance report and gives you estimates on what you can save by compressing and optimizing different things.

It even does most of it for you, it optimized all my images, css, and javascript files, showed me css that is not being used on the current page, it also shows a list of non-efficient CSS selectors and shows the selector and the line number it is on in your css file.

Here is one of the results for me that I use for a navigation menu

ul#menu-navigation li>ul li a Tag key with 3 descendant selectors and ID overly qualified with tag
ul#menu-navigation li>ul li a:hover Tag key with 3 descendant selectors and ID overly qualified with tag

So my question is, is there a better way to do a UL list menu that has sub-menus items?

Answer by Mohamed Meligy

First, you don’t need the ul before the ID, because the ID is unique enough, but it’s arguable for readability for you, etc..

Of course also you can remove the >ul, but I assume you added it consciously to be specific, and in CSS, it’s “safer” (while “better” is arguable) to be more specific than generic.

Then, assuming you don’t change your markup (with extra class or so), I think this is the right way. There is redundancy and such I completely agree. This is an inherited problem in CSS. You can’t solve it with CSS itself. You live with it, or you look for something that doesn’t have the problem to generate CSS for you.

In my current project, I’m using LESS CSS, this is a syntax very similar to CSS, and generates actual CSS files via a command prompt (or a Visual Studio extension called, well, LessExtension, which generates on save). There is also JS file for generation in the browser.

Check it out. I bet you’ll like it. You can take your CSS file as is, and start adding benefits.

http://lesscss.org

You selectors in LESS would be:

#menu-navigation {
    li>ul li a {
        /* some Anchor styles */

        &:hover {
            /* some Anchor hover styles */
        }
    }
}

Of course you can also have middle nesting levels as well. Here I did all li>ul li a one selector instead of multiple nesting levels for simplicity, but normally I’d make each of them a nesting level.

Answer by Starx

Since your css is for the anchor tag. Your selector can be brought down to

  1. Generalised Anhor #menu-navigation li a
  2. Speciliazed Anchor inside list #menu-navigation li > ul li a
January 13, 2012

Hide all elements except one div and its child element

Question by ANP

How to hide all elements except one div and its child element using jquery?

Answer by Orbling

Ignore that, does not appear to have the desired effect.

Perhaps the following?

$('body').children().hide();
$('#mydiv').children().andSelf().show();

Update

The problem is, the visible state of a child DIV often relies on it’s parent being visible. So you need to have an entire tree down to the DIV you want remaining visible.

You need to hide everything apart from that tree, the trick is identifying all children of the DOM structure that are not in the DIV ancestry, and all siblings of the ones that are.

Finally!

Managed to write a solution. Tried a recursive approach at first, but on complicated pages it died with “too much recursion”, so wrote a list-based version that works just fine. It is in the form of a single-function jQuery plugin, as that seems to be the most useful approach.

(function($) {
    $.fn.allBut = function(context) {
        var target = this;
        var otherList = $();
        var processList = $(context || 'body').children();

        while (processList.size() > 0) {
            var cElem = processList.first();
            processList = processList.slice(1);

            if (cElem.filter(target).size() != target.size()) {
                if (cElem.has(target).size() > 0) {
                    processList = processList.add(cElem.children());
                } else {
                    otherList = otherList.add(cElem);
                }
            }
        }

        return otherList;
    }
})(jQuery);

This routine finds all elements within the context (which defaults to <body>) that exclude the object and it’s ancestors.

This would achieve the result of the question:

$('#mydiv').allBut().hide();

Another use could be to retain all objects within a container with a certain class, fading out all the others:

$('.keep').allBut('#container').fadeOut();

Bare in mind that the layout and positioning of any given element can depend heavily on surrounding elements, so hiding something like that is likely to alter the layout unless things are absolutely positioned. I can see uses for the routine anyhow.

However!

Another poster came up with the following which returns the same information using a routine already built-in to jQuery which I had not seen.

target.add(target.parentsUntil(context)).siblings();

or without the variable

target.parentsUntil(context).andSelf().siblings();

Which is a tad simpler, must scour documentation in future.

PS. If anyone has a better way of checking if a given jQuery object is equivalent to another than a.filter(b).size() != b.size() I would be very glad to hear it!

Answer by Starx

This will do $(".mydivclass").not(this).hide();

mydivclass is the class given to all the divs that needs to be hidden

Update:

$(".mydivclass").children().hide();

will hide all the children element inside .mydivclass

January 12, 2012

My Future

Out of the blue.. sometime the thoughts of my future haunts me & I end up shaking…..

Most of the people I see around me are less complicated. They take this life the easy way…. But  then again it is only through my eye. After all, who can really see through a person? Right?

I am a simple person… with simple needs.

SIMPLE! Really?

Who am i kidding too? Myself? LOL…

Desires… is the only thing that affects one life..

It changes the course of your life

  • Your ambition
  • Your aim
  • Your career
  • Your Business
  • Your academic career
  • Your future
  • Your Girl/Boyfriend
  • Your Wife/husband
  • or even love of your life

If somebody doesn’t have desire!!.. they might as well drop whatever that they are doing… and start being jogi or sadhu or saint or vicchu.. whatever suits there personality.

How many desires you have? Just count ’em… big house, good business, happy family, ferrari (this is mine :P)  and the list goes on and on…

BUT

No matter to what they are or how many they are… the important thing that comes at last in MONEY.

Don’t lie to yourself… if you have desires… you cannot forget MONEY… because believe it or not.. it is probably the Greatest Resource and the Biggest Obstacle.. that you will always encounter unless either you are dead or have no desires left.

SO, here is the big equation of the day
future ∝ desire ∝ money

After such a long nonsense, lets me start talking about my future, now

My future… Oh Boy……
………
…..

What is going to happen to me? Where am i going to end up in the next five years?

Will i become important to somebody?

  • to some company?
  • to some field?
  • to some society?
  • to my family?

or, I will end up being the trash in the dustbin of this world.

What will i become?..

  • rich?
  • poor?
  • famous?
  • infamous?
  • rich & infamous?
  • be poor & famous?

or just mad?

What will be my biggest ambition then? 

  • Survival?….
  • Success?…
  • Responsibility

or will i be trying to escape?

What will happen to my career? Will i

  • reach the top position? …
  • still be truggling on

or Dumped on the pit bottom?

What will happen to my role as a family member? 

  • be respected?
  • be loved?

… or just a big burden?

What will happen to my studies? 

  • onto PhD?
  • or a FULL STOP at undergrad…

or a big stuck up on undergrad? beats me 😉

Study! where will i be studying? 

  • nepal?
  • or abroad?

or, my study ship would have set sails long ago. ha ha 😀

How will i  be then? 

  • happy?
  • sad?
  • settled?
  • hopeless?
  • satisfied?

or just frustrated?

Will I find the love of my life by then? 

  • or will she find me?
  • or still be searching?
  • or end of with another broken heart? 🙁

or just another “FOREVER ALONE” troll

So many questions…. race through my mind in a flash that i cannot even stop for a sec to think it twice and calm my self down.

:: The pressures ::
:: The responsibilities ::
:: The ambitions ::
I have

will not even take a second to change to

The TENSION..

and i end up breathing a heavy cold breath….

In the end 
my future is terrorizing threat rather than EXCITEMENT
January 6, 2012

How to get the action performed by an hyperlink in javascript

Question by Ramesh

How can i get the action performed by an hyperlink inside an div using javascript

<div id="example">
<a href="#">a<a>
<a href="#">b</a>
<a href="#">c</a>
</div>

Answer by Headshota

var links = document.getElementById('example').getElementsByTagName('a');

links[0].onclick = function(){
  alert('a clicked');
}

links[1].onclick = function(){
  alert('b clicked');
}

links[2].onclick = function(){
  alert('c clicked');
}

Working Example

you can attach event handlers in the loop as well:

var links = document.getElementById('example').getElementsByTagName('a');
    for(var i = 0;i < links.length; i++){
        links[i].onclick = function(e){
            var event = e || window.event;                    
            alert(e.target.innerHTML + ' link was clicked!!!');
        }
}

Answer by Starx

I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.

<a href="mypage.html"> Goes to a mypage.html </a>

Where As what you are asking by action performed is events. For that you should do something like this

<a href="#" onclick="test();">Test Link </a>

What this above link does is, executes a javascript function name test();

function test() {
    alert('ok the action is performed'); 
    return false; //so that the browser does not decides to navigate after the function is executed
}

Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery

$("#example a">.click(function() {
   //now you have got the action performed work around. 
   // You can use this as you like
   // $this represent the item that was clicked
});

For this functionality in core. @Headshota answers is good example.

January 3, 2012

How to get Controller, Action, URL informations with CodeIgniter

Question by noname.cs

I have these urls:

How to get controller name, action name from these urls. I’m codeigniter newbie. Are there any helper function to get this info

Ex:

$params = helper_function( current_url() )

Where $params becomes something like

array (
  'controller' => 'system/settings', 
  'action' => 'edit', 
  '...'=>'...'
)

Answer by Jonathan Sampson

You could use the URI Class:

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

I’ve also been told that the following work, but am currently unable to test:

$this->router->fetch_class();
$this->router->fetch_method();

Answer by Starx

As an addition

$this -> router -> fetch_module(); //Module Name if you are using HMVC Component
January 2, 2012

"var_dump" functions

Question by Joseph the Dreamer

by the function name itself, var_dump() dumps everything about a provided parameter EXCEPT the functions of an object.

is there a way of dumping out these functions?

Answer by zerkms

You cannot get the object’s methods, but you can get the class methods:

var_dump(get_class_methods('classname'));

or

var_dump(get_class_methods(get_class($object)));

Answer by Starx

You can use ReflectionClass API too

An Example:

$cls = new ReflectionClass("classname");
var_dump($cls -> getMethods());
January 1, 2012

Set php session via ajax

Question by ShadowBroker

I’m trying to build my ajax login system but i’m having some problems with php sessions.

This is the ajax code i use in my index.php:

    $("#buttonLogin").click(function(){
        $.post("<?php echo $AJAX ?>/ajaxLogin.php",{
            Username : $("#loginUsername").val(),
            Password : $("#loginPassword").val()
        }, 
        function(result){
            if(result == "OK"){
                window.location.href = "<?php echo $PUBLIC?>/home.php";
            } else {
                $("#loginMessageError").show();
            }
        });
    });

And this is the ajaxLogin.php that is called via ajax

<?php
require_once("../settings.php");
require_once($ABS_ENGINE."/classUser.php");

$user = new User();
if($user->loginUser($_POST["Username"], $_POST["Password"])){
    $UserID = $user->getUserId($_POST["Username"]);
    session_start();
    $_SESSION['UserID'] = $UserID;
    echo "OK";
} else {
    echo "ERROR";
}
?>

When i’m in home.php and i try to echo $_SESSION[“UserID”] i get the following error:

Notice: Undefined index: UserID in C:xampphtdocswebnameresourcestemplatesheaderHome.php on line 23

Probably this is not correct because session must be set before any output but if i try to echo $_SESSION['UserID'] = $UserID; line it’s session variable is correctly displayed.

Answer by Starx

Better check if session_start() is present in home.php. Without this you will not be able to read the session data.

When you are doing echo $_SESSION['UserID'] = $UserID; you will assigning and accessing at a same line, so it will obviously work.

...

Please fill the form - I will response as fast as I can!