text
stringlengths
8
267k
meta
dict
Q: Jquery: increase the current form input value with 1 I'm just trying to get a number from a hidden form input and plus 1 to that number and then put that value to the incremented number. Here is my code jQuery('#add_slider_image').live('click', function() { var slideId = jQuery('#count-level').attr('value'); jQuery('#count-level').attr('value',slideId+1); }); What am I doing wrong? as it changes the value to 11 or even 111 depending on the amount of clicks. It needs to add the value with 1. like 1+1=2 not 11. Thanks A: its converting it to a string. make sure to do var slideId = parseInt(jQuery('#count-level').attr('value')); A: It sounds like the variable needs to be converted from string to integer. Not positive, but this may work: change: jQuery('#count-level').attr('value',slideId+1); to: jQuery('#count-level').attr('value',parseInt(slideId)+1); More on jquery Integers and parsing numbers: http://docs.jquery.com/Types#Integer
{ "language": "en", "url": "https://stackoverflow.com/questions/7559722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I am not able to compare two object in my asp.net mvc application I have this code to compare two objects, these two out put results are same. but my equal condition is allways getting false. I am not understanding is that something I am doign wrong here? var t1 = repo.Model_Test_ViewAllBenefitCodes(2).OrderBy(p => p.ba_Object_id).ToArray();//.FirstOrDefault(); var t2 = x.ViewAllBenefitCodes.OrderBy(p => p.ba_Object_id).ToArray();//.FirstOrDefault(); for (int i = 0; i < t1.Count(); i++) { var res1 = t1[i]==(t2[i]); var res = t1[i].Equals(t2[i]); Assert.AreEqual(res, true); } A: It really depends on the object you're trying to compare, but this will compare classes that only have children (no grandchildren?) It's using reflection to pull all of the properties in the class and compare them. Private Function Compare(ByVal Obj1 As Object, ByVal Obj2 As Object) As Boolean 'We default the return value to false Dim ReturnValue As Boolean = False Try If Obj1.GetType() = Obj2.GetType() Then 'Create a property info for each of our objects Dim PropertiesInfo1 As PropertyInfo() = Obj1.GetType().GetProperties() Dim PropertiesInfo2 As PropertyInfo() = Obj2.GetType().GetProperties() 'loop through all of the properties in the first object and compare them to the second For Each pi As PropertyInfo In PropertiesInfo1 Dim CheckPI As PropertyInfo Dim CheckPI2 As PropertyInfo Dim Value1 As New Object Dim Value2 As New Object 'We have to do this because there are errors when iterating through lists CheckPI = pi 'Here we pull out the property info matching the name of the 1st object CheckPI2 = (From i As PropertyInfo In PropertiesInfo2 Where i.Name = CheckPI.Name).FirstOrDefault 'Here we get the values of the property Value1 = CType(CheckPI.GetValue(Obj1, Nothing), Object) Value2 = CType(CheckPI2.GetValue(Obj2, Nothing), Object) 'If the objects values don't match, it return false If Object.Equals(Value1, Value2) = False Then ReturnValue = False Exit Try End If Next 'We passed all of the checks! Great Success! ReturnValue = True End If Catch ex As Exception HandleException(ex) End Try Return ReturnValue End Function A: If a custom entity at your disposal, what I've done is override the Equals and GetHashCode to return an identifier of the object: public override void Equals(object obj) { if (obj == null || !(obj is MyObject)) return false; return this.Key == ((MyObject)obj).Key; } public override int GetHashCode() { return this.Key; //or some other unique hash code combination, which could include //the type or other parameters, depending on your needs } This worked for me especially in scenarios with LINQ where the entities generated by the designer would not compare properly. I also sometimes have better luck with Object.Equals(obj1, obj2).
{ "language": "en", "url": "https://stackoverflow.com/questions/7559728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why PUSH a variable via a register, rather than PUSH the variable directly in assembly language? I came across a key logger program in asm in a forum. I though that I might create a key logger myself. When I was reading the code to see what was actually going on in that program, I came across some interesting things. 1.The program almost never pushed a variable to the stack. It moved the value of the variable to a register and then pushed the register. eg. ;hInst:DWORD 4 lea esi, hInst push esi 2.The program cleared arrays using stosd. eg: ;array1 BYTE 256 DUP(?) lea edi, array1 push 256/4 xor eax, eax rep stosd 3 The program used push-pop to assign values as in the above example. What are the advantages of the above conventions? A: 1) I can't think of any advantages on current machines, but way back in the day, you could only push regs. There was no push mem/immed form. 2) Simplicity/same as #1. I've heard that nowadays the string instructions are all but deprecated. However, way back in the day they were the only way to fly as they were much faster (cycle times not much better, but conserved the VERY limited memory bandwidth of the day by not forcing more instruction loads).
{ "language": "en", "url": "https://stackoverflow.com/questions/7559732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting pixels to minutes I have an application where I convert pixels to minutes and hours. Basically using minutes as a unit of measure as such: 120 minutes = 240 px I run that through this function: convertToTime: function (min) { var hours = Math.floor( min / 60); var minutes = Math.round(min % 60); if (minutes < 10) { minutes = "0" + minutes; } if (hours > 12) { hours = hours % 12; } return hours + ":" + minutes; } It is returning everything properly except for when minutes reaches 60. So for example it returns: 12:58 12:59 12:60 Which isn't what I want because that isn't a real time. I think the issue is the 2 pixels to one minute ratio. But I am having trouble getting it nailed down. Any help is greatly appreciated thanks! A: Do Math.floor(min) % 60 instead of Math.round(min % 60). % is the modulus operator. x % 60 will always yield an integer value between 0 and 59 inclusive for positive integer x, which is what you want for your minutes display. Your problem is that min is not an integer - exactly half the time, since you are obtaining it by dividing an integer by 2. In particular, when your pixel count is 119, min is 59.5, and Math.round() will round that up to 60. Since % is unlikely to do what you want for floating point inputs in general, the correct solution is to make sure the value is an integer before you calculate its modulus, instead of trying to round it afterwards. A: You are using Math.floor for the hours but Math.round for the minutes. You could fix your problem by using Math.floor for both of them! convertToTime: function (min) { var hours = Math.floor( min / 60); var minutes = Math.floor(min % 60); if (minutes < 10) { minutes = "0" + minutes; } if (hours > 12) { hours = hours % 12; } return hours + ":" + minutes; } A: You need too do Math.round(Math.round(min) % 60) or Math.round(Math.floor(min) % 60) or Math.round(Math.ceil(min) % 60) when you are using float may give you that error... example Math.round(59.5 % 60)
{ "language": "en", "url": "https://stackoverflow.com/questions/7559734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can I put this into a for loop? Possible Duplicate: android: how to elegantly set many button IDs This is an android program made with eclipse. I've tried using string concatenation in the place of imageButton1 to no avail. R is the generated class so I cannot go into it and edit it so that the imageButtons are part of an array. How can I put this into a for loop? seatButton[0] = (ImageButton) findViewById(R.id.imageButton1); seatButton[1] = (ImageButton) findViewById(R.id.imageButton2); seatButton[2] = (ImageButton) findViewById(R.id.imageButton3); seatButton[3] = (ImageButton) findViewById(R.id.imageButton4); seatButton[4] = (ImageButton) findViewById(R.id.imageButton5); seatButton[5] = (ImageButton) findViewById(R.id.imageButton6); seatButton[6] = (ImageButton) findViewById(R.id.imageButton7); seatButton[7] = (ImageButton) findViewById(R.id.imageButton8); seatButton[8] = (ImageButton) findViewById(R.id.imageButton9); seatButton[9] = (ImageButton) findViewById(R.id.imageButton10); A: You can, one approach is the following: ImageButton[] btns = {R.id.imageButton1, R.id.imageButton2, ..., R.id.imageButton10}; for(int i = 0, len = btns.length; i < len; i++) { seatButton[i] = (ImageButton) findByViewId(btns[i]); } A: You can also use getResources().getIdentifier(String name, String defType, String defPackage) where name is the resource name, defType is drawable and defPackage is your full package name. Which would result in something like: for (int i = 0; i < 10; i++) { int resId = getResources().getIdentifier("imageButton" + (i + 1), "id", your_package"); seatButton[i] = (ImageButton) findViewById(resId); } A: I don't know anything about your application or about android, but you could use runtime reflection (although it should not be used if you can avoid it, in my opinion). import java.lang.reflect.Field; ... for(int i=1; ; i++) { try { Field f = R.id.getClass().getField("imageButton" + i); seatButton[i-1] = (ImageButton) findByViewId(f.get(R.id)); // Add cast to whatever type R.id.imageButton<i> is } catch (Exception e) { break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7559735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VIM: How to autocomplete in a CSS file with tag ids and class names declared in HTML file I'm trying VIM for HTML, CSS and JavaScript editting. I've installed a number of plugins and configured VIM so that it allows me to autocoplete standart HTML/CSS code. And now I want to autocomplete my CSS code with tag ids and class names placed in HTML files just like in Apatana. For example: I have 1.html file with the following lines: <div id="my_id"> </div> <div class="my_class"> </div> And I have 1.css file with: #my_id{border-style:dotted} .my_class{border-style:solid} When I'm edditing a CSS file and pressing <c-x><c-o> right after #, I want VIM to suggest me tag ids from the 1.html file. The same for tag class names. What should I do? A: What I found helpful was adding the following line to my .vimrc: autocmd FileType css,scss setlocal iskeyword+=-,?,! which helps me autocompleting ids and classes with various special characters. A: <C-x><C-o> is for language-specific keywords such as <table> in an HTML file or background-color in a CSS file, the right shortcuts for word completion are <C-n> and <C-p>. Supposing your HTML and CSS files are loaded in two buffers (the HTML can be hidden or visible in a split), you are supposed to type a couple of characters of the id or class name and hit <C-n> for a list of possible completions. Type :help ins-completion for more info. I use AutoComplPop which provides realtime completion but there are other options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Invalid 'client_id' when using fb:registration XFBML tag (FB.getSession incompatible with OAuth2) I am trying to use the fb:registration XFBML tag. For the most part it seems to work; however, when I click the 'X' in the name field and then click 'Log Out' I get the error message Invalid 'client_id'. Although this error occurs, it seems the actual log-out process was successful; if I manually refresh the page I get the form in its logged-out state. I tried getting around this issue by subscribing to auth.logout events and reloading the page, but the error prevents the events from being triggered until after a page reload. Using firebug, I have found that the actual javascript error is FB.getSession incompatible with OAuth2 and it is called on line 9 of connect.facebook.net/en_US/all.js. I am not calling anything involving sessions, so I am not really sure why this is happening. I have tried using firefox, chrome, and safari, and all three experience the problem. Additionally, on safari and chrome I also get the same error when I try to login with the registration plugin. If I manually refresh the error goes away and the login process is successful, just like with logout. I am running this locally while in development, and so I made a facebook app just for testing with the site URL and domain referencing localhost. I am not in sandbox mode, and I am loading the js sdk like this: <div id="fb-root"></div> <script src="{$pageProtocol}connect.facebook.net/en_US/all.js"></script> <script> FB.init({ appId: {$facebookAppId}, cookie: true, xfbml: true, status: true, channelUrl: '{$pageProtocol}{$webhost}/{$channel}', oauth: true }); (This is called from a smarty template; I have looked at the generated source and all of the {$var} bits get replaced correctly.) Here is my xfbml tag: <fb:registration redirect-uri="http://localhost:8888/join?with=facebook&done=true" fields='[{"name":"name"}, {"name":"email"}, {"name":"city", "description":"City", "type":"select", "options":{ "_98":"Albany / Capital Region", "_3":"Albuquerque", "_99":"Allentown / Reading" } } fb_only = true > </fb:registration> (I shortened the list of cities above.) So if anyone can figure out what I am doing wrong please let me know. Pictures: from this modal: http://i.stack.imgur.com/sVN1E.png click Log Out and you get: http://i.stack.imgur.com/eiLwY.png
{ "language": "en", "url": "https://stackoverflow.com/questions/7559746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to select fields from one table and order them by fields from another table I have two tables. Structure of first table: id secondtableid value Structure of second table: id title How can I select fields 'id' from first table know value of 'value' column and order result by value of 'title' column of second table, if secondtable id is id of second table? A: You can order by fields you don't select. select FirstTable.id, FirstTable.value from FirstTable inner join SecondTable on (FirstTable.SecondTableID=SecondTable.ID) order by SecondTable.Title A: Something like this: select firsttable.id, firsttable.value, secondtable.title from firsttable join secondtable on firsttable.secondtableid = secondtable.id order by secondtable.title A: :) select id from first_table inner join second_table on first_table.secondtableid = second_table.id where value = 'Known Value' order by second_table.title A: This a beginner question, so I will answer as simple as possible: SELECT t1.id, t1.value FROM table1 t1 INNER JOIN table2 t2 ON t1.secondtableid = t2.id ORDER BY t2.title You can JOIN the tables, indicating how they join.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the 'context' that is being passed into the onUpdate, onEnabled, onDeleted, and onDisabled methods of the AppWidgetProvider? Is it the ApplicationContext or the ActivityContext of my app? Does it make a difference which one it is? A: Is it the ApplicationContext or the ActivityContext of my app? You should not care. It is a Context, period. Any assumptions you make beyond that are undocumented and subject to change. That being said, since there is not necessarily an Activity in your entire application, the Context is rather unlikely to be an Activity. A: It should be the ActivityContext. Besides your methods should take the format of.. void onDeleted(Context context, int[] appWidgetIds) void onDisabled(Context context) void onEnabled(Context context) void onReceive(Context context, Intent intent) void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) Where context should be Context myContext or anything of this nature.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need help designing table of rules to be used for SQL selections I'm refining a script that I have so that it could be automated & maintained by end users. Previously, I mentioned a portion of this script in this SO post. As Randy describes in his answer, the logic of the SQL statement should be replaced with a combination of tables and joins to accomplish the same end result. The basic situation and objective are as follows: Currently, the script will automatically assign advisors to students based on a complex set of rules involving several variables. The rules for terminal scenarios will change over time due to changes in staff (advisors hired/fired), majors (programs added/removed), and credit hour constraints (minimum hours needed to determine advisor). These rules will need to be maintained outside of the script/SQL so that end-users (deans/department heads) can manage the terminal scenarios. A custom table needs to be created to manage these rules effectively. Here's the SQL that is currently used to enforce these rules: SELECT DISTINCT s.id stu_id, stu_id.fullname stu_name, p.major1 major, p.minor1 minor, s.reg_hrs, NVL(st.cum_earn_hrs,0) ttl_hrs, p.adv_id curr_adv_id, adv_id.fullname curr_adv_name, CASE WHEN (p.adv_id <> 35808 AND p.major1 = 'NS') THEN (1165) WHEN (p.adv_id = 35808 AND p.major1 = 'NS') THEN (35808) WHEN (p.adv_id = 9179 AND p.major1 = 'DART') THEN (9179) WHEN (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24) THEN (70897) WHEN (p.major1 IN ('CDSC','CDSD')) THEN (52125) WHEN (p.major1 IN ('CA','CB')) THEN (24702) WHEN (p.minor1 = 'NURS') THEN (51569) WHEN (p.major1 = 'LEG') THEN (13324) WHEN (p.major1 = 'CC') THEN (73837) WHEN (p.major1 = 'CCRE') THEN (1133) WHEN ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I')) OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24)) OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG')) OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0)) OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))) THEN (9238) ELSE (p.adv_id) END new_adv_id, CASE WHEN (p.adv_id <> 35808 AND p.major1 = 'NS') THEN ('Deborah') WHEN (p.adv_id = 35808 AND p.major1 = 'NS') THEN ('Veronica') WHEN (p.adv_id = 9179 AND p.major1 = 'DART') THEN ('Stella') WHEN (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24) THEN ('Lisa') WHEN (p.major1 IN ('CDSC','CDSD')) THEN ('Joanne') WHEN (p.major1 IN ('CA','CB')) THEN ('Barbara') WHEN (p.minor1 = 'NURS') THEN ('Karen') WHEN (p.major1 = 'LEG') THEN ('Nancy') WHEN (p.major1 = 'CC') THEN ('Alberta') WHEN (p.major1 = 'CCRE') THEN ('Naomi') WHEN ((p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I')) OR (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24)) OR (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG')) OR ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat <> 'A' OR max_stu <= 0)) OR ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0))) THEN ('Staff') ELSE (adv_id.fullname) END new_adv_name, CASE WHEN (p.adv_id <> 35808 AND p.major1 = 'NS') THEN ('NS majors not assigned to Veronica go to Debbie') WHEN (p.adv_id = 35808 AND p.major1 = 'NS') THEN ('NS majors stay with Veronica') WHEN (p.adv_id = 9179 AND p.major1 = 'DART') THEN ('DART majors stay with Stella') WHEN (p.minor1 IN ('RT','RESP') AND st.cum_earn_hrs >= 24) THEN ('RT-RESP minors go to Lisa') WHEN (p.major1 IN ('CDSC','CDSD')) THEN ('CDSC-CDSD majors go to Joanne') WHEN (p.major1 IN ('CA','CB')) THEN ('CA-CB majors go to Barbara') WHEN (p.minor1 = 'NURS') THEN ('NURS minors go to Karen') WHEN (p.major1 = 'LEG') THEN ('LEG majors go to Nancy') WHEN (p.major1 = 'CC') THEN ('CC majors go to Alberta') WHEN (p.major1 = 'CCRE') THEN ('CCRE majors go to Naomi') WHEN (p.adv_id IN (SELECT DISTINCT id FROM fac_rec WHERE stat = 'I')) THEN ('Current advisor is inactive') WHEN (st.cum_earn_hrs < 24 AND (p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0 AND min_hrs >= 24)) THEN ('Total credits for this student did not meet the advisor reqs for this major') WHEN (s.id NOT IN (SELECT DISTINCT stu.id FROM stu_acad_rec stu, sess_info si WHERE stu.yr = si.prev_yr AND stu.sess = si.prev_sess AND stu.reg_hrs > 0 AND stu.reg_stat IN ('C','R') AND stu.prog = 'UNDG')) THEN ('This student did not attend '||si.prev_sess||si.prev_yr) WHEN ((p.adv_id||p.major1) IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE (stat <> 'A' OR max_stu <= 0))) THEN ('Current advisor is not advising students with this major') WHEN ((p.adv_id||p.major1) NOT IN (SELECT DISTINCT (id||major) FROM adv_detail WHERE stat = 'A' AND max_stu > 0)) THEN ('Current advisor is not advising students with this major') ELSE ('Student will stay with current advisor') END change_comm FROM stu_acad_rec s, prog_enr_rec p, OUTER stu_stat_rec st, id_rec stu_id, id_rec adv_id, sess_info si WHERE s.id = p.id AND s.id = st.id AND s.id = stu_id.id AND p.adv_id = adv_id.id AND s.yr = si.curr_yr AND s.sess = si.curr_sess AND s.reg_hrs > 0 AND s.reg_stat IN ('C','R') AND s.prog = 'UNDG' AND p.prog = 'UNDG' AND st.prog = 'UNDG' AND s.id NOT IN (3,287,9238,59999) {System test use IDs} INTO TEMP stu_list WITH NO LOG; I'm trying to build a table to hold all these rules, but have never created a table with this type of purpose. My idea so far is a table with this structure: adv_assign_rules ---------------- rule_no curr_adv_id major1 major2 minor1 minor2 cum_earn_hrs new_adv_id rule_desc rule_no_ref rule_stat rule_date An example row of this table that would accommodate the first case in the SQL selection might look like: rule_no 1 curr_adv_id !35808 major1 =NS major2 minor1 minor2 cum_earn_hrs new_adv_id 1165 rule_desc NS majors not assigned to 35808 go to Debbie rule_no_ref rule_stat A rule_date 2011-09-26 15:02:26.000 Are there any flaws to such a table? Can this type of setup accommodate all of these rules? Does anyone know where to find examples of tables used for similar purposes? I'm looking for suggestions on improvements and or alternate solutions to this problem. The "else" scenarios in these case statements indicate that no change in the student's advisor is required. Also, the case that has the largest amount of logic in it (last case before the "else" case), defaults the new advisor to 9238 - this indicates that other logic already in place will be used to assign a new adivsor. All cases prior are default scenarios that are special cases that do not follow the rules for assigning new advisors - these are the special cases that I'm trying to recreate in table format. UPDATE: I'm also looking for functionality to reproduce and/or scenarios. I added two fields called: rule_no & rule_no_ref which is a serial number (auto-increment) and a reference to another rule's serial number, respectively. Thanks in advance to any help that can be provided! A: I would go around this slightly different: 1) Create a table rule_type id name 2) Create a table rule_set id -- rule type -- relation to talbe 1 name staff_group -- relation to the appropriate staff group for that rule student_group -- relation to the appropriate student group for that rule val_int --- for the rules that require numeric number val_chr --- for rules that require integer values val_date --- for date values rules date_start --- start date of a rule date_end --- end date of a rule you can also make fields for interval paranters like integer range from X ... Y like: val_int_start val_int_end or for any other data type for that matter then create a store procedure that will process the rules and evaluate the appropriate data The good think about this approach is that you will really rarely need to code something new in the long run
{ "language": "en", "url": "https://stackoverflow.com/questions/7559757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: show subview when UITextField touched I'm pretty new to iPhone development, so please excuse my ignorance. I've googled this a bit and so far come up with nothing useful. Here is what I would like to do: I would like a subview to popup(with the rest of the screen showing in the background) when a UITextField is touched. The popup is a calculator UIView that I created in the IB. It seems it is better to have a popup show than a customized keyboard, due to Apple's developer guidelines. Here is my question. How do I capture the touch on the UITextField and how do I show the subview? I have tried things like below to show the subview, with no luck: CustomCalculator *customCalc = [[CustomCalculator alloc] initWithNibName:@"CustomCalculator" bundle:nil]; UIViewController *calcController = [self.customCalc.view]; [self.view addSubview:calcController.view]; A: Use the delegate method: - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { //Add your subview here return NO; //this will stop the keyboard from poping up } This way when someone taps the textfield, your view will popup instead of the keyboard. Now once the user is interacting with your view, you will have to manipulate the string in the textfield.text property directly as a reaction to the User tapping buttons in your view. A: Implement the UITextFieldDelegate and the method for it is -(void) textFieldDidBeginEditing:(UITextField *)textField The above method is fired when you touch the UITextField. You may then position the UIPopoverController (I'm guessing that is what you're using to show the view in a popup) and as soon as you're done there pass the values back to the UITextField. Hence the popover's/viewcontroller presented's delegate should be your textfield object. EDIT: After seeing the other answer below it struck me that I forgot to tell you how to stop the keyboard from showing. Just make this the first line in the method I've mentioned above: [textField resignFirstResponder];
{ "language": "en", "url": "https://stackoverflow.com/questions/7559764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pattern for writing a wrapper script which calls several other scripts? I have several (bash) scripts that are run both individually and in sequence. Let's call them one, two, and three. They take awhile to run, so since we frequently run them in order, I'm writing a wrapper script to simply call them in order. I'm not running into any problems, per se, but I'm realizing how brittle this is. For example: script two has a -e argument for the user to specify an email address to send errors to. script three has a -t argument for the same thing. script one's -e argument means something else My wrapper script basically parses the union of all the arguments of the three subscripts, and "does the right thing." (i.e. it has its own args - say -e for email, and it passes its value to the -e arg to the second script but to the -t arg for the third). My problem is that these scripts are now so tightly coupled - for example, someone comes along, looks at scripts two and three, and says "oh, we should use the same argument for email address", and changes the -t to a -e in script three. Script three works fine on its own but now the wrapper script is broken. What would you do in this situation? I have some big warnings in the comments in each script, but this bothers me. The only other thing I can think of is to have one huge monolithic script, which I'm obviously not crazy about either. A: The problem seems to be that people are thoughtlessly changing the API of the underlying scripts. You can’t go around arbitrarily changing an API that you know others are depending on. After all, it might not just be this wrapper script that expects script #3 to take a -t argument. So the answer seems to be: stop changing the underlying scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to send kind of persistent "Authorization" headers with PHP I don't know if it's possible, but if I don't ask I'll never know :) I have the exact problem discuted in this topic. That's: I have some static files in some folders and I want only some users to see that content. That users are coming from a previous login. Some possible solutions are discussed in that topic, but I have thought another possible solution. If I could send with PHP the Authorization HTTP Header, which contains the username and password of the user, and keep it persitent in subsequents requests (as I think it happens with the apache authentication). I would send that headers during my previous login, and then when the user would try to access to its directory, an .htaccess would check if he is a valid user. I have tried to send the Authorization header with PHP with: header('Authorization: Basic '.base64_encode($USERNAME.':'.$PASSWORD).PHP_EOL); But they are only present for one request. In .htaccess, I have checked that it's not possible to have an unique `Require user USERNAME', so I think it would be necessary to create an htpasswd file storing the same credentials than the ones the login process use, and then create an usual authentication configuration (basic or digest): AuthType Basic AuthName "Restricted Files" AuthUserFile /path/to/htpasswd/file Require user USERNAME Thank you in advance A: You could have an Basic or Digest HTTP authentification handled by Apache, with a simple "require valid user". No apache can implement a lot of mod_auth variations, check for mod_auth* in this page. So you can tell apache to authenticate on your database, or even to perform authentification with a custom code that you provide with mod_authnz_external. External script support is good as you could implement a session authentification with a cache level (to prevent redoing the whole authentification for each requested resource), which is what basically happen with the default cookie based session (first authenticate, then just transfer the PHPSESSID, so we'll check the session exists). A: I have thought another possible solution. If I could send with PHP the Authorization HTTP Header, You couldn't
{ "language": "en", "url": "https://stackoverflow.com/questions/7559773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: jquery use image alt text as link anchor text i'm trying to use an image's alt text and use it as the text for its corresponding anchor tag. this would be used at some point in a slide show. this is what i have so far, but it's inserting the all text for anything other than the first image in the div. what am i missing? Here's the jsbin example A: $(document).ready(function(){ $("div img[alt^='slide']").each(function(i, item){ var imageAlt = $(item).attr("alt"); var text = "this is " + imageAlt + "."; console.log(imageAlt); $("ul a").eq(i).text(text); }); }); Fiddle: http://jsfiddle.net/maniator/g33H8/1/
{ "language": "en", "url": "https://stackoverflow.com/questions/7559775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS: Element behind all sibling elements within a parent element I want to have a inside of another that will serve as a background to the container and sit behind all of the other elements inside of the container. The HTML would be something like so: <div id='container'> <div>Blah</div> <input type='text'/> <input type='submit'/> <div id='background'> <img.../> Some Text Maybe? </div> </div> My failed CSS: #background{ float:left; z-index:-999; background-color:black; height:'+o.height+'px; width:'+o.width+'px; } The 0.variables are from a jQuery plugin I'm making this for - basically the div should be the same height and width that the parent is. Where I currently stand: My background sits below the sibling elements (along the y-axis not the z). When I play around with the position property, it either places the element behind the parent or it has no effect. What I ultimately am trying to do is create a jQuery plugin that adds an animated background to a specified element. I'm not even sure if what I'm trying to do with the CSS is possible. A: Try putting the background as the container's first child, then using position: absolute;. Mess around with the z-index until it works. Also, you may need to specify a "more negative" z-index on the <body>, otherwise your background element will end up behind the body (and thus invisible).
{ "language": "en", "url": "https://stackoverflow.com/questions/7559776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dimensional Level Security / Per User Data Security in SSAS Cube? I'm part of a team looking to move from our relational data warehouse to a SSAS cube. With our current setup we have an "EmployeeCache" table (basically a fact) which is a mapping from each of our employee ids to their viewable employee ids. This table is joined in our model to our DimEmployee table so that for every query that needs personally identifiable information the DimEmployee records are filtered. The filter is applied from a session variable that is the user id which is making the query. All of the examples we researched to provide dimension level security in a SSAS cube have required the use of Windows managed security. The systems that create the data that is being analyzed handle their own security. Our ETLs map the security structure into the aforementioned EmployeeCache and DimEmployee tables. We would like to keep this simple structure of security. As we see it there is no way to pass in session values (aside from using the query string which we're not seeing it possible with Cognos 10.1) to the cube. We're also not seeing any examples out there on security which does not require the use of Windows auth. Can someone explain if there is a way to achieve dimensional security as I have previously described in a SSAS cube? If there is no way possible could another cube provider have this functionality? A: Two thoughts. Firstly, SSAS only supports windows authentication (see Analysis Services Only Windows Authentication) and this is unchanged in Sql Server 2012. But you can pass credentials in the connection string to analysis services. Secondly, could you alter the MDX of every query and add a slicer to restrict the data to only the data a user should see?
{ "language": "en", "url": "https://stackoverflow.com/questions/7559777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 Asset Pipeline Woes I am using JW Player to play streaming audio files. I have built a custom skin but can't get the player to show up. When you build your custom skin, you zip up the skin along with the skin.xml file (where the flash reads for its image files and other settings) and then you point the javascript config object to point to that skin zip file. jw = { 'flashplayer':'/assets/player.swf', 'controlbar': 'top', 'autostart': 'false', 'width':'400', 'height':'49', 'playlist': '[]', 'skin':'/assets/skin.zip', 'dock':'false', 'wmode':'transparent' } jwplayer('player').setup(jw); For some reason the player does not show up on staging or prod envrionments, however, I can download the zip file from the browser. Would the new Rails 3.1 asset pipeline have anything to do with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7559779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I determine why JPA/eclipselink/J2EE is issuing a ROLLBACK to the DB? I am chasing a problem where I see SQL statements run in my database log in a transaction, then see that transaction rolledback. This happens on both Oracle and Postgres, but only on some installations. The application itself is a pretty standard J2EE application using JPA and Eclipselink. I am not seeing any exceptions, nor is the code explicitly giving up and rolling back. The best I have been able to do so far is find this log statement: [#|2011-09-26T11:30:56.052-0700|FINER|sun-appserver2.1|org.eclipse.persistence.session.file:/opt/glassfish/domains/domain1/applications/j2ee-apps/myapp/myapp-ejb_jar/_myapp-ejbPU.transaction|_ThreadID=18;_ThreadName=httpSSLWorkerThread-8888-2;ClassName=null;MethodName=null;_RequestID=e78196 09-bf2e-4026-8cbb-87fdd047c5eb;|begin unit of work flush|#] It occurs at the exact same time as the ROLLBACK in the postgres log: appuser @ dbname: 102012/7/67486 2011-09-26 18:30:56.052 UTC - LOG: execute S_3: ROLLBACK Note that the DB is on UTC while the application is on Pacific. The relevant code is being called using a webservice with @TransactionAttribute(TransactionAttributeType.SUPPORTS) I am working with both logging levels and the debugger to see if I can find an exception being thrown and swallowed that might cause this. How can I find out what code is causing the rollback? A: You can enable logging on finest with EclipseLink to debug the issue. Any exception that occurred within EclipseLink will be logged. See, http://wiki.eclipse.org/EclipseLink/Examples/JPA/Logging Also ensure you are not throwing an error to cause your SessionBean to rollback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I get an exit code from WMI spun remote process I'm executing a process remotely via WMI (Win32_Process Create) but am unable to figure out how I can determine when the process has completed executing. When I first issue the command, there is an exit code (0 for success) but that just tells me the process has been successfully spawned. Is there a way I can know when the process ends? Thanks! A: Faced same issue and wrote a simple VMI wrapper: var exitStatus = WmiOperations.Run("notepad.exe", wait:10); Synopsis for Run is: int Run(string command, // Required string commandline = null, // (default=none) string machine = null, // (default=local) string domain = null, // (default=current user domain) string username = null, // (default=current user login) string password = null, // (default=current user password) SecureString securePassword = null, // (default=current user password) double wait = double.PositiveInfinity); // (default=wait til command ends); Source code can be downloaded from here. Give caesar his due, code is inspired from this one. Simply: * *Refactored things to static class *Added more control on remoting parameters *Redesigned event watcher to suppress the unappealing CheckProcess test A: Here is an example create on the top of .NET objects but written in Powershell, it's easy to translate it to C# Clear-Host # Authentication object $ConOptions = New-Object System.Management.ConnectionOptions $ConOptions.Username = "socite\administrateur" $ConOptions.Password = "adm" $ConOptions.EnablePrivileges = $true $ConOptions.Impersonation = "Impersonate" $ConOptions.Authentication = "Default" $scope = New-Object System.Management.ManagementScope("\\192.168.183.220\root\cimV2", $ConOptions) $ObjectGetOptions = New-Object System.Management.ObjectGetOptions($null, [System.TimeSpan]::MaxValue, $true) # Equivalent to local : # $proc = [wmiclass]"\\.\ROOT\CIMV2:Win32_Process" $proc = New-Object System.Management.ManagementClass($scope, "\\192.168.183.220\ROOT\CIMV2:Win32_Process", $ObjectGetOptions) # Now create the process remotly $res = $proc.Create("cmd.exe") # Now create an event to detect remote death $timespan = New-Object System.TimeSpan(0, 0, 1) $querryString = "SELECT * From WIN32_ProcessStopTrace WHERE ProcessID=$($res.ProcessID)" $query = New-Object System.Management.WQLEventQuery ($querryString) $watcher = New-Object System.Management.ManagementEventWatcher($scope, $query) $b = $watcher.WaitForNextEvent() $b
{ "language": "en", "url": "https://stackoverflow.com/questions/7559787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: REGEX Str Replace- finding link text and making them links I've written this functionality in Flash before without issue; however, I'm now attempting to do it with JavaScript and I'm running into some difficulty. Using Regex, I'm trying to scour a string looking for anything that resembles a link... for example http://www.google.com or http://stacoverflow.com/question/ask; then wrap that result with the appropriate: : <script type="text/javascript> var mystring = "I'm trying to make this link http://facebook.com/lenfontes active." /// REGEX that worked in Flash to grab ALL parts of the URL including after the .com... var http = /\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/gi; // preform the replace based on the Regex mystring = mystring.replace(http, function(){ var link = arguments[0]; if (link.indexOf("http") == -1){ link = "http://" + link;} return "<a href='"+link+"'>"+arguments[0]+"</a>"; }); $('#results).html(mystring); </script> The issue I'm having: anything after the ...com/ is ignored. Therefore the link isn't correct... Even while I post this question, the Stack Overflow interface has taken my text and rendered it out with the appropriate link tags... I need to do that. Any suggestions welcomed. -- Update: Sorry, let me expand.. I'm not only looking for http:// it needs to detect and wrap links that start with "https://" and/or just start with "www" A: Your regex doesn't work because ECMA (JavaScript) doesn't support POSIX character classes, so [:punct:] ignores the . in .com.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to detect if user previously authorized rights to a tabbed application without showing the authorization dialog? How can you detect if a user previously authorized a tab application, without showing the user an authorization dialog? This is a user experience concern. We don't want to throw the user at an authorization dialog without a call-to-action, but we don't want a call to action to be shown to log the user in if the user previously authorized the app. Here's the scenario. A tab application is hosted on a page that has several other applications. In Facebook, the 'Like' button does not work at the tab level but on a page level, so a user may have liked a different application without having seen the current application. Therefore, if any 'Like gate' is used on the landing page of a tab application, and authorization is required to use the app, then when we log the user in the user will be immediately shown the authorization screen without a call to action, unless we can detect that the user previously authorized this application. A: You could use the javascript SDK and check the login status to see if they have authorized your application. If they have, you could redirect with javascript elsewhere or make the calls you need. If they haven't you could then show the call to action on your page. Something like: FB.getLoginStatus(function(response){ if(!response.authResponse){ // redirect to authorization page top.location.href="http://www.facebook.com/dialog/oauth?client_id=appid&redirect_uri=http://facebook.com/somefanpage"; // or instead show a call to action div } else { //load fan page specific content } }); But this will only tell if you if they are currently logged in and authenticated with your application or not. The only way you would be able to tell if this is a returning user vs a brand new user is if Facebook sent over the userId in the signed_request like ifaour mentioned (then you could call /userId/permissions with your app access token or look up in your database), but Facebook most likely won't send the userId since your users probably aren't authenticating with your individual tab application but a different shared application key. A: Well Facebook will send the user id in the signed_request only when the user authorize your application. So as long as that piece of information is missing then this means the user didn't authorize your application yet i.e. show the auth dialog (or redirect to auth screen)! More about this in the Page Tab Tutorial: Integrating with Facebook APIs When a user navigates to the Facebook Page, they will see your Page Tab added in the next available tab position. Broadly, a Page Tab is loaded in exactly the same way as a Canvas Page. Read more about this in the Canvas Tutorial. When a user selects your Page Tab, you will received the signed_request parameter with one additional parameter, page. This parameter contains a JSON object with an id (the page id of the current page), admin (if the user is a admin of the page), and liked (if the user has liked the page). As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can Excel charts be interactively zoomed and panned? I've always wanted this feature in excel I'm wondering if it's possible to develop a plugin or if one exists already? A: This might be irrelevant by now (seeing as it's been half a year), but: One improvement for Stephen Bullen's approach I would suggest is to map the scrollbar values to the actual values. What I mean is this: if you're fully zoomed out (you see everything), you can still scroll around which doesn't make sense. Additionally, if your dataset grows, you'd have to reformat the scrollbars max. values. I solved it like this: * *Let both scrollbars assume values 1-1000. *Let a specific cell contain the number of the last row of your dataset (can be formula-computed somehow, I guess) - I assume cell Z1 contains this information. *Define a new name 'ActualZoomVal', let it point to an arbitrary cell. I assume Z2 here. *Define a new name 'ActualScrollVal', let it point to a different arbitrary cell. I assume Z3 here. *Let the cell of 'ActualZoomVal' contain following formula: =MAX(2;ROUND(ZoomVal*($Z$1/1000);0)) *Let the cell of 'ActualScrollVal' contain following formula: =ROUND(($Z$1-ActualZoomVal)*(ScrollVal/1000);0) *Create the diagram as suggested in Stephen Bullen's example file, but with ActualZoomVal/ActualScrollVal instead of ZoomVal/ScrollVal Not only is this a 'cleaner' and more flexible solution, it also improves usability - say you want to zoom in on the last part of the data set from a fully zoomed out state, then just set the scroll bar all the way to the right and keep zooming in until you've reached the desired zoom level. A: Here is one solution for zooming on Excel charts. You add a zoom button to the chart, and pressing the button calls a macro to enlarge the chart by a specified amount. The workbook containing the macro is available for free download at http://www.excelcampus.com/vba/zoom-on-excel-charts A: They can if you use dynamic names ranges. Stephen Bullen has a great example here Screenshot below The data can be zoomed (amount of data) and scrolled (change start position)
{ "language": "en", "url": "https://stackoverflow.com/questions/7559795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: IP falls in CIDR range I have an IP like this: 12.12.12.12 I'm looping through different IP ranges (in 12.12.12.0/24 (example)) format, and trying to see if the IP is in the range. I have tried various methods such as inet_addr and comparing but I can't seem to get it. Is there an easy way to do this? I'm using Windows. A: Just test whether: (ip & netmask) == (range & netmask) You can determine the netmask from the CIDR parameters range/netbits as follows: uint32_t netmask = ~(~uint32_t(0) >> netbits); A: Take the binary representation and zero out what is not matching your network mask. Clarification: Let's say you have the IP a.b.c.d and want to match it to e.f.g.h/i then, you can throw the IP into one unsigned integer, uint32_t ip = a<<24 + b<<16 + c<<8 + d and do the same with uint32_t range = e<<24 + f<<16 + g<<8 + h. Now you can use your network mask: uint32_t mask = (~0u) << (32-i). Now, you can simply check if ip "is in" range by comparing them: ip & mask == range & mask.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Match results in multiple tables MYSQL Hi I have a query that is giving me a few problems and it was suggested I ask a separate question about the end result rather than the problem. So I have three tables and some user input. the tables are: * *users, *usersLanguages and *usersSkills each table has a related ID the users table has ID and on the other two they have userID to match skills and languages to users the user input is dynamic but for example it can be 1 for usersLanguages and 2 for usersSkills The user input is taken from a form and what i need to do is match get the results of users depending on the language IDs or skill ids passed through. for example i can pass two user ids and three language ID's. SELECT DISTINCT users.ID, users.name FROM users INNER JOIN usersSkills ON users.ID = usersSkills.userID INNER JOIN usersLanguages ON users.ID = usersLanguages.userID WHERE activated = "1" AND type = "GRADUATE" AND usersSkills.skillID IN(2) AND usersLanguages.languageID IN(2) GROUP BY usersSkills.userID HAVING COUNT(*) = 1, usersLanguages.userID HAVING COUNT(*) = 1 A: You do not mix group by and having clauses. having is not a part of group by, in fact you can have having without a group by, in which case it will work as a more capable (and slower) where clause. SELECT u.ID, u.name FROM users u INNER JOIN usersSkills us ON u.ID = us.userID INNER JOIN al ON u.ID = ul.userID WHERE u.activated = '1' AND u.type LIKE 'GRADUATE' AND us.skillID IN('2') AND ul.languageID IN('2') GROUP BY u.ID HAVING COUNT(*) = 1 * *because of the join criteria, ul.userID = us.userID = u.ID so it makes no sense to group by both. Just group by u.id, because that's the ID you select after all. *u.name is functionally dependent on ID, so that does not need to be listed (*). *When doing a test like u.type = 'GRADUATE', I prefer to do u.type LIKE 'GRADUATE' because LIKE is case insensitive and = may not be depending on the collation, but that's just me. *Distinct is not needed; group by already makes the results distinct. Having works on the resultset up to and including group by, so in this case you need only one having clause. If you want to have more, you need to treat them the same as a where clause: having count(*) = 1 AND SUM(money) > 10000 (*) this is only true in MySQL, in other SQL's you need to list all non-aggregated selected columns in your group by clause. Whether they are functionally dependent on the group by column or not. This slows things down and makes for very long query-syntax, but it does prevent a few beginners errors. Personally I like the MySQL way of doing things. A: something like SELECT * from users left join usersLanguage on users.id=usersLanguage.userID left join usersSkills on usersSkills.userID=users.id where usersLanguage.id in (1, 2, 3) and usersSkills.id in (1, 2, 3) GROUP BY users.id will probably work A: try this SELECT users.ID,user.name FROM users INNER JOIN usersSkills ON users.ID = usersSkills.userId INNER JOIN AND usersLanguages ON users.ID = usersLanguages.userID WHERE activate = '1' AND type = 'GRADUATE' AND usersSkill.skillID IN (2) AND usersLanguages.languageID IN (2) GROUP BY users.ID
{ "language": "en", "url": "https://stackoverflow.com/questions/7559805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Slow jQuery animation on iPad2 I'm currently building iPad-optimised website. I have some chunks of text that I should show/hide when user touches appropriate button. The text is inside of < p> tag. I use jQuery for toggling the visibility of the text: $("my selector").toggle("fast"); But it is really choppy ... Is there some iOS specific way to do the animation, maybe another framework or something else ? I don't think it should be that slow ... A: There are several animation scripts that targets iOS, but the basics are that you should use CSS animations instead, and more specifically the translate3d property (for positioning) that triggers the iOS hardware. For toggling opacity, you can use a regular -webkit-transition and toggleClass, f.ex: p { -webkit-transition: opacity 0.2s linear; opacity:1 } p.hide { opacity:0 } and then: $("my selector").toggleClass('hide'); I made a simple demo for you here: http://jsfiddle.net/rQFZd/ You can detect touch devices and serve css animation specifically to those that supports (and prefers) it. EDIT: example of animating height: http://jsfiddle.net/rQFZd/1/. I’m not sure about iOS performance though, but I think it should be better than jQuery. You can also add another container and then use translate3d to reposition the element instead of shrinking it, that should most certainly be smoother on iOS. Example: http://jsfiddle.net/rQFZd/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7559810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: xslt transform prints out entire xml file or none of it, rather than transforming it? I am trying to transform an xml file with xsl stylesheet into html. this is the java TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(classLoader.getResourceAsStream("driving.xsl"))); StreamResult drivingHtml = new StreamResult(new StringWriter()); transformer.transform(new StreamSource(classLoader.getResourceAsStream("driving.xml")), drivingHtml); System.out.println(drivingHtml.getWriter().toString()); this is some of the xml: <?xml version="1.0" encoding="UTF-8"?> <user xmlns="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2"> <address type="primary"> <street>1031 Court St.</street> <city>Monhegan, NY</city> </address> <address type="secondary"> <street> Elm St.</street> </address> this is the xsl: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <head> <title>User</title> </head> <body> <p>Detailed Addresses</p> <xsl:apply-templates select="/user/address"/> </body> </html> </xsl:template> <xsl:template match="address"> <table> <th>Primary</th> <th>Secondary</th> <tr> <td> <xsl:value-of select="address" /> </td> </tr> </table> </xsl:template> </xsl:stylesheet> when i run that, i get the html from the root template match, but nothing from the template matching address. i've tried other variations of templates, and instead of getting at least the basic html, i just get the entire contents of xml file ouputted. A: Check your namespace or or modify your XML to something like the following one to add a namespace-prefix: <?xml version="1.0" encoding="UTF-8"?> <user xmlns:a="http://notreal.org/ns1" xmlns:poi="http://notreal2.org/ns2"> <address type="primary"> <street>1031 Court St.</street> <city>Monhegan, NY</city> </address> <address type="secondary"> <street> Elm St.</street> </address> </user> A: Looks like a namespace issue. The address element in the source has the namespace http://notreal.org/ns1, but your XSLT doesn't reference that namespace at all. Try including the xmlns="http://notreal.org/ns1" in your xslt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: exit function when interrupted I have an interrupt function called, interrupt_Foo() {...} which turns on a flag when 1 second has elapsed, and a user-defined function foo_calling() {...} which calls another function foo_called() {...}. I want to stop the process in foo_called() when 1 second has elapsed. The code snippet below may elaborate further my need: void interrupt interrupt_foo() { ... if(1 second has elapsed) { flag1s = 1; } else { flag1s = 0; } } void foo_calling() { // need something here to stop the process of foo_called() ... (*fptr_called)(); // ptr to function which points to foo_called ... } void foo_called() { // or something here to stop the process of this function ... // long code ... } This is real time operating system so polling the 1 second flag inside foo_called() at some portion in the code is undesirable. Please help. A: If you are willing to write non-portable code, and test the heck out of it before deploying it, and if the processor supports it, there may be a solution. When the interrupt handler is called, the return address must be stored somewhere. If that is a location your code can query - like a fixed offset down the stack - then you can compare that address to the range occupied by your function to determine if 'foo_called is executing. You can get the address of the function by storing a dummy address, compiling, parsing the map file, then updating the address and recompiling. Then, if your processor supports it, you can replace the return address with the address of the last instruction(s) of foo_called. (make sure you include the stack cleanup and register restoration code.). Then exit the interrupt as normal, and the interrupt handling logic will return code to the end of your interrupted function. If the return address is not stored in the stack, but in an unwritable register, you still may be able to force quit your function - if the executable code is in writrable memory. Just store the instruction at the interruupt's return address, then overwrite it with a jump instruction which jumps to the function end. In the caller code, add a detector which restored the overwritten instruction. A: I would expect that your RTOS has some kind of timer signal/interrupt that you can use to notify you when one second has passed. For instance if it is a realtime UNIX/Linux then you would set a signal handler for SIGALRM for one second. On a RT variant of Linux this signal will have more granularity and better guarantees than on a non-RT variant. But it is still a good idea to set the signal for slightly less than a second and busy-wait (loop) until you reach one second.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I download code for game levels in iOS? guys! I want to build a game for iOS, and I need to download levels for it. Levels should allow me to organize conditional statements, simple object discription. I know that downloading any code in iOS is prohibited, so I can't use Lua or smth. But how do other applications solve this problem? A: Could you use XML? You can have flags like: <conditionalA>true</conditionalA> to handle your conditionals and descriptions (textual?) can again be wrapped inside tags: <descriptionA>description</description>. If you meant description in terms of position of objects, you can do things such as <position>100, 100</position> Have a look at NSXMLParser if you do decide to do something like this. A: You have some sort of file that describes how the level looks. Lets say you have a game where the user has to walk through a maze. You could have a text file which shows the map: ######## # # # # ######## # # ######## # # # # ######## Well, this is really simple. The # characters are walls ... You could then already implement all the logic in the code that you ship with your application and just download the files describing your levels. So you are not downloading any codes, just files that you have to parse with the code you already shipped A: Any code already should be in your app. Downloaded level could only contain data which app could decode and behave appropriately. A: Expansion packs, Mods, etc. are all data. Design your application to read XML / Text / Some sort of serialized data to create level's, characters, events etc. Then when you want to release something new, You package it up as that data (XML, text, serialized etc.). You don't need to have code, as your application should already know how to interpret that data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Communication between two data grids I am trying to make connection between two datagrid in two separate windows. Until now, I am able to create a datagrid in one FLEX browser window but got stuck furthur. On some click event in one of 1st datagrid row-column field value, (i.e itemRenderer in form of button), I want to open a new window (using some LocalConnection or ExternalInterface.call) to open another window with the part of the original data grid. Is it possible to do so ? Which method should I use - LocalConnection or ExternalInterface.call ? Please help. Thanks. A: On some click event use navigateToURL() to launch your second browser window with your second application that contains the second DataGrid. Once the two instances are up you can communicate between them using LocalConnection.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript regex to parse urls without protocol String.prototype.linkify = function() { this.replace(/((ht|f)tp:\/\/)?([^:\/\s]+)\w+.(com|net|org)/gi, '<a href="$&">$&</a>') } with http://www.google.com http://yahoo.com www.facebook.com it matches them all, however I want facebook to be prepended with the protocol group if it does not exist. Is there a way to do this without doing two .replace ? A: If you don't actually need to match FTP URLs, you can just assume the "http://" section of the link. This regex does that, while allowing you to also use https. this.replace(/(http(s)?:\/\/)?(([^:\/\s]+)\.(com|net|org))/gi, '<a href="http$2://$3">http$2://$3</a>') I'm not sure what your use case is, but I'd like to note this regex will fail on the following urls: * *http://google.com/spam = <a href="http://google.com">http://google.com</a>/spam *http://google.ca = no match This is because you're using few hardcoded tlds (com, net, org), and aren't matching any characters after the domain. A: I would do something like this: String.prototype.linkify = function () { return this.replace(/((?:ht|f)tp:\/\/)?([^:\/\s]+\w+\.(?:com|net|org))/gi, function (_, protocol, rest) { var url = (protocol || "http://") + rest return '<a href="' + url + '">' + url + '</a>' }) } (I fixed a couple of other problems with your code: you were missing a return and you were matching the domain name period using . rather than \..) And I assume I don’t need to point out how poorly this will match URL:s in general, due to a number of problems with your pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A short as possible unique ID I'm making a tool for optimizing script and now I want to compress all names in it to the minimum. I got the function started for it, but it somehow bugs and stops after length 2 is exceeded. Is there an easier way to do this? I just need a pattern that generates a String starting from a -> z then aa -> az ba -> bz and so on. public String getToken() { String result = ""; int i = 0; while(i < length){ result = result + charmap.substring(positions[i], positions[i]+1); positions[length]++; if (positions[current] >= charmap.length()){ positions[current] = 0; if ( current < 1 ) { current++;length++; }else{ int i2 = current-1; while( i2 > -1 ){ positions[i2]++; if(positions[i2] < charmap.length()){ break; }else if( i2 > 0 ){ positions[i2] = 0; }else{ positions[i2] = 0; length++;current++; } i2--; } } } i++; } return result; } UNLIKE THE OTHER QUESTIONS!! I dont just want to increase an integer, the length increases to much. A: I would use a base 36 or base 64 (depending on case sensitivity) library and run it with an integer and before you output, convert the integer to a base 36/64 number. You can think in terms of sequence, which is easier, and the output value is handled by a trusted library. A: You can use: Integer.toString(i++, Character.MAX_RADIX) It's base36. It will be not as greatly compressed as Base64 but you have a 1-line implementation. A: Here's one I used public class AsciiID { private static final String alphabet= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; private int currentId; public String nextId() { int id = currentId++; StringBuilder b = new StringBuilder(); do { b.append(alphabet.charAt(id % alphabet.length())); } while((id /=alphabet.length()) != 0); return b.toString(); } } A: You could search for some library that operates numbers of any radix, say 27, 37 or more. Then you output that number as alphanumeric string (like HEX, but with a-zA-Z0-9). A: Well let's assume we can only output ASCII (for unicode this problem gets.. complicated): As a quick look shows its printable characters are in the range [32,126]. So to get the most efficient representation of this problem we have to encode a given integer in base 94 so to speak and add 32 to any generated char. How you do that? Look up how Sun does it in Integer.toString() and adapt it accordingly. Well it's probably more complex than necessary - just think about how you convert a number into radix 2 and adapt that. In its simplest form that's basically a loop with one division and modulo. A: In your tool you need to create a dictionary, which will contain an unique integer id for each unique string and the string itself. When adding strings to the dictionary you increment given id for each newly added unique string. Once dictionary is completed, you can simply convert ids to String using something like this: static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static final int CHARS_LENGTH = CHARS.length(); public String convert(int id) { StringBuilder sb = new StringBuilder(); do { sb.append(CHARS.charAt(id % CHARS_LENGTH)); id = id / CHARS_LENGTH; } while(id != 0); return sb.toString(); } A: This function generates the Nth Bijective Number (except zeroth). This is the most optimal coding ever possible. (The zeroth would be an empty string.) If there were 10 possible characters, 0-9, it generates, in order: * *10 strings of length 1, from "0" to "9" *10*10 strings of length 2, from "00" to "99" *10*10*10 strings of length 3, from "000" to "999" *etc. The example uses 93 characters, because I just happened to need those for Json. private static final char[] ALLOWED_CHARS = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~" .toCharArray(); private static final AtomicInteger uniqueIdCounter = new AtomicInteger(); public static String getToken() { int id = uniqueIdCounter.getAndIncrement(); return toBijectiveNumber(id, ALLOWED_CHARS); } public static String toBijectiveNumber(int id, char[] allowedChars) { assert id >= 0; StringBuilder sb = new StringBuilder(8); int divisor = 1; int length = 1; while (id >= divisor * allowedChars.length) { divisor *= allowedChars.length; length++; id -= divisor; } for (int i = 0; i < length; i++) { sb.append(allowedChars[(id / divisor) % allowedChars.length]); divisor /= allowedChars.length; } return sb.toString(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7559834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Chances of memory leak when valgrind says no memory leak My C code does not show any memory leak while checking with valgrind. But when i integrate that code with another system, which has its own memory management but of course calls malloc for allocating memory, shows memory leak. Valgrind check used to be correct everytime, but this time its not working for me. I would like to know if there is chances of memory leak although valgrind says no memory leak. What can be the strongest parameters of valgrind to set to find the hardest memory leak? A: I think it's very possible that you still have a memory leak - not because I think that valgrind has bugs, but because I think that integrating it with another project probably exercises the code differently than your test does. (FYI - I haven't found any cases of memory leaks where valgrind says my code is clear, although that's hardly exhaustive proof). I think in order to solve the problem is to either add tests to your un-integrated version or to run the integrated version in valgrind. Other options might be making sure you're not suppressing any errors that could be harmful, add --leak-check=full, or otherwise play with your valgrind setup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jqGrid Resizing Problem I have a jqGrid at my web page. I have a resizing problem. When I restore down my web page, all the elements at my page resizes automatically however my jqGrid table doesn't. Actually I have edited my table's width as follows: ... width:1000, ... I want it has a minimum width but have a automatic resizing when I restore down (get more smaller) my web page. How can I do that? EDIT: I tried thatbut I am not sure is this the right way: confTable is my jqGrid id and content is the parent element's id of it. $("#confTable").jqGrid('gridResize', { minWidth: 800, minHeight: 100 }); $(window).bind('resize', function() { var gridWidth = $("#confTable").width(); var contentWidth = $("#content").width(); if (gridWidth > 0 && Math.abs(gridWidth - contentWidth) > 5) { $("#confTable").jqGrid('setGridWidth', contentWidth); } }).trigger('resize'); I wanted to implement the solution here described. However setgridWidht and the lines of .attr() didn't work. Is my code browser compatible and what is the wrong can be while I was trying the implement the solution of that question? PS: It says: $("#confTable").setGridWidth is not a function. Actually I need to resize my jqGrid according to its parent's parent. A: Here is a simple example you could try: $(window).resize(function(){ $("#confTable").setGridWidth($(this).width() * .95); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7559841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML syntax for selector with multiple subclasses I am trying to define a css rule for multiple sublcasses of a selector. Here is an example of the html. <div id="row1"> <div class="col1"> <div class="col2"> <div class="col3"> </div> <div id="row2"> <div class="col1"> <div class="col2"> <div class="col3"> </div> Say I want to make the width of col1, col2, col3 within row1 all the same. I tried this css but it doesnt stay specific to row1: #row1 .col1, .col2, .col3{ width: 80px; } I can probably add #row1 infront of every .col but that wouldnt look as nice. What is the correct way to do this?? A: I can probably add #row1 infront of every .col but that wouldnt look as nice. What is the correct way to do this?? That is the only way to do that, at least to get the rule you describe. With the markup you have, you could get the same effect with: #row1 div A: This should do: #row1 > div { width: 80px; } The rule applies to every div element that is a child of #row1. I specified a child selector (the >) in case you have nested div elements that you do not want the rule to apply to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting Resources from a jar: classloader vs class resourceasstream I am trying to implement a method that when called, get a string from a particular resource in the jar that the class is loaded from. For example: import mypath.myclass; //from a jar String result = gitid.getGitId(myclass.class); On the backed I am currently using: InputStream is = null; BufferedReader br = null; String line; is = c.getResourceAsStream("/com/file.text"); The problem is I keep getting the same resource for no matter what class I give it. I have also tried: is = c.getClassLoader().getResourceAsStream("/com/file.text"); This fails completely. Any suggestions would be much appreciated. Also,what is the difference between calling getResourceAsStream from the class loader vs the class? A: The Class.getResourceAsStream() gets a ClassLoader instance, pretty much the same you get from Class.getClassLoader() call. What you could do, is get the URL for a given class and replace class resource path your path of your file. for example, the following code will return resource from the same jar: Class c = String.class; URL u = c.getResource('/' + c.getName().replace('.', '/') + ".class"); String s = u.toString(); URL url = new URL(s.substring(0, s.indexOf('!')) + "!/META-INF/MANIFEST.MF"); InputStream is = url.openStream(); You'll have to handle not jarred class folders separately. A: Probably all classes were loaded by the same ClassLoader instance. So as long as the path of the resource doesn't change you will get the same resource every time. getResourceAsStream: This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).
{ "language": "en", "url": "https://stackoverflow.com/questions/7559846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: is it a good idea to handle deadlock retry from stored procedure catch block From what i undertand it is impossible to completely prevent a transaction from deadlocking. I would like to have transaction that neverfail from the perpective of application code. So i have seen this pattern in use for Microsoft SQL and I wonder if this is a good idea? DECLARE @retry tinyint SET @retry = 5 WHILE @retry >0 BEGIN BEGIN TRANSACTION BEGIN TRY // do transaction her COMMIT BREAK END TRY BEGIN CATCH ROLLBACK if (ERROR_NUMBER() = 1205 OR ERROR_NUMBER() = 1222) BEGIN SET @retry = @retry - 1 IF @retry = 0 RAISEERROR('Could not complete transaction',16,1); WAITFOR DELAY '00:00:00.05' -- Wait for 50 ms CONTINUE END ELSE BEGIN RAISEERROR('Non-deadlock condition encountered',16,1); BREAK; END END CATCH; END A: The implementation you have is not a good idea, as it blindly retries without finding out the actual error. If the error was a timeout, for example, you might end up tying up a connection for 5 times the timeout amount, without ever resolving a thing. A much better approach is to detect that it was Error 1205 - a deadlock victim and retry only in that case. You can use: IF ERROR_NUMBER() = 1205 See the documentation for ERROR_NUMBER(). A: Retry logic for recoverable errors should be in the client code. For deadlocks, MSDN states to do it there If you retry in SQL, then you may hit CommandTimeout eventually. There are other errors too so you can write a generic handler
{ "language": "en", "url": "https://stackoverflow.com/questions/7559849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How can i overwrite the parent Style to an element <div class="jqueryslidemenu"> <ul> <li class="menuitem">TEST1</li> <li class="navOFFTDDisabled" id="TEST2">TEST2</li> <li class="navOFFTDDisabled" id="TEST3">TEST3</li> <li class="navOFFTDDisabled" id="TEST4">TEST4</li> </ul> </div> CSS FILE .jqueryslidemenu ul li { display: block; background: #FFCC00; color: white; padding: 4px 12px 6px 5px; border-right: 1px solid #778; color: #2d2b2b; text-decoration: none; font-weight: bold; cursor: hand; } .navOFFTDDisabled{ //Aplly Style } I cannot Apply class="navOFFTDDisabled" to each (li) Items because the "jqueryslidemenu" is overwriting the navOFFTDDisabled style .How can i apply both styles A: Make it a better match, .jqueryslidemenu ul li.navOFFTDDisabled{ //I'm more important neener neener. } Just to be more useful, you can actually calculate which selector with take precedence as described in the specification A: You have three possibilities to override a selector: * *order of the selector: a selector further down in your stylesheet overrides a selector that is further to the top *selector specifity: http://www.w3.org/TR/CSS2/cascade.html and http://www.molly.com/2005/10/06/css2-and-css21-specificity-clarified/ basically it depends on how many tags, classes and ids you have in your selector. classes add more weight than tags and ids add more weight than classes *the last thing you can do is to add an !importantto your style rule, which overrides any other selector. To be correct you can still have more !importantrules, than the selector specifity rule comes into play again. E.g. .klass{color:red !important}
{ "language": "en", "url": "https://stackoverflow.com/questions/7559851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Solr Client - Request Entity Too Large I am using SOLR PHP client to query data from a solr service. My code looks similar to the below in that I'm passing in a query to search on multiple IDs (in my case, a lot). The problem arises for me when I'm searching for too many IDs at once. I get a 'Request Entity Too Large' when passing in too many IDs. Is there a way to get around this? From what I see in various examples, the syntax seems to be 'id:1 OR id:2 OR id:3 etc.' when searching on multiple values. This there a different syntax that would reduce the size of the request being passed into the service? e.g. In SQL we can say, 'id in (1,2,3,etc.)'. Can we do something similar for the SOLR query? <?php require_once( 'SolrPHPClient/Apache/Solr/Service.php' ); $solr = new Apache_Solr_Service( 'localhost', '8983', '/solr' ); $offset = 0; $limit = 10; $queries = array( 'id: 1 OR id: 2 OR id:3 OR id:4 OR id:5 OR id:6 or id:7 or id:8' // in my case, this list keeps growing and growing ); foreach ( $queries as $query ) { $response = $solr->search( $query, $offset, $limit ); if ( $response->getHttpStatus() == 200 ) { print_r( $response->getRawResponse() ); } else { echo $response->getHttpStatusMessage(); } } ?> A: Solr supports searching through POST HTTP requests instead of GET requests which will allow you to have a much bigger query. I don't know how to enable this in the PHP client you're using. However this is only a bandaid. The real problem is that you seem to be misusing Solr. You will likely run into other limits and performance issues, simply because Solr wasn't designed to do what you're trying to do. You wouldn't use PHP to write an operating system, right? It's the same with this. I recommend creating a new question with the real issue you have that led you to run this kind of queries. A: Solr supports range queries, i.e. id:[1 TO 10], or id:[* TO *] to match all. Since it looks like many of your "ORs" are with respect to sequential IDs, this should help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using fixed type constraints inside an interface in Java? interface I1 { ... } interface I2 { ... } interface I3 { ... } interface I4 { ... } interface MyFactory { Object<? extends I1 & I2 & I3> createI1I2I3(); // doesn't work Object<? extends I2 & I3 & I4> createI2I3I4(); // doesn't work } Is there a trick to do it? I was thinking about things like interface I1I2I3 extends I1, I2, I3 { ... } But I1I2I3 != <? extends I1 & I2 & I3>. There's a reason I just can't use this approach - I1, I2 and I3 are foreign code. Update For those who curious why might someone need such a weird thing: interface Clickable {} interface Moveable {} interface ThatHasText {} interface Factory { Object<? extends Clickable> createButton(); // just a button with no text on it Object<? extends Clickable & ThatHasText> createButtonWithText(); Object<? extends Moveable & ThatHasText> createAnnoyingBanner(); } A: Object doesn't accept type parameter You can use the following construct instead: interface I1 { } interface I2 { } interface I3 { } interface I4 { } interface MyFactory { public <T extends I1 & I2 & I3> T createI1I2I3(); public <T extends I2 & I3 & I4> T createI2I3I4(); } A: Your return type should be parameterized, so you can do interface MyFactory { <T extends I1 & I2 & I3> T createI1I2I3(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7559861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: No response using express proxy route I've written a small proxy with nodejs, express and htt-proxy. It works well for serving local files but fails when it comes to proxy to external api: var express = require('express'), app = express.createServer(), httpProxy = require('http-proxy'); app.use(express.bodyParser()); app.listen(process.env.PORT || 1235); var proxy = new httpProxy.RoutingProxy(); app.get('/', function(req, res) { res.sendfile(__dirname + '/index.html'); }); app.get('/js/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.get('/css/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.all('/*', function(req, res) { req.url = 'v1/public/yql?q=show%20tables&format=json&callback='; proxy.proxyRequest(req, res, { host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault port: 8080 }); }); The problem is that there is no response from the yahoo api, maybe there is an response but i dont came up in the browser. A: Maybe your code is different when you're testing, but I'm querying the same URL as in your code sample using the following: http://query.yahooapis.com:8080/v1/public/yql?q=show%20tables&format=json&callback= and I get nothing back. My guess is you want to change port to 80 (from 8080) -- it works when I change it like so: http://query.yahooapis.com:80/v1/public/yql?q=show%20tables&format=json&callback= So that means it should be: proxy.proxyRequest(req, res, { host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault port: 80 }); A: Maybe I use http-proxy in a wrong way. Using restler does what I want: var express = require('express'), app = express.createServer(), restler = require('restler'); app.use(express.bodyParser()); app.listen( 1234); app.get('/', function(req, res) { console.log(__dirname + '/index.html') res.sendfile(__dirname + '/index.html'); }); app.get('/js/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.get('/css/*', function(req, res) { res.sendfile(__dirname + req.url); }); app.all('/*', function(req, res) { restler.get('http://myUrl.com:80/app_test.php/api' + req.url, { }).on('complete', function (data) { console.log(data) res.json(data) }); }); A: Even simpler with pipe and request-Package var request = require('request'); app.use('/api', function(req, res) { var url = apiUrl + req.url; req.pipe(request(url)).pipe(res); }); It pipes the whole request to the API and pipes the response back to the requestor. This also handles POST/PUT/DELETE and all other requests \o/ If you also care about query string you should pipe it as well req.pipe(request({ qs:req.query, uri: url })).pipe(res); A: I ended up using http-proxy-middleware. The code looks something like this: var express = require("express"); var proxy = require("http-proxy-middleware"); const theProxy = proxy({ target: "query.yahooapis.com", changeOrigin: true, }); app.use("/", theProxy); app.listen(process.env.PORT || 3002); A: That's what I've been using for a while. Can handle both JSON and binary requests. app.use('/api', (req, res, next) => { const redirectUrl = config.api_server + req.url.slice(1); const redirectedRequest = request({ url: redirectUrl, method: req.method, body: req.readable ? undefined : req.body, json: req.readable ? false : true, qs: req.query, // Pass redirect back to the browser followRedirect: false }); if (req.readable) { // Handles all the streamable data (e.g. image uploads) req.pipe(redirectedRequest).pipe(res); } else { // Handles everything else redirectedRequest.pipe(res); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7559862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Dangerous file types to avoid in file-sharing website I am making a small file-sharing website where users can upload content. Recently somebody uploaded a PHP script that was presumably intended to harm the site. It got me thinking: what file types should I block users from uploading? I have already blocked .exe files. What other file types could cause harm to either my website or its users? This script can be viewed here. A: Don't store the files where they're directly accessible - only provide access via a script YOU control. Don't store the files using their user-supplied filename - use a filename YOU generate (best option is to store file details in a database, including the original filename, and store the actual file using that db record's primary key field. With those two, people can upload antyhing they want, and there'll be zero chance of the file being executed/interpreted on your server, because it's never in a position where it CAN be executed/interpreted. A: It looks like the script is cut off while it's still defining functions, so I can't make out what it's doing. However, if you're doing things correctly you should have an .htaccess file in your "uploaded files" directory with: Header set Content-Disposition "attachment" This will ensure that accessing any file in that directory will result in a download, and that script will not be run. (Actually even better is to have the files outside the webroot, and have a "downloader" php script echoing the file contents) A: That script could euphemistically be described as a remote administration script. You should always use a whitelist, not a blacklist. Instead of "enumerating badness", make a list of allowed file types and reject everything else. Also, all files uploaded should be put in a directory which does not run the PHP handler, or any other script handlers at all (check for instance what other content management systems written in PHP do in the .htaccess for their upload directories). It is also a good idea to put the uploaded files in a separate subdomain which does not have any access to the cookies of the main domain, to avoid attacks which attempt to run JavaScript code on the same origin as the main site (a whitelist of content types is not enough for this, since some browsers are known to guess the content type and treat non-HTML files as HTML).
{ "language": "en", "url": "https://stackoverflow.com/questions/7559863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Open remote shared folder with credentials I need to open a folder on a remote server with different credentials in a window (explorer.exe). I managed to do it with no credentials (my credentials), but when I do it with another username and another password than mine, it opens a prompt to enter a username and a password, and it says "access denied". In the access log on the remote desktop, it says that I tried to connect with my own username, and not the other username I entered. So, the process obviously did not work. But, I can't figure out why. My code is as follows: Dim domain, username, passwordStr, remoteServerName As String Dim password As New Security.SecureString Dim command As New Process domain = "domain.com" username = "username" passwordStr = "password" remoteServerName = "serverName" For Each c As Char In passwordStr.ToCharArray password.AppendChar(c) Next command.StartInfo.FileName = "explorer.exe" command.StartInfo.Arguments = "\\" & serverName & "\admin$\Temp" command.StartInfo.UserName = username command.StartInfo.Password = password command.StartInfo.Domain = domain command.StartInfo.Verb = "open" command.StartInfo.UseShellExecute = False command.Start() A: I ran into this same problem at work and was able to solve it with impersonation. just add a new class with the following: '***************************************************************************************** '***************************************************************************************** ' Contents: AliasAccount Class ' ' This Class is a template class that provides all the functionality to impersonate a user ' over a designated instance. '***************************************************************************************** '***************************************************************************************** Public Class AliasAccount Private _username, _password, _domainname As String Private _tokenHandle As New IntPtr(0) Private _dupeTokenHandle As New IntPtr(0) Private _impersonatedUser As System.Security.Principal.WindowsImpersonationContext Public Sub New(ByVal username As String, ByVal password As String) Dim nameparts() As String = username.Split("\") If nameparts.Length > 1 Then _domainname = nameparts(0) _username = nameparts(1) Else _username = username End If _password = password End Sub Public Sub New(ByVal username As String, ByVal password As String, ByVal domainname As String) _username = username _password = password _domainname = domainname End Sub Public Sub BeginImpersonation() 'Const LOGON32_PROVIDER_DEFAULT As Integer = 0 'Const LOGON32_LOGON_INTERACTIVE As Integer = 2 Const LOGON32_LOGON_NEW_CREDENTIALS As Integer = 9 Const LOGON32_PROVIDER_WINNT50 As Integer = 3 Const SecurityImpersonation As Integer = 2 Dim win32ErrorNumber As Integer _tokenHandle = IntPtr.Zero _dupeTokenHandle = IntPtr.Zero If Not LogonUser(_username, _domainname, _password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, _tokenHandle) Then win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error() Throw New ImpersonationException(win32ErrorNumber, GetErrorMessage(win32ErrorNumber), _username, _domainname) End If If Not DuplicateToken(_tokenHandle, SecurityImpersonation, _dupeTokenHandle) Then win32ErrorNumber = System.Runtime.InteropServices.Marshal.GetLastWin32Error() CloseHandle(_tokenHandle) Throw New ImpersonationException(win32ErrorNumber, "Unable to duplicate token!", _username, _domainname) End If Dim newId As New System.Security.Principal.WindowsIdentity(_dupeTokenHandle) _impersonatedUser = newId.Impersonate() End Sub Public Sub EndImpersonation() If Not _impersonatedUser Is Nothing Then _impersonatedUser.Undo() _impersonatedUser = Nothing If Not System.IntPtr.op_Equality(_tokenHandle, IntPtr.Zero) Then CloseHandle(_tokenHandle) End If If Not System.IntPtr.op_Equality(_dupeTokenHandle, IntPtr.Zero) Then CloseHandle(_dupeTokenHandle) End If End If End Sub Public ReadOnly Property username() As String Get Return _username End Get End Property Public ReadOnly Property domainname() As String Get Return _domainname End Get End Property Public ReadOnly Property currentWindowsUsername() As String Get Return System.Security.Principal.WindowsIdentity.GetCurrent().Name End Get End Property #Region "Exception Class" Public Class ImpersonationException Inherits System.Exception Public ReadOnly win32ErrorNumber As Integer Public Sub New(ByVal win32ErrorNumber As Integer, ByVal msg As String, ByVal username As String, ByVal domainname As String) MyBase.New(String.Format("Impersonation of {1}\{0} failed! [{2}] {3}", username, domainname, win32ErrorNumber, msg)) Me.win32ErrorNumber = win32ErrorNumber End Sub End Class #End Region #Region "External Declarations and Helpers" Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _ ByVal lpszDomain As [String], ByVal lpszPassword As [String], _ ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _ ByRef phToken As IntPtr) As Boolean Private Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, _ ByVal SECURITY_IMPERSONATION_LEVEL As Integer, _ ByRef DuplicateTokenHandle As IntPtr) As Boolean Private Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean <System.Runtime.InteropServices.DllImport("kernel32.dll")> _ Private Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, _ ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], _ ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer End Function Private Function GetErrorMessage(ByVal errorCode As Integer) As String Dim FORMAT_MESSAGE_ALLOCATE_BUFFER As Integer = &H100 Dim FORMAT_MESSAGE_IGNORE_INSERTS As Integer = &H200 Dim FORMAT_MESSAGE_FROM_SYSTEM As Integer = &H1000 Dim messageSize As Integer = 255 Dim lpMsgBuf As String = "" Dim dwFlags As Integer = FORMAT_MESSAGE_ALLOCATE_BUFFER Or FORMAT_MESSAGE_FROM_SYSTEM Or FORMAT_MESSAGE_IGNORE_INSERTS Dim ptrlpSource As IntPtr = IntPtr.Zero Dim prtArguments As IntPtr = IntPtr.Zero Dim retVal As Integer = FormatMessage(dwFlags, ptrlpSource, errorCode, 0, lpMsgBuf, messageSize, prtArguments) If 0 = retVal Then Throw New System.Exception("Failed to format message for error code " + errorCode.ToString() + ". ") End If Return lpMsgBuf End Function #End Region End Class This will allow you to impersonate a designated user for a session. so you would than change your code to: Dim domain, username, passwordStr, remoteServerName As String Dim password As New Security.SecureString Dim command As New Process domain = "domain.com" username = "username" passwordStr = "password" remoteServerName = "serverName" Dim impersonator As New AliasAccount(username, password) For Each c As Char In passwordStr.ToCharArray password.AppendChar(c) Next command.StartInfo.FileName = "explorer.exe" command.StartInfo.Arguments = "\\" & serverName & "\admin$\Temp" command.StartInfo.UserName = username command.StartInfo.Password = password command.StartInfo.Domain = domain command.StartInfo.Verb = "open" command.StartInfo.UseShellExecute = False impersonator.BeginImpersonation() command.Start() impersonator.EndImpersonation() A: The answer given is a very long-winded solution that is unnecessary. I know the answer is from 2011, but all you need to do is the following: Public Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUsername As String, ByVal strPassword As String) Try Dim procInfo As New ProcessStartInfo procInfo.FileName = "net" procInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword procInfo.WindowStyle = ProcessWindowStyle.Hidden procInfo.CreateNoWindow = True Dim proc As New Process proc.StartInfo = procInfo proc.Start() proc.WaitForExit(15000) Catch ex As Exception MsgBox("Open_Remote_Connection" & vbCrLf & vbCrLf & ex.Message, 4096, "Error") End Try End Sub and then this function to actually open the C$ share: Private Sub OpenCDriveofPC(ByVal compName As String) Try If isPingable(compName) Then Open_Remote_Connection(compName, strUserName, strPassword) Process.Start("explorer.exe", "\\" & compName & "\c$") End If Catch ex As Exception MsgBox("OpenCDriveofPC" & vbCrLf & vbCrLf & ex.message, 4096, "Error") Finally Close_Remote_Connection("net use \\" & compName & "\c$ /delete /yes") End Try And here is the 'Close_Remote_Connection' sub, which needs to be called so that you don't make your net use list get crazy huge. Even if you call this sub, you will still have full admin rights to the c$ you open: Public Sub Close_Remote_Connection(ByVal device As String) Shell("cmd.exe /c " & device, vbHidden) End Sub I looked all over the Internet for how to do this and no one came even close to this simplicity. It does exactly what you want and is crazy simple and not long-winded with all sorts of crazy functions/classes that just are not needed to do this simple thing. Hope it helps others like it helped me! :) LilD
{ "language": "en", "url": "https://stackoverflow.com/questions/7559867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AudioQueue capture and returning different buffer sizes I have an AudioQueue based application working almost perfectly. I'm suffering an issue, however. When I call AudioQueueAllocateBuffer I specifically request a buffer size of 512 (as I'm performing an FFT on the data). However when the callback fires I find that from time to time I get buffer sizes that are less than 512. This is infuriating. Is my only solution to set up some sort of internal buffering of the incoming data to smooth out these issues? Why do I specify a value to the allocate buffer and then the iPhone return me a different number of samples? Any help would be much appreciated, as I'm about to go mad. Cheers! Oscar A: Your solution is to set up your own internal buffering of the incoming audio data until you have buffered the amount of data required. The buffer size you allocate indicates the maximum amount of data that can fill that buffer, not the minimum. The Audio Queue API is based on top of other iOS audio APIs, and may change its behavior depending on a number of things (what that underlying API is doing, audio session or sample rate as requested by other apps, background state(s), OS version, different underlying hardware on different device models, etc.) Even the lowest level public audio API (RemoteIO) will change it's returned buffer size, depending.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the correct way to initialize a pointer in c? What is the difference between the following initialization of a pointer? char array_thing[10]; char *char_pointer; what is the difference of the following initialization? 1.) char_pointer = array_thing; 2.) char_pointer = &array_thing Is the second initialization even valid? A: The second initialization is not valid. You need to use: char_pointer = array_thing; or char_pointer = &array_thing[0]; &array_thing is a pointer to an array (in this case, type char (*)[10], and you're looking for a pointer to the first element of the array. A: See comp.lang.c FAQ, Question 6.12: http://c-faq.com/aryptr/aryvsadr.html A: Note that there are no initializations at all in the code you posted. That said, you should keep in mind that arrays decay to pointers (a pointer to the first element within the array). Taking the address of an array is certainly valid, but now you have a (*char)[10] instead of a char*. A: In the first case, you're setting char_pointer to the first element of array_thing (the address of it, rather). Using pointer arithmetic will bring you to other elements, as will indexing. For example char_pointer[3] = 'c'; is the same as char_pointer += 3; char_pointer = 'c'; The second example...I don't believe that's valid the way you're doing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Inconsistent behavior when calling same method from different event handlers I've built a little camera capture daemon which captures a sequence of images from an attached DSLR using Canon's EDSDK and Wayne Hartman's C# wrapper. Capturing works great and very reliably when I call takePhotograph() from a test button click handler on the form itself. However, when I try to call takePhotograph() from socketServer_MessageReceived(), it's very unreliable and frequently causes the app stop responding. After tracing the call stack, it looks like the entire order of calls gets jumbled up, ultimately causing the EDSDK to hang up when calling EdsDownload() prematurely (before all images have been captured). I'm coming from a non-multithreaded environment (Flex/ActionScript), and have a hunch I'm just doing something elementarily wrong related to my handlers. Here's the gist of my code: private SocketServer socketServer; private void initSocketServer() { socketServer = new SocketServer(); socketServer.Start( Convert.ToInt16( serverPortField.Text ) ); socketServer.MessageReceived += new EventHandler<SocketEventArgs>( socketServer_MessageReceived ); } private void socketServer_MessageReceived ( object sender , SocketEventArgs e ) { Console.WriteLine( "[CaptureDaemon] socketServer_MessageReceived() >> " + (String)e.Data ); var serializer = new JavaScriptSerializer(); serializer.RegisterConverters( new[] { new DynamicJsonConverter() } ); dynamic obj = serializer.Deserialize( (String)e.Data , typeof( object ) ); if ( (String)obj.destinationID != "captureDaemon" ) return; switch ( (String)obj.messageID ) { case "capture": takePhotograph( obj.body.successiveShotDelay , obj.body.successiveShots ); break; } } private void testCaptureButton_Click ( object sender , EventArgs e ) { takePhotograph( 500 , 4 ) ); } A: Did you try to wrap the takePhotograph with the Form.Invoke (this.Invoke)? There's a chance that if it works from the GUI then it will also work when you force a correct thread for the call.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: page_fan query not returning results I have authorized my app and made sure it gets 'user_likes' permissions. When I execute this query: select uid from page_fan where uid='&lt;uid here>' This is the result: <fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true"/> What do I need to check? What am I missing? A: Your query is asking for the user id, but you already know it. I believe your intention was to do the following: select page_id from page_fan where uid={uid here}
{ "language": "en", "url": "https://stackoverflow.com/questions/7559878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LeaseExpiredException: No lease error on HDFS I am trying to load large data to HDFS and I sometimes get the error below. any idea why? The error: org.apache.hadoop.ipc.RemoteException: org.apache.hadoop.hdfs.server.namenode.LeaseExpiredException: No lease on /data/work/20110926-134514/_temporary/_attempt_201109110407_0167_r_000026_0/hbase/site=3815120/day=20110925/107-107-3815120-20110926-134514-r-00026 File does not exist. Holder DFSClient_attempt_201109110407_0167_r_000026_0 does not have any open files. at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1557) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkLease(FSNamesystem.java:1548) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFileInternal(FSNamesystem.java:1603) at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.completeFile(FSNamesystem.java:1591) at org.apache.hadoop.hdfs.server.namenode.NameNode.complete(NameNode.java:675) at sun.reflect.GeneratedMethodAccessor16.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:557) at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1434) at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:1430) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127) at org.apache.hadoop.ipc.Server$Handler.run(Server.java:1428) at org.apache.hadoop.ipc.Client.call(Client.java:1107) at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:226) at $Proxy1.complete(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:82) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:59) at $Proxy1.complete(Unknown Source) at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.closeInternal(DFSClient.java:3566) at org.apache.hadoop.hdfs.DFSClient$DFSOutputStream.close(DFSClient.java:3481) at org.apache.hadoop.fs.FSDataOutputStream$PositionCache.close(FSDataOutputStream.java:61) at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:86) at org.apache.hadoop.io.SequenceFile$Writer.close(SequenceFile.java:966) at org.apache.hadoop.io.SequenceFile$BlockCompressWriter.close(SequenceFile.java:1297) at org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat$1.close(SequenceFileOutputFormat.java:78) at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs$RecordWriterWithCounter.close(MultipleOutputs.java:303) at org.apache.hadoop.mapreduce.lib.output.MultipleOutputs.close(MultipleOutputs.java:456) at com.my.hadoop.platform.sortmerger.MergeSortHBaseReducer.cleanup(MergeSortHBaseReducer.java:145) at org.apache.hadoop.mapreduce.Reducer.run(Reducer.java:178) at org.apache.hadoop.mapred.ReduceTask.runNewReducer(ReduceTask.java:572) at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:414) at org.apache.hadoop.mapred.Child$4.run(Child.java:270) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:396) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1127) at org.apache.hadoop.mapred.Child.main(Child.java:264) A: I meet the same problem when i use spark streaming to saveAsHadoopFile to Hadoop(2.6.0-cdh5.7.1), of course i use MultipleTextOutputFormat to write different data to different path. Sometimes the exception what Zohar said would happen. The reason is as Matiji66 say: another program read,write and delete this tmp file cause this error. but the root reason he didn't talk about is the hadoop speculative: Hadoop doesn’t try to diagnose and fix slow running tasks, instead, it tries to detect them and runs backup tasks for them. So the really reason is that, your task execute slow, then hadoop run another task to do the same thing(in my case is to save data to a file on hadoop), when one task of the two task finished, it will delete the temp file, and the other after finished, it will delete the same file, then it does not exists, so the exception does not have any open files happened you can fix it by close the speculative of spark and hadoop: sparkConf.set("spark.speculation", "false"); sparkConf.set("spark.hadoop.mapreduce.map.speculative", "false"); sparkConf.set("spark.hadoop.mapreduce.reduce.speculative", "false") A: I managed to fix the problem: When the job ends he deletes /data/work/ folder. If few jobs are running in parallel the deletion will also delete the files of the another job. actually I need to delete /data/work/. In other words this exception is thrown when the job try to access to files which are not existed anymore A: For my case, another program read,write and delete this tmp file cause this error. Try to avoid this. A: ROOT CAUSE Storage policy was set on staging directory and hence MAPREDUCE job failed. <property> <name>yarn.app.mapreduce.am.staging-dir</name> <value>/user</value> </property> RESOLUTION Setup staging directory for which storage policy is not setup. I.e. modify yarn.app.mapreduce.am.staging-dir in yarn-site.xml <property> <name>yarn.app.mapreduce.am.staging-dir</name> <value>/tmp</value> </property> A: I use Sqoop to import into HDFS and have same error. By the help of previous answers I have realized that I needed to remove last "/" from --target-dir /dw/data/ I used --target-dir /dw/data works fine A: I encountered this problem when I changed my program to use saveAsHadoopFile method to improve performance, in which scenario I can't make use of DataFrame API directly. see the problem The reason why this would happen is basically what Zohar said, the saveAsHadoopFile method with MultipleTextOutputFormat actually doesn't allow multiple programs concurrently running to save files to the same directory. Once a program finished, it would delete the common _temporary directory the others still need, I am not sure if it's a bug in M/R API. (2.6.0-cdh5.12.1) You can try this solution below if you can't redesign your program: This is the source code of FileOutputCommitter in M/R API: (you must download an according version) package org.apache.hadoop.mapreduce.lib.output; public class FileOutputCommitter extends OutputCommitter { private static final Log LOG = LogFactory.getLog(FileOutputCommitter.class); /** * Name of directory where pending data is placed. Data that has not been * committed yet. */ public static final String PENDING_DIR_NAME = "_temporary"; Changes: "_temporary" To: System.getProperty("[the property name you like]") Compiles the single Class with all required dependencies, then creates a jar with the three output class files and places the jar to you classpath. (make it before the original jar) Or, you can simply put the source file to your project. Now, you can config the temp directory for each program by setting a different system property. Hope it can help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: DataSet table adapter manager help i have a plain and simple console app where i'm trying to update customers and orders tables and i'm getting an error message: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Orders_Customers". The conflict occurred in database "CustomerOrder", table "dbo.Customers", column 'Id'. The statement has been terminated. Am I missing something obvious? RsNorthwinds ds = new RsNorthwinds(); RsNorthwinds.CustomersRow cRow = ds.Customers.NewCustomersRow(); cRow.Name = "John Smith"; ds.Customers.AddCustomersRow(cRow); RsNorthwinds.OrdersRow oRow = ds.Orders.NewOrdersRow(); oRow.CustomerId = cRow.Id; oRow.OrderDate = "9/26/11"; ds.Orders.AddOrdersRow(oRow); RsNorthwindsTableAdapters.TableAdapterManager tm = new DataTableAdapterTester.RsNorthwindsTableAdapters.TableAdapterManager(); tm.OrdersTableAdapter = new DataTableAdapterTester.RsNorthwindsTableAdapters.OrdersTableAdapter(); tm.CustomersTableAdapter = new DataTableAdapterTester.RsNorthwindsTableAdapters.CustomersTableAdapter(); tm.UpdateAll(ds); A: Regardless of that the issue is at the C# side, always use the Sql Profiler to check the sequence of sql statements that is executed at the SQL Server side. This way you'll quickly locate the issue. Possibly the UpdateAll method executes both inserts in an invalid order. Using Table Adapters instead of an ORMapper you are asking yourself for such issues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select all of a unique attribute I would like to find all the Records that have unique email addresses. I am trying to perform this : @uniq_referrals = [] CardReferral.all.select{|a| @uniq_referrals << a.email} @referral_count = @uniq_referrals.uniq.each{|a|CardReferral.find_by_email(a)} But I would like to do it in a single call. Is that possible? A: You can use: CardReferral.select("distinct(email), other_field_you_need") where other_field_you_need it's a list of field name you need to use from the objects you get from ActiveRecord. To get the count of unique email record you can use: CardReferral.count("distinct(email)") A: I would like to find all the Records that have unique email addresses. I am trying to perform this : @uniq_referrals = [] CardReferral.all.select{|a| @uniq_referrals << a.email} @referral_count = @uniq_referrals.uniq.each{|a|CardReferral.find_by_email(a)} But I would like to do it in a single call. Is that possible? I think that it would help you: Model.group("email") when we group all the record by email id then you will find all the record that have uniq email. if some record have same id then you will get first record. please prefer to image for more understanding. If you could not get yet, then i will explain elaborate more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with user features with Jtwitter My code is : List<Status> list = new ArrayList<Status>(); User user; Twitter twitter = new Twitter(); list = twitter.search(string); for(int i=0; i<list.size();i++){ user=list.get(i).getUser(); System.out.print(i+1); System.out.println(list.get(i)); System.out.println(list.get(i).getId()); System.out.println(list.get(i).getUser()); System.out.println(user.getId()); System.out.println(user.getCreatedAt()); System.out.println(user.getLocation()); System.out.println(user.getFavoritesCount()); } The problem is that good print the status, id of status and user, but user features how user id, location, etc, prints all as null. What I can do to take the features???? Thanks for response A: According to the JTwitter API Docs, calling the default constructor creates a new instance without a user. You need to authenticate with Twitter using Twitter.IHttpClient (which depends on Signpost) to get user data. A: The Twitter search method is unusual in that it only returns a small part of the User information. This is a limitation from Twitter & there's nothing you can do about that. Fields such as location will be blank. You always get the screen-name, and this can be used to fetch the extra info via the show() method. E.g. Twitter twitter; List<String> userNames; // make this list from user.screenName List<User> fullUserInfo = twitter.users().show(userNames) If you have an up-to-date copy of JTwitter (http://www.winterwell.com/software/jtwitter.php) it is all in the javadoc. NB: Other methods sometimes return missing fields in User, if Twitter is experiencing heavy load.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can you use assert to test type defintions in C++? Can I use assert to enforce type definitions. Suppose there is a variable, double d, how can you use assert to assert that d is a double? If assert is not applicable (which I am betting isn't), is there another option? I am specifically looking to test for implicit type casting during debugging, while benefiting from the functionality of assert and #define NDEBUG. P.S Obviously I would want to use this for any type definition, just using double as an example here. The solution should be cross platform compatible and be compatible with C++03. I like to add error checking to my class setters. For example, suppose there is a class, MyClass, with a private member variable, x: void MyClass::setX(double input) { // assert x is double x = input; } A: You can use the == operator defined in the type_info class to test for a specific type definition. #include <assert.h> #include <iostream> #include <typeinfo> int main () { double a = 0; std::cout << typeid(a).name() << std::endl; assert(typeid(a)==typeid(double)); assert(typeid(a)==typeid(int)); // FAIL } Or borrowing from another SO answer using templates and try/catch: #include <assert.h> #include <iostream> #include <typeinfo> template <typename X, typename A> inline void Assert(A assertion) { if( !assertion ) throw X(); } #ifdef NDEBUG const bool CHECK_ASSERT = false; #else const bool CHECK_ASSERT = true; #endif struct Wrong { }; int main () { double a = 0; std::cout << typeid(a).name() << std::endl; assert(typeid(a)==typeid(double)); Assert<Wrong>(!CHECK_ASSERT || typeid(a)==typeid(double)); try { //assert(typeid(a)==typeid(int)); // FAIL and Abort() Assert<Wrong>(!CHECK_ASSERT || typeid(a)==typeid(int)); // FALL } catch (Wrong) { std::cerr <<"Exception, not an int" <<std::endl; } } A: You should be able to compare using std::is_same and using decltype. You can even use std::static_assert to move the check to compile time. I've seen it happen in libc++ :) Note these are C++11 features, so you'll need to have a compiler that supports decltype A: It's really a compile time check, so you should use static asserts for this. Here is an example using boost's static asserts and type traits. #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> template<typename T> void some_func() { BOOST_STATIC_ASSERT( (boost::is_same<double, T>::value) ); } TEST(type_check) { some_func<double>(); } I assume you mean in terms of a template anyway. A: Given the current definition of the code, a way to check at compile time whether both are of the same type is: template< typename T, typename U > void assert_same_type( T const&, U const& ) { int error[ sizeof( T ) ? -1 : -2 ]; // error array of negative size, dependent on T otherwise some implementations may cause an early error message even when they shouldn't } template< typename T > void assert_same_type( T&, T& ){} void MyClass::setX(double input) { assert_same_type( x, input ); // If the fallback case is instantiated then a compile time error will arise of trying to declare an array of negative size. x = input; } A: You can create a template function, then overload the argument type for double like this: #include <cassert> template<class T> bool is_double(T) { return false; } bool is_double(double) { return true; } int main() { int i = 1; double d = 3.14; assert( is_double(d) ); assert( is_double(i) ); // fails } That would give a run-time error. You can generate a compile time error by simply defining a function that takes a double reference: void is_double(double&) { } void MyClass::setX(double input) { is_double(x); // assert x is double x = input; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7559908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: In web application, how does DateTime.Now know the local time for user? According to this DateTime.Now vs. DateTime.UtcNow you store date time information in UTC and show it to user as DateTime.Now. If it is on web application, how does DateTime.Now know about user's location and adjusts UTC time accordingly? Is location inferred from header information that user passes in? A: DateTime.Now does not know the user's location and adjust for it. It is based off the server the site is running on. A: As Blake said, it doesn't. If a server is calculating the current time for the end user, it must be based on information that user has provided. Otherwise, you typically would use javascript to provide the current date/time reference based on the local machine's clock. A: DateTime.Now returns the current time according to the server, not the client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Single characters are not printed on the terminal I have 3 different processes that all print out single characters using printf. But I can't see them in the terminal. When I add a newline, printf("\n H") so each character is on a new line, I can see them. Why doesn't it work without the newline character? A: Its a matter of flushing. If you flush the buffers after each printf, you should get output closer to what you want. To flush the standard output simply do fflush( stdout ). A: The C standard defines 3 types of buffering for output streams: * *Unbuffered → no buffering done *Line-buffered → buffer until newline seen *Fully-bufferd → buffer up to the buffer size An output stream's buffering type can be changed via the setvbuf(3) and setbuf(3) functions. The C standard requires stderr to not be fully-buffered at startup (it is usually unbuffered on many implementations, so as to see errors as soon as posible); and stdout to be fully-buffered only if it can be determined to not refer to a terminal (when it refers to a terminal, many implementations initialize it as line-buffered, which is what you are seeing). A: use'write(1,&c,1)' system call, or fprintf(stderr,'%c', c);
{ "language": "en", "url": "https://stackoverflow.com/questions/7559917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to determine if mousepointer is over an element that should trigger onMouseOver? I am attempting to mimic the bing video search preview feature. I have a single flash video player element which loads on page load. I also have multiple images contained in overlay divs that should trigger playback (onMouseOver event in the div), and move the flash player into the div position. I have two problems related to where the mouse pointer is located: * *When the onMouseOver event is triggered, I do a $(element).css("visibility","hidden"); on the <img />, and move the flash player into the exact same position. This works okay, except that the onMouseOut event is triggered immediately followed by the onMouseOver event once again causing the video to 'flicker' as it reloads the video. How can I make sure the incorrectly fired onMouseOut event is indeed incorrect (and not stop/start video playback)? *If the mousepointer is over a div with the preview image on page load (before the flash player is loaded), the onMouseOver event is never triggered for this element - how can I do this? When the flash is loaded, it triggers a callback - but I don't really know how I can accurately mimic the onMouseOver event? This is less of an issue than the other problem, but would be cool if it's possible to fix A: * *Use mouseenter() and mouseleave() instead. *Reinitialize the function for mouseenter when the flash is loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: STL Sort on nested Classes I have a graph class that has a vector of nodes. In each node, there is a vertex and a STL list of edges. Essentially it's an adjacency list. For my assignment, I am trying to display the vertices with the most edges. I figured I would sort the graph's vector of nodes by edge size and print the top N vertices. So I am trying to figure out STL sort, but I'm having difficulties. I have std::sort(path.begin(), path.end()); Where path is the vector of nodes (node = vertex value and list of edges) In my node class, I have bool operator<(const Node<T>& rhs){ return size < rhs.size; //size is how many edges the vertex has } But it's giving me errors. How can I construct the operator< function in my node class to work with STL sort? Here are the errors: $ make g++ -c -g -std=c++0x graphBuilder.cpp In file included from /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/algorithm:63:0, from graph.h:6, from graphBuilder.cpp:2: /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h: In function '_RandomAccessIterator std::__unguarded_partition(_RandomAccessIterator, _RandomAccessIterator, const _Tp&) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Node<std::basic_string<char> >*, std::vector<Node<std::basic_string<char> >, std::allocator<Node<std::basic_string<char> > > > >, _Tp = Node<std::basic_string<char> >]': /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h:2249:70: instantiated from '_RandomAccessIterator std::__unguarded_partition_pivot(_RandomAccessIterator, _RandomAccessIterator) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Node<std::basic_string<char> >*, std::vector<Node<std::basic_string<char> >, std::allocator<Node<std::basic_string<char> > > > >]' /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h:2280:54: instantiated from 'void std::__introsort_loop(_RandomAccessIterator, _RandomAccessIterator, _Size) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Node<std::basic_string<char> >*, std::vector<Node<std::basic_string<char> >, std::allocator<Node<std::basic_string<char> > > > >, _Size = int]' /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h:5212:4: instantiated from 'void std::sort(_RAIter, _RAIter) [with _RAIter = __gnu_cxx::__normal_iterator<Node<std::basic_string<char> >*, std::vector<Node<std::basic_string<char> >, std::allocator<Node<std::basic_string<char> > > > >]' graph.h:32:13: instantiated from 'void Graph<T>::topN(int) [with T = std::basic_string<char>]' graphBuilder.cpp:10:17: instantiated from here /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h:2211:4: error: passing 'const Node<std::basic_string<char> >' as 'this' argument of 'bool Node<T>::operator<(const Node<T>&) [with T = std::basic_string<char>]' discards qualifiers make: *** [graphBuilder.o] Error 1 A: Your member function needs to be const-qualified: bool operator<(const Node<T>& rhs) const{ EDIT Per request, here is a bit more how I knew that you needed to make the member function const. Divining the hidden meanings in stdlib-related compiler errors is something of an art, and something that you get better at with practice. Stdlib-related errors will often emit a whole series of compiler errors. Usually the most useful of these errors is the last one, because that one is generated from the context of the code you actually wrote, rather than coming from the bowels of the library code. In this case, the last compiler error was: graphBuilder.cpp:10:17: instantiated from here /usr/lib/gcc/i486-slackware-linux/4.5.2/../../../../include/c++/4.5.2/bits/stl_algo.h:2211:4: error: passing 'const Node >' as 'this' argument of 'bool Node::operator<(const Node&) [with T = std::basic_string]' discards qualifiers I've highlighted the illuminating bits. This tells me that in OP's actual code, because of how the code is constructed (maybe the sort call is itself in a const member function? who knows...) the this pointer must be const, but as we can see from the posted declaration of operator<, the method is not const. The "qualifiers" referred to in the compiler errors are what the Standard calls "cv-qualifiers". "cv" stands for "const/volatile." When the compiler says "Passing const X as this to Node::operator< discards qualifiers" what it's really trying to say is: "You said X was const but then you tried to call a non-const member function through const X. In order for me to make this call, I would have to discard the const qualifier on X. I'm not allowed to do that, so you have to fix your code." The qualifiers being "discarded" here are the qualifiers on the method itself. In other words, operator< must be a const member function, but it's not. A: bool operator<(const Node<T>& rhs) const { return size() < rhs.size(); } Making the operator const as it should be may help with not angering the compiler. Note: The problem arises because this is always const so the compiler expects you to promise not to change it which you specify by making the method using this to have the const qualifier. Alternately you could make a non-member comparison for use with sort like so: <template typename T> struct CompareNodes { bool operator()(const Node<T>& lhs, const Node<T>& rhs) const { return lhs.size() < rhs.size(); } }; std::sort(path.cbegin(), path.cend(), CompareNodes<T>());
{ "language": "en", "url": "https://stackoverflow.com/questions/7559928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to optimize this IP to Location lookup query? UPDATE tracker SET t_loc_id=(SELECT cb_loc_id FROM city_blocks WHERE INET_ATON(t_ip) BETWEEN cb_start_ip_num AND cb_end_ip_num LIMIT 1); There are about 300K records in tracker and about 3.6M records in city_blocks. It's been running for over 30min now. I've got unique indexes on cb_start_ip_num and cb_end_ip_num already. Any way I can speed it up? Okay, I let it run for about 2 hours and it only did about 9K records. A: Create an index on the upper bound column (cb_end_ip_num) and find the first row for which that value is greater than or equal to the given value. SELECT * FROM city_blocks WHERE cb_end_ip_num >= 123456789 LIMIT 1 I've used this for maxmind, and it works very well. A: http://jcole.us/blog/archives/2007/11/24/on-efficiently-geo-referencing-ips-with-maxmind-geoip-and-mysql-gis/ I converted my IP ranges into polygons and added a spatial index, as per the article above, then ran my update query: UPDATE tracker JOIN city_blocks ON mbrcontains(cb_ip_poly, pointfromwkb(point(inet_aton(track_ip),0))) SET t_loc_id=cb_loc_id Which ran in 45 seconds the first time, 8 the second, vs the estimated 10 hours to 4 days that the other query would have taken. The article also mentions blockhead's solution, but it still ran atrociously slow. Can't figure out why... I don't know if my indexes were broken (I tried rebuilding them) or it didn't like being in a subquery or something?? Speaking of subqueries...this solution doesn't work well at all with a subquery. I figured a subquery would have been faster because I could add the limit 1 and it wouldn't have to join everything to everything, but that doesn't appear to be the case. Technically without the limit it would have to continue searching to see if the are other potential matches/ranges the IP falls within, but I guess it doesn't really matter in this scenario because everything's properly indexed and there's only 1 bucket it can fall in to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing displayed data from a static method in ASP.NET I have two user controls that sit on a page which determines which should be displayed. The user controls generate some html that is passed into an asp:literal and subsequently manipulated via javascript. It is done this way due to the lack of a suitable control that I am allowed to use on the project. When a user clicks a view change button, a WebMethod is called on the main page (the one that holds the controls) from the control's javascript. From here, a static method on the control is called. The control then needs to regenerate the html and place it into the asp:literal for the view change to be complete. My problem is that I am in a static method on the control's page, and have no access to the non-static genorateHtml function. I have tried a singleton pattern with no success (this could have been due to improper implementation). Any ideas on how to make this call? THANKS! A: I used to hit similar issues at with one of the projects i worked on. The solution we ended up adopting was implementation of System.Web.UI.ICallbackEventHandler with partial rendering to return just the needed content depending on arguments. ICallbackEventHandler runs in the page lifecycle. The only trouble we had then was performance issues relative to implementation which posts back the whole form instead of just the arguments you want. Maybe the best way for you would be through this method in which they render the control from a static method. That would probably suit your needs. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7559936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add multiple form fields (at once) with an 'add new fields' button See http://jsfiddle.net/jFzhC/ for the button I'm looking for. Although, this only allows for one input field to be added at a time. How can I display 3 fields, horizontally aligned, where the 'add new fields' button creates 3 additional new fields under the original 3 and so on. A: You can clone a template and save yourself a lot of code at the same time: http://jsfiddle.net/minitech/bPhBG/ A: http://jsfiddle.net/cADRY/1/ You can simplify your code A LOT!
{ "language": "en", "url": "https://stackoverflow.com/questions/7559938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Red arrow icon in subclipse My computer set-up: -eclipse with aptana studio 3 plugin, plugin development tools and subclipse and i have 2 projects under version control. i managed to copy the files from one project to the second since i don't know how to merge two projects yet. when i tried to copy the js folder from one project to the other, this happens: notice the red arrow. now, i thought it was nothing. i committed the project and left for work. when i went to the office and updated my copy of the project, i found out that the js folder was not there. when i checked the repository, the js folder was not there at all. i was sure it was there when i left home. found this link which is a thread that gives an heads-up on subversion icons but this red outward pointing icon isnt there in the list. what do they mean? A: Using Eclipse Mars.1 Release (4.5.1) and SVN 1.8.10. My icons reverted back to normal after running Team > Cleanup. A: The arrow indicates switched http://www.eclipse.org/subversive/documentation/teamSupport/svn_label_decor.php A: I see there is already a solution in the comments above, just thought id share my solution which seemed easier , simply * *Right click on project > Team > Disconnect (from repository) *Right click on project > Team > Re-connect (to repository) *Problem solved! NOTE: After re-connecting had to commit all changes in project, seemed scary at first but simply updated version number. (I am always a little nervous when synchronizing with the repo) NOTE: Using subversion SVN plugin in eclipse
{ "language": "en", "url": "https://stackoverflow.com/questions/7559941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Hide a Column in datagrid, without setting column.visble=false <asp:BoundField DataField="TimeRead" ItemStyle-Width="25%" HeaderText="TimeRead" SortExpression="TimeRead" /> <asp:BoundField DataField="Name" ItemStyle-Width="45%" HeaderText="Name" SortExpression="Name" /> <asp:BoundField DataField="Email" ReadOnly="True" Display="none" HeaderText="Email" SortExpression="Email" /> How Can I hide the Email column in the datagrid., I dont Want to use column.visible property. How Can i hide it using css properties or anyother method. Thanks A: <asp:BoundField DataField="Email" ItemStyle-Width="45%" HeaderText="Email" SortExpression="Email"> <ItemStyle CssClass="boundfield-hidden" /> <HeaderStyle CssClass="boundfield-hidden" /> </asp:BoundField> That's how you add a CSS class directly to the bound field. Now, in your css file, just add the following: .boundfield-hidden { display: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7559949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to load a partial view on button click in mvc3 I have a DDL, on its change I load a partial view _GetX. Right now I am using it like this @Html.DropDownListFor(model => model.XId, Model.XList, "Select", new { GetUrl = Url.Action("GetX", "Route") }) I need to load this partial view on clicking a button. How do I do this? A: Assuming your GetX controller action already returns the partial view: $(function() { $('#someButton').click(function() { // get the DDL. It would be better to add an id to it var ddl = $('#XId'); // get the url from the ddl var url = ddl.attr('GetUrl'); // get the selected value of the ddl to send it to the action as well var selectedValue = ddl.val(); // send an AJAX request to the controller action passing the currently // selected value of the DDL and store the results into // some content placeholder $('#somePlaceholder').load(url, { value: selectedValue }); return false; }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7559957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load swf without instantiating Is there a way I can load a swf file but not automatically instantiate it's DocumentClass? Instead I want to do something like the following: protected function mainLoaded(e:Event = null):void { trace('mainLoaded'); var main:* = this.mainLoad.createClassByName('Main'); trace(main); } where mainLoad is an instance of CasaLib's SwfLoad and createClassByName is the equivalent to loaderInfo.applicationDomain.getDefinition(); The thing is that when my swf finishes loading I can see it is created, because of some trace calls, although its obviously not added to the display list. A: In your child swf's document class, use the following: //constructor public function ChildSWF() { if(stage) init() else addEventListener(Event.ADDED_TO_STAGE, init); }// end if private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); trace("This will only trace when an instance of ChildSWF is added to the stage, not when it's instantiated"); }// end function
{ "language": "en", "url": "https://stackoverflow.com/questions/7559970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Customize Django Admin Change Form Foreignkey to Include View Record When selecting a foreignkey in the django admin change form I am trying to add an href that can view the record next to the plus that adds the record. What I've tried just to get the href to render is I've copied out the admins def render into my own custom widgets file and added it to and subclassed it: widgets.py class RelatedFieldWidgetWrapperLink(RelatedFieldWidgetWrapper): def render(self, name, value, *args, **kwargs): rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) try: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) except NoReverseMatch: info = (self.admin_site.root_path, rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = '%s%s/%s/add/' % info self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if self.can_add_related: # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \ (related_url, name)) output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another'))) output.append(u'<a href="%s" class="testing" id="add_id_%s" onclick="#"> ' % \ (related_url, name)) return mark_safe(u''.join(output)) and in admin.py formfield_overrides = {models.ForeignKey:{'widget':RelatedFieldWidgetWrapperLink}} however I get thefollowing error: TypeError init() takes at least 4 arguments (1 given) Has anyone run into this problem before? A: The RelatedFieldWidgetWrapper widget, and your subclass, are not meant to be used as the widget in formfield_overrides. The __init__ methods have different function signatures, hence the TypeError. If you look at the code in django.contrib.admin.options, you can see that the RelatedFieldWidgetWrapper widget is instantiated in the model admin's formfield_for_dbfield method, so that it can be passed the arguments rel, admin_site and can_add_related. I think you may have to override your model admin class' formfield_for_dbfield method, and use your custom RelatedFieldWidgetWrapperLink widget there. class YourModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **kwargs): <snip> # ForeignKey or ManyToManyFields if isinstance(db_field, (models.ForeignKey, models.ManyToManyField)): # Combine the field kwargs with any options for formfield_overrides. # Make sure the passed in **kwargs override anything in # formfield_overrides because **kwargs is more specific, and should # always win. if db_field.__class__ in self.formfield_overrides: kwargs = dict(self.formfield_overrides[db_field.__class__], **kwargs) # Get the correct formfield. if isinstance(db_field, models.ForeignKey): formfield = self.formfield_for_foreignkey(db_field, request, **kwargs) elif isinstance(db_field, models.ManyToManyField): formfield = self.formfield_for_manytomany(db_field, request, **kwargs) # For non-raw_id fields, wrap the widget with a wrapper that adds # extra HTML -- the "add other" interface -- to the end of the # rendered output. formfield can be None if it came from a # OneToOneField with parent_link=True or a M2M intermediary. if formfield and db_field.name not in self.raw_id_fields: related_modeladmin = self.admin_site._registry.get( db_field.rel.to) can_add_related = bool(related_modeladmin and related_modeladmin.has_add_permission(request)) # use your custom widget formfield.widget = RelatedFieldWidgetWrapperLink( formfield.widget, db_field.rel, self.admin_site, can_add_related=can_add_related) return formfield <snip> Other approaches You may find it cleaner to override the formfield_for_foreignkey method than formfield_for_dbfield. You may be able to subclass the Select widget, and add your link in it's render method. Your custom select widget would then be wrapped by the RelatedFieldWidgetWrapper. However, I am not sure whether you can produce the view_url inside the scope of the render method. from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.forms.widgets import Select def get_admin_change_url(obj): ct = ContentType.objects.get_for_model(obj) change_url_name = 'admin:%s_%s_change' % (ct.app_label, ct.model) return reverse(change_url_name, args=(obj.id,)) class LinkedSelect(Select): def render(self, name, value, attrs=None, *args, **kwargs): output = super(LinkedSelect, self).render(name, value, attrs=attrs, *args, **kwargs) model = self.choices.field.queryset.model try: id = int(value) obj = model.objects.get(id=id) view_url = get_admin_change_url(obj) output += mark_safe('&nbsp;<a href="%s" target="_blank">view</a>&nbsp;' % (view_url,)) except model.DoesNotExist: pass return output class YourModelAdmin(admin.ModelAdmin): formfield_overrides = {models.ForeignKey:{'widget':LinkedSelect}} A: I improved @Alasdair solution a bit: from django.contrib.admin.templatetags import admin_static from django.core import urlresolvers from django.utils import safestring from django.utils.translation import ugettext_lazy as _ class LinkedSelect(widgets.Select): def render(self, name, value, attrs=None, *args, **kwargs): output = [super(LinkedSelect, self).render(name, value, attrs=attrs, *args, **kwargs)] model = self.choices.field.queryset.model try: obj = model.objects.get(id=value) change_url = urlresolvers.reverse('admin:%s_%s_change' % (obj._meta.app_label, obj._meta.object_name.lower()), args=(obj.pk,)) output.append(u'<a href="%s" class="change-object" id="change_id_%s"> ' % (change_url, name)) output.append(u'<img src="%s" width="10" height="10" alt="%s"/></a>' % (admin_static.static('admin/img/icon_changelink.gif'), _('Change Object'))) except (model.DoesNotExist, urlresolvers.NoReverseMatch): pass return safestring.mark_safe(u''.join(output)) class YourModelAdmin(admin.ModelAdmin): formfield_overrides = {models.ForeignKey: {'widget': LinkedSelect}} It uses the same code structure and style as RelatedFieldWidgetWrapper. Additionally, it uses "change" icon instead of just string. It gracefully survives when foreign key points nowhere or where foreign key points to a model which does not have admin interface defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Visual Studio 2010 randomly says the command line changed, and rebuilds Visual Studio sometimes decides to rebuild my entire huge project because of one small change. I turned build logging up to Diagnostic to see what was the problem, and here's what I'm seeing: < Bunch of spam > Outputs for C:\<snip>\PRECOMPILEDHEADERS.CPP: C:\<snip>\PRECOMPILEDHEADERS.OBJ All outputs are up-to-date. Forcing rebuild of all source files due to a change in the command line ... and then it rebuilds my precompiled headers, then everything else. This happens when I change a single .cpp or .h file inside the project. I'm not changing anything in the project settings. It also doesn't happen all the time for the same change; it's random. Any ideas on what's going on here? Where can I get more information? I tried enabling debugging via the description in http://blogs.msdn.com/b/vsproject/archive/2009/07/21/enable-c-project-system-logging.aspx but it didn't give any more information. I can't figure out where this "Forcing rebuild of all source files due to a change in the command line" is coming from. It's not in any of the factory MSBuild files. Some other info: it's a C++/CLI dll project that links a lot of other projects, including C#, native c++, and other C++/CLI dll's. I tried removing all the C# projects from the dependencies since those tend to cause problems, but that didn't change it. I've googled that specific string, but my situation doesn't match that of any of the other people reporting it. (One was using Intel C++, another was MSBuild from the command line and changing the case. I'm hitting build solution from within Visual Studio itself). Edit to explain common fixes I've tried: I've tried building only the project. Does the same thing. I'm not including any .h files that don't exist. I've deleted the bin/object folders and rebuilt from scratch. This usually makes it go away for a couple builds, but then it comes right back. Edit #2: Found something suspicious earlier in the log: 3>Using "ResolveNonMSBuildProjectOutput" task from assembly "Microsoft.Build.Tasks.v4.0, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". 3>Task "ResolveNonMSBuildProjectOutput" 3> Resolving project reference "..\..\..\..\CommonCore\VS2010\Project1\Project1.vcxproj". 3> Project reference "..\..\..\..\CommonCore\VS2010\Project1\Project1.vcxproj" has not been resolved. This is repeated for several of my projects... I'm gonna chase that down and see if maybe it's a problem with the project reference hint paths. A: Ok, it's an old thread, but I encountered the same problem recently. My solution was to disable the precompiled headers - now a simple change in one sourcefile won't lead into a "rebuild" any more. A: I have had the same problem with Visual Studio 2012 recently. I'm on Windows 7 with Visual Studio 2012 Professional (2012.2) building C++ projects. It's worth noting that I recently migrated the solution from Visual Studio 2008 to Visual Studio 2012. One of the C++ projects (an executable with a DLL project as a reference) was rebuilding every time one of its compilation units was changed, e.g. simply saving main.cpp would cause all compilation units (including the pre-compiled header) to rebuild. I spotted the the following message in the build logs: Forcing rebuild of all source files due to a change in the command line since the last build. I turned build log file verbosity to Diagnostic (Tools > Options > Projects and Solutions > Build and Run) and compared the log files from a clean build and a build after one compilation unit has been changed (which forced a full rebuild). I noticed that: * *"Path" had changed from one build to the next (";C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\VsGraphics" seems to have been tacked on the end) *there was a difference in TaskTracker.exe command lines to do with CancelEvents *there was a warning about OutputPath not being set I pulled my hair out. I eventually resorted to recreating the offending project from scratch rather than relying on the project that was automatically generated during the migration process from 2008 to 2012. It seems to be behaving as expected now. A: I did three things, and the problem seems to have gone away. I'm trying to narrow it down a little but I figured I'd go ahead and post them: * *Deleted and re-added all the references and project references *Fixed one of my projects that wasn't setting the .NET framework target to 3.5 to match the rest of my solution (I was getting away with it because the project didn't use .NET anyway) *Set "Copy Local Satellite Assemblies" to false for all references including System ones. Beware that some or all of this stuff might be voodoo...
{ "language": "en", "url": "https://stackoverflow.com/questions/7559972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jenkins with the Measurement Plots plugin does not plot measurements Is there anyone who was successful in getting a plot using Jenkins with the Measurement Plots plugin and a xUnit test results file with the tags? If yes, I'd like to see a sample of a working xUnit file and get from you any tips you may have about configuring Jenkins and the appropriate Jenkins job to accomplish this feat. A: I just figured it out with some help from the author. The trick is to escape the XML inside the XML and use <system-out>to feed the Measurements Plot plugin. The steps below shows how to use it and feed various values into the plugin: * *Create a New Job in Jenkins "free-style software project" *Add String Parameter VALUETEST *Add Build step Execute Shell Command is the code below. *Add Post-build Action: Publish JUnit * *Test report XMLs: testdetail-*.xml *Check Retain long staandard output *Check Measurement Plots *Save and Build Now. *Plot will appear under Test Results. You need more than one run for the plot appear. Execute Shell Command: echo '<?xml version="1.0" encoding="UTF-8"?>' > testdetail-lcov.xml echo '<testsuites name="CodeAnalysis" tests="2" failures="0" disabled="0" errors="0" time="0">' >> testdetail-lcov.xml echo '<testsuite name="Suite" tests="1" >' >> testdetail-lcov.xml echo '<testcase name="Case" status="run" time="0" classname="Suite">' >> testdetail-lcov.xml echo '</testcase></testsuite>' >> testdetail-lcov.xml echo '<testsuite tests="1" >' >> testdetail-lcov.xml echo '<testcase name="Lcov" status="run" time="0" classname="CodeAnalysis.Coverage">' >> testdetail-lcov.xml echo '<system-out>' >> testdetail-lcov.xml echo "&lt;measurement&gt;&lt;name&gt;Line Coverage&lt;/name&gt;&lt;value&gt;$VALUETEST&lt;/value&gt;&lt;/measurement&gt;" >> testdetail-lcov.xml echo '</system-out>' >> testdetail-lcov.xml echo '</testcase></testsuite></testsuites>' >> testdetail-lcov.xml A: The Measurement Plots plugin is designed to take values out of standard output and error buffer and should not be used to plot stats and details of test frameworks. For xUnit there is a xUnit plugin that does the job quite nicely. Unless you want to handle some very specific type of data/information used by xUnit, this should the trick of nicely showing the tests results.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to retrieve similar named tags in the xml using linq I have the code like this: Here if I give same named tags inside the parent tags then 'Object reference not set to instance of object' error comes.(the DataList is object of type List) IEnumerable<XElement> elements = xmlDoc.Descendants(); foreach (DataSource Data in DataList) { XElement xmlElem = ( from xmlData in elements where Data.Name == xmlData.Name.LocalName && Data.Store == xmlData.Element( XName.Get("Store", "")).Value select xmlData.Element(XName.Get("Val", "")) ).Single(); xmlElem.ReplaceWith(new XElement(XName.Get("Val", ""), Data.Value)); } 'XML' used is (sample):- <Tag1> <lang> </lang> <Tag2> <lang> </lang> </Tag2> <Tag1> "Kindly suggest some way to solve."
{ "language": "en", "url": "https://stackoverflow.com/questions/7559974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery - $.each link in object I have the following API example: "urls": [ { "value": "http://twitter.com" }, { "value": "http://gplus.to" }, { "value": "http://plus.ly" }, { "value": "http://glpl.us" }, { "value": "http://microsoft.ms/+" }, { "value": "https://plus.google.com", "type": "profile" }, { "value": "https://www.googleapis.com/plus/v1/people", "type": "json" } ] How can I use .each() to display each href from the link value in the object? Also how can I exclude the values with type = profile and type = json? I've tried: var yourLinks = data.urls; $.each(yourLinks, function(key, value) { alert(key + ': ' + value); }); But the alert just contains object : object. A: alert(value.value); //<<<try that Or more verbose: var yourLinks = data.urls; $.each(yourLinks, function(index, vals) { alert(index + ":" + vals.value); }); A: What's happening is that each element of data.urls is an object, so you basically need to run a double-each to get the key/value pairs for each one: $.each(data.urls, function(index, obj) { $.each(obj, function(key, value) { alert(key + ': ' + value); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7559975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ConcurrentHashMap foreach loop problem I have a concurrenthashmap called users. I have user objects in it with some integer keys that is not id. I want to find the user with a given id. Therefore, I check all elements of hashmap and return the user object if it is present. Here is my code : for(User u : users.values()) { logger.error("u.getId() : " + u.getId()); logger.error("id : " + id ); if( u.getId() == id ) { logger.error("match"); return u; } } logger.error("Not found: id:" + id); for(User u : users.values()) { logger.error(u.getPos() + ". user: " + u.getId()); } However even tough my u.getId() and id are the same I cannot see "match" at my logs. 213 matches but It can not enter the following if statement. here are my logs: What do you think about it? A: What type returned from User.getId() method and what type of id variable? If it is not a primitive type, you need to use equals() instead of ==. By the way, a good static code analyzer like FindBugs can find such kind of errors. A: You haven't shown the types involved, but is it possible that id or getId() is an Integer instead of an int? If so, you'll be comparing references, so you should just use if (u.getId().equals(id)) to compare the values within the Integer objects. Be careful if getId can return null though...
{ "language": "en", "url": "https://stackoverflow.com/questions/7559979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: WinRT Data Virtualization implementation in C# I have asked this question on the MSDN forum (with no success), maybe StackOverflow will prove its strength one more time... I was attending Hamid Mahmood's session on collection and list apps and was excited to see control-level support for data virtualization. Unfortunately, no details were given on how to implement IVirtualizingVector and IIncrementalLoadingVector, and it is not evident how to do so by looking at the interfaces themselves. Can anybody post a sample? Additional bonus question for SO - is there an easier way to implement IAsyncOperation (needed by IIncrementalLoadingVector implementation) than coding it "from scratch"? A: For your bonus question, have a look at the overloaded Create method available in System.Runtime.InteropServices.WindowsRuntime.AsyncInfoFactory, specifically the overloads that take Func<Task<T>>. A: I have posted an article on my blog showing how to implement IVirtualizingVector here. It describes an overview of how IVirtualizingVector works, as well as an implementation that you can use released as part of the open-source Cocoon framework. I hope to also show how to use IIncrementalLoadingVector in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Git: How do I remove files listed in git status -s with "??", these are files I added to local repo? I have a few files in my git status -s listed as, ?? file1 ?? filepath/file2 ?? file3 ?? filepath/file4 I have been ignoring these and going along committing, pushing, pulling, and I am at the point where there are too many of these in my status report. I tried git rm file1. It doesn't work. It says fatal path doesn't match any files. Thanks! A: These are untracked files, i.e. the files which are present in your file system, but you've never added them to your repository by git add. If you don't need them, you can just rm them. Or simply git clean -fd if you want to delete them all. If you want to do some filtering before removing them, you can do: git ls-files -o --exclude-standard | grep 'my custom filter' | xargs rm If you want to keep those files, but want git status to ignore them, add them to .gitignore file. Read man gitignore for the details. A: You can temporarily add those to your .gitignorefile so they won't show up in your git status and you don't accidentally add them. That git rm file doesn't work because those files have not been added to your repository so there is nothing to delete A: These files are untracked, hence git rm does not work (it is the command to remove files from Git's control). You essentially have two options: * *Ignore these files. Read gitignore. You can either add the ignore patterns to a .gitignore file that you can commit and share with your co-workers, or in a per-repo .git/info/exclude, or in a per-user .config/git/ignore file. *Delete these files. Any tool you use to delete files when you're not using Git would work. Additionally, Git provides you git clean to help you in this task. A: I use this way and it was work for me: git status | grep file | xargs rm
{ "language": "en", "url": "https://stackoverflow.com/questions/7559985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: FedEx "Service INTERNATIONAL_GROUND is invalid" message i made integration with FedEx web services. All things works like a charm, but when i try to use international ground service type it raised me this error "Service INTERNATIONAL_GROUND is invalid" error N782. What could be the problem? FedEx support told me that i used dropoff type "DROP_BOX" and this causes the error, but i tried to change that to all 5 variants without success. I sent them a ticket, but still no answer. Here is the SOAP request i send: <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v9"> <SOAP-ENV:Body> <ns1:RateRequest> <ns1:WebAuthenticationDetail> <ns1:UserCredential> <ns1:Key>my key</ns1:Key> <ns1:Password>my pass</ns1:Password> </ns1:UserCredential> </ns1:WebAuthenticationDetail> <ns1:ClientDetail> <ns1:AccountNumber>acc number</ns1:AccountNumber> <ns1:MeterNumber>metter number</ns1:MeterNumber> </ns1:ClientDetail> <ns1:TransactionDetail> <ns1:CustomerTransactionId>SearchFit Shopping Cart v8.20.5 (Sep 27, 2011)</ns1:CustomerTransactionId> </ns1:TransactionDetail> <ns1:Version> <ns1:ServiceId>crs</ns1:ServiceId> <ns1:Major>9</ns1:Major> <ns1:Intermediate>0</ns1:Intermediate> <ns1:Minor>0</ns1:Minor> </ns1:Version> <ns1:ReturnTransitAndCommit>true</ns1:ReturnTransitAndCommit> <ns1:RequestedShipment> <ns1:ShipTimestamp>2011-09-28T01:15:54+03:00</ns1:ShipTimestamp> <ns1:ServiceType>INTERNATIONAL_GROUND</ns1:ServiceType> <ns1:PackagingType>YOUR_PACKAGING</ns1:PackagingType> <ns1:TotalInsuredValue> <ns1:Currency>USD</ns1:Currency> </ns1:TotalInsuredValue> <ns1:Shipper> <ns1:Address> <ns1:StateOrProvinceCode>GA</ns1:StateOrProvinceCode> <ns1:PostalCode>30030</ns1:PostalCode> <ns1:CountryCode>US</ns1:CountryCode> </ns1:Address> </ns1:Shipper> <ns1:Recipient> <ns1:Address> <ns1:PostalCode>HP10</ns1:PostalCode> <ns1:CountryCode>GB</ns1:CountryCode> <ns1:Residential>true</ns1:Residential> </ns1:Address> </ns1:Recipient> <ns1:ShippingChargesPayment> <ns1:PaymentType>SENDER</ns1:PaymentType> <ns1:Payor> <ns1:AccountNumber>acc number</ns1:AccountNumber> <ns1:CountryCode>US</ns1:CountryCode> </ns1:Payor> </ns1:ShippingChargesPayment> <ns1:RateRequestTypes>ACCOUNT</ns1:RateRequestTypes> <ns1:PackageCount>1</ns1:PackageCount> <ns1:PackageDetail>INDIVIDUAL_PACKAGES</ns1:PackageDetail> <ns1:RequestedPackageLineItems> <ns1:Weight> <ns1:Units>LB</ns1:Units> <ns1:Value>10.0</ns1:Value> </ns1:Weight> <ns1:Dimensions> <ns1:Length>5</ns1:Length> <ns1:Width>11</ns1:Width> <ns1:Height>8</ns1:Height> <ns1:Units>IN</ns1:Units> </ns1:Dimensions> </ns1:RequestedPackageLineItems> </ns1:RequestedShipment> </ns1:RateRequest> </SOAP-ENV:Body> </SOAP-ENV:Envelope> And here is the response: <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <env:Header xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> <soapenv:Body> <v9:RateReply xmlns:v9="http://fedex.com/ws/rate/v9"> <v9:HighestSeverity xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">ERROR</v9:HighestSeverity> <v9:Notifications xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <v9:Severity>ERROR</v9:Severity> <v9:Source>crs</v9:Source> <v9:Code>782</v9:Code> <v9:Message>Service INTERNATIONAL_GROUND is invalid.</v9:Message> <v9:LocalizedMessage>Service INTERNATIONAL_GROUND is invalid.</v9:LocalizedMessage> <v9:MessageParameters> <v9:Id>SERVICE_TYPE</v9:Id> <v9:Value>INTERNATIONAL_GROUND</v9:Value> </v9:MessageParameters> </v9:Notifications> <ns1:TransactionDetail xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v9"> <ns1:CustomerTransactionId>SearchFit Shopping Cart v8.20.5 (Sep 27, 2011)</ns1:CustomerTransactionId> </ns1:TransactionDetail> <ns1:Version xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://fedex.com/ws/rate/v9"> <ns1:ServiceId>crs</ns1:ServiceId> <ns1:Major>9</ns1:Major> <ns1:Intermediate>0</ns1:Intermediate> <ns1:Minor>0</ns1:Minor> </ns1:Version> </v9:RateReply> </soapenv:Body> </soapenv:Envelope> A: After a week of waiting i got the response from them. In short: FedEx International Ground is a direct-ship method for you to send single or multi-weight small package shipments directly from the U.S. to Canada, Canada to the U.S. There are no minimum package requirements. They doesn't support international ground even their documentation tells the opposite. A: In your request, the recipient has a country code of GB, which is not Canada. That probably explains why international ground is not coming back as a valid shipping option.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TortoiseHg: Overlay icon issues (Windows)? My TortoiseHg Windows explorer overlay icons are often in the wrong state for unknown reasons. In order to fix this I need to update icons on the folder, which I cant seem to do for multiple folders at once. This is annoying as I am often working on a large number of projects at once and would like to be able to rely on TortoiseHg to help me figure out which projects need commits. Does anyone else see the same issues? Has anyone figured anything out to eliminate or alleviate the problem? A: I usually keep a command-line open at repository root to do a quick hg st or even better thg stat to get visual overview on what needs to be committed, if there's any. In addition thg commit allows you to cherry pick what you want to commit and see their diffs on the fly. Relying on icons and browsing folders one by one is cumbersome and prone to human errors. A: Can you check this post out and see if it helps? There's a limit to the number of overlays Windows will support. TortoiseSVN icons not showing up under Windows 7 A: I know this behaviour, but I don't mind / don't care. I rarely look at the overlay icons at all, I have the Workbench open anyway and do everything in there. It all depends on one's point of view. For you, TortoiseHg's behaviour is annoying because you want to rely on the overlay icons. The other extreme is (was?) TortoiseSvn. When I last used it (about two years ago), it had a resource-hogging background process that was updating all the icons all the time. That was annoying for me at the time, because it visibly slowed down my machine (yes, you could change this somewhere in the settings, but the default setting was the resource-hogging one). No matter how they do it, someone will always complain :-) A: You can disable and enable the overlays in the Icon tab of the TortoiseHg Shell configuration, which worked for me
{ "language": "en", "url": "https://stackoverflow.com/questions/7559995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: POST vs GET method for a search form in CMS I'm a bit stuck with one thing. Just can't make up my mind on whether to use POST or GET method at my search form. Normally I would use GET method for such a form, so users could bookmark their results they got. But this time, the search form is present in administration area, so results are relevant shortly and there is no need to bookmark results and of course, they aren't public for everyone. To be more specific, the search feature is meant to be used along with a list of users, so there could be some specific user to be searched. My idea was to use POST method, where the form would be redirected to the same page so I would get a list of users filtered by search string. There was also pagination, so I would add the search string at the and of each pagination link (next page, previous page, first page and last page link) so the search string wouldn't be lost later on (within any session coming after the search like paginating of searched results etc.). There is no obvious reason to prefer one before another, both can be used. The POST method would be a little bit more hassle, but on the other hand, there are advanced options within the search form (about 5 checkboxes) and I don't like the idea of having meesed up URL bar with way too many values (and I expect users not to use pagination after search session so often, so the values wouldn't get to the address bar so often) if POST method used. Which one would you prefer for searching in CMS and alike systems? Thanks everyone! A: You are getting data, so use GET. POST will create issues with refreshing and going back. Don't obsess over the beauty of your URIs, they are a tool not a piece of art. A: Maybe, I would (mostly) always choose post over get, it's more tidy and refreshing and going back issues with post method are a thing from the past in any major browser, they just ask you if you want to resend the data, don't they? The MAJOR exception would be bookmark of a dynamic webpage (like movieweb.com/movies.php?movie=the_three_mosqueteers, for example), but still, if that's not the case I think it's better to use POST.
{ "language": "en", "url": "https://stackoverflow.com/questions/7559996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: php pagination querying multiple tables I am trying to display data from 6 different tables and use pagination so the user can scroll through the items similar to a shopping site. I am using the following code to display a field called request id from a table call request (as a test) in pages of 10 which works fine. <?php include('connect.php'); $targetpage = "page.php"; $limit = 10; $query = "SELECT COUNT(*) as num FROM request"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; $stages = 3; $page = mysql_escape_string($_GET['page']); if($page){ $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM request LIMIT $start, $limit"; $result = mysql_query($query1); // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <ul> <?php while($row = mysql_fetch_array($result)) { echo '<li>'.$row['requestid'].'</li>'; } ?> I am now trying to display the data from a total of 6 tables using the following query and it doesn't work? I don't think I have used the COUNT command correctly in the query? $query = "SELECT COUNT as num r.*, m.*, u.*, a.*, i.*, b.*, r.* FROM request r INNER JOIN movie m ON m.movieid = r.movieid INNER JOIN actor a ON a.actorid = r.actorid INNER JOIN users u ON u.userid = r.userid INNER JOIN item i ON i.itemid = r.itemid INNER JOIN brand b ON b.brandid = r.brandid WHERE gender = 'male'"; A: This is how you use the COUNT feature, you have to specify what you're counting. SELECT COUNT(*) as num r.*, m.*, u.*, a.*, i.*, b.*, r.* FROM request r INNER JOIN movie m ON m.movieid = r.movieid INNER JOIN actor a ON a.actorid = r.actorid INNER JOIN users u ON u.userid = r.userid INNER JOIN item i ON i.itemid = r.itemid INNER JOIN brand b ON b.brandid = r.brandid WHERE gender = 'male'";
{ "language": "en", "url": "https://stackoverflow.com/questions/7559997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I override locale values with custom values in Rails? In my en.yml locale file (config/locales/en.yml), I have en: settings: updated: 'Your settings have been updated.' Sometimes, I want to override settings.updated with other text but still use the en locale. I've tried the following, but settings.updated is not being overwritten: locale_overrides = {"settings"=>{"updated"=>"override text"}} I18n.backend.store_translations(I18n.locale, {"settings"=>{"updated"=>"override text"}}) p locale_overrides['settings']['updated'] p I18n.t('settings.updated') assert I18n.t('settings.updated') == locale_overrides['settings']['updated'] and the following prints to the console: "override text" "Your settings have been updated." Any ideas what I'm doing wrong or how to correctly overwrite locale settings? UPDATE Looks like this is happening because, as the documentation states, The backend will lazy-load these translations when a translation is looked up for the first time. A: I ended up using Chaining with a KeyValue backend: key_value_i18n_backend = I18n::Backend::KeyValue.new(locale_overrides_hash) I18n.backend = I18n::Backend::Chain.new(key_value_i18n_backend, I18n.backend)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring themes with hibernate by implementing Spring's ThemeSource class Does anyone know how to use a custom ThemeSource in spring? I have seen many examples on how to use themes with property files using ResourceBundleThemeSource. Yet I have seen nothing on how to use hibernate to store vairous properties (such as a single css property) , read the properties with a custom ThemeSource and still be able to use the spring theme tags in the jsp. I know I can create a controller and fetch these properties from the database with hibernate but I am more interested on knowing how to do this with Spring's ThemeSource implementation. If anyone has any ideas or examples I'd appreciate it. Thanks A: To use themes in your web application, you must set up an implementation of the org.springframework.ui.context.ThemeSource interface. To use a custom ThemeSource implementation you can register a bean in the application context with the reserved name themeSource. The web application context automatically detects a bean with that name and uses it. Here is the ThemeSource interface: package org.springframework.ui.context; public interface ThemeSource { Theme getTheme(String themeName); } The only dark horse here is a Theme type, which in fact is nothing more than: package org.springframework.ui.context; public interface Theme { String getName(); MessageSource getMessageSource(); } And in fact there is already a convenience implementation of Theme type from Spring => SimpleTheme Notice that ThemeSource expects a Spring's MessageSource, which means that theme attributes that are stored in a database, in your case, would need to be "converted" to be used with a MessageSource interface. You can either write your own DatabaseDrivenMessageSource, or just take it from here Now, having all these variables in place, here is a custom DatabaseThemeSource ( that will become a themeSource bean ): public class DatabaseThemeSource implements ThemeSource { private YourThemeDao themeDao; public Theme getTheme( String themeName ) { if (themeName == null) { return null; } MessageSource messageSource = new DatabaseDrivenMessageSource( themeDao ); theme = new SimpleTheme( themeName, messageSource ); return theme; } // init your themeDao } A: The answer that tolitius gives would work fine, but for real-world use I think that you need to incorporate some kind of caching. Every request to your website is going to need your theme, but do you want every request to hit your database just to look up some colours? Themes usually aren't very large and don't change very often. So they're a good candidate for loading into memory and keeping them there. This is what we do with a site that we run, we keep about 50 themes in memory which are loaded from Hibernate on startup. It makes serving theme requests very quick. The core class is, of course, your DatabaseThemeSource bean, which implements ThemeSource. If you have a cache library available such as Ehcache you could use that, but most people have fairly few themes and so a simple Map will do for that cache. We use something like this: @Component("themeSource") public class DatabaseThemeSource implements ThemeSource { @Autowired ThemeDAO themeDAO; private final Map<String, Theme> themeCache; public DatabaseThemeSource() { themeCache = new HashMap<String, Theme>(); } /** * @see org.springframework.ui.context.ThemeSource#getTheme(java.lang.String) */ @Override public Theme getTheme(String themeName) { if (themeName == null) { return null; } Theme theme = themeCache.get(themeName); if (theme == null) { Theme theme = themeDAO.getTheme(themeName); if (theme != null) { MessageSource messageSource = new ThemeMessageSource(theme); theme = new SimpleTheme(themeName, messageSource); synchronized (this.themeCache) { themeCache.put(themeName, theme); } } } return theme; } /** * Clears the cache of themes. This should be called whenever the theme is updated in the database. */ public void clearCache() { synchronized (this.themeCache) { themeCache.clear(); } } } Then you'll need to implement a MessageSource that holds all the individual components of your theme. It's worth copying the individual elements of your theme from your Hibernate object into a dedicated MessageSource so that you don't have any problems with closed Hibernate sessions and LazyLoadingExceptions etc. It's also more efficient, because you can construct the necessary MessageFormat objects just once instead of having to do so on each request: public class ThemeMessageSource extends AbstractMessageSource { private final Map<String, MessageFormat> messages; public ThemeMessageSource(Theme theme) { messages = new HashMap<String, MessageFormat>(); messages.put("heading1", createMessageFormat(theme.getHeading1(), null)); messages.put("heading2", createMessageFormat(theme.getHeading2(), null)); messages.put("colour1", createMessageFormat(theme.getColour1(), null)); messages.put("colour2", createMessageFormat(theme.getColour2(), null)); } public ThemeMessageSource(Map<String, MessageFormat> messages) { this.messages = messages; } @Override protected MessageFormat resolveCode(String code, Locale locale) { return messages.get(code); } } The end result is that it's quick. All your themes are kept in memory, and the elements of the themes are accessed rapidly though a simple Map lookup. We've been using this for a while and it works very well for us.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to register a Controller into ASP.NET MVC when the controller class is in a different assembly? My goal is to modify asp.net mvc's controller registery so that I can create controllers and views in a separate (child) assembly, and just copy the View files and the DLLs to the host MVC application and the new controllers are effectively "Plugged In" to the host app. Obviously, I will need some sort of IoC pattern, but I'm at a loss. My thought was to have a child assembly with system.web.mvc referenced and then to just start building controller classes that inherited from Controller: Separate Assembly: using System.Web; using System.Web.Mvc; namespace ChildApp { public class ChildController : Controller { ActionResult Index() { return View(); } } } Yay all fine and dandy. But then I looked into modifying the host application's Controller registry to load my new child controller at runtime, and I got confused. Perhaps because I need a deeper understanding of C#. Anyway, I thought I needed to create a CustomControllerFactory class. So I started writing a class that would override the GetControllerInstance() method. As I was typing, intellisence popped this up: Host MVC Application: public class CustomControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { return base.GetControllerInstance(requestContext, controllerType); } } Now, at this point I'm at a loss. I don't know what that does. Originally, I was going to write a "Controller Loader" class like a Service Locator like this: Host MVC Application: public class ControllerLoader { public static IList<IController> Load(string folder) { IList<IController> controllers = new List<IController>(); // Get files in folder string[] files = Directory.GetFiles(folder, "*.plug.dll"); foreach(string file in files) { Assembly assembly = Assembly.LoadFile(file); var types = assembly.GetExportedTypes(); foreach (Type type in types) { if (type.GetInterfaces().Contains(typeof(IController))) { object instance = Activator.CreateInstance(type); controllers.Add(instance as IController); } } } return controllers; } } And then I was planning on using my list of controllers to register them in the controller factory. But ... how? I feel like I'm on the edge of figuring it out. I guess it all bois down to this question: How do I hook into return base.GetControllerInstance(requestContext, controllerType);? Or, should I use a different approach altogether? A: Your other project should be set up like an area and you will get the desired result. The area registration class will bring your area project into the mix. Then you can just drop the dll into a running app and it will run without building the entire app and redeploying it. The easiest way to do it is to add a new mvc project to your solution and have Visual Studio create the new project inside /areas/mynewprog/. Delete out all the files you don't need and add an area registration class to wire it up. Build the project, grab it's dll and drop it into your running websites bin directory and that its.. You then just have to deal with the views and stuff, either compile them into the dll or copy them to the server into the areas/mynewproj/ folder. A: Reference the other assembly from the 'root' ASP.NET MVC project. If the controllers are in another namespace, you'll need to modify the routes in global.asax, like this: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { typeof(HomeController).Namespace } ); } Notice the additional namespaces argument to the MapRoute method. A: Create a separate module as shown Plugin Project structure: Notice that some files where excluded from the project. The MessagingController.cs file is as follows: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MessagingModule.Controllers { public class MessagingController : Controller { // // GET: /Messaging/ public ActionResult Index() { var appName = Session["appName"]; // Get some value from another module return Content("Yep Messaging module @"+ appName); } } } The MessagingAreaRegistration file is as shown: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Mvc; namespace MessagingModule { public class MessagingAreaRegistration : AreaRegistration { public override string AreaName { get { return "Messaging"; } } public override void RegisterArea( AreaRegistrationContext context ) { context.MapRoute( "Messaging_default", "Messaging/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } //new[] { "MessagingModule.Controllers" } ); } } } The relevant potion of the Global.asax.cs file is as follows: [Load the external plugin (controllers, api controllers library) into the current app domain. After this asp.net mvc does the rest for you (area registration and controllers discovery ][3] using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Reflection; using System.Web.Configuration; using System.Text.RegularExpressions; namespace mvcapp { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { var domain = AppDomain.CurrentDomain; domain.Load("MessagingModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); A: my experience with controllers is that this just works. Copy the assembly into the bin directory (or add a reference to the assembly and it will be copied there for you) I have not tried with views
{ "language": "en", "url": "https://stackoverflow.com/questions/7560005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Stopping a c# system tray application in .net 3.5 I have a .net 3.5 C# windows tray application that is installed using inno. In the uninstall script I need to stop the application if it is running. I've tried several methods - all unsucessfully. Is there a standard way of doing this that I am ignorant of? Simon A: You can use the Taskkill to kill the process. Read more about Taskkill here: http://technet.microsoft.com/en-us/library/bb491009.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7560007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manipulating Strings in x86 assembly code , NASM, Linux I have been trying to manipulate a string in my .s file i want that the variable "pa" that contains "/bin/bash" be transformed into "/bin/sh" and then i want to make a call to the system that executes "/bin/sh" I have written a print mechanism to make sure that "pa" has "/bin/bash" I have tried to do this mov eax,pa mov [eax+5],[eax+7]; /bin/bash becomes /bin/sash\0 mov [eax+6],[eax+8]; /bin/sash becomes /bin/shsh\0 mov [eax+7],[eax+9]; /bin/shsh becomes /bin/sh\0 but i guess thats not the way it works I am new to NASM Please help me out the entire code snippet is below `section .data %defstr path %!SHELL pa db path,10 palen equ $-pa section .text global _start _start: mov eax,pa mov [eax+5],[eax+7] ; /bin/bash becomes /bin/sash\0 mov [eax+6],[eax+8] ; /bin/sash becomes /bin/shsh\0 mov [eax+7],[eax+9] ; /bin/shsh becomes /bin/sh\0 mov eax,4 ; The system call for write (sys_write) mov ebx,1 ; File descriptor 1 - standard output mov ecx,pa mov edx,palen int 80h mov eax,1 ; The system call for exit (sys_exit) mov ebx,0 ; Exit with return code of 0 (no error) int 80h ' A: It's been a while since I worked with ASM, and I'm not real familiar with NASM, so I could be wrong here. But you might want to give it a shot. . . The problem is that you can't do a memory-to-memory move like that. Try this: mov bx,[eax+7] mov [eax],bx mov byte [eax+7], 0 In the future, it would be helpful if you let us know that you were getting an assembler error rather than incorrect output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fscanf in C for storing data from file Here's my code. #include<stdio.h> struct element { int value; char activity; }; typedef struct element element; int main(int argc,char** argv) { FILE* fp; fp = fopen(argv[1], "r"); element a; while(feof(fp) == 0) { fscanf(fp, "%c %d", &a.activity, &a.value); printf("\n%d", a.value); } } now,it outputs me every integer on file two time.. Howcome i am getting this weird answer? My structure is: struct element { int value; char activity; }; typedef struct element element; and my input file is: i 23 i 56 i 19 i 20 i 44 A: Look at your fscanf pattern: fscanf(fp, "%c,%d", &a.activity, &a.value); Then at your file format: i 23 i 56 i 19 i 20 i 44 I don't see any commas. Try a space instead, and be sure to take the newline into account: fscanf(fp, "%c %d\n", &a.activity, &a.value); Remember fscanf doesn't just read values in order, it respects the fixed characters surrounding the wildcards. Edit -- also important, pointed out by Keith in the comments: Note that using \n in the fscanf format string may be slightly misleading. Any white-space character (including \n) matches zero or more white-space characters. So adding the \n works for the given input -- but it would also work if the input were all on one line separated by spaces or tabs: i 23 i 56 i 19 i 20 i 44. If you really want line-oriented input, use fgets() (not gets()) to read a line at a time into a string, then sscanf() to parse the string. (All the *scanf() functions have problems with numeric overflow, though.) Hope it helps! (PS: oh, and I fixed your code formatting. Next time you post, take a second to make sure the code looks properly indented and stuff. Seeing a messy code snippet kinda takes away the desire to answer, you'll get much less feedback in your questions!) A: a.activity is uninitialized until fscanf returns the first time. While you are debugging, keep this in mind. Most debuggers will put a "cursor" on the first line which has not yet been executed; therefore, when the fscanf line is highlighted the first time, a.activity will not yet be initialized, and may have any value at all in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Programmatic performance of a Java method Two way of doing things and I'm curious which is faster: First way: if (!map.containsKey(key)) { map.put(key, new ArrayList<String>()); } map.get(key).addAll(someList); Second way: List<String> existingList = map.get(key); if (existingList == null){ existingList = new ArrayList<String>(); } existingList.addAll(someList); map.put(key, existingList); The first way would seem to involve having to hash the key more often, but require less object creation than the second way. It seems to me that the second way might be faster but more resource intensive than the first way. Thoughts? A: A modified version of your second way would be optimal: List<String> existingList = map.get(key); if (existingList == null){ existingList = new ArrayList<String>(); map.put(key, existingList); } existingList.addAll(someList); This ensures that a lookup is only done once, and the List is only instantiated and put in the Map when necessary. EDIT: As @Martijn Courteaux noted, a second lookup is done by put() when the key is not found.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to escape a period (.) in WCF Data Services QueryString I have a WCF Data Services service that exposes a set of ICD codes. The primary key for the underlying table and the data set that WCF provides access to is a varchar or string in C#. The service works properly if I have a query like this: http://somehost/someService.svc/IcdSet('001') If, however, the ICD code happens to have a . in the identifier as many do, the service fails. Here's an example of one that won't work (IIS gives a 404 - Not Found response): http://somehost/someService.svc/IcdSet('001.1') So the question is how can I escape the period or properly pass it to WCF Data Services? It must be interpreting it as a different type of filter condition. Note: The code for the underlying class seems irrelevant to the question but I can provide it if needed. Edit: My guess at the moment is that IIS is trying to find a file that ends with .1') which is then producing the 404 error. But how can I tell IIS that it shouldn't be looking for files as these are all data queries? A: check this out http://blogs.msdn.com/b/peter_qian/archive/2010/05/25/using-wcf-data-service-with-restricted-characrters-as-keys.aspx Also might be of interest if you're using .Net 3.5 http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=5121
{ "language": "en", "url": "https://stackoverflow.com/questions/7560030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Selected Index changed doesnt fire I have a drop down list that is populated on page load and by default the selected index is 0 and its set to an emty string. On page load if we change the selected value the selected index method doesnt fire. if(!page.isPostback) { this.ddl.DataSource = list; this.ddl.DataValueField = "Id"; this.ddl.DataTextField = "Name"; this.ddl.DataBind(); this.ddl.Items.Insert(0, String.Empty); if (Request.QueryString != null) { string name = Request.QueryString["name"]; long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault(); this.selectedIndex = 1; this.ddl.SelectedValue = Id.ToString(); } } A: That's as it should be. If you want to execute some piece of logic from both the event and/or from page load, put that logic in a separate method so you can call it easily from your page load. A: private void BindList() { this.ddl.Items.Clear(); this.ddl.DataSource = list; this.ddl.DataValueField = "Id"; this.ddl.DataTextField = "Name"; this.ddl.DataBind(); this.ddl.Items.Insert(0, String.Empty); this.ddl.Items.SelectedIndex = 0; } if(!page.isPostback) { BindList(); if (Request.QueryString != null) { string name = Request.QueryString["name"]; long Id = list.Where(item => item.Name == name).Select(item =>item.Id).SingleOrDefault(); this.ddl.Items.ClearSelection(); this.ddl.Items.FindByValue(Id.ToString()).Selected = true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is void a type? I can't answer completely "why should we call "void" is 'return type'?" How do I prove that "void" is a type? A: Quote: TYPE public static final Class TYPE The Class object representing the primitive Java type void. Taken from : http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Void.html Or have I misunderstood the question? A: Hope class void explains why void is a type. The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void. public final class Void extends Object A: void is not a type, it is not also a return type: in JLS 14.8 you can find a note about this type: Note that the Java programming language does not allow a "cast to void"-void is not a type A: The Java Language Specification says that: [...] every variable and every expression has a type that can be determined at compile time. The type may be a primitive type or a reference type. void is not a valid type. However, void is a valid keyword used to indicate that a method does not return a value. The Void JavaDoc also says that void is a keyword: The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void Contrast that to the Integer JavaDoc: The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. The Void class represents the void keyword; while the Integer class represents an int type. A: Yes, void is definitely type, meaning 'nothing'. By the way, do you mean C (C++, Objective-C, ...). Couldn't say for any language, but in C (C++, Objective-C, ...) void is a type. But it is special data type. You couldn't declare variable of type void. That's differ void from any other types. But you could declare pointer to void. Function which return value is void means function has no return value, or returns nothing. That's afraid all cases where void type could be used. void * v; /** declares variable v as pointer to void */ *v used as left value in expression could be assigned value of any type without type cast. That's why void type was introduced into language. You updated your question, underlining you were asking about Java. Java has no pointers and no functions. void type is used in declarations of methods returning nothing. A: Any class method must specify a return type. The 'void' keyword can be specified, specifying that it has no return type, for example: public void SetPantsSize(int width); There is also a void class: http://download.oracle.com/javase/6/docs/api/java/lang/Void.html A: Void is a type in most languages, and given the typical type system, it makes the most sense to think about it as a type that specifies "nothing". You didn't state your language, but for example, in C#, the void keyword corresponds to the .NET framework void type. A: void is a type in the Java language (you can read that directly in the Java Language Specification). However the type void has no member values, that is no concrete value will ever have the type void. void is therefore used to indicate that a method cannot return a value when called (that is void is the type of "no value").
{ "language": "en", "url": "https://stackoverflow.com/questions/7560034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: superscript altering the line height I have a superscript that is messing up the line spacing. How do i make it even? I tried sup{vertical-align:0; position: relative;} but that doesn't help. Any suggestions? A: We can achieve it by ignoring the <sup></sup> tags and directly using something like <span style="position:relative; top:0.3em;"> A: You may need to try altering the line height of the sup element to be smaller than the parent text. sup{vertical-align:super; line-height:0.5em;} http://en.wikipedia.org/wiki/Superscript has lots of examples that you can inspect. Some of them increase the line height of the parent, some do not. If that isn't working for you, you can also try sup{vertical-align:top;} A: sup{vertical-align:top; line-height:0.5em;} This works for me, even though I have sup defined in my stylesheet. I have a link, which also has styling applied, between the <sup> and </sup> tags, but this seems to force the intended effect of keeping the line spacing consistent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: MVC JSONP TreeStore I'm starting coding with Sencha Touch and I would like to do the same thing as below, but at distance: MyApp.search = new Ext.data.TreeStore({ model: 'ListItemSearch', proxy: { type: 'ajax', url: 'search.json', reader: { type: 'tree', root: 'items' } } }); It's working fine, but I'd like to make it at distance with JSONP like this: MyApp.search = new Ext.data.TreeStore({ model: 'ListItemSearch', proxy: { type: 'ajax', url: 'http://www.test.com/search.json', reader: { type: 'tree', root: 'items' } } }); I don't know how to code this, and the examples that I tried didn't work. How can I do this? A: if your JavaScript code isn't running at the same domain as your ajax request (test.com) then you will have security issues. Check to make sure the proxy type 'ajax' is using JSONP I think you have to use the sencha JSONP library to do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: setTimeout is not staying true to the delay I give it inside a $.each Given this code: counter = 0; $('div').each(function () { counter++; console.log(counter + ': Timeout is: ' + $(this).index() * 150); setTimeout(testTime(), $(this).index() * 150); }); function testTime() { var currentDate = new Date(); console.log(counter + ': Call time is: ' + currentDate.getMilliseconds()); } If you look at the console log you can see the millisecond it is called on and the supposed delay in between each call. As you can see each call is only a few milliseconds between each one. A: The first argument to setTimeout should be a function. You are calling testTime and passing its return value (undefined) as that argument. Get rid of the (). Update in response to comments: If you need to pass arguments, then you need to either need to pass them in an array as the third argument (as per the documentation) or, for wider browser support, use a closure. counter = 0; $('div').each(function () { counter++; console.log(counter + ': Timeout is: ' + $(this).index() * 150); setTimeout(testTimeFactory(foo, bar, baz), $(this).index() * 150); }); function testTime() { var currentDate = new Date(); console.log(counter + ': Call time is: ' + currentDate.getMilliseconds()); } function testTimeFactory(a, b, c) { return function() { testTime(a, b, c); } } A: In your code you were calling the function in the timeout immediately. Try this: http://jsfiddle.net/maniator/VSQ4j/2/ setTimeout(testTime, $(this).index() * 150); A: The problem is the call to setTimeout. You need to be passing a function to the first parameter but instead you're invoking a function. Change the call to the following setTimeout(testTime, $(this).index() * 150);
{ "language": "en", "url": "https://stackoverflow.com/questions/7560038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET Repeater loading image In my application i used repeater control.For that i have loaded item at a time.But my client wants to display first 6 items then if the user come to end of the page it will display a image named loading image and after a short time display another 6 items and again the user came to end of page it will display loading image at the end of screen and load another 6 items like that and so on. ex:Facebook loading A: It sounds like you need to use continuous scrolling, to load images as the user scrolls. Here are a couple of articles which demonstrate how to use continuous scrolling: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=371 http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/ Here's an example of an image gallery that uses continuous scrolling: <!DOCTYPE html> <html> <head> <style type="text/css" > div { border: solid 1px black; height:200px; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> </head> <body> <script type="text/javascript"> var pixelsBetweenImages = 200; var imagesArray = {} var imagesArray = new Array(); // regular array (add an optional integer argument to control array's size) imagesArray[0] = ""; imagesArray[1] = ""; imagesArray[2] = ""; imagesArray[3] = "/images/ImageThree.gif"; imagesArray[4] = "/images/ImageFour.gif"; imagesArray[5] = "/images/ImageFive.gif"; imagesArray[6] = "/images/ImageSix.gif"; imagesArray[7] = "/images/ImageSeven.gif"; imagesArray[8] = "/images/ImageEight.gif"; $(window).scroll(function() { var scrollpos = $(window).scrollTop() + $(window).height(); var imageIndex = Math.floor(scrollpos / pixelsBetweenImages); if (imagesArray[imageIndex] != "") { var div = $("#" + imageIndex); div.html(imagesArray[imageIndex]); imagesArray[imageIndex] = ""; } }); </script> <div>Visible on first load</div> <div>Visible on first load</div> <div>Visible on first load</div> <div id="3">3&nbsp;</div> <div id="4">4&nbsp;</div> <div id="5">5&nbsp;</div> <div id="6">6&nbsp;</div> <div id="7">7&nbsp;</div> <div id="8">8&nbsp;</div> </body> </html> Source: Is there ability to load page images partially when scroll down to it or is it just effect? As for displaying a loading image, just use an animated gif as the default image, and delay loading of the actual image for effect, using setTimeout or something along those lines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Images showing in wrong places I am trying to make a very simple tiled rpg. In the first tests, tiles where in the correct places, but when I refactored the program and created classes called map and tile.map for storing and displaying maps and tile for storing tile's pos and img and for collision detection, it was mis-placing the images. The class's structure includes a Main class "Frame" that holds the map stored in string array, then makes a map class and puts the string array, grass and water textures,also the tile Height and Width and the Graphics object (the init is called inside the paint method soo i will get an graphics object not a null). The map makes an 2d array made out of tile classes which is based on the string array. The tile gets the graphics object and draws the img on to it. Now when I run it it puts the tiles in wrong location. Links to the code: * *(main class) Frame : pastebin.com/dephCtfg *Map : pastebin.com/hKitArsf *Tile : pastebin.com/aagDjEWp Edit: Added whole code: import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; public class UsersFrame extends JFrame { // images private Image imgs[] = new Image[2]; private int tileH = 25; private int tileW = 25; // map1 private Map map1; String map1St[] = { "0000000000000000000000000", "0111111110011111111000000", "0111111110011111111000000", "0111111110011111111000000", "0111000110011100011000000", "0110000110011000011000000", "0111001110011100111000000", "0111101110011110111000000", "0111111110011111111000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000001000000000000000", "0000000010000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", }; public UsersFrame() { loadPics(); } public void paint(Graphics gg) { map1 = new Map(map1St, tileW, tileH, imgs, gg); map1.drawMap(); } public static void main(String s[]) { JFrame frame = new UsersFrame(); frame.setTitle("RPG"); // Add a window listner for close button frame.setDefaultCloseOperation(EXIT_ON_CLOSE); // This is an empty content area in the frame JLabel jlbempty = new JLabel(""); jlbempty.setPreferredSize(new Dimension(600, 625)); frame.getContentPane().add(jlbempty, BorderLayout.CENTER); frame.setResizable(false); frame.pack(); frame.setVisible(true); } private void loadPics() { Image grass = new ImageIcon("/Users/olek/RESOURCES/RPG/grass.jpg") .getImage(); Image water = new ImageIcon("/Users/olek/RESOURCES/RPG/water.jpg") .getImage(); imgs[0] = grass; imgs[1] = water; } } class Map { // TODO: fix images not showing // position private int dx = 0; private int dy = 0; // position on the frame private int tx = 0; private int ty = 0; private int tileH; private int tileW; private int mapW = 25; private int mapH = 25; private Image imgs[] = { null, null }; private Graphics g; Tile map[][] = new Tile[mapW][mapH]; String mapSt[]; private boolean doneDrawing = false; public Map(String mapSt[], int tileW, int tileH, Image imgs[], Graphics g) { this.mapSt = mapSt; this.tileW = tileW; this.tileH = tileH; dx = 0; dy = 0; tx = 0; ty = 0; this.imgs = imgs; doneDrawing = false; this.g = g; System.out.print(g.toString()); } public void drawMap() { if (g == null) { System.out.print("g is null"); return; } char currTile = mapSt[dy].charAt(dx); System.out.print(currTile + "\n"); if (currTile == '0') { System.out.print("drawing water at " + tx + " , " + ty + "\n"); map[dx][dy] = new Tile(imgs[1], tileW, tileH, tx, ty, true, false, g); } if (currTile == '1') { System.out.print("drawing grass at " + tx + " , " + ty + "\n"); map[dx][dy] = new Tile(imgs[0], tileH, tileH, tx, ty, false, false, g); } calcPlacePos(); if (!doneDrawing) { drawMap(); } } private void calcPlacePos() { if (dx != (mapW - 1)) { // System.out.print(dx+" != ("+mapW+"-1)\n"); dx++; } // System.out.print(dx+" == ("+mapW+"-1) && "+dy+" != ("+mapH+"-1)\n"); if (dx == (mapW - 1) && dy != (mapH - 1)) { dx = 0; dy++; } if (dx == (mapW - 1) && dy == (mapH - 1)) { doneDrawing = true; System.out.print("done"); } tx = dx * tileW; ty = dy * tileH; } } class Tile { private Image img; private int tileH; private int tileW; private int posX; private int posY; private boolean isWall; private boolean front; private Graphics gr; public Tile(Image i, int w, int h, int pX, int pY, boolean wall, boolean inFront, Graphics g) { img = i; tileH = h; tileW = w; posX = pX; posY = pY; isWall = wall; front = inFront; gr = g; drawTile(); } public boolean isWall() { return isWall; } public boolean isInFront() { return front; } public Image getImage() { return img; } public void setImage(Image i) { if (i != null) { img = i; } else { System.out.print("Could not assign image to Tile object becouse \n" + " gotten image is null"); } } private void drawTile() { Graphics2D g2d = (Graphics2D) gr; g2d.translate(0, 22); g2d.drawImage(img, posX, posX, null); System.out.print(posX + " , " + posY); } public Dimension getDimension() { return new Dimension(tileW, tileH); } } A: In Tile.drawTile(), you must do the following: private void drawTile() { Graphics2D g2d = (Graphics2D) gr; AffineTransform oldTransform = g2d.getTransform(); //new g2d.translate(0, 22); g2d.drawImage(img, posX, posY, null); g2d.setTransform(oldTransform); //new System.out.print(posX+" , "+posY); } However, there is a lot of sub-optimal code in there, but you will learn as you go along! A: Don't draw directly in your JFrame nor in a paint method, nor should you create objects and initialize them from within a paint or paintComponent method. Why not simply display the tile images as ImageIcons held by JLabels? The JFrame's contentPane could hold the JLabels in a GridLayout to make it super easy to do. You'll also want to review a tutorial or two on Swing Graphics as it can get tricky (at least it was for me), and often we have to throw out a lot of preconceived assumptions when learning to do this type of coding. Again, just to see how easy it is with JLabels (images simplified since I don't have access to your image files): import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.*; public class UsersFrame2 extends JFrame { private static final int TILE_H = 25; private static final int TILE_W = 25; private static final String MAP_1_ST[] = { "0000000000000000000000000", "0111111110011111111000000", "0111111110011111111000000", "0111111110011111111000000", "0111000110011100011000000", "0110000110011000011000000", "0111001110011100111000000", "0111101110011110111000000", "0111111110011111111000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000001000000000000000", "0000000010000000000000000", "0000000000000000000000000", "0000000000000000000000000", "0000000000000000000000000", }; private ImageIcon grassIcon; private ImageIcon waterIcon; private JLabel[][] labelGrid = new JLabel[MAP_1_ST.length][MAP_1_ST[0].length()]; public UsersFrame2() { loadPics(); } public static void main(String s[]) { JFrame frame = new UsersFrame2(); frame.setTitle("RPG"); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //frame.setResizable(false); frame.pack(); frame.setVisible(true); } private void loadPics() { // TODO: uncomment this: // Image grass = new ImageIcon("/Users/olek/RESOURCES/RPG/grass.jpg").getImage(); // Image water = new ImageIcon("/Users/olek/RESOURCES/RPG/water.jpg").getImage(); Image grass = createImage(Color.green); // TODO: delete this Image water = createImage(Color.blue); // TODO: delete this grassIcon = new ImageIcon(grass); waterIcon = new ImageIcon(water); setLayout(new GridLayout(labelGrid.length, labelGrid[0].length)); for (int row = 0; row < labelGrid.length; row++) { for (int col = 0; col < labelGrid[row].length; col++) { ImageIcon icon = MAP_1_ST[row].charAt(col) == '0' ? grassIcon : waterIcon; labelGrid[row][col] = new JLabel(icon); add(labelGrid[row][col]); } } } // TODO: delete this: private Image createImage(Color color) { BufferedImage bImg = new BufferedImage(TILE_W, TILE_H, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bImg.createGraphics(); g2.setBackground(color); g2.clearRect(0, 0, TILE_W, TILE_H); g2.dispose(); return bImg; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why do I get a SIGSEGV with glib? When I run the following function I get a SIGSEGV. I can't figure out why... Can anybody help? Point me in the right direction? I is ment as a part of a larger program which scans the directory hierarchy for duplicate files. #include <stdio.h> #include <stdlib.h> #include <glib.h> int main ( int argc , char *argv[]) { GError *error = NULL; const gchar* filename = NULL; gchar *directory_path = "/tmp"; GDir* dp = g_dir_open (directory_path, 0, &error); if (error) { g_warning("g_dir_open() failed: %s\n", error->message); g_clear_error(&error); return 1; } while ( (filename = g_dir_read_name(dp)) ){ filename = g_dir_read_name(dp); gchar* path = g_build_filename (directory_path, filename, NULL); printf("%s\n", filename); g_free (path); } return 0; } A: Maybe get rid of the second filename = g_dir_read_name(dp); (the first line inside of the loop) When it does the loop test condition, it already assigns filename to the next entry in the dir. If you run that line again from within the loop, it will attempt to read one more entry after the last one. If there are an odd number of files in the directory, filename could be pointing to a null value on the last execution of the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue loading content with jQuery UI Tabs with Ajax I have my jQuery UI Tabs working right now but need help implementing the Ajax side. What I need help with is getting #tab-2 to show information (@user.messages) from the MessagesController in a layout that exists as a partial in the MessagesController. My application.js: $(function() { $( "#tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo." ); } } }); }); My profile show.html.erb: <div id="tabs"> <ul id="infoContainer"> <li><a href="#tabs-1">About</a></li> <li><%= link_to "Messages", "messages/profile_messages", :remote => true %></li> </ul> <div id="tabs-1"> </div><!-- end profile-about --> </div> My _profile_messages partial in MessagesController: <div id="tabs-2"> <% for 'message' in @user.messages %> <div class="message"> </div> <% end %> </div> Here is the HTML output of the jQuery UI Tabs: <div id="tabs"> <ul id="infoContainer"> <li><a href="#tabs-1">About</a></li> <li><a href="messages/profile_messages" data-remote="true">Messages</a></li> </ul> <div id="tabs-1"> Here are the tabs as seen in Firebug: <div id="tabs" class="ui-tabs ui-widget ui-widget-content ui-corner-all"> <ul id="infoContainer" class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"> <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">About</a></li> <li class="ui-state-default ui-corner-top"><a href="#ui-tabs-1" data-remote="true">Messages</a></li> </ul> <div id="tabs-1" class="ui-tabs-panel ui-widget-content ui-corner-bottom"> </div> </div> The fact that Firebug shows the second link as #ui-tabs-1 seems odd to me. Then when I click the "Messages" link to load the @user.messages, Firebug shows an error Failed to load resource: the server responded with a status of 404 (Not Found) - :3000/profiles/messages/profile_messages. A: Thanks to the combined efforts of folks here on SO I was able to get this to work. Check out these questions for more code: Exclude application layout in Rails 3 div Rails 3 jQuery UI Tabs issue loading with Ajax
{ "language": "en", "url": "https://stackoverflow.com/questions/7560054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add comment box to page? I am trying to model my "add comment" interface with what you see in the diagram below. However, I was unable to find such a UI element in the XCode library. Is this a customized UI element? Or can I find a UI with the same look and feel as what you see in the diagram? A: You can approximate it using a UIImageView (the silver gray background) and a UITextView on top of it which has a proper cornerRadius set. You'll need to: #import <QuartzCore/QuartzCore.h> in order to be able to set the cornerRadius property of the UITextView like this: textView.layer.cornerRadius = 1.0f; // play around to see what gives you the above rounded effect to your needs. A: Assuming you just want the textfield shape, you can use a UIImageView as background and have a textfield or textview on top of it accordingly...Now if you want that textview to expand thats another story, you can use strechableImageWithleftCapWidth: method on the image in order to be able to strech and expand it, and then you would need to create a custom UITextView class that expands as characters are typed in...
{ "language": "en", "url": "https://stackoverflow.com/questions/7560056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bits vs Char - What's the best way to store 3 mutually exclusive flags? I've got a table which is set to keep track of various items. Among other properties, items can be either A, B, or C, each mutually exclusive of the rest. Is it best practice to store this information as a character, or as 3 sets of bits (isA isB, isC, etc), or some other method? I could understand using the character if I would possibly need more data types in the future, however it also makes sense to me that using bit datatypes would consume smaller amounts of storage. Or am I overanalyzing this and will the difference be so miniscule as to not even matter? A: Or am I overanalyzing this and will the difference be so miniscule as to not even matter? A little bit, yes. But you must understand that there's a crucial difference between your design proposals: having a char column will make exclusive exception work. Having IsX fields (alone) will not. Explained: by having IsA and IsB columns, you can, potentially, have both set to true in the same record, unless you use another mechanism to prevent that (trigger, check constraint, etc.) Additionally, having a new column every time a new value is possible is not good DB design. A: Just use Char. Space wise, you will be using an extra 625kb per million rows (assuming 5 bits saved per row, which is a best-case scenario savings-wise). That isn't very much. To put it into perspective, that's 625 MB per BILLION rows. When you get to tables of that size you don't care about any units that don't start with giga, tera, or peta. Internally, SQL Server stores them all as a byte regardless (up to 8 bit fields). By the time the space matters, any architecture changes (from using bit fields to something more flexible) will be extremely painful. A: I'd use a single char, byte, enum, whatever. If the states are mutually exclusive, then that isn't the best use for flags. A: Come to think of it a really tight, but kind of crazy, way to pull your scenario off would be to stored them in a nullable bit. "An integer data type that can take a value of 1, 0, or NULL." but I don't quite see how they pull that off though since "The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte." Both from http://msdn.microsoft.com/en-us/library/ms177603.aspx If you need to index on the three values I would go for a tinyint instead of three bit fields. A: I'd use a tiny int, basically a one byte number 0 to 255. As you expand your possible values, you end up using crazy letters that don't mean anything. So, I just start out with numbers. Keeping the three bits mutually exclusive isn't worth the hassle, they'll take a byte of storage anyways.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to Plugin Web Pages dynamically in ASP .NET (and update the plugin)? For regular assemblies one can use MEF to load assemblies dynamically. If a live update is required of those assemblies, the recommendation is to use AppDomains to host the dynamic assemblies (potentially one can use Managed Add-in Framework (MAF)). When requiring an update, the appdomain is stopped, the assemblies are updated and the appdomain is reloaded. What about assemblies that are loaded by ASP .NET that contain that code behind classes? How can I update them without forcing a restart of the main appdomain. Is it possible to host some of my pages in a dynamic appdomain? How would you do that? Can this appdomain share login token and authentication stuff so the user doesn't have to re-login? Thanks A: MEF doesn't support AppDomain isolation, so unfortunately, even during recomposition, those assemblies that had previously been loaded are still loaded in the main web application AppDomain. There are two things you'd need to battle in ASP.NET: * *Any changes to physical files (e.g. .aspx, .cshtml, etc), or any changes to configuration files (.config), or any changes to the \bin directory will cause the application to be recycled. This is due to two things, file monitoring of pages/configs, and file monitoring of the \bin directory (which is because by default ASP.NET uses shadow copying of files - this is recommended). *To use MEF in another AppDomain would require a hideous amount of cross-domain communication, either through serialisation or MarshalByRef, which I just don't think would ever be a clean implementation. Not sure how you would trigger BuildProvider instances used to dynamically compile your pages in another AppDomain either. I'm wondering if you're thinking about this too much. Since IIS6, HTTP.SYS has managed the routing of incoming requests to the appropriate website, this is handled at the kernel level. Even if the main application did restart (which there are a variety of reasons why it could), no requests will be dropped, it would simply queue waiting for a new worker process before passing the request on. Sure, from the user's point of view, they may notice some idle time waiting for the new application to restart, but realistically, how often are you going to be making these changes? A lot of application design suffers from over-engineering. You may want to design for every scenario, but realistically it is easier to maintain a system which is simple but extensible. In my opinion, wanting to do what you have specified would be classed as over-engineering. Keep it simple. A: Using the session "StateServer" will preserve your authentication between app pool recycles (caused by file updates). For your actual question: * *Create a folder outside of your website that your app pool has access to. *Put your new assemblies in there *Have a Task/Thread/Web Service that reads the folder and loads the assemblies into the current App Domain * * *Assembly.LoadFrom(string) http://msdn.microsoft.com/en-us/library/1009fa28.aspx * * *The newer version of the assembly should take precedence when an instance is created I guess your question is saying this method doesn't work? What error are you getting...
{ "language": "en", "url": "https://stackoverflow.com/questions/7560058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Ajax contact form with Mootools I'm currently using the following tutorial for my website: http://www.roscripts.com/AJAX_contact_form-144.html I've changed a couple variables in the code, namely my form and the corresponding variables in the PHP file. This is what my form looks like: <form id="contactus" action="send.php" method="get" name="contactus"> <div class="box"> <span style="text-indent: 20px;"><h2>Contact Us!</h2><br /></span> <div id="log"> <div id="log_res"> </div> </div> <label> <span>Name:</span> <input type="text" class="input_text" name="name" id="name" /> </label> <label> <span>Email:</span> <input type="text" class="input_text" name="e_mail" id="e_mail"/> </label> <label> <span>Subject:</span> <input type="text" class="input_text" name="subject" id="subject"/> </label> <label> <span style="padding: 5px 10px 0 0;">Message:</span> <textarea class="message" name="feedback" id="feedback"></textarea> </label> <input type="submit" class="button" value="Send!" /> </div> </form> And my script: http://pastebin.com/iNR1TXBk (pastebinned for space) And my send.php: http://pastebin.com/Wv7GsMVC (pastebinned for space) When I fill in the fields and click submit, <div id="log_res"> changes to <div id="log_res" class="ajax-loading"></div> which says to me that the Ajax is working, but in the dev console of Iron, I get an HTTP Error 500. Is there an error in my PHP or the Javascript?
{ "language": "en", "url": "https://stackoverflow.com/questions/7560059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing NALU h.264/avc, for RTP encupsulation What I can and cant change in NALU in terms of syntex and size, if the nal is meant for RTP encupsulation? A: You can change whatever you want, provided that resulting bit stream is still compliant to: * *MPEG-4 Part 10 Specification (H.264) *RTP RFCs 3550 (RTP), 3984 (RTP Payload for H.264)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Guard with Haml, Livereload, not compiling changes I've successfully installed guard with haml and livereload plugins. In a running guard shell, when both are running, if I press enter, haml successfully gets compiled to html, then served up to a listening browser. However, when only editing the haml file, and I save a change, livereload simply reloads the browser with the same generated .html. It does not recompile .haml -> .html, then serve it to the browser. My Guardfile is below. What am I missing in this setup? i) In the guard shell, pressing enter compiles then serves the generated html. ii) But saving changes in the haml file only serves up old html, without compiling the haml. guard 'haml', :input => 'public', :output => 'public' do watch(%r{^public/.+\.html\.haml}) end guard 'livereload' do watch(%r{.+\.(css|js|html)}) end Thanks ps - this is not a rails project. just using the raw guard, guard-haml & guard-livereload gems A: With help from Thibaud ('guard' author), I got this working. Basically, I ran guard under the directory from which files are being served. My project tree looks like "root/public/css/etc", and I was running guard under "root", and setting "public" as the directory to watch (guard -w public/). But I updated and moved the Guardfile to public/ , and ran guard from there. Now haml is getting compiled and served as desired. guard 'haml' do watch(/^.+\.html\.haml$/) end guard 'livereload' do watch(/^.+\.html$/) end
{ "language": "en", "url": "https://stackoverflow.com/questions/7560068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: How to know where the app is running There is some way to know if my Android app is running on debugger or on a phone?. I want to check some variable, property, or something like that to know where the app is running to prevent some crash when I call some 3rd applications (not available on debugging time) Thanks and sorry for my poor english A: You might want to look into DDMS You can access logs, threads and heap information. also check running apps and services. You can also simulate phone behaviours on the emulator, like an incoming call, as an example. Well, I would also recommend reading all the information in the debugging section, there are a lot of useful tools available for Android developers. A: You mean detecting the emulator? Because you can run under debugger also on your device. Use this to detect the emulator (worked for me a while ago): "google_sdk".equals(Build.MODEL)
{ "language": "en", "url": "https://stackoverflow.com/questions/7560075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: mssql_connect for sql server in windows authentication mode I am trying to connect to sql server 2008 in windows authentication mode (w/o username and password) by using $connect=mssql_connect('username\SQLEXPRESS') But it is giving me a fatal error Fatal error: Call to undefined function mssql_connect() What should I give in the place of username and password when I am logging into the sql server express using windows authentication mode?(I am using sql server management studio) Note: I have changed mssql.secure_connection = On on php.ini file A: It sounds as if your copy of PHP doesn't have the MS SQL module built into it. If you're running PHP 5.3 on Windows, this is because the MS SQL module is no longer available from PHP 5.3 and upwards. See the PHP manual for confirmation of this: http://www.php.net/manual/en/mssql.requirements.php The same manual page also gives details of an alternative driver provided by Microsoft, which you can download and install (assuming you have permissions to install stuff on your web server of course). If you're running a Linux-based PHP installation or PHP 5.2 or earlier on Windows, your problem is still that the MS SQL module hasn't been installed into your copy of PHP, but it should be possible to get it installed and working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7560077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing XML in PHP returns SimpleXMLElement Object. What next? Below is the response I get when I try to parse the XML code returned from Library of Congress SRU Service for a book search. How do I look into [recordData] => SimpleXMLElement Object to get the title, creator, publisher information? This is the first time I am delving into XML. Any help would be greatly appreciated. Here is the response I get. I found code to deal with the name spaces, however cannot figure out how to get beyond the recordData tag. SimpleXMLElement Object ( [version] => 1.1 [numberOfRecords] => 1 [records] => SimpleXMLElement Object ( [record] => SimpleXMLElement Object ( [recordSchema] => info:srw/schema/1/dc-v1.1 [recordPacking] => xml [recordData] => SimpleXMLElement Object ( ) [recordPosition] => 1 ) ) $entry=simplexml_load_file('xml_data.xml'); $namespaces = $entry->getNameSpaces(true); $yr = $entry->children($namespaces['zs']); print_r($yr); <zs:searchRetrieveResponse xmlns:zs="http://www.loc.gov/zing/srw/"> <zs:version>1.1</zs:version> <zs:numberOfRecords>1</zs:numberOfRecords> <zs:records> <zs:record> <zs:recordSchema>info:srw/schema/1/dc-v1.1</zs:recordSchema> <zs:recordPacking>xml</zs:recordPacking> <zs:recordData> <srw_dc:dc xmlns:srw_dc="info:srw/schema/1/dc-schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://purl.org/dc/elements/1.1/" xsi:schemaLocation="info:srw/schema/1/dc-schema http://www.loc.gov/standards/sru/resources/dc-schema.xsd"> <title>My life /</title> <creator>Clinton, Bill, 1946-</creator> <type>text</type> <publisher>New York : Knopf,</publisher> <date>2004.</date> <language>eng</language> <description>Includes index.</description> <subject>Clinton, Bill, 1946-</subject> <subject>Clinton, Bill, 1946---Family.</subject> <subject>Clinton family.</subject> <subject>Presidents--United States--Biography.</subject> <coverage>United States--Politics and government--1993-2001.</coverage> <identifier> http://www.loc.gov/catdir/samples/random051/2004107564.html </identifier> <identifier> http://www.loc.gov/catdir/description/random051/2004107564.html </identifier> <identifier>URN:ISBN:0375414576</identifier> </srw_dc:dc> </zs:recordData> <zs:recordPosition>1</zs:recordPosition> </zs:record> </zs:records> </zs:searchRetrieveResponse> A: See the docs : http://us3.php.net/SimpleXMLElement A simple example there shows: foreach( $xmldata->children() AS $child ) { //run any query you want on the children.. they are also nodes. $name = $child->getName(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7560082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }