Search Results

Search found 2448 results on 98 pages for 'val'.

Page 6/98 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Split string with delimiter in sql server

    - by Renju
    I'm having a coloumn name with varchar field that holds some folder path like "C:\Program Files\Internet Explorer\en-US" .I need to update the root folder name(Program files to profilesNew).Can anyone please help. I tried with a query declare @val as varchar(100) set @val='C:\Program Files\Internet Explorer\en-US' select substring(@val,charindex(':\',@val),charindex('\',@val)) but not getting the exact answer C:\Program FilesNew\Internet Explorer\en-US

    Read the article

  • Group multiple or statements within an IF in javascript

    - by nick
    The following code works: $(".valClear").each(function () { if ($(this).val().indexOf(".png") == -1) { $(this).val(''); } }); However this doesn't (the value is removed even if it contains .png or .jpeg), what am I doing wrong? $(".valClear").each(function () { if (($(this).val().indexOf(".png") == -1) || ($(this).val().indexOf(".jpeg") == -1)) { $(this).val(''); } });

    Read the article

  • May be my example site may answer my question about ajax call... Help me

    - by booota
    Okay I have this ajax call $('.updatecom .registercomplaint').click(function(){ updatecomplaints(); }); This calls the function updatecomplaints() function updatecomplaints() { var tno = $(".updatecom #tno").val(); var status = $(".updatecom #status").val(); if(status=='DONE') { $(".updatecom #con").val(''); } var tname = $(".updatecom #tname").val(); var rg11 = $(".updatecom #crg11").val(); var rg06 = $(".updatecom #crg06").val(); var tvpins = $(".updatecom #tvpins").val(); var jointer = $(".updatecom #jointer").val(); var cquantity = $(".updatecom #conqty").val(); var nooftv = $(".updatecom #tvno").val(); var misc = $(".updatecom #misc").val(); var tcomments = $(".updatecom #tcomments").val(); var con = $(".updatecom #con").val(); //alert(tno+status+tname+rg11+rg06+tvpins+jointer+cquantity+nooftv+misc+tcomments+con); $.ajax( { type: "POST", url: "up_functions.php", data: "ticket="+ tno +"& opt=upcom" +"& status="+ status +"& tname="+ tname +"& rg11="+ rg11 +"& rg06="+ rg06 +"& tvpins="+ tvpins +"& jointer="+ jointer +"& cquantity="+ cquantity +"& nooftv="+ nooftv +"& misc="+ misc +"& tcomments="+ tcomments +"& con="+ con, success: function(response) { alert(response); } }); } here is my up_functions.php $tno = htmlspecialchars(trim($_REQUEST['ticket'])); $status = htmlspecialchars(trim($_REQUEST['status'])); $tname = htmlspecialchars(trim($_REQUEST['tname'])); $rg11 = htmlspecialchars(trim($_REQUEST['rg11'])); $rg06 = htmlspecialchars(trim($_REQUEST['rg06'])); $tvpins = htmlspecialchars(trim($_REQUEST['tvpins'])); $jointer = htmlspecialchars(trim($_REQUEST['jointer'])); $cquantity = htmlspecialchars(trim($_REQUEST['cquantity'])); $nooftv = htmlspecialchars(trim($_REQUEST['nooftv'])); $misc = htmlspecialchars(trim($_REQUEST['misc'])); $tcomments = htmlspecialchars(trim($_REQUEST['tcomments'])); $con = htmlspecialchars(trim($_REQUEST['con'])); $result=$ptr-upcomticketinfo($tno,$status,$tname,$rg11,$rg06,$tvpins,$jointer,$cquantity,$nooftv,$misc,$tcomments,$con); echo $result; and here is my upconticketinfo() php function function upcomticketinfo($tno,$status,$tname,$rg11,$rg06,$tvpins,$jointer,$cquantity,$nooftv,$misc,$tcomments,$con) { if($con!='' || $con!=NULL) { $this-query = "update booking discription set STATUS='$status',CLOSED ON='$con' where TICKET NO='$tno'"; $this-q_result = mysql_query($this-query,$this-conn) or die(mysql_error()); if($this-q_result) { $query = "update tech detail set TECH NAME='$tname',CABLE RG11='$rg11',CABLE RG06='$rg06',TV PINS USED='$tvpins',JOINTER USED='$jointer',CONNECTOR QTY='$cquantity',NO OF TV='$nooftv',MISC='$misc',TECH COMMENTS='$tcomments' where BOOKING='$tno'"; $q_result = mysql_query($query,$this-conn) or die(mysql_error()); if($q_result) { $response = "updated"; } else { $response = "error"; } } else { $response = "error"; } } else { $this-query = "update booking discription set STATUS='$status' where TICKET NO='$tno'"; $this-q_result = mysql_query($this-query,$this-conn) or die(mysql_error()); if($this-q_result) { $query = "update tech detail set TECH NAME='$tname',CABLE RG11='$rg11',CABLE RG06='$rg06',TV PINS USED='$tvpins',JOINTER USED='$jointer',CONNECTOR QTY='$cquantity',NO OF TV='$nooftv',MISC='$misc',TECH COMMENTS='$tcomments' where BOOKING='$tno'"; $q_result = mysql_query($query,$this-conn) or die(mysql_error()); if($q_result) { $response = "updated"; } else { $response = "error"; } } else { $response = "error"; } } return $response; } Question is that, this code is working just fine in IE8 i.e i am using... but it is not working in FF 3.6.3... I have checked each n everything... One thing is that the code works fine on FF too only when i debug the page with firebug debugger. Otherwise the alert in ajax success shows itself with nothing in it... Help me... Goto link text Enter 6628 in the Ticket No. box under Update Complaint Status section... A new form will open. In that form press update... Try it in FF and IE... IE8 shows the results as needed but FF does not...

    Read the article

  • Why does Windows XP (during a rename operation) report file already exists when it doesn't?

    - by Hawk
    From the command-line: E:\menu\html\tom\val\.svn\tmp\text-base>ver Microsoft Windows [Version 5.2.3790] E:\menu\html\tom\val\.svn\tmp\text-base>dir Volume in drive E is DATA Volume Serial Number is F047-F44B Directory of E:\menu\html\tom\val\.svn\tmp\text-base 12/23/2010 04:36 PM <DIR> . 12/23/2010 04:36 PM <DIR> .. 12/23/2010 04:01 PM 0 wtf.com3.csv.svn-base 1 File(s) 0 bytes 2 Dir(s) 170,780,262,400 bytes free E:\menu\html\tom\val\.svn\tmp\text-base>rename wtf.com3.csv.svn-base com3.csv.svn-base A duplicate file name exists, or the file cannot be found. E:\menu\html\tom\val\.svn\tmp\text-base>dir Volume in drive E is DATA Volume Serial Number is F047-F44B Directory of E:\menu\html\tom\val\.svn\tmp\text-base 12/23/2010 04:36 PM <DIR> . 12/23/2010 04:36 PM <DIR> .. 12/23/2010 04:01 PM 0 wtf.com3.csv.svn-base 1 File(s) 0 bytes 2 Dir(s) 170,753,064,960 bytes free E:\menu\html\tom\val\.svn\tmp\text-base>` I don't know what to do about this, as there is no other file in this directory. Why does Windows XP report that there is already a file here named com3.csv.svn-base when there is clearly no other file here?

    Read the article

  • preg_replace function to append a string to all the hyperlinks of a page

    - by KoolKabin
    hi guys, i want to append my own value to all hyperlinks in a page... e.g if there are links: <a href="abc.htm?val=1">abc 1</a> <br/> <a href="abc.htm?val=2">abc 1</a> <br/> <a href="abc.htm?val=3">abc 1</a> <br/> <a href="abc.htm?val=4">abc 1</a> <br/> I want to add next var like "type=int" to all hyperlinks output should be: <a href="abc.htm?val=1&type=int">abc 1</a> <br/> <a href="abc.htm?val=2&type=int">abc 1</a> <br/> <a href="abc.htm?val=3&type=int">abc 1</a> <br/> <a href="abc.htm?val=4&type=int">abc 1</a> <br/> I hope it can be done quite easily with preg_replace function

    Read the article

  • mysterical error

    - by Görkem Buzcu
    i get "customer_service_simulator.exe stopped" error, but i dont know why? this is my c programming project and i have limited time left before deadline. the code is: #include <stdio.h> #include <stdlib.h> #include<time.h> #define FALSE 0 #define TRUE 1 /*A Node declaration to store a value, pointer to the next node and a priority value*/ struct Node { int priority; //arrival time int val; //type int wait_time; int departure_time; struct Node *next; }; Queue Record that will store the following: size: total number of elements stored in the list front: it shows the front node of the queue (front of the queue) rear: it shows the rare node of the queue (rear of the queue) availability: availabity of the teller struct QueueRecord { struct Node *front; struct Node *rear; int size; int availability; }; typedef struct Node *niyazi; typedef struct QueueRecord *Queue; Queue CreateQueue(int); void MakeEmptyQueue(Queue); void enqueue(Queue, int, int); int QueueSize(Queue); int FrontOfQueue(Queue); int RearOfQueue(Queue); niyazi dequeue(Queue); int IsFullQueue(Queue); int IsEmptyQueue(Queue); void DisplayQueue(Queue); void sorteddequeue(Queue); void sortedenqueue(Queue, int, int); void tellerzfunctionz(Queue *, Queue, int, int); int main() { int system_clock=0; Queue waitqueue; int exit, val, priority, customers, tellers, avg_serv_time, sim_time,counter; char command; waitqueue = CreateQueue(0); srand(time(NULL)); fflush(stdin); printf("Enter number of customers, number of tellers, average service time, simulation time\n:"); scanf("%d%c %d%c %d%c %d",&customers, &command,&tellers,&command,&avg_serv_time,&command,&sim_time); fflush(stdin); Queue tellerarray[tellers]; for(counter=0;counter<tellers;counter++){ tellerarray[counter]=CreateQueue(0); //burada teller sayisi kadar queue yaratiyorum } for(counter=0;counter<customers;counter++){ priority=1+(int)rand()%sim_time; //this will generate the arrival time sortedenqueue(waitqueue,1,priority); //here i put the customers in the waiting queue } tellerzfunctionz(tellerarray,waitqueue,tellers,customers); DisplayQueue(waitqueue); DisplayQueue(tellerarray[0]); DisplayQueue(tellerarray[1]); // waitqueue-> printf("\n\n"); system("PAUSE"); return 0; } /*This function initialises the queue*/ Queue CreateQueue(int maxElements) { Queue q; q = (struct QueueRecord *) malloc(sizeof(struct QueueRecord)); if (q == NULL) printf("Out of memory space\n"); else MakeEmptyQueue(q); return q; } /*This function sets the queue size to 0, and creates a dummy element and sets the front and rear point to this dummy element*/ void MakeEmptyQueue(Queue q) { q->size = 0; q->availability=0; q->front = (struct Node *) malloc(sizeof(struct Node)); if (q->front == NULL) printf("Out of memory space\n"); else{ q->front->next = NULL; q->rear = q->front; } } /*Shows if the queue is empty*/ int IsEmptyQueue(Queue q) { return (q->size == 0); } /*Returns the queue size*/ int QueueSize(Queue q) { return (q->size); } /*Shows the queue is full or not*/ int IsFullQueue(Queue q) { return FALSE; } /*Returns the value stored in the front of the queue*/ int FrontOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->front->next->val; else { printf("The queue is empty\n"); return -1; } } /*Returns the value stored in the rear of the queue*/ int RearOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->rear->val; else { printf("The queue is empty\n"); return -1; } } /*Displays the content of the queue*/ void DisplayQueue(Queue q) { struct Node *pos; pos=q->front->next; printf("Queue content:\n"); printf("-->Priority Value\n"); while (pos != NULL) { printf("--> %d\t %d\n", pos->priority, pos->val); pos = pos->next; } } void enqueue(Queue q, int element, int priority){ if(IsFullQueue(q)){ printf("Error queue is full"); } else{ q->rear->next=(struct Node *)malloc(sizeof(struct Node)); q->rear=q->rear->next; q->rear->next=NULL; q->rear->val=element; q->rear->priority=priority; q->size++; } } void sortedenqueue(Queue q, int val, int priority) { struct Node *insert,*temp; insert=(struct Node *)malloc(sizeof(struct Node)); insert->val=val; insert->priority=priority; temp=q->front; if(q->size==0){ enqueue(q, val, priority); } else{ while(temp->next!=NULL && temp->next->priority<insert->priority){ temp=temp->next; } //printf("%d",temp->priority); insert->next=temp->next; temp->next=insert; q->size++; if(insert->next==NULL){ q->rear=insert; } } } niyazi dequeue(Queue q) { niyazi del; niyazi deli; del=(niyazi)malloc(sizeof(struct Node)); deli=(niyazi)malloc(sizeof(struct Node)); if(IsEmptyQueue(q)){ printf("Queue is empty!"); return NULL; } else { del=q->front->next; q->front->next=del->next; deli->val=del->val; deli->priority=del->priority; free(del); q->size--; return deli; } } void sorteddequeue(Queue q) { struct Node *temp; struct Node *min; temp=q->front->next; min=q->front; int i; for(i=1;i<q->size;i++) { if(temp->next->priority<min->next->priority) { min=temp; } temp=temp->next; } temp=min->next; min->next=min->next->next; free(temp); if(min->next==NULL){ q->rear=min; } q->size--; } void tellerzfunctionz(Queue *a, Queue b, int c, int d){ int i; int value=0; int priority; niyazi temp; temp=(niyazi)malloc(sizeof(struct Node)); if(c==1){ for(i=0;i<d;i++){ temp=dequeue(b); sortedenqueue((*(a)),temp->val,temp->priority); } } else{ for(i=0;i<d;i++){ while(b->front->next->val==1){ if((*(a+value))->availability==1){ temp=dequeue(b); sortedenqueue((*(a+value)),temp->val,temp->priority); (*(a+value))->rear->val=2; } else{ value++; } } } } } //end of the program

    Read the article

  • JSON is not being recognised

    - by richzilla
    Hi All, Im having a bit of trouble getting my JSON to be recognised by my web page. I have validated JSON that im getting returned from server, so i know that is correct, however my javascript function is not doing anything with it. My succes function is as follows: success: function(data) { $('input[name=customer_name]').val(data.name); $('textarea[name=customer_address]').text(data.address); $('input[name=customer_email]').val(data.email); $('input[name=customer_tel]').val(data.tel); $('input[name=user_id]').val(item.id); } Yet the fields are not being repopulated with the data that is returned, if it helps, a sample of my JSON data: { "name": "Terry O'Toole", "address": "Terrys House\nTerry Street\nTerrysville\nTerrytown\nTT1 6TT", "email": "[email protected]", "tel": "05110000000" } Any help would be appreciated. [EDIT] Expanded ajax call: $.ajax({ url: "<?php echo site_url('user/users/ajax'); ?>", type: 'POST', data: {"userid": item.id}, success: function(data) { $('input[name=customer_name]').val(data.name); $('textarea[name=customer_address]').text(data.address); $('input[name=customer_email]').val(data.email); $('input[name=customer_tel]').val(data.tel); $('input[name=user_id]').val(item.id); } }) });

    Read the article

  • jQuery trigger function on change

    - by Michael Pasqualone
    I have the following two slider functions which work well and display like so: I have diskAmount and transferAmount stored in global vars, however what I am now trying to figure out is how do I get the sum of the two to initially show as the monthly fee, and then update when either of the two sliders are changed. So in my screenshot above the initial state will be $24.75, and the fee will update if the sliders change. Can anyone point me in the right direction? I get can the initial fee to show, but can't figure out how to get 1 function to call another function within jQuery. $(function() { $("#disk").slider({ value:3, min: 1, max: 80, step: 1, slide: function(event, ui) { $("#diskamount").val(ui.value + ' Gb'); $("#diskamountUnit").val('$' + parseFloat(ui.value * diskCost).toFixed(2)); } }); // Set initial diskamount state $("#diskamount").val($("#disk").slider("value") + ' Gb'); // Set initial diskamountUnit state diskAmount = $("#disk").slider("value") * diskCost; $("#diskamountUnit").val('$' + diskAmount.toFixed(2)); }); $(function() { $("#data").slider({ value:25, min: 1, max: 200, step: 1, slide: function(event, ui) { $("#dataamount").val(ui.value + ' Gb'); $("#dataamountUnit").val('$' + parseFloat(ui.value * transferCost).toFixed(2)); } }); // Set initial dataamount state $("#dataamount").val($("#data").slider("value") + ' Gb'); // Set initial dataamountUnit state transferAmount = $("#data").slider("value") * transferCost; $("#dataamountUnit").val('$' + transferAmount.toFixed(2)); });

    Read the article

  • Pulling Data out of an object in Javascript

    - by PerryCS
    I am having a problem retreiving data out of an object passed back from PHP. I've tried many different ways to access this data and none work. In Firebug I see the following... (it looks nicer in Firebug) - I tried to make this look as close to Firebug as possible results Object { data="{"formName":"form3","formData":"data goes here"}", phpLiveDebug="<...s: 198.91.215.227"} data "{"formName":"form3","formData":"data goes here"}" phpLiveDebug "<...s: 198.91.215.227" I can access phpLiveDebug no problem, but the data portion is an object. I have tried the following... success: function(results) { //$("#formName").val(results.data.formName); //$("#formName").val(results.data[0].formName); //$("#formName").val(results.data[0]); //$("#formName").val(results.data[1]); //$("#formName").val(results.data[0]["formName"]); var tmp = results.data[formName]; alert("!" + tmp + "!"); $("#formName").val(tmp); $("#jqueryPHPDebug").val(results.phpLiveDebug); } This line works in the example above... $("#jqueryPHPDebug").val(results.phpLiveDebug); but... I can't figure out how to get at the data inside the results.data portion... as you can see above, I have been trying different things and more not even listed there. I was really hoping this line would work :) var tmp = results.data[formName]; But it doesn't. So, after many days of reading, tinkering, my solution was to re-write it to return data similar to the phpLiveDebug but then I thought... it's gotta be something simple I'm overlooking... Thank you for your time. Please try and explain why my logic (my horrible attempts at trying to figure out the proper method) above is wrong if you can?

    Read the article

  • jQuery encoding values differently than expected for jQuery.ajax data elements

    - by Adam Tuttle
    I'm using jQuery.ajax() to make a PUT request to a REST web service, but seeing some really strange serialization behavior. (Before you say it: Yes, I know that not all browsers support PUT -- this is just an example implementation for an api/framework, and ultimately will not be called by a browser, but rather by a server-side library that does support the extra http verbs.) Here's the form: <form action="/example/api/artist" method="put" id="update"> First Name: <input type="text" name="firstname" /><br/> Last Name: <input type="text" name="lastname" /><br/> Address: <input type="text" name="address" /><br/> City: <input type="text" name="city" /><br/> State: <input type="text" name="state" /><br/> Postal Code: <input type="text" name="postalcode" /><br/> Email: <input type="text" name="email" /><br/> Phone: <input type="text" name="phone" /><br/> Fax: <input type="text" name="fax" /><br/> Password: <input type="text" name="thepassword" /><br/> <input type="hidden" name="debug" value="true" /> <input type="submit" value="Update Artist" /> <input type="reset" value="Cancel" id="updateCancel" /> </form> And the JS: $("#update").submit(function(e){ e.preventDefault(); var frm = $(this); $.ajax({ url: frm.attr('action'), data:{ firstname: $("#update input[name=firstname]").val(), lastname: $("#update input[name=lastname]").val(), address: $("#update input[name=address]").val(), city: $("#update input[name=city]").val(), state: $("#update input[name=state]").val(), postalcode: $("#update input[name=postalcode]").val(), email: $("#update input[name=email]").val(), phone: $("#update input[name=phone]").val(), fax: $("#update input[name=fax]").val(), thepassword: $("#update input[name=thepassword]").val() }, type: frm.attr('method'), dataType: "json", contentType: "application/json", success: function (data, textStatus, xhr){ console.log(data); reloadData(); }, error: function (xhr, textStatus, err){ console.log(textStatus); console.log(err); } }); }); When using FireBug, I see the request go through as this: firstname=Austin&lastname=Weber&address=25463+Main+Street%2C+Suite+C&city=Berkeley&state=CA&postalcode=94707-4513&email=austin%40life.com&phone=555-513-4318&fax=510-513-4888&thepassword=nopolyes That's not horrible, but ideally I'd rather get %20 instead of + for spaces. I tried wrapping each field value lookup in an escape: firstname: escape($("#update input[name=firstname]").val()) But that makes things worse: firstname=Austin&lastname=Weber&address=25463%2520Main%2520Street%252C%2520Suite%2520C&city=Berkeley&state=CA&postalcode=94707-4513&email=austin%40life.com&phone=555-513-4318&fax=510-513-4888&thepassword=nopolyes In this case, the value is being escaped twice; so first the space is encoded to %20, and then the % sign is escaped to %25 resulting in the %2520 for spaces, and %252C for the comma in the address field. What am I doing wrong here?

    Read the article

  • Help with Jquery and multiple forms on a page.

    - by Will
    I have a several forms that are output from a database on the same page. It works fine when I don't use ajax. When I use Jquery it will only work for the first form. Could anyone point me in the right direction please? Jquery..... $('.updateSubmit').live('click', function() { var id = $('.id').val(); var hardSoft = $('.hardSoft').val(); var brand = $('.brand').val(); var subCat = $('.subCat').val(); var subSubCat = $('.subSubCat').val(); var tProduct = $('.tProduct').val(); var description = $('.description').val(); var quantity = $('.quantity').val(); var price = $('.price').val(); var tCondition = $('.tCondition').val(); var featured = $('.featured').val(); var theData = 'id=' + id + '&hardSoft=' + hardSoft + '&brand=' + brand + '&subCat=' + subCat + '&subSubCat=' + subSubCat + '&tProduct=' + tProduct +'&description=' + description + '&quantity=' + quantity + '&price=' + price + '&tCondition=' + tCondition + '&featured=' + featured; $.ajax ({ type: 'POST', url: '/updateGrab.php', data: theData, success: function(aaa) { $('.'+id).append('<div class="forSuccess">'+aaa+'</div>'); } // end success }); // end ajax return false; }); // end click and my php form...... while ($row = $stmt->fetch()) { echo " <form action='http://www.wbrock.com/updateGrab.php' method='post' name='".$id."'> <input type='hidden' class='id' name='id' value='".$id."' /> Hardware/Software <input type='text' class='hardSoft' name='hardSoft' value='".$hardSoft."' /> Brand <input type='text' class='brand' name='brand' value='".$brand."' /> Sub-category <input type='text' class='subCat' name='subCat' value='".$subCat."' /> Sub-Sub-Cat <input type='text' class='subSubCat' name='subSubCat' value='".$subSubCat."' /> Product <input type='text' class='tProduct' name='tProduct' value='".$tProduct."' /> Description <input type='text' class='description' name='description' value='".$description."' /> Qty <input type='text' class='quantity' name='quantity' value='".$quantity."' /> Price <input type='text' class='price' name='price' value='".$price."' /> Cond <input type='text' class='tCondition' name='tCondition'value='".$tCondition."' /> Featured <input type='text' class='featured' name='featured' value='".$featured."' /> <input type='submit' id='".$id."' class='updateSubmit' name='updateSubmit' value='Update' /> </form> <span class='".$id."'></span> "; // end echo } // end while loop from database This is the first time I've posted here so sorry if its not in the right format. Thanks in advance for the help.

    Read the article

  • Super constructor must be a first statement in Java constructor [closed]

    - by Val
    I know the answer: "we need rules to prevent shooting into your own foot". Ok, I make millions of programming mistakes every day. To be prevented, we need one simple rule: prohibit all JLS and do not use Java. If we explain everything by "not shooting your foot", this is reasonable. But there is not much reason is such reason. When I programmed in Delphy, I always wanted the compiler to check me if I read uninitializable. I have discovered myself that is is stupid to read uncertain variable because it leads unpredictable result and is errorenous obviously. By just looking at the code I could see if there is an error. I wished if compiler could do this job. It is also a reliable signal of programming error if function does not return any value. But I never wanted it do enforce me the super constructor first. Why? You say that constructors just initialize fields. Super fields are derived; extra fields are introduced. From the goal point of view, it does not matter in which order you initialize the variables. I have studied parallel architectures and can say that all the fields can even be assigned in parallel... What? Do you want to use the unitialized fields? Stupid people always want to take away our freedoms and break the JLS rules the God gives to us! Please, policeman, take away that person! Where do I say so? I'm just saying only about initializing/assigning, not using the fields. Java compiler already defends me from the mistake of accessing notinitialized. Some cases sneak but this example shows how this stupid rule does not save us from the read-accessing incompletely initialized in construction: public class BadSuper { String field; public String toString() { return "field = " + field; } public BadSuper(String val) { field = val; // yea, superfirst does not protect from accessing // inconstructed subclass fields. Subclass constr // must be called before super()! System.err.println(this); } } public class BadPost extends BadSuper { Object o; public BadPost(Object o) { super("str"); this. o = o; } public String toString() { // superconstructor will boom here, because o is not initialized! return super.toString() + ", obj = " + o.toString(); } public static void main(String[] args) { new BadSuper("test 1"); new BadPost(new Object()); } } It shows that actually, subfields have to be inilialized before the supreclass! Meantime, java requirement "saves" us from writing specializing the class by specializing what the super constructor argument is, public class MyKryo extends Kryo { class MyClassResolver extends DefaultClassResolver { public Registration register(Registration registration) { System.out.println(MyKryo.this.getDepth()); return super.register(registration); } } MyKryo() { // cannot instantiate MyClassResolver in super super(new MyClassResolver(), new MapReferenceResolver()); } } Try to make it compilable. It is always pain. Especially, when you cannot assign the argument later. Initialization order is not important for initialization in general. I could understand that you should not use super methods before initializing super. But, the requirement for super to be the first statement is different. It only saves you from the code that does useful things simply. I do not see how this adds safety. Actually, safety is degraded because we need to use ugly workarounds. Doing post-initialization, outside the constructors also degrades safety (otherwise, why do we need constructors?) and defeats the java final safety reenforcer. To conclude Reading not initialized is a bug. Initialization order is not important from the computer science point of view. Doing initalization or computations in different order is not a bug. Reenforcing read-access to not initialized is good but compilers fail to detect all such bugs Making super the first does not solve the problem as it "Prevents" shooting into right things but not into the foot It requires to invent workarounds, where, because of complexity of analysis, it is easier to shoot into the foot doing post-initialization outside the constructors degrades safety (otherwise, why do we need constructors?) and that degrade safety by defeating final access modifier When there was java forum alive, java bigots attecked me for these thoughts. Particularly, they dislaked that fields can be initialized in parallel, saying that natural development ensures correctness. When I replied that you could use an advanced engineering to create a human right away, without "developing" any ape first, and it still be an ape, they stopped to listen me. Cos modern technology cannot afford it. Ok, Take something simpler. How do you produce a Renault? Should you construct an Automobile first? No, you start by producing a Renault and, once completed, you'll see that this is an automobile. So, the requirement to produce fields in "natural order" is unnatural. In case of alarmclock or armchair, which are still chair and clock, you may need first develop the base (clock and chair) and then add extra. So, I can have examples where superfields must be initialized first and, oppositely, when they need to be initialized later. The order does not exist in advance. So, the compiler cannot be aware of the proper order. Only programmer/constructor knows is. Compiler should not take more responsibility and enforce the wrong order onto programmer. Saying that I cannot initialize some fields because I did not ininialized the others is like "you cannot initialize the thing because it is not initialized". This is a kind of argument we have. So, to conclude once more, the feature that "protects" me from doing things in simple and right way in order to enforce something that does not add noticeably to the bug elimination at that is a strongly negative thing and it pisses me off, altogether with the all the arguments to support it I've seen so far. It is "a conceptual question about software development" Should there be the requirement to call super() first or not. I do not know. If you do or have an idea, you have place to answer. I think that I have provided enough arguments against this feature. Lets appreciate the ones who benefit form it. Let it just be something more than simple abstract and stupid "write your own language" or "protection" kind of argument. Why do we need it in the language that I am going to develop?

    Read the article

  • jquery ajax method always returning an error?

    - by General_9
    I have the following ajax call and it always hits the error callback function every time it is called. The code in the handler is still run after the error but the success callback is never executed. What have I got wrong? $.ajax({ type: "POST", url: "Handlers/TheHandler.ashx", data: { control1: $('[id*=control1]').val(), control2: $('[id*=control2]').val(), control3: $('[id*=control3]').val(), control4: $('#control4').val(), control5: $('[id*=control5]').val(), control6: $('[id*=control6]').val() }, error: function (jqXHR, textStatus, errorThrown) { alert(jqXHR.readyState); alert(textStatus); alert(errorThrown); }, success: function (returnedValue) { alert("Got Here"); alert(returnedValue); } });

    Read the article

  • Writing a rails validator with integer

    - by user297008
    I was trying to write a validation for Rails to ensure that a price entered on a form was greater than zero. It works…sort of. The problem is that when I run it, val is turned into an integer, so it thinks that .99 is less than .1. What's going on, and how should I fix the code? class Product < ActiveRecord::Base protected def self.validates_greater_than_zero(*attr_names) validates_each(attr_names) do |record, attr, val| record.errors.add(attr, "should be at least 0.01 (current val = #{val.to_f})") if val.nil? || val < 0.01 end end public validates_presence_of :title, :description, :image_url validates_numericality_of :price validates_greater_than_zero :price end

    Read the article

  • How to show that the double-checked-lock pattern with Dictionary's TryGetValue is not threadsafe in

    - by Amir
    Recently I've seen some C# projects that use a double-checked-lock pattern on a Dictionary. Something like this: private static readonly object _lock = new object(); private static volatile IDictionary<string, object> _cache = new Dictionary<string, object>(); public static object Create(string key) { object val; if (!_cache.TryGetValue(key, out val)) { lock (_lock) { if (!_cache.TryGetValue(key, out val)) { val = new object(); // factory construction based on key here. _cache.Add(key, val); } } } return val; } This code is incorrect, since the Dictionary can be "growing" the collection in _cache.Add() while _cache.TryGetValue (outside the lock) is iterating over the collection. It might be extremely unlikely in many situations, but is still wrong. Is there a simple program to demonstrate that this code fails? Does it make sense to incorporate this into a unit test? And if so, how?

    Read the article

  • Default type-parametrized function literal class parameter

    - by doom2.wad
    Is this an intended behavior or is it a bug? Consider the following trait (be it a class, doesn't matter): trait P[T] { class Inner(val f: T => Unit = _ => println("nope")) } This is what I would have expected: scala> val p = new P[Int] { | val inner = new Inner | } p: java.lang.Object with P[Int]{def inner: this.Inner} = $anon$1@12192a9 scala> p.inner.f(5) nope But this? scala> val p = new P[Int] { | val inner = new Inner() { | println("some primary constructor code in here") | } | } <console>:6: error: type mismatch; found : (T) => Unit required: (Int) => Unit val inner = new Inner() { ^

    Read the article

  • Dynamically Casting In ActionScript

    - by Joshua
    Is there a way to cast dynamically in Actionscript? What I want to accomplish is illustrated by the following code: var Val:*; var S:String=SomeTextEdit.text; switch (DesiredTypeTextEdit.text) { case 'int':Val=int(S);break; case 'uint':Val=uint(S);break; case 'String':Val=String(S);break; case 'Number':Val=Number(S);break; ... } SomeDisplayObject[SomePropertyNameTextEdit.text]=Val; I am looking for something LIKE the following PSEUDOCODE: SomeDisplayObject[SomePropertyName]=eval(DesiredType)(SomeTextEdit.text); Yes, I already realize that "eval" is not on the table, nor is that how one would use it. What's the RIGHT way?

    Read the article

  • Repopulating a collection of Backbone forms with previously submitted data

    - by Brian Wheat
    I am able to post my forms to my database and I have stepped through my back end function to check and see that my Get function is returning the same data I submitted. However I am having trouble understanding how to have this data rendered upon visiting the page again. What am I missing? The intention is to be able to create, read, update, or delete (CRUD) some personal contact data for a variable collection of individuals. //Model var PersonItem = Backbone.Model.extend({ url: "/Application/PersonList", idAttribute: "PersonId", schema: { Title: { type: 'Select', options: function (callback) { $.getJSON("/Application/GetTitles/").done(callback); } }, Salutation: { type: 'Select', options: ['Mr.', 'Mrs.', 'Ms.', 'Dr.'] }, FirstName: 'Text', LastName: 'Text', MiddleName: 'Text', NameSuffix: 'Text', StreetAddress: 'Text', City: 'Text', State: { type: 'Select', options: function (callback) { $.getJSON("/Application/GetStates/").done(callback); } }, ZipCode: 'Text', PhoneNumber: 'Text', DateOfBirth: 'Date', } }); Backbone.Form.setTemplates(template, PersonItem); //Collection var PersonList = Backbone.Collection.extend({ model: PersonItem , url: "/Application/PersonList" }); //Views var PersonItemView = Backbone.Form.extend({ tagName: "li", events: { 'click button.delete': 'remove', 'change input': 'change' }, initialize: function (options) { console.log("ItemView init"); PersonItemView.__super__.initialize.call(this, options); _.bindAll(this, 'render', 'remove'); console.log("ItemView set attr = " + options); }, render: function () { PersonItemView.__super__.render.call(this); $('fieldset', this.el).append("<button class=\"delete\" style=\"float: right;\">Delete</button>"); return this; }, change: function (event) { var target = event.target; console.log('changing ' + target.id + ' from: ' + target.defaultValue + ' to: ' + target.value); }, remove: function () { console.log("delete button pressed"); this.model.destroy({ success: function () { alert('person deleted successfully'); } }); return false; } }); var PersonListView = Backbone.View.extend({ el: $("#application_fieldset"), events: { 'click button#add': 'addPerson', 'click button#save': 'save2db' }, initialize: function () { console.log("PersonListView Constructor"); _.bindAll(this, 'render', 'addPerson', 'appendItem', 'save'); this.collection = new PersonList(); this.collection.bind('add', this.appendItem); //this.collection.fetch(); this.collection.add([new PersonItem()]); console.log("collection length = " + this.collection.length); }, render: function () { var self = this; console.log(this.collection.models); $(this.el).append("<button id='add'>Add Person</button>"); $(this.el).append("<button id='save'>Save</button>"); $(this.el).append("<fieldset><legend>Contact</legend><ul id=\"anchor_list\"></ul>"); _(this.collection.models).each(function (item) { self.appendItem(item); }, this); $(this.el).append("</fieldset>"); }, addPerson: function () { console.log("addPerson clicked"); var item = new PersonItem(); this.collection.add(item); }, appendItem: function (item) { var itemView = new PersonItemView({ model: item }); $('#anchor_list', this.el).append(itemView.render().el); }, save2db: function () { var self = this; console.log("PersonListView save"); _(this.collection.models).each(function (item) { console.log("item = " + item.toJSON()); var cid = item.cid; console.log("item.set"); item.set({ Title: $('#' + cid + '_Title').val(), Salutation: $('#' + cid + '_Salutation').val(), FirstName: $('#' + cid + '_FirstName').val(), LastName: $('#' + cid + '_LastName').val(), MiddleName: $('#' + cid + '_MiddleName').val(), NameSuffix: $('#' + cid + '_NameSuffix').val(), StreetAddress: $('#' + cid + '_StreetAddress').val(), City: $('#' + cid + '_City').val(), State: $('#' + cid + '_State').val(), ZipCode: $('#' + cid + '_ZipCode').val(), PhoneNumber: $('#' + cid + '_PhoneNumber').val(), DateOfBirth: $('#' + cid + '_DateOfBirth').find('input').val() }); if (item.isNew()) { console.log("item.isNew"); self.collection.create(item); } else { console.log("!item.isNew"); item.save(); } }); return false; } }); var personList = new PersonList(); var view = new PersonListView({ collection: personList }); personList.fetch({ success: function () { $("#application_fieldset").append(view.render()); } });

    Read the article

  • Javascript & Jquery why it doesnt work on IE?

    - by Yetkin EREN
    i cant run any function on ie this is a little part; my test page : http://www.yetkineren.com/testpage.html code: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <title>test page</title> </head> <body> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"> </script> <script type="text/javascript" language="javascript"> function kutuyap(Eid,iduzan,yazi,yer,ekle){ var div; div = document.createElement('div') div.id = Eid+iduzan; document.getElementById(yer).appendChild(div); //$('#'+yer).append("<div id="+Eid+iduzan+"></div>") $('#'+Eid+iduzan).addClass("minikutu"); $('#'+Eid+iduzan).html(" "+yazi+'<span id='+Eid+'y'+iduzan+' class="yokedici">X</span>'); // $("#"+Eid+'y'+iduzan).attr("onclick","kutusil('"+Eid+"y"+iduzan+"','"+iduzan+"','"+ekle+"');"); $("#"+Eid+'y'+iduzan).click(function() { kutusil(Eid+'y'+iduzan, iduzan, ekle); }); $('#'+ekle).val($('#'+ekle).val()+Eid+'-'); } function kutusil(Eid,iduzan,ekle){ $('#'+Eid).live('click',function() { sil=$(this).parents("div:first").attr("id"); silinecek=sil.replace(iduzan,''); $('#'+ekle).val($('#'+ekle).val().replace(silinecek+'-','')); $(this).parents("div:first").remove(); }); } </script> <select name="Mturs" class="inputs" id="Mturs"> <option value="0" selected="selected">Choise One</option> <option value="4">Pop</option> <option value="3">Pop-Rock </option> <option value="5">Rock (Yabanci)</option> </select> <input name="secMtur" id="secMtur" value="" type="hidden"> <script> $('#Mturs').live('change', function() { $('#Mturs :selected').each(function (i) { if ( $('#Mturs :selected').val() != 0 ) { secMturde=$('#secMtur').val().indexOf($('#Mturs :selected').val()+'-'); splitter=$('#secMtur').val().split("-") if(splitter.length<=12){ if (secMturde<0) { kutuyap($('#Mturs :selected').val(),'mtur',$(this).html(),'divmtur','secMtur'); }else{ alert("Choisen before") } }else{ alert("Max limit is 12 !") } } }); }); </script>

    Read the article

  • idiomatic property changed notification in scala?

    - by Jeremy Bell
    I'm trying to find a cleaner alternative (that is idiomatic to Scala) to the kind of thing you see with data-binding in WPF/silverlight data-binding - that is, implementing INotifyPropertyChanged. First, some background: In .Net WPF or silverlight applications, you have the concept of two-way data-binding (that is, binding the value of some element of the UI to a .net property of the DataContext in such a way that changes to the UI element affect the property, and vise versa. One way to enable this is to implement the INotifyPropertyChanged interface in your DataContext. Unfortunately, this introduces a lot of boilerplate code for any property you add to the "ModelView" type. Here is how it might look in Scala: trait IDrawable extends INotifyPropertyChanged { protected var drawOrder : Int = 0 def DrawOrder : Int = drawOrder def DrawOrder_=(value : Int) { if(drawOrder != value) { drawOrder = value OnPropertyChanged("DrawOrder") } } protected var visible : Boolean = true def Visible : Boolean = visible def Visible_=(value: Boolean) = { if(visible != value) { visible = value OnPropertyChanged("Visible") } } def Mutate() : Unit = { if(Visible) { DrawOrder += 1 // Should trigger the PropertyChanged "Event" of INotifyPropertyChanged trait } } } For the sake of space, let's assume the INotifyPropertyChanged type is a trait that manages a list of callbacks of type (AnyRef, String) = Unit, and that OnPropertyChanged is a method that invokes all those callbacks, passing "this" as the AnyRef, and the passed-in String). This would just be an event in C#. You can immediately see the problem: that's a ton of boilerplate code for just two properties. I've always wanted to write something like this instead: trait IDrawable { val Visible = new ObservableProperty[Boolean]('Visible, true) val DrawOrder = new ObservableProperty[Int]('DrawOrder, 0) def Mutate() : Unit = { if(Visible) { DrawOrder += 1 // Should trigger the PropertyChanged "Event" of ObservableProperty class } } } I know that I can easily write it like this, if ObservableProperty[T] has Value/Value_= methods (this is the method I'm using now): trait IDrawable { // on a side note, is there some way to get a Symbol representing the Visible field // on the following line, instead of hard-coding it in the ObservableProperty // constructor? val Visible = new ObservableProperty[Boolean]('Visible, true) val DrawOrder = new ObservableProperty[Int]('DrawOrder, 0) def Mutate() : Unit = { if(Visible.Value) { DrawOrder.Value += 1 } } } // given this implementation of ObservableProperty[T] in my library // note: IEvent, Event, and EventArgs are classes in my library for // handling lists of callbacks - they work similarly to events in C# class PropertyChangedEventArgs(val PropertyName: Symbol) extends EventArgs("") class ObservableProperty[T](val PropertyName: Symbol, private var value: T) { protected val propertyChanged = new Event[PropertyChangedEventArgs] def PropertyChanged: IEvent[PropertyChangedEventArgs] = propertyChanged def Value = value; def Value_=(value: T) { if(this.value != value) { this.value = value propertyChanged(this, new PropertyChangedEventArgs(PropertyName)) } } } But is there any way to implement the first version using implicits or some other feature/idiom of Scala to make ObservableProperty instances function as if they were regular "properties" in scala, without needing to call the Value methods? The only other thing I can think of is something like this, which is more verbose than either of the above two versions, but is still less verbose than the original: trait IDrawable { private val visible = new ObservableProperty[Boolean]('Visible, false) def Visible = visible.Value def Visible_=(value: Boolean): Unit = { visible.Value = value } private val drawOrder = new ObservableProperty[Int]('DrawOrder, 0) def DrawOrder = drawOrder.Value def DrawOrder_=(value: Int): Unit = { drawOrder.Value = value } def Mutate() : Unit = { if(Visible) { DrawOrder += 1 } } }

    Read the article

  • Simulating C-style for loops in python

    - by YGA
    (even the title of this is going to cause flames, I realize) Python made the deliberate design choice to have the for loop use explicit iterables, with the benefit of considerably simplified code in most cases. However, sometimes it is quite a pain to construct an iterable if your test case and update function are complicated, and so I find myself writing the following while loops: val = START_VAL while <awkward/complicated test case>: # do stuff ... val = <awkward/complicated update> The problem with this is that the update is at the bottom of the while block, meaning that if I want to have a continue embedded somewhere in it I have to: use duplicate code for the complicated/awkard update, AND run the risk of forgetting it and having my code infinite loop I could go the route of hand-rolling a complicated iterator: def complicated_iterator(val): while <awkward/complicated test case>: yeild val val = <awkward/complicated update> for val in complicated_iterator(start_val): if <random check>: continue # no issues here # do stuff This strikes me as waaaaay too verbose and complicated. Do folks in stack overflow have a simpler suggestion?

    Read the article

  • jQuery keyup() illegal characters

    - by FFish
    I have a field and want to prevent some illegal characters while showing the user as he types. How can I do this in follow example? $('input').bind("change keyup", function() { var val = $(this).attr("value"); /* if (val --contains-- '"') { $(this).css("background", "red"); val = val.replace('"', ""); $(this).attr("value", val) } */ $("p").html(val); }); EDIT: I should put the illegal characters in an array var vowels = new Array('"', "<", ">", "&");

    Read the article

  • PHP is not returning me a number type

    - by Tristan
    Hello, i tryed to follow that great tutorial (STAR rating with css : http://stackoverflow.com/questions/1987524/turn-a-number-into-star-rating-display-using-jquery-and-css) but i've just a big problem : When i do <span class="stars">1.75</span> or $foo='1.75'; echo '<span class="stars">'.$foo.'</span> the stars is correctly shown, but as soon as i do : while($val = mysql_fetch_array($result)) { $average = ($val['services'] + $val['serviceCli'] + $val['interface'] + $val['qualite'] + $val['rapport'] ) / 5 ; <span class="stars">.$average.</span> } the stars stops working i double checked the data type in mysql : they're all TINYINT(2) and i tryed that : $average = intval($average); but it's still not working, Thank you

    Read the article

  • how to use trigger in Jquery to pass parameter data as well as control (this)

    - by Shantanu Gupta
    I am trying to use same validation funtion for all my controls. But I dont know much in jquery and not been able to pass event handler to the trigger. I want to pass textbox id to my custom function. How can i do this <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#txtFirstName").bind('focusout', function() { $(this).trigger("customblurfocus",[$(this).val(), $(this).val() + " Required !", "Ok !"]); } ); $(this).bind('customblurfocus',function(defaultInputValue,ErrorMessage,ValidMessage) {alert($(this).val()); if($(this).val()=="" || $(this).val()==defaultInputValue) { $(this).val(defaultInputValue); $(this).siblings("span[id*='error']").toggleClass("error_set").text(ErrorMessage).fadeOut(3000); } else { $(this).siblings("span[id*='error']").toggleClass("error_ok").text(ValidMessage).show(1000); } } ); }); </script>

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >