...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
October 27, 2012

Custom Number format and images in between

Question by Maarten Hartman

I’d like to format a number(stored as 10000.23, or 1.23) with php, , and place images between them, like the following.

10000,23

becomes

[img1]100[img2]00[img3]10

and

1,10

becomes

[img1]0[img2]1[img3]10

Anyone knows how to do this?

I tried several number formats but none of them allowed me to separate the last 4 digits into two pairs ( 00.00.00 )

Answer by Starx

Looks as if you want currency Format and replace the quotation marks with images. Here is a small function to add commas on the number.

function cFormat($number) {
    while (true) {
        $replaced = preg_replace('/(-?d+)(ddd)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}

Then, here is how to replace them with images.

$int = 10000.23;
$int = cFormat($int);

// After adding comma, use str_replace() to replace comma with images
$int = str_replace(",", "<img src="comma.jpg" />", $int);
$int = str_replace(".", "<img src="period.jpg" />", $int);
Read more

how to get integer value from textfield and retrieve the value to another class in java

Question by user1778569

How to get integer value from textfield and retrieve the value to another class in java ??

I know how to get but if i used in another class he get me 0 value,,,

“this is in the GUI” x1,x2,y1,y2 predefined

private void X2_accesActionPerformed(java.awt.event.ActionEvent evt){              
     x2=(int)(Double.parseDouble(X2_acces.getText())); 
}

I want to draw line the user inter 2 point (x1,y1) and (x2,y2) after that move the value to class draw line

“this is in class drawLine”

Next_frame nf=new Next_frame();
Point2D.Double p2=new Point2D.Double(nf.x2,nf.y2);

Answer by Starx

The following statement is quite ambigous.

x2=(int)(Double.parseDouble(X2_acces.getText())); 

You are parsing the value as Double and casting it down to int. This is enough:

x2 = Integer.parseInt(x2_acces.getTest());

Now, when passing this value to another class, you have to make sure, that the method to which you are passing to accept the data type you are about to send.

For example:

For a class like this:

class DummyClass {
   public DummyClass(int X) {
      //Here note that 'x' is asking for a integer so you have to provide it with integer
   }
}

Then you have use them in the following order:

x2 = Integer.parseInt(x2_acces.getTest());
DummyClass c = new DummyClass(x2);
Read more
October 26, 2012

Jquery – Creating a general language file to declare defaults for any plugins

Question by denislexic

Like most people, I use a bunch of jquery plugins on my website. From Twitter bootstrap to jquery ui datepicker and so on.

But I need my website to be multilingual, so I created a general language file called english.js , and in that file I want to declare some of the defaults from plugins as well as other language variables.

The problem is that all these plugins have varying structures to declare defaults. I saw a couple of questions already ( jquery – setting plugin defaults?, Globally defining jQuery plugin parameters , jQuery plugin defaults , …). But they are not clear.

STRUCTURE 1

$.fn.ajaxStatus = function (params)
{
    var settings = $.extend(
            {
                defaultLoadingText :"Loading...",
                defaultSavingText  :"Saving...",
                defaultDoneText    :"Done",
                defaultRedirectText:"Redirecting...",
                defaultErrorText   :"Oops! Our bad, something wrong.";
            },$.fn.ajaxStatus.defaults,
            params),
});

STRUCTURE 2

   jQuery.fn.extend({
        shrinker:function (options) {
            var opts = $.extend({
                "moreText":"Read more", 
                "lessText":"hide",
            }, $.fn.shrinker.defaults, options);
   });

THE QUESTION

Without modifying the plugin, is it possible to assign some defaults for the function that will be used every time I use the plugin?
How can I define the language defaults in an external file?

Right now, I have this in my language file, but it feels wrong, is this how you do it?

if ($.fn.ajaxStatus !== undefined) {
    $.fn.ajaxStatus.defaults =
    {
        defaultLoadingText :"Loading2...",
        defaultSavingText  :"Saving2...",
        defaultDoneText    :"Done2",
        defaultRedirectText:"Redirecting2...",
        defaultErrorText   :"Oops! Our bad, something wrong"
    };
}

Thanks in advance for you help.

Answer by Starx

I have done somehow similar to this. But I am not giving the full implementation.

Here is how to do it.

Define your plugins params for language like this:

var options = {
    lang: "np" //your default language
};

Set up your language objects like this

var lang = {
    "en": {
        "var1" : "This is variable one"
    },
    "np": {
        "var1": "यो एउटा भेरियबल हो ।"  //Different text based on language initials
    }
};

Then you can simply create a function to read the value like this

function showVar1() {
    alert(lang[options.lang].var1);
}

[Demo]Its not a plugin based.

Read more
October 24, 2012

Reality about me: Nabin Nepal

Realizing who you are and how you perceive things around you is one of the biggest step you will ever take in life. Like a good job and good academic background, this is also the base upon which you will keep growing up.

 Phisophically I am a realist and behaviorally I am an introvert.

On the remainder of this post, I am going to tell who I really am based on this two topics. I will taking help of few articles already on the internet. Why?  Who will believe what I say? seriously, Who the hell am I?.

I am Nabin Nepal, and I am just a simple guy. If you take your time to read through them, hopefully you will be able to meet me next time without feeling ackward around me. 😉

The realiable Realist

Source: Your iPersonic Type: The Reliable Realist

Reliable Realists like me are down-to-earth and responsible-minded. They are precise, reserved and demanding. Their most prominent quality is reliability and they will always make every effort to keep any promise given. Reliable Realists are more quiet and serious persons, they do not talk a lot but they are good listeners. They sometimes seem reserved and distant to outsiders although they have a great deal of wit and esprit. Their strong points are thoroughness, a marked sense of justice, doggedness and a pragmatic, vigorous and purposeful manner. They do not dither about if something has to be done. They do what is necessary without wasting words.

They not only expect a lot of themself but also of others. Once they have set their mind on something, it is difficult to persuade them otherwise. They do not like to leave anything to chance. Planning means safety to them, as well as order and discipline. They have no problem respecting authorities and hierarchies but do not like to delegate tasks. They are certain that others would not deal with them as conscientiously as they do. In management positions, they are very task-oriented – they make sure that things are well done; however, they do not have a great deal of interest in personal contacts at work.

As a Reliable Realist they belong to the introverted personality types. They don’t appreciate too much commotion around them preferring to work relatively independently of others. They need to give themselves plenty of time to work in peace and deal with their projects thoroughly and intensely. Their ability to concentrate is exceptionally high and if they are interested in something they can truly immerse themselves forgetting everything around them. Very strongly team-oriented professional fields, or employment where their concentration is continuously disturbed, or their work is disrupted, are not really for them. It is just too important to them to complete their projects really well.

One or two colleagues who are on their wavelength or possibly a small group of like-minded colleagues are the most they need. Too many people are stressful to them because the emotionality and irrationality that comes with interpersonal relationships tends to disturb them. They are reserved when revealing themselves, and often have the effect of being aloof. Sometimes, and although it may not be their intention, they even convey the impression of being dismissive to the people around them. The continuous locker room and water cooler banter enervate them more than anything else. For them, work is work, and they feel that private matters don’t really belong there. When they choose their profession, watch out that they are not made to adjust to and interact with others around the clock.

Reliability is their middle name. Whoever hands them a project can rest assured that it will be handled diligently and delivered on time. The thought not to keep a promise or a commitment on time is total horror to them. Therefore, it is important to them to be in an environment providing smooth working conditions where they receive consistent and predictable feedback about their efforts. Clear and definite objectives, and the assurance that the necessary resources for their activities will be available, are a must.

Introverts:

Few years back, I thought myself as I am an introvert with people I don’t know and extrovert around people I know, colleagues, family, friends e.t.c. But as it turns outs this behavior is complete introversion. I am not unaware of the fact that such tendencies are not social, but nevertheless it is very normal behavior.

The common modern perception is that introverts tend to be more reserved and less outspoken in groups. They often take pleasure in solitary activities such as reading, writing, using computers, hiking and fishing. The archetypal artist, writer, sculptor, engineer, composer and inventor are all highly introverted. An introvert is likely to enjoy time spent alone and find less reward in time spent with large groups of people, though he or she may enjoy interactions with close friends. Trust is usually an issue of significance: a virtue of utmost importance to an introvert choosing a worthy companion. They prefer to concentrate on a single activity at a time and like to observe situations before they participate, especially observed in developing children and adolescents.They are more analytical before speaking.Introverts are easily overwhelmed by too much stimulation from social gatherings and engagement, introversion having even been defined by some in terms of a preference for a quiet, more minimally stimulating environment.

Introversion is not seen as being identical to shy or to being a social outcast. Introverts prefer solitary activities over social ones, whereas shy people (who may be extroverts at heart) avoid social encounters out of fear,and the social outcast has little choice in the matter of his or her solitude.

Source: Extraversion and Introversion

Mostly people take introversion in a very wrong way. There are a lot of misunderstanding with the topic of Who are introverts? Below are the a list of myths that the society has regarding introvert people.

Myth #1 – Introverts don’t like to talk.
This is not true. Introverts just don’t talk unless they have something to say. They hate small talk. Get an introvert talking about something they are interested in, and they won’t shut up for days.

Myth #2 – Introverts are shy.
Shyness has nothing to do with being an Introvert. Introverts are not necessarily afraid of people. What they need is a reason to interact. They don’t interact for the sake of interacting. If you want to talk to an Introvert, just start talking. Don’t worry about being polite.

Myth #3 – Introverts are rude.
Introverts often don’t see a reason for beating around the bush with social pleasantries. They want everyone to just be real and honest. Unfortunately, this is not acceptable in most settings, so Introverts can feel a lot of pressure to fit in, which they find exhausting.

Myth #4 – Introverts don’t like people.
On the contrary, Introverts intensely value the few friends they have. They can count their close friends on one hand. If you are lucky enough for an introvert to consider you a friend, you probably have a loyal ally for life. Once you have earned their respect as being a person of substance, you’re in.

Myth #5 – Introverts don’t like to go out in public.
Nonsense. Introverts just don’t like to go out in public FOR AS LONG. They also like to avoid the complications that are involved in public activities. They take in data and experiences very quickly, and as a result, don’t need to be there for long to “get it.” They’re ready to go home, recharge, and process it all. In fact, recharging is absolutely crucial for Introverts.

Myth #6 – Introverts always want to be alone.
Introverts are perfectly comfortable with their own thoughts. They think a lot. They daydream. They like to have problems to work on, puzzles to solve. But they can also get incredibly lonely if they don’t have anyone to share their discoveries with. They crave an authentic and sincere connection with ONE PERSON at a time.

Myth #7 – Introverts are weird.
Introverts are often individualists. They don’t follow the crowd. They’d prefer to be valued for their novel ways of living. They think for themselves and because of that, they often challenge the norm. They don’t make most decisions based on what is popular or trendy.

Myth #8 – Introverts are aloof nerds.
Introverts are people who primarily look inward, paying close attention to their thoughts and emotions. It’s not that they are incapable of paying attention to what is going on around them, it’s just that their inner world is much more stimulating and rewarding to them.

Myth #9 – Introverts don’t know how to relax and have fun.
Introverts typically relax at home or in nature, not in busy public places. Introverts are not thrill seekers and adrenaline junkies. If there is too much talking and noise going on, they shut down. Their brains are too sensitive to the neurotransmitter called Dopamine. Introverts and Extroverts have different dominant neuro-pathways. Just look it up.

Myth #10 – Introverts can fix themselves and become Extroverts.
A world without Introverts would be a world with few scientists, musicians, artists, poets, filmmakers, doctors, mathematicians, writers, and philosophers. That being said, there are still plenty of techniques an Extrovert can learn in order to interact with Introverts. (Yes, I reversed these two terms on purpose to show you how biased our society is.) Introverts cannot “fix themselves” and deserve respect for their natural temperament and contributions to the human race. In fact, one study (Silverman, 1986) showed that the percentage of Introverts increases with IQ.

It can be terribly destructive for an Introvert to deny themselves in order to get along in an Extrovert-Dominant World. Like other minorities, Introverts can end up hating themselves and others because of the differences. If you think you are an Introvert, I recommend you research the topic and seek out other Introverts to compare notes. The burden is not entirely on Introverts to try and become “normal.” Extroverts need to recognize and respect us, and we also need to respect ourselves.

Source: 10 Myth about introverts

Carl, wrote these points based on his experience. And me myself as an introvert am saying that these facts are very true and often misunderstood by almost everyone.

——————————-

Some of my close friends often get surprised at me. Quoting some of my them:

danny says

I think too much. More than it is necessary.

mundre says,

Haven’t seen anyone, who takes his relations this seriously.

Fucchi says,

I am so complicated.

I really don’t know what to tell you guys, neither I have anything to  tell to other people reading this post. It’s just a simple reality about me 🙂

Read more
October 21, 2012

Compare two diff array with same size

Question by Pranali

I have a simple application in which I want compare two arrays.

function check() {
    var Array1 = value.length;
    var Array2 = selected_value.length;
    alert(Array1 + "," + Array2);
    for (var i = 0; i < Array1; i++) {
        for (var j = 0; j < Array2; j++) {
            if (value[i] == selected_value[j]) {
                alert("both div are same");
            }
        }
    }
}​

my arrays have 4 elements each but the if condition is not satisfied.

Answer by Starx

Here is function, with which you can compare two arrays

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

Source

You can check if array return false, like this

if(!arrayEqual(arr1,arr2)) {
   // false
}
Read more
October 18, 2012

General CSS for #id ending with numbers

Question by Rahul TS

I will start with an example

I have something like this. Same id name with different ending numbers.

#samplelist_1 { color: #fff; }
#samplelist_2 { color: #fff; }
#samplelist_3 { color: #fff; }
#samplelist_4 { color: #fff; }  

and these css are automatically generated. So I want to declare and define a css for #samplelist_.. which will affect all the #ids generally. So any #ids generated say: _15, _86 or anything like that can be styled.

Is that possible.

Please let me know, if the explaination make sense

Thanks in advance.
Rahul TS

Answer by Blender

You can use the attribute starts-with selector:

[id^="samplelist_"] {
    color: white;
}

Better yet, give them a class.

Answer by Starx

Don’t generate such redundant styles, instead use class to apply same style to multiple element at once. Thus, eliminating the need to go look for such stupid solution on first place.

If not going for cross-browser compatible CSS then you can do something like

[id^="samplelist_"] {
    color: #FFF;
}

Let me explain this selector in detail

  • [id]: means it is going to match the id attribute of the element
  • ^=: means if the value starts with ....

Combined it says “if id starts with samplelist_” then apply this style.

Read more

Retrieve posts from craigslist in PHP

Question by TapThatApp

I want to use file_get_contents to grab only information between the p
tags.

I’ve tried to use DOM elements but when I use getElementByTagName and loop through the array, it strips all HTML within the <p> tag.

<?php
function search(){
    $city = $_POST['city'];
    $scity = trim($city);
    $dom = new DOMDocument;
    libxml_use_internal_errors(true);

    $dom->loadHTMLFile('http://'.$scity.'.craigslist.org/search/cto?query=Toyota');
    libxml_use_internal_errors(false);
    $xpath = new DOMXPath($dom);
    $contents = $xpath->query('//p[@class="row"]');

    foreach($contents as $val){
        echo '<a href="' . $val->getElementsByTagName('a')->getAttribute('href') . '">' .  utf8_decode(trim($val->nodeValue, " -,")) . "</a><br />n";;
    }
}
?>

I want it to display just as it does on craigslist.
The title with the link to craigslist and price, img etc…

Answer by Starx

Use preg_match_all():

$text = file_get_contents("....");

preg_match_all('|<p>(.*?)</p>|',$texst, $matches); //Use regex to match all inside `p`

var_dump($matches); //View the matches
Read more

Using appendTo() on the parent `ul` of $this (current) element

Question by uriah

I’m having difficulty with some syntax.

JS

function sortAlpha(a,b){
       return a.innerHTML > b.innerHTML ? 1 : -1;
};

$('.brick ul li').each(function() {
       $(this).sort(sortAlpha).appendTo('ul');
});

HTML

<div id="studio" class="brick">
<div class="listlist">
<h3 class="title">Studio</h3>
<ul class="list">
    <li class="odd">
        <a href="#">
            <span class="title">Apple</span>
        </a>
    </li>
    <li class="even">
    <span class="title"><a href="#">Cat</span>
            </a>
    </li>
    <li class="odd">
        <span class="title">
                        <a href="#">Bar</span>
        </a>
    </li>
</ul>
</div>
</div>

I would like to append $this li to it’s own parent ul not all the lists

Edit: Just to make sure I’m selecting the correct li and parent. Thanks

Answer by Sheikh Heera

You have inaccurate html, not properly nested, anyways, you may try this, I’ve answered assuming that the first li have the right nesting, as given below

<li class="odd">
    <a href="#">
        <span class="title">Apple</span>
    </a>
</li>

Working Example Here.

// Sorter
function sorter(){
    var arr=[], len=$('.brick').find('ul.list li').length;    
    $('.brick ul.list li').each(function(i) {
        var el=$(this).find('a span').text();
        arr.push(el);
        if(i==(len-1))
        {
            arr=sortAlpha(arr);
            var ul=$(this).closest('ul.list').empty();
            $.each(arr, function(k, v){
                var cls=(k%2) ? 'even':'odd',
                li=$('<li/>', {'class':cls}),
                a=$('<a/>',{'href':'#'}).append($('<span/>', {'class':'title'}).text(v));
                ul.append(li.append(a));
            });
        }
    });    
}

//Sort helper
function sortAlpha(list){
    var result = [], map = [];
    for (var i=0, length = list.length; i < length; i++) {
        map.push({ index: i, value: list[i].toLowerCase() });
    }
    map.sort(function(a, b) {
        return a.value > b.value ? 1 : -1;
    });
    for (var i=0, length = map.length; i < length; i++) {
        result.push(list[map[i].index]);
    }
    return result;
} 

Answer by Starx

If you are unsure of the parent element, then use this

$(this).sort(sortAlpha).appendTo($(this).parent("ul"));

If you are still not sure that parent is going to right above the DOM Tree then use .closest()

$(this).sort(sortAlpha).appendTo($(this).closest("ul"));

But, performance will better if you uniquely identify the ul with an id like

<ul id="meParent">
   ...
</ul>

Then

$(this).sort(sortAlpha).appendTo("#meParent");
Read more

Load order of jquery animations

Question by Eric Baldwin

I am just starting a jQuery tutorial and I have a basic question on the load order of jQuery animations.

Clicking on a link causes both an alert and a hide animation to appear when I use the following HTML code:

 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
       $("a").click(function(event){
         event.preventDefault();
         $(this).hide("slow");
       });
     });
   </script>
 </body>

However, when I take the second click function out of the document.ready function so that the code looks as it does below, the popup appears and the text disappears, but the hide animation does not happen.

 <!DOCTYPE html>
 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
   <style>
    a.test { font-weight: bold; }
  </style>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
     $(document).ready(function(){
       $("a").click(function(event){
         alert("As you can see, the link no longer took you to jquery.com");
         event.preventDefault();
       });
     });
     $("a").click(function(event){
       event.preventDefault();
       $(this).hide("slow");
     });
   </script>
 </body>
 </html>

Can anyone explain why the hide animation shows up only for the first example and not the second?

Answer by Starx

This is because the second handler is not get attached to all the anchor <a> tags on the div.

 $("a").click(function(event){ //This function will execute as the script loads
                               // and during this time, DOM might have been loaded yet
   event.preventDefault();
   $(this).hide("slow");
 });

But, by wrapping this inside.

$(document).ready(function() {

    // DOM is loaded

});

You first make sure the DOM is loaded first, then attach the handler.

Read more
October 16, 2012

explode and select each element from array

Question by user1694724

I have a small task where I have a mysql table “shops”.It contains a column “categories”. Each field of categories contains diiferent values like “22,44,33,55,24,33,22”
Now taking each value from that field, i need to get the value from a column “parent” in another table. (linking with ids) I am selecting the whole string, but i want to select each number. Please help me with this.

$db_selected = mysql_select_db("",$con);
$sql = "SELECT categories from shops";
$array = mysql_query($sql,$con);
while($row=mysql_fetch_array($array)){
foreach($row as $value){
    $result= explode(" ", $value);
    foreach($result as $newvalue){
    $query="SELECT parent FROM categories where categories.id=$newvalue<br/>";
    echo $query;
    }
    }
    }
mysql_close($con);
?>

Answer by Starx

You are exploding based on a space charater but your value needs to be exploded on the basis of ,. So try that

$result= explode(",", $value);
foreach($result as $newvalue){

    $query="SELECT parent FROM categories where categories.id='$newvalue'";
                                                           // ^ Quotes the Value
                                                           // Remove the <br />

    echo $query."<br />"; //Instead add it here and avoid the bug if you decide the run the query

    // This example is showing mysql_* library but it is deprecated

    $result = mysql_query($query);
    $row = mysql_fetch_assoc($result);
    $parent = $row['parent']; //Now you can something like this


}
Read more
...

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