text
stringlengths
8
267k
meta
dict
Q: cacerts issue in JAVA and OPEN JDK 6 how can i build cacerts automatically in java , instead of using the Jre/lib/security/cacerts because openJDK didn't contain the cacerts file. A: You can create your own keystore using the keytool. Then you must import all CAs (Certificate Authorities) you need and either place the keystore in <JRE>/lib/security or explicitly set it using a system property. See this post for details. Of course, you could reuse an existing keystore available in other JDKs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the difference between SubscribeOn and ObserveOn I just discovered SubscribeOn, which makes me wonder if I should be using that instead of ObserveOn. Google took me here and here, but neither have helped me grok the difference: it seems incredibly subtle. (In my context, I've got events 'coming up' on a non-gui thread, and I need to switch over to a gui thread before using the event data to update controls). A: It helped me to understand this by thinking of SubscribeOn as setting the thread being "passed up" the chain and ObserveOn as setting the thread "passed down" the chain. The code below uses named threads which you can play with. Thread.CurrentThread.Name = "Main"; IScheduler thread1 = new NewThreadScheduler(x => new Thread(x) { Name = "Thread1" }); IScheduler thread2 = new NewThreadScheduler(x => new Thread(x) { Name = "Thread2" }); Observable.Create<int>(o => { Console.WriteLine("Subscribing on " + Thread.CurrentThread.Name); o.OnNext(1); return Disposable.Create(() => {}); }) .SubscribeOn(thread1) .ObserveOn(thread2) .Subscribe(x => Console.WriteLine("Observing '" + x + "' on " + Thread.CurrentThread.Name)); The output of the above is: Subscribing on Thread1 Observing 1 on Thread2 It's also interesting to see that when you comment out the SubscribeOn line, the output is: Subscribing on Main Observing 1 on Thread2 Because by default the subscription "passes up" whichever thread was running (Main here). Then the ObserveOn "passes down" Thread2. If you instead comment out the ObserveOn line, the output is: Subscribing on Thread1 Observing 1 on Thread1 Because we "pass up" the subscription on Thread1, and by default this same thread is "passed down" and used to run the observation. In a GUI context, to keep things responsive you want the least amount of work done on the GUI thread but you need the subscription done on the GUI thread (to synchronise UI updates). So you want to .ObserveOn the GUI thread. A: I had a similar problem a while back and asked this question about it. I think the responses (including the comments) there will answer your question. To summarize: * *If you want to update controls on a gui thread, use ObserveOn. If you reference System.Reactive.Windows.Forms.dll you get the .ObserveOn(form) which is handy. *SubscribeOn controls the thread on which the actual call to subscribe happens. The problem solved here is that WinForms and WPF will throw exceptions if you add event handlers from multiple different threads. Also, this post was very helpful in figuring out the relationship between ObserveOn and SubscribeOn. A: The differences basically is that subscribeOn force the whole pipeline to be processed by another thread, but with observerOn only the steps in your pipeline define after observerOn will run in another thread only after you set it will be executed in another thread. Observable.just(1) .map ---> executed in io thread .filter ---> executed in io thread .subscribeOn(Scheduers.io) .subscribe() All the steps of the pipeline will be executed in another thread. Observable.just(1) .map ---> executed in Main thread .filter ---> executed in Main thread .observerOn(Scheduers.io) .map ---> executed in New thread .filter ---> executed in New thread .subscribe()
{ "language": "en", "url": "https://stackoverflow.com/questions/7579237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: How to launch android application when volume key is pressed android i want to launch my application when the volume turned to very low.. Edit: Or my application should run in background and it should listen to the volume changes.. I think it sounds good... Is it possible to do that? A: Use registerMediaButtonEventReceiver with a BroadcastReceiver that handles ACTION_MEDIA_BUTTON. This thread explains it: Volume change listener?
{ "language": "en", "url": "https://stackoverflow.com/questions/7579238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C Typed Stack: Linked-List Implementation I have a computer science exam coming up and a large portion is going to be on programming in ansi C. I'm new to C and as a review I tried to implement a stack using a linked-list. My code compiles but it doesn't run as expected. I believe there is an error with my push() function. I'm assuming that my stack reference isn't being updated properly. I wrote the following code from scratch to study / practice. Any advice on how to fix my code or improve my programming style would be greatly appreciated. Thanks guys! stack.h #ifndef __STACK__ #define __STACK__ #include <stdlib.h> #include "bool.h" #define EMPTY -1 typedef struct Node { int index; enum { INT = 0, CHAR, STRING } type; union { int i; char c; char* s; } value; struct Node* prev; } Node; typedef Node* Stack; Stack init(); void push(Stack stack, int type, void* value); void pop(Stack stack, Node* node); void empty(Stack stack); Bool isempty(Stack stack); #endif stack.c #include <stdlib.h> #include <string.h> #include "stack.h" Stack init() { Stack stack = (Node*) malloc(sizeof(Node)); stack->index = EMPTY; stack->type = INT; stack->value.i = 0; stack->prev = 0; return stack; } void push(Stack stack, int type, void* value) { int length; Node* node = (Node*) malloc(sizeof(Node)); node->index = stack->index + 1; node->type = type; switch(node->type) { case INT: node->value.i = *((int*) value); break; case CHAR: node->value.c = *((char*) value); break; case STRING: length = strlen((char*) value) + 1; node->value.s = (char*) malloc(length * sizeof(char)); strcpy(node->value.s, value); break; } node->prev = stack; stack = node; } void pop(Stack stack, Node* node) { int length; Node* temp = stack; if (!isempty(stack)) { node->index = stack->index; node->type = stack->type; switch(stack->type) { case INT: node->value.i = stack->value.i; break; case CHAR: node->value.c = stack->value.c; break; case STRING: length = strlen(stack->value.s) + 1; node->value.s = (char*) malloc(length * sizeof(char)); strcpy(node->value.s, stack->value.s); free(stack->value.s); break; } node->prev = 0; stack = stack->prev; free(temp); } else { /*TODO: handle empty case */ puts("Stack empty!"); } } void empty(Stack stack) { while (!isempty(stack)) { Node* temp = malloc(sizeof(Node)); pop(stack, temp); free(temp); } } Bool isempty(Stack stack) { return stack->index == EMPTY ? TRUE : FALSE; } bool.h #ifndef __BOOL__ #define __BOOL__ typedef int Bool; #define FALSE 0 #define TRUE 1 #endif main.c #include <stdlib.h> #include <stdio.h> #include "stack.h" int main() { Stack stack = init(); Node* node = malloc(sizeof(Node)); int i = 5; push(stack, 0, &i); pop(stack, node); printf("Node value: %d\n", node->value.i); free(node); empty(stack); puts("done."); return 0; } A: Really you are not modifying stack. You must to use &stack for push, pop and empty methods. They will have following signature: void push(Stack * stack, int type, void* value); void pop(Stack * stack, Node* node); void empty(Stack *stack); and, of course, use pointer contents inside these methods, like: void push(Stack * stack, int type, void* value) { int length; Node* node = (Node*) malloc(sizeof(Node)); node->index = (*stack)->index + 1; node->type = type; switch(node->type) { case INT: node->value.i = *((int*) value); break; case CHAR: node->value.c = *((char*) value); break; case STRING: length = strlen((char*) value) + 1; node->value.s = (char*) malloc(length * sizeof(char)); strcpy(node->value.s, value); break; } node->prev = *stack; *stack = node; } void pop(Stack * stack, Node* node) { int length; Node* temp = *stack; if (!isempty(*stack)) { node->index = (*stack)->index; node->type = (*stack)->type; switch((*stack)->type) { case INT: node->value.i = (*stack)->value.i; break; case CHAR: node->value.c = (*stack)->value.c; break; case STRING: length = strlen((*stack)->value.s) + 1; node->value.s = (char*) malloc(length * sizeof(char)); strcpy(node->value.s, (*stack)->value.s); free((*stack)->value.s); break; } node->prev = 0; *stack = (*stack)->prev; free(temp); } else { /*TODO: handle empty case */ puts("Stack empty!"); } } void empty(Stack *stack) { while (!isempty(*stack)) { Node* temp = malloc(sizeof(Node)); pop(stack, temp); free(temp); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Problem while updating table in android I created a table in the database that has the data like this: Now i have written a query that updates the contact field by concatinating name and email fields: UPDATE MyContacts SET contact=(SELECT name||'--'||email FROM MyContacts); Here the problem is after executing the query the table is as below: Why is it happening like this? In oracle i never faced this problem. Please help me. Thank you A: Right now you're not specifying the correct row to retrieve the values from. Try something like this: UPDATE MyContacts SET contact = name||'--'||email; EDIT: Glad it worked. Your first issue was that your sub-select uses a SELECT statement with no WHERE clause (SELECT name||'--'||email FROM MyContacts will return 3 rows). One possible solution would be for SQLite to throw an error and say You've tried to set a column to the result of an expression that returns more than 1 row: I've seen this with MySQL and SQL Server. However, in this case SQLite appears to just use only the very first value returned. However, your second error then kicks in: since you don't narrow your UPDATE statement with a WHERE clause, it uses that first value returned to update EVERY single row, which is what you see.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Agile Requirements Up-front I understand that it is better to discover requirements through iterative approaches in Agile, however I often hear of people rejecting projects on the basis that they are given up-front requirements. Why is this the case? Why can't up-front requirements just be taken as-is, e.g. just added to a product backlog and then prioritized and implemented? A: There's nothing wrong with up-front requirements. In fact it helps to know where you're heading before you set sail! Agile is a lot about being able to be adaptable, so that should requirements change you're not locked into something you don't want. A: The kind of up front requirements that would cause a developer to think twice about a project, would be those which indicate that the client are likely to be a nightmare to work with: * *an obsession with one particular, unsuitable technology or presentation style *insisting on 'security' with glaringly obvious vulnerabilities In an agile project, it's good to show a client the current state of the partially working system at an early stage, and get feedback, using this information to help design the subsequent parts of the system. If a client is too fixed on ideas of the final product then they might not be able to give useful feedback at this stage, and the final product may be not as good as it could have been. A: This something that can be quite problematic with Agile. Some teams will use it as an excuse to not have a plan as they want to be 'adaptable'. Requirements can help to focus on the software architecture, which is something else that is not always given much focus in some Agile teams. It is points like these that lead me to believe that Agile should just be principles but not a methodology. Digital Animal wrote an interesting article about how Agile can be used in such a way that it stops being effective. For some teams, it is better to learn from what is great about Agile and use it to build a methodology that works for them. http://digitalanimal.com/blog/slaying-the-agile-dragon-the-game-of-thrones-methodology/?AT=CZcb6f
{ "language": "en", "url": "https://stackoverflow.com/questions/7579244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: .Net 4: How to reference a dynamic object with property named "return" I'm retrieving json from a public api and converting it into a dynamic object using JsonFx. JsonFx.Json.JsonReader reader = new JsonFx.Json.JsonReader(); dynamic response = reader.Read(jsonAsString); The json contains a property named return. e.g. {"result":"success","return":{"high":{"value":"3.85001","value_int":"385001","display":"3.85001\u00a0\u20ac","currency":"EUR"}} JsonFx creates the dynamic object fine and I can also debug into it and see the values. The problem is when I try to reference the property in my code the compiler complains: response.return.high.currency Identifier expected; 'return' is a keyword How can I reference the return property without the compiler complaining? A: Try response.@return.high.currency. You need to append @ at the begining of any field wich name is the same as C# keywords.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How to access/reference DLL in CodeIgniter? Is it possible to reference a DLL (made from C# or C++) in PHP using CodeIgniter Framework? If yes, how? I'm gathering info, I've also asked the CodeIgniter forums. :D A: No, it's not possible. You are trying to access "application" written in different language. Maybe you should give us more info, what do you want to achieve.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery simulate click, check boxes and call function I have set up a workspace area which represents a blank PDF page where users can select paper size using radio buttons, orientation of landscape or portrait using radio buttons and personal motivation and goal statements using checkboxes. The user checks / unchecks the statement(s) they would like to place on the workspace and are also able to drag and drop them. When a user changes the orientation I need all the checked statement items to be briefly saved, which I am putting into an array. Then uncheck all the checkboxes of the statements that were chosen to be added (this works) and remove all the statements from the workspace (this does not work). I need to then loop through the array to go back and check the checkboxes (this works) and call the BoardElement function (this does not work) to run the ajax call. The related code I am using is below, and have tried many suggestion from different posts. The OrientationChange function is what I am using to attempt the save, remove and call to BoardElement which gets the elements. Thanks. HTML <h3>Paper Size</h3> <input type="radio" name="paper_size" id="paper_size1" value="8-5x11" checked="checked" /> 8.5&quot;x11&quot; &nbsp; <input type="radio" name="paper_size" id="paper_size2" value="11x17" /> 11&quot;x17&quot; </fieldset> <fieldset> <h3>Orientation</h3> <input type="radio" name="orientation" id="orientation1" value="l" checked="checked" /> Landscape &nbsp; <input type="radio" name="orientation" id="orientation2" value="p" /> Portrait </fieldset> <fieldset> <h3>Elements</h3> <input type="checkbox" name="board_element_cb" id="board_ele_0" value="0" /> "Who Am I" Image&nbsp; <input type="checkbox" name="board_element_cb" id="board_ele_1" value="1" /> "Who Am I" Text&nbsp; <input type="checkbox" name="board_element_cb" id="board_ele_2" value="2" /> Mission Statement&nbsp; </fieldset> jQuery $(document).ready ( function () { BoardElement = function () { var elements_array = new Array('wai_img_', 'wai_text_', 'mission_text_', 'affirmation_text_', 'gratitude_text_', 'role_model_'); if ($(this).is(':checked')) { var data_string = 'board_element=' + $(this).val(); $.ajax ({ type: 'POST', url: 'get_board_element_ajax.php', data: data_string, success: function(html) { $('#board_area').append(html); $('.draggable_item').draggable ({ containment: '#board_area', stack: '#board_area div' }); } }); } else { var checked_value = $(this).val(); $('.draggable_item').each ( function () { if (this.id.indexOf(elements_array[checked_value]) > -1) { $('#' + this.id).remove(); } }); } } $('input[id^=board_ele_]').click(BoardElement); // save, remove and get selected board items on orientation change OrientationChange = function () { var board_ele_array = new Array(); // save $('input[id^=board_ele_]').each ( function (i) { if ($('#board_ele_' + i).is(':checked')) { $('#board_ele_' + i).attr('checked', false); board_ele_array.push(i); $('#board_ele_' + i).attr('checked', false); } }); //for (var j = 0; j < board_ele_array.length; j++) //{ var j = 0; function BoardEleCheckbox () { if (j < board_ele_array.length) { $('#board_ele_' + board_ele_array[j]).attr('checked', true); //$('#board_ele_' + board_ele_array[j]).click(); //BoardElement(); $('#board_ele_' + board_ele_array[j]).click(BoardElement); j++; setTimeout(BoardEleCheckbox, 1000); } } setTimeout(BoardEleCheckbox, 1000); //} } $('input[name=orientation]').click(OrientationChange); }); A: Have you tried: $('#board_ele_' + i).removeAttr('checked'); BoardElement.call($('#board_ele_' + i).get(0)); board_ele_array.push(i); and then: $('#board_ele_' + board_ele_array[j]).attr('checked', 'checked'); BoardElement.call($('#board_ele_' + board_ele_array[j]).get(0)); j++; setTimeout(BoardEleCheckbox, 1000); Once a handler is assigned to the element, you invoke it with a no-args call, hence click(). Edit: http://jsfiddle.net/uxqWv/3/ Edit 2: http://jsfiddle.net/uxqWv/7/ When you click on the checkbox, first the state changes and then the handler gets fired. It seems though that when you invoke a click handler through jQuery it's the other way around. So the handler thinks that you just checked the button, and adds another board element. To work around this you have to call the handler on the checkbox manually with call method of the javascript Function object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: displaying time when page is refreshed In my xslt file, is it possible to display the time (with the help of a label) whenever the browser detects a page refresh? How is it done? A: You can emit javascript that writes out the local time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Subscribers model in rails Consider a model for keeping user id's of subscribers on a particular comment thread, such that thread has_many subscribers where subscribers is of type user. I feel like generating a new a table for subscribers is overkill. In principle, I'd like to access thread.subscribers to get a list of subscribers- surely there is a 'lighter' way? I'm using Rails 3 with SQLite. A: There are two methods you could use. Options One is to use a habtm relationship like: class Thread has_and_belongs_to_many :users end However personally I would use an additional model, so that should you even need it you can specify stuff about subscriptions: class Thread has_many :subscriptions end class Subscription belongs_to :thread belongs_to :user end Generally a useful join model is considered better practice. Additionally I wouldn't really be worrying about how 'light' you database schema is. Databases are very good at what they're good at, and that's why we let they do it. Encoding this kind of information as a string or the like as other issues and may even be less efficient. A: Just store it is a regular attribute on the Thread model, corresponding to a column in the threads table. Call it subscriber_list, and define it as a pipe-delimited list of subscribers. In the database, make it type :text. Then in Thread just create a couple accessors: class Thread < ActiveRecord::Base def subscribers self.subscribers_list.split('|') end def subscribers=(arr) self.subscribers_list = arr.join('|') end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7579257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get HiddenField Value from ascx.cs page to aspx.cs page my ascx code: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Demo.ascx.cs" Inherits="Demo" %> <asp:HiddenField ID="hidden1" runat="server" Value=""/> <asp:Label ID="lbl1" runat="server" Text="Hiii"></asp:Label> my ascx.cs code : protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { lbl1.Text = "Mahendra Kamble"; hidden1.Value = "123"; } } my aspx code: <%@ Register TagName="TopBar" TagPrefix="CRS" Src="~/Demo.ascx" %> --- -- <div> <CRS:TopBar ID="Hide" runat="server" Visible="false"/> </div> my aspx.cs code if (!IsPostBack) { //Label lb = (Label)Hide.FindControl("lbl1"); // Response.Write("---" + lb.Text); //HiddenField hf = (HiddenField)Hide.FindControl("hidden1"); //Response.Write("---" + hf.Value); // UserControl control = (UserControl)LoadControl("Demo.ascx"); Demo uc = (Demo)Page.LoadControl("Demo.ascx"); // HiddenField hf1 = (HiddenField)control.FindControl("hidden1"); HiddenField hide = (HiddenField)uc.FindControl("hidden1"); Response.Write("--- " + hide.Value + " Value "); form1.Controls.Add(uc); } Now How should I get the Value of HiddenField i.e. hidden1.value="123" in this aspx.cs page? A: You can pass the value of hidden field to a view state property. so you can set or get the value of hidden fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery banner with random quotes in random positions I'm looking for a jquery script that will load various quotes randomly and into random positions over an image (banner). I know this is a vague question but I don't know how it can be achieved and I'm looking for something to begin with. A: Maybe a daft idea, but have you considered using a tag cloud? There are several ready-made plugins available (e.g. here, here, here and many others). It's not what a cloud is meant for, but if you used your quotes as tags and gave them all the same weighting it might give you the visual layout you are looking for and save some work (obviously switch any animations off). The div could then be styled to position over your image. Just an idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Ajax.BeginForm does not pass form values? I'm trying to show a partial view via calling Ajax.BeginForm, but I can't receive the values of my form(I need to get the value of hidden input, bookId, in controller, e.g 5). // View @using (Ajax.BeginForm("Detail", "Books", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "ShowBookDiv" })) { <input type="hidden" id="bookId" value="5" /> <input type="submit" id="sBtn" value="Details" /> } // Controller [HttpGet] public ActionResult Detail(string bookId) { if (Request.IsAjaxRequest()) { var a = Request["bookId"].ToString(); // some code to get details return PartialView("ShowBooks", details); } ... } When I trace the code in Controller bookId is null! A: I've added the "name" property to hidden field and it works !!! really strange! <input type="hidden" name="bookId" id="bookId" value="5" /> A: Ajax.BeginForm is a pain, IMO. I would Use $.ajax from JQuery Ajax API : http://api.jquery.com/jQuery.ajax here is a good example for you to see how it works : http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views Posting the whole form requires a little bit of work (in terms of validation, etc.) but you will have complete control over the action if you are good with JavaScript.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Re-creating tables in SQLite While implementing the save-/loadfunction of my database, I dropped the tables to see if my app can handle the creation of the tables if necessary - well it can't So in the onCreate of my testactivity, I create an instance of DB which creates in it's constructor an instance of DBOpenHelper. Basically when the DBOpenHelper instance calls getWritableDatabase() DBOpenHelper's onCreate should be executed, creating the tables in my database. I think the problem is, that getWritableDatabase() doesn't get called, because the Database itself already exists - think I've read something like this method absorbed the function of openOrCreateDatabase. How can I make sure, that the tables are recreated if not existing without having to delete and recreate the database everytime? DBOpenhelper: public class DBOpenHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static String DATABASE_NAME = "RTDB"; public static final String DB_TABLE_NAME1 = "playertable"; public static final String DB_TABLE_NAME2 = "itemtable"; public static String TAG = "openhelper"; private static final String DB_CREATE_TABLE_PT = "CREATE TABLE IF NOT EXISTS " + DB_TABLE_NAME1 + " (" + "ID INT(2) PRIMARY KEY AUTOINCREMENT," + "Name VARCHAR(30) ," + "HP INT(3) ," + "Satisfaction INT(3) ," + "Hygiene INT(1) , " + "IsAlive INT(1) " + " )"; private static final String DB_CREATE_TABLE_IT = "CREATE TABLE IF NOT EXISTS " + DB_TABLE_NAME2 + " (" + "Money INT(3) ," + "Gas INT(3) ," + "Food INT(3) ," + "Toiletries INT(3) ," + "Spareparts INT(3) ," + "Meds INT(3) ," + "Tents INT(3) ," + "Ration INT(1) ," + "Trabbihp INT(3) ," + "Trabbispeed INT(2)" + " )"; public DBOpenHelper(Context context, String databaseName) { super(context, databaseName, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { Log.d("TAG", "PT :" + DB_CREATE_TABLE_PT); db.execSQL(DB_CREATE_TABLE_PT); Log.d(TAG, "PT create" + DB_CREATE_TABLE_PT); db.execSQL(DB_CREATE_TABLE_IT); Log.d(TAG, "IT create" + DB_CREATE_TABLE_IT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME1); db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME2); onCreate(db); } } DB: public class DB { private Context context; private SQLiteDatabase db; private static String TAG = "save"; private static ContentValues itemValues = new ContentValues(); private static ContentValues playerValues = new ContentValues(); public DB(Context context) { this.context = context; DBOpenHelper dbHelper = new DBOpenHelper(this.context, "RTDB"); this.db = dbHelper.getWritableDatabase(); } public void savePlayer(Player player[]) { for (int i = 0; i <= 3; i++) { playerValues.put("Name", player[i].getName()); playerValues.put("HP", player[i].getHp()); playerValues.put("Satisfaction", player[i].getsatisfaction()); playerValues.put("Hygiene", player[i].isHygieneInt()); playerValues.put("IsAlive", player[i].isAliveInt()); } db.insert("playertable", null, playerValues); } // Speichern der Items // TODO Position fehlt noch public void saveItems() { itemValues.put("Money", Resource.money); itemValues.put("Gas", Resource.gas); itemValues.put("Food", Resource.food); itemValues.put("Toiletries", Resource.toiletries); itemValues.put("Spareparts", Resource.spareparts); itemValues.put("Meds", Resource.meds); itemValues.put("Tents", Resource.tents); itemValues.put("Ration", Resource.ration); itemValues.put("Trabbihp", Resource.trabbihp); itemValues.put("Trabbispeed", Resource.trabbispeed); db.insert("itemtable", null, itemValues); } // Hier werden die Items aus der Datenbank abgefragt, der zurueckgelieferte // Cursor vie cursorToIntArray() in einen Int Array umgewandelt und dessen // Inhalt in die Ressource Klasse geschrieben public void loadItems() { Cursor itemCursor = db.query("itemtable", null, null, null, null, null, null); int[] itemIntArray = cursorToInt(itemCursor, 9); Resource.money = itemIntArray[0]; Resource.gas = itemIntArray[1]; Resource.food = itemIntArray[2]; Resource.toiletries = itemIntArray[3]; Resource.meds = itemIntArray[4]; Resource.tents = itemIntArray[5]; Resource.ration = itemIntArray[6]; Resource.trabbihp = itemIntArray[7]; Resource.trabbispeed = itemIntArray[8]; } // Name und Restliche Int-Werte der Playerobjekte werden separat aus der // Datenbank geholt und gesetzt public void loadPlayer() { String[] namecolumn = { "Name" }; String[] intcolumn = { "ID, Name, HP, Satisfaction, Hygiene, IsAlive" }; String[] namesToString = new String[4]; Cursor playerCursor = db.query("playertable", intcolumn, null, null, null, null, "ID"); playerCursor.moveToPosition(-1); int i = 0; while (i <= 3) { playerCursor.moveToNext(); String temp = playerCursor.getString(1); Resource.playerArray[i].setName(temp); int tempint = playerCursor.getInt(2); Resource.playerArray[i].setHp(tempint); tempint = playerCursor.getInt(3); Resource.playerArray[i].setsatisfaction(tempint); tempint = playerCursor.getInt(4); Resource.playerArray[i].setHygieneInt(tempint); tempint = playerCursor.getInt(5); Resource.playerArray[i].setAliveInt(tempint); i++; } } public void dropTables() { db.execSQL("DROP TABLE 'playertable';"); db.execSQL("DROP TABLE 'itemtable';"); } private int[] cursorToInt(Cursor cursor, int n) { int[] results = new int[n]; for (int i = 0; i <= n - 1; i++) { results[i] = cursor.getInt(i + 1); } return results; } private String[] cursorToString(Cursor cursor) { String[] results = new String[4]; int columnIndex = cursor.getColumnIndex("Name"); for (int i = 0; i <= 3; i++) { results[i] = cursor.getString(columnIndex); } return results; } } Testactivity onCreate instancing DB: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.myDB = new DB(this); initUI(); testcase1(); A: Not sure your description of how getWritableDatabase functions is correct: looking at your code you appear to be doing the right thing, as I use a very similar structure in many deployed apps without any errors. It correctly handles creating/upgrading all tables, regardless of whether or not they exist or the database exists. You might want to try making DBOpenHelper a static class: that works for me. Alternatively check your logs carefully: if there's some other exception taking place that may not appear related at first glance then that might point you towards a solution. EDIT: Try private static class DBOpenHelper extends SQLiteOpenHelper. What I'd also suggest is changing the database version to force the onUpgrade method to be called. In general the case where you've dropped tables but the file exists would need you to call into the information schema to check if the database file has the tables defined. onCreate only gets called if the file doesn't exist, and onUpdate only gets called if you change the database version. EDIT: see http://www.sqlite.org/faq.html#q7 for more detail on using the information schema table to check if your table exists. You can just run a query against the SQLITE_MASTER table and then if you can't find a particular table run the CREATE statement.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Verify Digital Signature with SignedCms I get the CryptographicException "The hash value is not correct." I tried verifyCms.CheckSignature(true); (same error) I tried to add in ContentInfo the whole mail (Sender , Subject , Body, HTML Sectione ...) (same error) public static bool Verify(byte[] signature, X509Certificate2 certificate) { X509Certificate2 cert=new X509Certificate2(@"D:\Work\Digital Signature\smime.p7s"); certificate = cert; if(signature == null) throw new ArgumentNullException("signature"); if(certificate == null) throw new ArgumentNullException("certificate"); //the text from the body of the mail string text = "FINAL TEST SIGNED"; //hash the text // Methode 3 for Hashing System.Security.Cryptography.SHA1 hash3 = System.Security.Cryptography.SHA1.Create(); System.Text.UnicodeEncoding encoder = new System.Text.UnicodeEncoding(); byte[] combined = encoder.GetBytes(text); byte[] hash3byte = hash3.ComputeHash(combined); //Adding the text from the email, to a contentInfo ContentInfo content = new ContentInfo(hash3byte); // decode the signature SignedCms verifyCms = new SignedCms(content,true); verifyCms.Decode(signature); // verify it try { verifyCms.CheckSignature(new X509Certificate2Collection(certificate), false); return true; } catch(CryptographicException) { return false; } } Where is the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7579269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate Help required I tried to look around for information regarding returning a list using Hibnerate but couldn't find something that matches what I'm looking for and thus needs some advise. I have the following classes BPDataPK: public class BPDataPK implements Serializable { private String id; private int userProfile; private Date when; ..... } BPData: public class BPData implements Serializable { private BPDataPK dataPK; private Date sessionStart; ... } HibernateBPDataDAO : public class HibernateBPDataDAO extends HibernateDaoSupport implements IBPDataDAO{ .... public BPData[] getSessionBPData(Session session) throws Exception { /**I need to get a list of BPData that matches the following 1. BPDataPK.id== session.getID; 2. BPDataPK.userProfile == session.getUserProfile; **3. BPData.sessionStart == session.getSessionStart();** */ } } How do I return a list of BPData that matches two of the primary key and a non primary key?? A: You should not look around for some information. Instead, you should read the reference documentation. This documentation has a full chapter dedicated to queries using the HQL query language, and another one dedicated to criteria queries. Since you have a fixed set of criteria here, HQL is more suited to the task: String hql = "select b from BPData b where b.dataPK.id = :id" + " and b.dataPK.userProfile = :profile" + " and b.sessionStart = :sessionStart"; Query q = hibernateSession.createQuery(hql); q.setString("id", session.getID()); q.setInt("profile", session.getUserProfile()); q.setTimestamp("sessionStart", session.getSessionStart()); // or setDate, depending on the type of this field List<BPData> result = q.list(); A: if you are using JPA immplementaion of hibernate you do this @Entity @NamedQuery( name="findByMyQuery", queryString="SELECT bpdata FROM BPData bpdata WHERE bpdata.dataPK = :sessionId AND bpdata.userProfile = :userProfile AND bpdata.sessionStart = :sessionStart " ) public class BPData implements Serializable { private BPDataPK dataPK; private Date sessionStart; ... } public BPData[] getSessionBPData(Session session) throws Exception { Query queryFindByMyQuery = entityManager.createNamedQuery("findByMyQuery"); queryEmployeeByFirstName.setParameter("sessionId", session.getID()); queryEmployeeByFirstName.setParameter("userProfile", session.getUserProfile()); queryEmployeeByFirstName.setParameter("sessionStart", session.getSessionStart()); return queryEmployessByFirstName.getResultList().toArray(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting at javascript values where a range is the index in an array I'm probably going about this in entirely the wrong way, but pseudocode-wise, this is what I'd like to do: ranges = new Array([0 - 400] = 'dog', [401 - 1000] = 'cat', [1001 - 1233] = 'rat'); alert(ranges[243]); and magically get 'dog' pop up on my screen. Now, I'm well aware you can't do something that simple, but I have absolutely no idea how to do something like this (without looping through an array, performing a > and < on a value etc..) Any ideas? :) A: Well you could populate a simple array with all the duplicates: var i, ranges = []; for (i = 0; i <= 400; i++) ranges[i] = "dog"; for (i = 401; i <= 1000; i++) ranges[i] = "cat"; for (i = 1001; i <= 1233; i++) ranges[i] = "rat"; alert(ranges[243]); // "dog" A more sensible option might be to use some kind of data structure that actually holds the low and high values of each range: var ranges = [ { "low" : 0, "high" : 400, "animal" : "dog" }, { "low" : 401, "high" : 1000, "animal" : "cat" }, { "low" : 1001, "high" : 1233, "animal" : "rat" } ]; function getAnimal(index) { for (var i=0; i < ranges.length; i++) if (ranges[i].low <= index && ranges[i].high >= index) return ranges[i].animal; return "Out of range"; // or could leave it to return undefined } alert(getAnimal(243)); // "dog" alert(getAnimal(100000)); // "Out of range" Or you could combine the two approaches: pass the ranges data structure with the low and high values to a function that uses the information to populate another array as per the first approach. A: You could fully populate an array sp you can dp a direct index into the array at run-time. Once the original data structure is created, that will be fast at run-time, but not very storage efficient. I generally wouldn't recommend this, but to build the array: var ranges = [ {min: 0, max: 400, value: 'dog'}, {min: 401, max: 1000, value: 'cat'}, {min: 1001, max: 1233, value: 'rat'} ]; var lookupArray = []; for (var i = 0; i < ranges.length; i++) { // make sure array is big enough lookupArray.length = Math.max(lookupArray.length, ranges[i].max); for (var j = ranges[i].min, j <= ranges[i].max; j++) { lookupArray[j] = ranges[i].value; } } // function to find the value for a given index function findValue(index) { return(lookupArray[index]); } Or, in a more compact structure, you can use a data structure and function like this: var ranges = [ {min: 0, max: 400, value: 'dog'}, {min: 401, max: 1000, value: 'cat'}, {min: 1001, max: 1233, value: 'rat'} ]; function findValue(index) { var range; for (var i = 0; i < ranges.length; i++) { range = ranges[i]; if (index >= range.min && index <= range.max) { return(range.value); } } } alert(findValue(402)); // 'cat' You could also use a straight array with implicit positions in the array (code and data are a little more compact, but both are a bit less readable): var ranges = [ 0, 400, 'dog', 401, 1000, 'cat', 1001, 1233, 'rat' ]; function findValue(index) { for (var i = 0; i < ranges.length; i+=3) { if (index >= ranges[i] && index <= ranges[i+1]) { return(ranges[i+2]; } } } A: This one is very simple and straightforward - though it assumes that you don't want "holes" in your ranges. No error handling in this example, but essentially you just need to pass upper bounds, lower bounds are implicit. function test() { var array = MakeRangeArray([500,1000,2000], ['dog', 'cat', 'rat']); alert (array[243]); alert (array[500]); alert (array[501]); } function MakeRangeArray(upperBounds, values) { var rangeArray = new Array(upperBounds[upperBounds.length-1]); var idx = 0; for (var i=0; i < rangeArray.length; i++) { if (i > upperBounds[idx]) { idx++; } rangeArray[i] = values[idx]; } return rangeArray; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using 16-Bit textures WP7 textures are supported in the Reach-Profile that WP7 devices falls into. But XNA converts all my ressources upon adding them to a project to RGBA8, that's insane, the displays of WP7 devices are 16 Bit! Information: WP7 SDK 7.1 (XNA 4), Visual Studio 2010 Question part 1: How can I add a RGB565 texture to a XNA project and what is the correct way to load them inside a game? Question part 2: Is there a reasonable 16 Bit texture format (within Reach) that supports alpha with MORE than 1Bit? Question part 3: Is the normal rendertarget (I think that's what the screenbuffer is?) already 16 bit? A: Part 1: change surfaceformat like graphics.PreferredBackBufferFormat = SurfaceFormat.Color; (XNA) OR (in Silverlight/XNA Project) SharedGraphicsDeviceManager.Current.PreferredBackBufferFormat = SurfaceFormat.Color; //supports 32bit ARGB each color 8bit Part 2: PNG should work... it supports 8bit (256) and 16Bit alpha channel(65.536 possibilities)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: GUI/view doesn't notice about changes in the viewmodel. Who should notify? I'm rather new to Silverlight and have a question about the notifying-mechanism. My solution is an MVVM-application stacked like this: VIEW Contains a RadGridView bound to a collection in the viewmodel, the data is an entitycollection. The GridView's SelectedItem is bound to corresponding property in the viewmodel. VIEWMODEL Holds the properties below that the GridView is bound to and implements INotifyPropertyChanged. •SelectList - an entitycollection that inherits ObservableCollection. When SelectList is set, it runs a notify-call. •SelectedItem - an entity that also implements INotifyPropertyChanged for its own properties. When SelectedItem is set, it runs a notify-call. My question is, who should make the notify-call so that the GridView knows value has changed? Occasionally, a property in the entity is set programmatically directly in the viewmodel. As for now, nothing is happening in the GUI although the properties gets the new values correctly. Regards, Clas -- UPDATE WITH CODE ------------------------- VIEW <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" x:Class="X.Y.Z.MonthReport.MonthReportView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot"> <telerik:RadGridView x:Name="MonthReportGrid" Grid.Row="1" ItemsSource="{Binding SelectList}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" AutoGenerateColumns="False"> <telerik:RadGridView.Columns> <!-- The other columns have been cut out of this example --> <telerik:GridViewDataColumn DataMemberBinding="{Binding curDate, Mode=TwoWay, TargetNullValue=''}" DataFormatString="{} {0:d}" Header="Avläst datum" UniqueName="curDate" IsVisible="True" IsReadOnly="False"> <telerik:GridViewDataColumn.CellEditTemplate> <DataTemplate> <telerik:RadDateTimePicker SelectedValue="{Binding curDate, Mode=TwoWay, TargetNullValue=''}" InputMode="DatePicker" DateTimeWatermarkContent="ÅÅÅÅ-MM-DD" /> </DataTemplate> </telerik:GridViewDataColumn.CellEditTemplate> </telerik:GridViewDataColumn> <telerik:GridViewDataColumn DataMemberBinding="{Binding curValue, Mode=TwoWay, TargetNullValue=''}" Header="Avläst värde" UniqueName="curValue" IsVisible="True" IsReadOnly="False" /> </telerik:RadGridView> </Grid> </UserControl> VIEW .CS using System; using System.Collections.Generic; using System.Windows.Data; using System.Linq; using System.Linq.Expressions; using System.Windows.Controls; using Telerik.Windows.Controls; using Telerik.Windows.Controls.GridView; namespace X.Y.Z.MonthReport { public partial class MonthReportView : UserControl, IMonthReportView { /// <summary> /// ViewModel attached to the View /// </summary> public IMonthReportViewModel Model { get { return this.DataContext as IMonthReportViewModel; } set { this.DataContext = value; } } public MonthReportView() { InitializeComponent(); this.MonthReportGrid.CellEditEnded += new EventHandler<GridViewCellEditEndedEventArgs>(MonthReportGrid_OnCellEditEnded); } public void MonthReportGrid_OnCellEditEnded(object sender, GridViewCellEditEndedEventArgs e) { if (e.Cell.Column.UniqueName == "curValue") { // ... this.Model.SetAutomaticReadingDate(); } if (e.Cell.Column.UniqueName == "curDate") { this.Model.UpdateAutomaticReadingDate(); } } } } VIEWMODEL using System; using Microsoft.Practices.Prism.Events; using Microsoft.Practices.Prism.Modularity; using Microsoft.Practices.Unity; using Microsoft.Practices.Prism.Commands; namespace X.Y.Z.MonthReport { public class MonthReportViewModel : ViewModel<IMonthReportView>, IMonthReportViewModel { private readonly IEventAggregator eventAggregator; private readonly IMonthReportService dataService; private readonly IMonthReportController dataController; private DateTime? _newReadingDate; public DateTime? NewReadingDate { get { return _newReadingDate; } set { _newReadingDate = value; } } //Holds the selected entity private MonthReportEntity _selectedItem; public MonthReportEntity SelectedItem { get { return _selectedItem; } set { if (_selectedItem != value) { _selectedItem = value; //The INotifyPropertyChanged implementation inherited from ViewModel-base. Notify(() => this.SelectedItem); } } } //The entitycollection private MonthReportEntityCollection _selectList; public MonthReportEntityCollection SelectList { get { return _selectList; } set { if (_selectList != value) { _selectList = value; //The INotifyPropertyChanged implementation inherited from ViewModel-base. Notify(() => this.SelectList); } } } public MonthReportViewModel(IMonthReportView view, IEventAggregator eventAggregator, IMonthReportService dataService, IMonthReportController dataController) { this.InitializeCommands(); this.eventAggregator = eventAggregator; this.dataController = dataController; this.dataService = dataService; this.View = view; this.View.Model = this; dataService.onGetMonthReportComplete += new EventHandler<MonthReportEventArgs>(OnGetMonthReportComplete); dataService.onSaveMonthReportComplete += new EventHandler<MonthReportEventArgs>(OnSaveMonthReportComplete); InitializeData(); } public void InitializeCommands() { // ... } public void InitializeData() { GetMonthReport(); } //This function is not working as I want it to. //The gridview doesn't notice the new value. //If a user edits the grid row, he should not need to //add the date manually, Therefor I use this code snippet. public void SetAutomaticReadingDate() { if ((NewReadingDate.HasValue) && (!SelectedItem.curDate.HasValue)) { SelectedItem.curDate = NewReadingDate; //The INotifyPropertyChanged implementation inherited from ViewModel-base. Notify(() => this.SelectedItem.curDate); } } public void GetMonthReport() { dataService.GetMonthReport(); } public void SaveMonthReport() { dataService.SaveMonthReport(SelectList); } void OnGetMonthReportComplete(object sender, MonthReportEventArgs e) { // ... } void OnSaveMonthReportComplete(object sender, MonthReportEventArgs e) { // ... } #region ICleanable public override void Clean() { base.Clean(); } #endregion } } A: if you do your binding like this <telerik:GridViewDataColumn DataMemberBinding="{Binding curValue, Mode=TwoWay, TargetNullValue=''}" Header="Avläst värde" UniqueName="curValue" IsVisible="True" IsReadOnly="False" /> you just have to look at the binding to know where you have to call PropertyChanged and your binding said: the class whith the property "curValue" has to implement INotifyProperyChanged to get the View informed. public void SetAutomaticReadingDate() { if ((NewReadingDate.HasValue) && (!SelectedItem.curDate.HasValue)) { //this is enough if the class of SelectedItem implements INotifyPropertyChanged //and the curDate Poperty raise the event SelectedItem.curDate = NewReadingDate; } } btw BAD code style to name the Property curDate! it should be CurDate, Properties with camlCase hurts my eyes :) A: Your "MonthReportEntityCollection" must implement interface "INotifyCollectionChanged" to allow informing UI about collection changes (items add/remove). Your "MonthReportEntity" must implement interface "INotifyPropertyChanged" to allow informing UI about entitie's property changing. Other stuff looks correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SPDH protocol documentation I seem not to be able to find any documentation on SPDH protocol for POS terminals. It would be very helpful if anyone could point me to some.... Thank you EDIT: forgot to mention that i did look at this question, but the link to the documentation does not work... An analyzer for SPDH frame A: you can try with this link : http://www.aciworldwide.com/en/Products-and-services/Retail-payments/Payments-processing/BASE24-eps/SPDH-document.aspx you have to provide credentials and you will be in position to download documentation. Hope this helped you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Increasing height of a div while dynamically loading content (it's height is 100%) I have a div(InnerDiv) which contains a grid with paging enabled... After some user actions , data inside that grid will load and we will have a big grid! The problem is when grid's data loads , overflow the div's bottom portion(InnerDiv) and some of those data get's displayed out of the div. my css of body and html like below : html, body { margin: 0; /* get rid of default spacing on the edges */ padding: 0; /* get rid of default spacing on the edges */ border: 0; /* get rid of that 2px window border in Internet Explorer 6 */ height: 100%; /* fill the height of the browser */ border:3px solid red; } i need 100% height of body when page loads... OuterDiv inside body like below : div#OuterDiv { position:absolute; width: 100%; height: 100%; /*height: auto;*/ margin: 0px; padding: 0px; top: 0; bottom: 0; left: 0; right: 0; border:5px solid green; } InnerDiv Inside OuterDiv Is Like Below : div#InnerDiv { position: relative; width: 100px; height: 100%; margin: 0 auto; background: transparent url('../Images/Blue.png') repeat scroll left top; } Content Inside InnerDiv Like Below : #Content { position: relative; top: 10px; background: transparent url('../Images/Red.png') repeat scroll left top; width: 550px; height: 1080px; /*>>>>>>>>>>>>>>>>>>> plz see this line*/ top: 10px; right: 10px; padding: 7px; border: 10px ridge #ce004e; color: black; } that grid(Content) is inside InnerDiv... EDIT 1 the below example can show my situation : Here's an example at jsFiddle we can not remove position:absolute of OuterDiv , by doing that height:auto or height:100% on it does not work at page start -> outerDiv should be 100% because Of InnerDiv Background and remember InnerDiv height is not 1080px at start -> it is only 200px at page load and dynamically it will change to 1080px! i want to force yellow area (InnerDiv) to fill entire Purple Area... also InnerDiv Should Have 100% Height Because Of It's Background At Page Start... i know this problem is about 100% height / but how can i fix that ? EDIT 2 : AT LAST HERE IS MY WEB SITE : MY WEB SITE plz change the height of red area with firebug - so by changing it to 1080px body and OuterDiv And InnerDiv Will grow. but at page load i want body and OuterDiv And InnerDiv 100% height. how can i do that? thanks in advance A: You need less constraints on #OuterDiv. By specifying top, bottom, left, and right, you're locking the edges of #OuterDiv to the edges of body; and your body rule locks body to the same size as the viewport. Try changing your div#OuterDiv rule like this: div#OuterDiv { position:absolute; margin: 0px; padding: 0px; border: 5px solid green; } Here's an example at jsFiddle A: From what I could gather from your explanation and styles you basically want this: http://jsfiddle.net/sg3s/zXSXx/ If this is correct I will also explain what is happening to each div. Else please tell me what div is behaving not as you would like and why. By the way if possible use absolute paths (whole links) to images. Seeing how they need to fit together will help us all to find something that works for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best way to serve static resource (CSS, Images) with XDV in Plone I have tried several ways to serve my static resources from Plone with XDV: * *Putting the CSS and images in the Custom folder - files are 404 not found *Serving them from Apache and setting the Absolute URL Prefix in the XDV config - works, but any other relatively URL'd links (e.g. PDF files in my content) get prefixed as well and therefore are 404 not found *Setting browser:resourceDirectory - 404 not found *Setting cmf:registerDirectory - 404 not found Any suggestions? I've turned the log level to DEBUG but this doesn't give me any clues. A: You just need to put your css/js in the "static" directory and than use relative path in the index.html. Diazo/XDV will automagically remap relative paths. Or you can also register a resourceDirectory in the usual way and than link files like so "++resource++myresourcedirid/my.css" See an example here. A: I managed to use static content served by Apache using mod_rewrite and the following rules in Apache Virtual Host configuration. RewriteRule ^/css - [L] RewriteRule ^/img - [L] I have also used Giacomo method for specific Plone content style with the static directory in my package which is linked in the "index.html" as "++resource++mypackage.theme/plone.css"
{ "language": "en", "url": "https://stackoverflow.com/questions/7579300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pick an html 'a' tag using php, especially by POST or GET technique? Suppose I have a code like this in my page <a href="some_url" name="" value=""> Jokes</a> <a href="some_url" name="" value=""> Quotes</a> Now If I click on one of these links, say I clicked the 'Jokes' link, I want to pick up the 'Jokes' category through POST or GET method of php and compare it my categories in MYSQL database. If there is a match, then I want to display certain details. Please help me on how to proceed with this. A: You will need to construct the some_url to have parameters on it that relate to the Joke category. For example <a href="http://www.example.com/show.php?category=jokes">Jokes</a> <a href="http://www.example.com/show.php?category=quotes">Quotes</a> Then in your script (let's say show.php you would query the $_GET['category'] parameter and use that to compare against your database records. Make sure you sanitize all GET and POST parameters prior to them being used in a database query (or for any other purpose really). You can not trust that input from the user will be friendly. Refer to this link for information about escaping dangerous characters, or better yet, use PDO with prepared statements I'm not sure if name and value are valid attributes of an <a> tag. A: <?php $category = $_GET['category']; ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Running migration file before ./manage.py migrate component I have update our project from svn. There was a migration file in update. I have run this migration file before ./manage.py migrate component . Now I have this error: raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. How can I solve this? I have deleted the migration file and updated again but nothing fixed. Thanks in advance A: https://docs.djangoproject.com/en/dev/topics/settings/ You do not have a system Environment Variable DJANGO_SETTINGS_MODULE, see the site above on how to set the environment variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: image positions on jquery Hello Friends I have a website. In this I want the logo image will be like same on home page but in other pages it will be go towards the up and only the name will be seen not the whole logo image. So how to do that in jQuery? Any advice will be highly appreciable. A: You don't need to use javascript, just change it from position:absolute to position:fixed. (If IE <7 support is needed, there's workarounds for bugs in position:fixed). UPDATE (See Comments) Based on my understanding of what you're trying to accomplish from the comment string below, try this: $(document).ready(function() { $('ul.menu li a').each(function() { $(this).click(function() { $('#logo').css('top', $($(this).attr('href')).offset().top); setTimeout("$('#logo').fadeIn('slow');", 600); }); if ($(this).hasClass('selected')) $(this).click(); }); }); A: I got it. It will be like this <script type="text/javascript"> if(jQuery(window).scrollTop() > 0) { jQuery('h1#logo').css({ top: '-85px' }); } jQuery(window).scroll(function() { if(jQuery(this).scrollTop() > 0) { jQuery('h1#logo').clearQueue(); jQuery('h1#logo').animate({ top: '-85px' }); } else if(jQuery('h1#logo').position().top != 0) { jQuery('h1#logo').clearQueue(); jQuery('h1#logo').animate({ top: '0px' }); } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check a form is available or not by using its id - jquery Is it possible to check weather a form is available or not using jquery. For example : 1. I am having a form ID called form1 2. I need to check in the page weather the id contains a form or not. 3. How can i achieve it using jquery. Thanks in advance.... A: You can use the length property like this: if ($('#form1').length > 0){ // form exists } else { // form does NOT exist } Docs: * *http://api.jquery.com/length/ A: look after a form + id if($("form#form1").length > 0) { alert('a form with and id "idname" was found!'); } or: var form = $("#form1"); if(form.length > 0 && form[0].tagName === "FORM") { alert('a form with and id "idnam" was found!'); } if you want to really check if #form1 is a form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: System Design Document template for firmware development on Atmel UC3 platfrom Do any body have or know any site where I can get a template for System Design Document for my firmware develop project for Atmel UC3 platform?
{ "language": "en", "url": "https://stackoverflow.com/questions/7579312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Show All Local Variables in Eclipse I think I already know the answer to this question is "No", but I ask anyway just in case I missed something in the dox. I adore the Eclipse "Quick Outline" feature where I can easily see all the member variables and methods for the class my cursor is currently located in by typing Control + O (or Navigate -> Quick Outline). What would be equally useful is a way to see all local variables available at the point my cursor is. Does such a feature exist? Thanks! A: You can probably use content assist for this. Just press Ctrl+Space on an empty line, the resulting content assist popup should offer suggestions on what can be inserted at that point, local variables should be on top followed by fields and then member functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Object null-ness check in Java Which one is recommended and to be used to check the Object null-ness? null != Object or Object != null and other way null == Object or Object == null ...and is there any difference between them? A: (In)equality is commutative, so there is no difference. Historically the former stems from C to avoid accidentally assigning a value in a conditional statement, however that mostly applies to ==, not !=. Also Java requires the condition in a conditional statement to have a boolean value, so the only place where it could go wrong nowadays would be if (a == false) ... if you accidentally omit one of the =. A rare case, I guess (though probably not so much, given what students frequently write in their first two terms). Joonas also points out another (more obscure) case in the comments. A: It's always more readable to use Object != null because that reads as "the object is not null", which is literally what the condition is. The only case where you want to swap the two is to avoid accidentally using Object = null which will return true even though it is not the desired behavior, when you wanted to say Object == null but in reality not only do modern tools catch these kinds of mistakes, but wide use of the reverse can actually be an impediment to anyone who has to read the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery - AJAX request using both native XHR and flXHR (Flash) fallback - how to minimize code duplication? I need to retrieve data via cross-domain XMLHttpRequest. To make this work in (almost) all browsers, I use native XHR first and, if that fails, flXHR. The (working) code I currently have for this is as follows: jQuery.support.cors = true; // must set this for IE to work $.ajax({ url: 'http://site.com/dataToGet', transport : 'xhr', success: function(data) { console.log('Got data via XHR'); doStuff(data); }, error: function(xhr, textStatus, error) { console.log('Error in xhr:', error.message); console.log('Trying flXHR...'); $.ajax({ url: 'http://site.com/dataToGet', transport : 'flXHRproxy', success: function (data) { console.log('Got data via flXHR'); doStuff(data); }, error: function (xhr, textStatus, error) { console.log('Error in flXHR:', error.message); console.log('Both methods failed, data not retrieved.'); } }); } }); This feels like a lot of code duplication to me, especially in the success handlers. Is there a more efficient way to do this? I'd really prefer to make one $.ajax call that would try both transports in turn, instead of having to use the error handler to make the call a second time. It's not too bad in this example, but rapidly gets more complicated if the success handler is longer or if the success handler has to itself issue another $.ajax call. A: I've created a jquery-specific and slimmed-down fork of flxhr that simplifies your code sample above. You can see an example of usage in the "Usage" section in the README. https://github.com/b9chris/flxhr-jquery-packed In particular, you don't want to waste time waiting for a standard CORS request to fail. It's easy to determine whether flxhr is necessary by testing $.support.cors upfront (no need to override it). Then just use flxhr explicitly where necessary. A: Why don't you just wrap this in a function by itself? That's after all, how you end up reusing code. You can even pass functions as arguments to make sure that you don't have to repeat this code more than once. To me this is pretty straight forward but maybe I've misunderstood. function xhr(success) { $.ajax({ success: success, error: function() { $.ajax({ success: success }) } }); } Then just pass the success handler once xhr(function(data){/*magic*/}); Or if you wanna basically avoid redundant configuration of the ajax call use the first object as a template, like this: function xhr(success) { var ajaxParams = { success: success }; ajaxParams.error = function() { $.ajax($.extend(ajaxParams, { transport: 'xhr' })); } $.ajax(ajaxParams); } I simplified the whole thing a bit, but I hope you get the point. Edit Reading that last bit, maybe this will give you some ideas... it's a variation of that last snippet. function xhr(success) { var ajaxParams = { success: success }; ajaxParams.error = function() { var newParams = $.extend(ajaxParams, { transport: 'xhr' }); newParams.success = function() { // do something // arguments is a special array, even if no parameters were // defined in any arguments where passed they will be found // in the order they were passed in the arguments array // this makes it possible to forward the call to another // function success.apply(this, arguments); } $.ajax(newParams); } $.ajax(ajaxParams); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ComboBox text longer than the combo visible at the end instead of start My problem is ComboBox, with the text of the first item longer than the combo - I don't see the text from the start, I see the end of the text. I wanna see text from the start. I've tried 'SelectionStart' property set to 0, but it has nothing to do with my problem - it only sets where from text is selected. Longer explanation: I have several combo boxes on my form, which I have to adjust theirs drop down list width to be suitable for the longest item. So, when I open drop down list, it's width is long as the longest item is. But, there is a problem - I have a special function, which goes through list of combo boxes and made theirs drop down width long as the longest item: Public Sub MakeDropDownListWider() Dim conKontrola As ComboBox conKontrola = Me 'make the dropdown wider so the entire selection can be seen If conKontrola.Items.Count > 0 Then Dim pixlength As Graphics = Graphics.FromHwnd(New IntPtr) Dim lengthHolding As Int32 Dim stringWidth As Int32 Dim g As Graphics = conKontrola.CreateGraphics For Each myItem As Object In conKontrola.Items If myItem.GetType().ToString() = "System.Data.DataRowView" Then lengthHolding = pixlength.MeasureString(myItem.Row.Item(conKontrola.DisplayMember).ToString, conKontrola.Font).ToSize.Width Else lengthHolding = g.MeasureString(myItem, conKontrola.Font).Width + 15 End If If lengthHolding > stringWidth Then stringWidth = lengthHolding End If Next Dim allowedWidth As Int32 = 0 If Me.Parent.Width > 0 Then allowedWidth = Me.Parent.Width - conKontrola.Location.X - 10 End If If allowedWidth > 0 And (stringWidth + 15 > allowedWidth) Then conKontrola.DropDownWidth = allowedWidth Else conKontrola.DropDownWidth = stringWidth + 15 'add 15 for the scrollbar End If End If End Sub When I run this function on every combo box of my form, all of my combo boxes are selected after the form is shown. (I call this method on forms shown event). I didn't wanted combo boxes to be selected, so I used SelectionStart property of combo box, like this: myComboBox1.SelectionStart = myComboBox1.Text.Length That way, none of the combo boxes appears to be selected. But, another problem has arised: I see only end of the selection on my combo boxes. If the first item is short, then everything is cool. But, if the first item is longer than the combo box, I see only the end of the item - but, I must the item from the start. So, f.e.: my first item is: "C# is a very good programming language designed by Anders Hejlsberg" and my combo is shorter than the text, I will see only "designed by Anders Hejlsberg." - I wanna see "C# is a very good programming". I can't move the 'SelectionStart' property to 0, because all of my combo boxes gets selected again. And even if I do that, I still see end of the first item, not the start - the only difference is that item is selected. Any idea how to see the text of the first item from the start? A: check that the "right to left" property is set to false. that could cause this problem. hope this helps. A: You can try this: Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged Me.BeginInvoke(New Action(Sub() ComboBox1.Select(0, 0))) End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/7579336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect that file is located on SD card? Is there any durable way to detect that is file located somewhere on external (detachable/dismountable) storage? For sure there's a way to parse file path and extract file:///sdcard string, but as we know on some devices this path can be different, e.g. file:///mount/sdcard or file:///sdcard, not saying that some modern devices support USB host mode, so file easily can be placed on usb stick attached to device. Any ideas? A: Get a location of external storage via Environment.getExternalStorageDirectory() and then compare it to the path of your file. Make sure you have the absolute path to your file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Curve a bitmap in android I am developing a game and I want to give a smoke effect at the tail of the objects moving freely on the screen. I just created a bitmap and attached it at the end of object but the problem is that this doesn't look good because when the objects turns towards a new angle the effect doesn't curve it self. All I want is to know that how can I do this? Is there any possibility to give curve to the bitmap or another solution? I want to give a smoke effect at the tail of a bike. I hope someone will provide me a solution. Thanks A: Yes. Finally I got the answer myself so sharing it with you. What I wanted was to give a smoke effect at the tail of a moving object such that when the object take turns in screen the tail should do the same. What I do us that I take four bitmap images which gives a smoke effect when combined. I recorded the points X and Y which the boat has passed from and then drew the bitmap on these points which solved my problem. I hope it will help someone else someday so I shared it. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7579341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting the last answer id for the questions In M.C.Q test, when user come back to the same question again how can I track the last answer given for the question?, following is the table structure Method: 1 temptblUserAnswer id uid qid ansid 1 1 1 5 2 1 2 6 Should I update the table value for that particular Question? OR Should I use following table structure? Method: 2 temptblUserAnswer id uid qid ansid timestamp 1 1 1 5 2011-09-28 11:54:32 2 1 2 12 2011-09-28 11:58:40 3 1 1 7 2011-09-28 12:02:50 Here with the help of timestamp I can find the the last answer for any particular question. Now the question is, which method to follow, and which will be performance oriented? Or any better suggestion for the same? Should I go with Method:1 and apply the index on uid, ansid column? A: If your Id is autoincrementing, you can get last answer based on Id: SELECT TOP 1 AnsID WHERE Uid=@UserId AND Qid=@QuestionID ORDER BY Id DESC About performance:you should put non-clustered index on Uid AND Qid AND ID and Include AnsID You can avoid of using timestamp column in this table. A: 1: For the first method: To get the last answer id for a given question id, you can use this script: --index creation CREATE UNIQUE INDEX IUN_temptblUserAnswer_qid_id ON temptblUserAnswer(uid,qid,id DESC); --query DECLARE @QuestionID INT, @UserID INT; SELECT @QuestionID=123, @UserID = 456; SELECT TOP 1 ansid FROM temptblUserAnswer WHERE qid = @QuestionID AND uid = @UserID ORDER BY id DESC; In this case, I have assumed that the last answer is given by the last temptblUserAnswer.id. Also I have assumed that temptblUserAnswer.id is IDENTITY(1,1). Problem: if somebody runs an ad-hoc insert on temptblUserAnswer table it's possible to get wrong results. 2: For the second method: You should use a date/time data type with higher precision (for SQL version<=SQL2005: DATETIME is the only option, for SQL version>SQL2005 you can use DATETIME2(7) data type and SYSDATETIME() function instead of GETDATE()/CURRENT_TIMESTAMP functions). Even so, you could get two or more answers with the same timestamp. In this case, you could use 'temptblUserAnswer.id' column as the second criteria. --index creation CREATE UNIQUE INDEX IUN_temptblUserAnswer_qid_id ON temptblUserAnswer(uid,qid,timestamp DESC, id DESC); --query DECLARE @QuestionID INT, @UserID INT; SELECT @QuestionID=123, @UserID = 456; SELECT TOP 1 ansid FROM temptblUserAnswer WHERE qid = @QuestionID AND uid = @UserID ORDER BY timestamp DESC, id DESC;
{ "language": "en", "url": "https://stackoverflow.com/questions/7579344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: kernel module for htc flyer I have to compile a kernel module for htc flyer,I got the kernel source for htc flyer from http://htcdev.com/devcenter/downloads I have compiled the same module for htc hero in the past(by pulling out the /proc/config.gz file from the device). I didn't have a htc flyer with me . can someone tell me how to compile a kernel module for htc flyer, if the process is similar to htc hero can someone please post the config.gz file for htc flyer. If not can some one tell me how to build a kernel module for htc flyer or point to resources. I googled and can not find anything useful. Thanks in advance. A: The config files are available with the kernel source code in the folder /arch/arm/config . In this case it's flyer_defconfig
{ "language": "en", "url": "https://stackoverflow.com/questions/7579345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uploadify in Zend Framework I use uplodify to upload files in zend. <link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/uploadify/jquery-1.5.2.min.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.min.js"></script> <script type="text/javascript" src="/uploadify/swfobject.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.js"></script> <script type="text/javascript"> $(document).ready(function () { $('#file_upload').uploadify({ 'uploader': '/uploadify/uploadify.swf', 'script': '/upload/upload', 'cancelImg': '/uploadify/cancel.png', 'folder': '/uploadify/uploads', 'auto': true }); }); </script> <input id="file_upload" name="file_upload" type="file" /> This code is in view part index.phtml. But when i run my web application i see in my web devloper tool it shows in console NetworkError: 404 Not Found - http://localhost/upload/uploadify.swf?preventswfcaching=1317192234400 Help me to solv this problem.... A: "Some of the option names have changed in v3 to be more intuitive. The 'uploader' option should now point to the php script. The 'swf' option will point to the flash file. " http://www.uploadify.com/forums/discussion/7296/uploader-being-rewritten-in-v3.0.0/p1 part of code: $("#gallery").uploadify({ id : jQuery(this).attr('id'), langFile : 'http://www.static-xxx.nu/uploader/uploadifyLang_en.js', swf : 'http://www.static-xxx.nu/uploader/uploadify.swf', uploader : '/uploadify/galleri.php', A: The path specified is wrong somewhere. In jquery function, it is given as; 'uploader': '/uploadify/uploadify.swf', Check from where request is going for "upload/uploadify.swf" to get a 404 error. also, if you are using a .htaccess file, make sure the request for these files are not denied.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple attachments per model with paperclip I'm trying to integrate paperclip into a simple comment thread so users can attach files to their comments. I understand that following the instructions that come with paperclip will end up with me being able to attach one file to one comment. I would like to be able to attach multiple files. Do I need to create a separate 'Attachments' model with a has_many relationship? A: Creating a separate attachment model linked by a has_many relationship is the best way to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ContextMenuOpening event not trigered I have a button with a context menu, but I just can get the ContextMenuOpening event to triger. <Button Name="a_button" ContextMenu="{StaticResource MyContextMenu}" ContextMenuOpening="MyContextMenu_Opening" > </Button> private void MyContextMenu_Opening(object sender, ContextMenuEventArgs e) { // doesnt get here. } Any ideas how to make this work ? Thanks. A: ContextMenuOpening event must be handled on an ancestor of the ContextMenu not on the ContextMenu itself. If you try handling it on the ContextMenu the event only fires when you right click once ContextMenu is already open. A: I've just checked your code and it works perfectly. Here is my full xaml: <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Window.Resources> <ContextMenu x:Key="MyContextMenu"> <MenuItem Header="Send" /> </ContextMenu> </Window.Resources> <Grid> <Button Name="a_button" ContextMenu="{StaticResource MyContextMenu}" ContextMenuOpening="MyContextMenu_Opening" > </Button> </Grid> </Window> And *.cs: private void MyContextMenu_Opening(object sender, ContextMenuEventArgs e) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to resolve ANR in android Wen i install my apk file on android device and after installation wen i hit the open button my application does not start and shows force close. The logcat output of my application is shown below : 09-28 12:14:57.651: INFO/ActivityManager(124): Starting activity: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.biz.mlm/.SplashScreen } 09-28 12:14:57.660: WARN/ActivityManager(124): Permission Denial: starting Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.biz.mlm/.SplashScreen } from ProcessRecord{44ffa660 1130:com.android.packageinstaller/10026} (pid=1130, uid=10026) requires android.permission.WRITE_CONTACTS 09-28 12:14:57.672: DEBUG/AndroidRuntime(1130): Shutting down VM 09-28 12:14:57.672: WARN/dalvikvm(1130): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): FATAL EXCEPTION: main 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): java.lang.SecurityException: Permission Denial: starting Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.biz.mlm/.SplashScreen } from ProcessRecord{44ffa660 1130:com.android.packageinstaller/10026} (pid=1130, uid=10026) requires android.permission.WRITE_CONTACTS 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.os.Parcel.readException(Parcel.java:1247) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.os.Parcel.readException(Parcel.java:1235) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1298) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1373) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.app.Activity.startActivityForResult(Activity.java:2817) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.app.Activity.startActivity(Activity.java:2923) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at com.android.packageinstaller.InstallAppProgress.onClick(InstallAppProgress.java:224) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.view.View.performClick(View.java:2408) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.view.View$PerformClick.run(View.java:8816) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.os.Handler.handleCallback(Handler.java:587) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.os.Handler.dispatchMessage(Handler.java:92) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.os.Looper.loop(Looper.java:123) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at java.lang.reflect.Method.invokeNative(Native Method) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at java.lang.reflect.Method.invoke(Method.java:521) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-28 12:14:57.700: ERROR/AndroidRuntime(1130): at dalvik.system.NativeStart.main(Native Method) 09-28 12:14:57.740: WARN/ActivityManager(124): Force finishing activity com.android.packageinstaller/.InstallAppProgress Please help me by guiding me about what I have done wrong EDIT : The permissions in my manifest are : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <!-- <uses-permission android:name="android.permission.INSTALL_PACKAGES"/> --> <application android:icon="@drawable/biz_logo" android:permission="android.permission.WRITE_CONTACTS"> After this also it is behaving same A: Looks like you need to add the permission android.permission.WRITE_CONTACTS to your manifest file. Barry A: The logcat output has everything you need to know :-) Your app basically is writing contacts but it does not have permissions to do so (in Android, applications need to be given permissions explicitly for various operations). Edit the file AndroidManifest.xml to include the following line/XML element: <uses-permission android:name="android.permission.WRITE_CONTACTS" /> within the <manifest> XML element, and then rebuild, reinstall and rerun. For more information, take a look here: http://developer.android.com/guide/topics/manifest/uses-permission-element.html A: yes i rebuilt it.my mistake was i have written in manifest <uses-permission android:name="android.permission.WRITE_CONTACTS" /> and also inside the application tag like this <application android:icon="@drawable/logo" android:permission="android.permission.WRITE_CONTACTS"> so i was getting force close. This permission should be written only once in the manifest file
{ "language": "en", "url": "https://stackoverflow.com/questions/7579359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use ctags for autocomplete in vim I try to develop android project in vim.But find it a bit of boring to look up in ctags for one method.Is there a way to show up a auto-complete list in vim using ctags? thanks it's my ctags's version below: Exuberant Ctags 5.8, Copyright (C) 1996-2009 Darren Hiebert Compiled: Mar 21 2011, 10:34:51 Addresses: <dhiebert@users.sourceforge.net>, http://ctags.sourceforge.net Optional compiled features: +wildcards, +regex and vim's version: Exuberant Ctags 5.8, Copyright (C) 1996-2009 Darren Hiebert Compiled: Mar 21 2011, 10:34:51 Addresses: <dhiebert@users.sourceforge.net>, http://ctags.sourceforge.net Optional compiled features: +wildcards, +regex ccheng@ccheng-desktop:~$ vim --version VIM - Vi IMproved 7.3 (2010 Aug 15, compiled Mar 24 2011 07:10:07) Included patches: 1-35 Modified by pkg-vim-maintainers@lists.alioth.debian.org Compiled by buildd@ Huge version without GUI. Features included (+) or not (-): +arabic +autocmd -balloon_eval -browse ++builtin_terms +byte_offset +cindent -clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments +conceal +cryptv +cscope +cursorbind +cursorshape +dialog_con +diff +digraphs -dnd -ebcdic +emacs_tags +eval +ex_extra +extra_search +farsi +file_in_path +find_in_path +float +folding -footer +fork() +gettext -hangul_input +iconv +insert_expand +jumplist +keymap +langmap +libcall +linebreak +lispindent +listcmds +localmap -lua +menu +mksession +modify_fname +mouse -mouseshape +mouse_dec +mouse_gpm -mouse_jsbterm +mouse_netterm -mouse_sysmouse +mouse_xterm +multi_byte +multi_lang -mzscheme +netbeans_intg -osfiletype +path_extra -perl +persistent_undo +postscript +printer +profile +python/dyn +python3/dyn +quickfix +reltime +rightleft -ruby +scrollbind +signs +smartindent -sniff +startuptime +statusline -sun_workshop +syntax +tag_binary +tag_old_static -tag_any_white -tcl +terminfo +termresponse +textobjects +title -toolbar +user_commands +vertsplit +virtualedit +visual +visualextra +viminfo +vreplace +wildignore +wildmenu +windows +writebackup -X11 -xfontset -xim -xsmp -xterm_clipboard -xterm_save system vimrc file: "$VIM/vimrc" user vimrc file: "$HOME/.vimrc" user exrc file: "$HOME/.exrc" fall-back for $VIM: "/usr/share/vim" Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -Wall -g -O2 -D_FORTIFY_SOURCE=1 Linking: gcc -Wl,--as-needed -o vim -lm -lncurses -lselinux -lacl -lgpm my .vimrc file: 1 set autochdir 2 filetype plugin indent on 3 set nu 4 set tags=./tags 5 set path=.,..,../.. 6 set tabstop=4 7 set hlsearch 8 set cscopequickfix=s-,c-,d-,i-,t-,e- 9 set tags=$HOME/gingerbread/frameworks/tags,$HOME/gingerbread/packages/provid ers/ContactsProvider/tags 10 11 :" Only do this part when compiled with support for autocommands. 12 :if has("autocmd") 13 : autocmd Filetype java setlocal omnifunc=javacomplete#Complete 14 :endif 15 setlocal completefunc=javacomplete#CompleteParamsInfo A: I want to clarify: it sounds like you have ctags set up already and would like to know how to use it to autocomplete method names, is that right? As romainl mentions, <C-n> and <C-p> are what you're looking for then. They're complete using next match and complete using previous match, respectively. They are not the only types of autocompletion vim has though, see :he ins-completion for the rest (includes spelling and file names). One specific completion I'd like to point out is <C-x><C-o> (omni-completion) which you might find useful. In case you weren't only concerned with autocompletion: in this similar SO question, the accepted answer by richq has some good info on ctags in general. A: I haven't tried autocomplete in VIM but a quick search found http://vim.wikia.com/wiki/Any_word_completion: The 'complete' option controls where the keywords are searched (include files, tag files, buffers, and more). A: You can complete everything with [TAB], with this in vimrc. We use [char][char][dot][tab] to trigger tag completion, Also see https://stackoverflow.com/a/46645434/476175 on how to integrate spelling, thesaurus, dictionary. :inoremap <Tab> <C-R>=MoshTabOrComplete()<CR> function! MoshTabOrComplete() if col('.') > 3 \ && strpart( getline('.'), col('.')-3, 4 ) =~ '^[a-zA-Z]\+[.]' " prev 2 char are alpha+dot? " Tag-completion eg. print.<tab> will complete to printf or println return "\<BS>\<C-x>\<C-]>" endif " if exists("g:MoshThesaurusOmniCompleter") && col('.') > 3 " \ && strpart( getline('.'), col('.')-3, 4 ) =~ '^[a-zA-Z]\+[!%?~-]' " prev 2 char are alpha+punct? " Calls MoshThesaurusOmniCompleter " Test: qieut!<tab> will spell correct to quiet, more tests in ./thesaurus-omni.vim " return "\<C-x>\<C-o>" " endif if col('.') > 1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w' " prev char is alphabet? " Usual omni-completion return "\<C-N>" endif " Insert regular TAB return "\<Tab>" endfunction
{ "language": "en", "url": "https://stackoverflow.com/questions/7579361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: asp.net MVC 3 folders purpose I am working on an asp.net MVC 3 project as a team member. This project has some folders like repositories, infrastructure, Datalayer, services, providers and ViewModels. When I create an asp.net MVC 3 application, It has only 5 folders views, models, controllers, contents and scripts. Why these additional folders are created. I read in an article (http://msdn.microsoft.com/en-us/library/aa973811.aspx) that service is an object that performs a distinct part of the application functionality and Repositories are strongly typed classes that provide create/read/update/delete for objects. what is difference between service and repository. If I name these folders to something else will it make any difference. What type of classes should go in below folder classes: repositories infrastructure Datalayer services providers ViewModels I read somewhere that repository is a pattern what does it mean? Also are services also a pattern? Please suggest Regards, Asif Hameed A: It is most likely something added by the software architect in your project. I would guess that Datalayer and repositories are there to help out with implementing a layered architecture. Perhaps something like: * *Datalayer (NHibernate or some other ORM or whatever) *Repositories (Classes used for CRUD stuff) *Application (Your MVC application, where controllers use repositories to fetch data, then put this data in the models, then sending the models to the views where the data is displayed) Something like this, I guess, would be a typical way to use MVC3. Hope it helped :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing error after call to RDF::RDFa::Reader I've posted a question relating to this before but it was unclear. I've simplified the code so I can copy it here and have it be as straightforward as possible. I'm still not sure what the best way to debug this may be but here it goes: My 'new' action (could be any really) for a resource (again, can be any): def new RDF::RDFa::Reader.open("http://www.tripadvisor.com/Hotel_Review-g186525-d280839-Reviews-Gerald_s_Place-Edinburgh_Scotland.html") do |r| r.each_statement do |statement| Rails.logger.debug(statement) end end respond_to do |format| format.html { }# new.html.haml format.json { render json: @base_item } format.js end end The page renders fine and the RDF code is run successfully, however, when I refresh the page or try to access anything else, I get the following (substitude 'base_item' with whatever resource I'm trying to access, they all fail with this error): ActionController::RoutingError (private method `redefine_method' called for #<Class:0x000001058527c0>): app/models/base_item.rb:3:in `<class:BaseItem>' app/models/base_item.rb:2:in `<top (required)>' app/controllers/base_items_controller.rb:3:in `<top (required)>' I'm wondering if this is something specific to the rdf gem (which uses nokogiri) or if it is a general routing issue but haven't found a way to test that. Any help appreciated. EDIT: It seems it has to do with the r.each_statement line as if I take that out, things keep working.. UPDATE: I haven't been able to reproduce this outside of Rails but I've narrowed it down to an issue with ActiveRecord. I've set up a sample app at https://github.com/slamorsi/rdfTest There are two models, Test and TestChild. The error is reproducible if Test and TestChild are related - right now Test has a has_many relationship with TestChild. The root of the app goes to test#index which has sample RDF/RDFa code. If you load the page once then refresh, you'll see the 'redefine method called...' error. If there's no relationship between the models or if no RDF/RDFa statements.each code is executed, everything works fine. I don't know what could possibly cause this. A: The RDF gem doesn't use Nokogiri, but the RDF::RDFa gem does. You could try to run this with a Turtle input file, for example, and see if you get the same results. Queryable#each_statement does use an iterator, but I don't see how this could infect the context your running in. You might look to see if any new methods have been defined on @base_item. It may be that some of the RDF classes are defining methods that interfere with Rails, which would be a bug. If you can make a short example, I can look at it further. Submit an issue to http://github.com/gkellogg/rdf/issues (if it isn't RDF::RDFa specific), or rdf-rdfa/issues otherwise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I get implicit declaration of function strncmp I get "implicit declaration of function 'strncmp' isinvalid in C99" when use strncmp (xcode 4/ gcc version 4.2.1) How to avoid this ? A: Did you forget to #include <string.h>? A: From the strncmp(3) man page: #include <string.h>
{ "language": "en", "url": "https://stackoverflow.com/questions/7579370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: inheritance and "invalid covariant return type" error on operator overloading I have the following class representing numerical arrays class Array { protected : double *data; // this will hold the data of the array int n; // number of elements in the array public : virtual Array operator+ ( double value ) const { // return a new array with the argument added to each element } // other declarations follow here... }; and another class inheriting from the previous one and adding a boolean mask for each element class MaskedArray : public Array { private : bool *mask; // this holds the boolean mask of the array public : MaskedArray operator+ ( double value ) const { // return a new MaskedArray with the argument added to each element } // other declarations follow here... } When I try to compile I get the error "invalid covariant return type", which is normal since the two overloaded operators in both classes have the same signature. I was able to circumvent this problem by passing the argument of the overloaded operator of the inherited class by reference rather than by value, as this changes the signature of the function, while keeping the same interface for both classes. But I feel this is not very clean, and what if I wanted to inherit from MaskedArray ? I would face the same problem. I want to be able to write stuff like this in my client code Array array; // populate array here Array array2 = array + 1.0; MaskedArray maskedArray; // populate maskedArray here MaskedArray maskedArray2 = maskedArray + 1.0 Is there another more elegant way than my 'hack' to achieve this ? A: Covariant means that the return type of an overridden virtual function is inherited from the return type of the base class function. But: Although covariance is generally supported by C++, the standard allows covariance only when returning pointers or references. operator+ returns by value, that's why you get the compiler error. That is not specific to operators but applies to every function. Removing the virtual keyword will eleminate the compiler error. But if you do so, keep in mind that applying operator+ to an Array reference or pointer, which actually references a MaskedArray returns an Array (and thus does not contain the mask member. If you cast it to a MaskedArray the original mask is lost). A: A workaround for your issue could be using containment instead of inheritance: class MaskedArray { private : Array array; bool *mask; // this holds the boolean mask of the array public : MaskedArray operator+ ( double value ) const { // return a new MaskedArray with the argument added to each element } // delegate public functions } Ofcourse, now MaskedArray can't use the protected members of Array (in a lot of cases, this is a good thing) and the public interface must be delegated. A: First, your reported error about covariant result is not consistent with the presented code. It only appears for virtual member functions, and in the presented code, as I write this, there is no such. Do not in the future waste our time again by asking about what's wrong with your real code, and presenting some made up fantasy code. Anyway, cure: in your real code, just remove the word virtual. Also, word of advice: use a std::vector to hold the data and take care of allocation, copying and deallocation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Translating php code to jsp $postdata = http_build_query(array('name' => $album_name,'message' => $album_description)); $opts = array('http' =>array( 'method'=> 'POST', 'header'=>'Content-type: application/x-www-form-urlencoded', 'content' => $postdata)); $context = stream_context_create($opts); Could anyone tell me similar function on jsp http_build_query() is php function, similar function in Jsp is what? stream_context_create() also php function A: With scriptlets you can call java libraries in jsps. For http_build_query, the analog in Java is the URLEncoder class. Here's a simple tutorial on how to use it. For stream_context_create, I guess you want to send an http request to a server, the analog in Java is Java.net. See this post for mini a torial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Millennial Media PHP Request not returning anything So I can't figure out what it is about my code that isn't working. Basically, I'm trying to get a Flash actionscript method of getting Millennial Media ads into an app I've been making. But I'm a little stuck because I can't seem to get a response from Millennial Media when I send off the PHP from my actionscript. Here's the PHP: <?php /*--------------------------------------------------------------*/ /* Millennial Media PHP Ad Coding, v.7.4.20 */ /* Copyright Millennial Media, Inc. 2006 */ /* */ /* The following code requires PHP >= 4.3.0 and */ /* allow_url_fopen 1 set in php.ini file. */ /* */ /* NOTE: */ /* It is recommended that you lower the default_socket_timeout */ /* value in the php.ini file to 5 seconds. */ /* This will prevent network connectivity from affecting */ /* page loading. */ /*--------------------------------------------------------------*/ /*------- Publisher Specific Section -------*/ $mm_placementid = XXXXX; $mm_adserver = "ads.mp.mydas.mobi"; /* The default response will be echo'd on the page */ /* if no Ad is returned, so any valid WML/XHTML string */ /* is acceptable. */ $mm_default_response = ""; /*------------------------------------------*/ /*----------- BEGIN AD INITIALIZATION ----------*/ /*----- PLEASE DO NOT EDIT BELOW THIS LINE -----*/ $mm_id = "NONE"; $mm_ua = "NONE"; @$mm_ip = $_SERVER['REMOTE_ADDR']; if (isset($_SERVER['HTTP_USER_AGENT'] )){ $mm_ua = $_SERVER['HTTP_USER_AGENT']; } if (isset($_SERVER['HTTP_X_UP_SUBNO'])) { $mm_id = $_SERVER['HTTP_X_UP_SUBNO']; } elseif (isset($_SERVER['HTTP_XID'])) { $mm_id = $_SERVER['HTTP_XID']; } elseif (isset($_SERVER['HTTP_CLIENTID'])) { $mm_id = $_SERVER['HTTP_CLIENTID']; } else { $mm_id = $_SERVER['REMOTE_ADDR']; } $mm_url = "http://$mm_adserver/getAd.php5?apid=$mm_placementid&auid=" . urlencode($mm_id) . "&ua=" . urlencode($mm_ua) . "&uip=" . urlencode($mm_id); echo $mm_url; /*------------ END AD INITIALIZATION -----------*/ ?> This basically sends back a big long URL that I then use to display the ad inside my Actionscript file like so: package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.Event; import flash.events.LocationChangeEvent; import flash.events.UncaughtErrorEvent; import flash.geom.Rectangle; import flash.media.StageWebView; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.net.URLStream; import flash.net.URLVariables; public class Main extends Sprite { public var s:String = new String(); public var final:String = new String(); private var _swv:StageWebView; public function Main() { initRequest(); } public function initRequest():void { var request:URLRequest = new URLRequest("http://www.xxx.com.au/connect copy.php"); request.method = URLRequestMethod.POST; var recVars:URLVariables = new URLVariables(); request.data = recVars; var loader:URLLoader = new URLLoader(request); loader.addEventListener(Event.COMPLETE, onComplete); loader.dataFormat = URLLoaderDataFormat.TEXT; loader.load(request); function onComplete(event:Event):void{ s = event.target.data; } AdDisplay(); } public function AdDisplay():void { if (! _swv) { _swv = new StageWebView () ; _swv.viewPort = new Rectangle(stage.stageWidth/2 - 175,stage.stageHeight/2,500,500); _swv.loadURL(s); _swv.stage = stage; } } } } Now, with trace statements, I know that the URL that gets returned is whole and can be used. Currently it returns: http://ads.mp.mydas.mobi/getAd.php5?apid=56926&auid=144.132.17.0&ua=Mozilla%2F5.0+%28Android%3B+U%3B+en-GB%29+AppleWebKit%2F531.9+%28KHTML%2C+like+Gecko%29+AdobeAIR%2F2.6&uip=144.132.17.0 But then when I put it into the StageWebView box to be shown, it doesn't show anything! I have gotten it to work previously, not sure how, but it would only show up ONE ad, and that was it, and it would only do that some of the time. I've been testing it in my browser, and have come to the conclusion that it's something to do with the &uip= etc. etc. Because, if I replace that IP address with the one given in the examples 63.145.58.2 - it works and I get a whole bunch of different ads from groupon. I'm not sure if it's because I'm on wireless here and as such it just plain refuses or something, or what's going on, but some help would be great if anyone can think of anything that I'm missing, or knows something about Millennial Media not showing ads 100% of the time. Oh! Final thing, I did try to create a house ad to fill in the gaps when the ads were working, but that didn't work either... Thanks everyone! A: I am pretty sure IP address with last octet 0 isn't really good address. From what i can recall routing to/from this kind of address will be sporadic at best depending on the route itself :) Apart from that can you make sure (with traces and/or debug) that the actual loadUrl method is performing well ? I can't see the code behind it, but you should check if there is some error events handling and stuff that are not logged or propagated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Directory Size in Objective C Since NSFileManager has no capabilities of returning the size of a directory, what would be a suitable & fast method for obtaining directory size? A: There is no fast method: you have to recursively request size of every file in the directory hierarchy. Don't forget to handle special cases: * *files (or directories on a Time Machine volume) with multiple hard links: count them only once. *special files such as what is found in /dev but can be created everywhere. *symbolic links: don't follow them, but count their size. Depending on your needs, you also have to choose between size of file contents or size of file on disk. A: Enumerate all directories inside your folder. "Folder size will be = Sum of All file sizes in side that folder." Some options: * *Programatically doing the same I suggest opendir with readdir_r to enumarate all files -- based on its CPU and Memory. *You can run du command using shell. There are other options too ... it depend on how you want to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android how to call layout events in other class? I have main.xml, mainActivity.java class file and Book.java class file, I want to use button click event (which is from main.xml) in Book class file. How can I do this? A: Well i'm a little short on info here. But it seems you have to copy/paste the code in your onClickListener and put it inside you Book class buttons onClickListener. Another solution which i dont think is a great solution is that you put your action in a public static method, this way you'll be able to acces it from your Book class. If this doesn't make sense, please post your code and xml files. And elaborate your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Spring security doesn't work on Glassfish v3 I have a java web application that use spring security for log in users, restriction access etc. , and it is working without problems on Glassfish 2.1, Tomcat, jetty, but on glassfish v3 doesn't work, when I try to login, and press button login, I'm getting login box from glassfish server(the box "The server xxxx requires user name and password"). Has somebody got such issue? Please let me know how I can solve this. Thanks, Iurie A: I don't know what is causing this (and potentially it could be one of a number of things), but I suggest that you turn the logging level up to the max and see if that gives you some clues as to what is going on. (When the logging level is DEBUG or higher, SpringSecurity generates lots of logging.) ... the request is not sent to spring security, the glassfish stopped it with his basic authentication, the question is why. I don't know what the cause of this is, but it sounds like some aspect of Glassfish authentication / authorization needs to be turned off if you want to use SpringSecurity. (Maybe you did this in your Glassfish 2.1 installation ...) The way that SpringSecurity works, you will definitely see logging messages if a request goes to a servlet that has the SS filter chain in place. It is possible that there is a SS misconfiguration that means that you've not got the SS filter chain in place, but I suspect that the real problem is that Glassfish is doing its bit before the requests get sent to the filter chain. A: Try to comment the following fragment: <login-config> <auth-method>BASIC</auth-method> </login-config> in ".../glassfish/domains/domain1/config/default-web.xml" file A: Did you create a JDBC Connection pool and Resource in Glassfish server? For ex: User: root Password: java databaseName: theDatabase serverName: localhost portNumber: 3306 driverClass: com.mysql.jdbc.Driver URL: jdbc:mysql://localhost:3306/dbname A: The issue seems to be confusion over the /j_spring_security_check url, if you change it everything works again. <security:form-login login-processing-url="/whatever_security_check" /> See this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is bit twiddling a good test for embedded engineer I am questioning candidates for embedded software engineers (in our company we use mostly C, sometimes C++). I usually give to the candidate a bit twiddling question. I do not mention that it can be solved with bit twiddling, when it is not obvious. I also accept solutions without using bit operations, but then I guide the candidate into bits (e.g. by saying: "What if you can't use modulo operator"). The example question could be: * *check if a number is divisible by 2 and not divisible by 4 *round up a number to next power of 2 *count set bits in a word *find the oldest bit that is set in a word *etc. In my opinion such questions should be easily solved within one minute by any decent software engineer (or even fresh graduate), regardless in which software domain he works. However my boss recently complains that these questions are too low-level for someone that is going to work e.g. in GUI. It came to the situation, where my questioning was useless, because my boss hired a candidate that utterly failed in this topic, but he claimed that he was experienced in Qt (I could not check this, as I have never used Qt, and for some reason I was the only one that could interview him at this moment). So my question is: is bit twiddling a good question for any (embedded) software engineer, or my boss is right and I should give up asking it to all candidates? A: I think the thing to be careful about is that you aren't asking for knowledge where it's basically random whether the interviewee has it to hand or not. For your examples, I cannot immediately remember what the bit-twiddling hacks are for the most-significant bit questions (finding it, and rounding up to the next power of 2). I know that there are hacks that I could look up, and I know about __builtin_clz on GCC which of course isn't portable. So, have I failed the interview? And if so, are you sure that I'm not fit to program Qt in your company? You're implementing a filter, and you just have to think about the false positive rate (how many people will know the bit-twiddles but be poor employees) and the false negative rate (how many good employees have forgotten the bit-twiddles). Of course all interviews have a false negative rate. The cost to your company hiring a bad employee is pretty high, so you have to be certain. For that reason, I think that if this employee turns out to be good, that's probably more by luck than judgement on the part of your company -- you shouldn't hire someone to be a Qt programmer without testing their ability with Qt or something similar. What's the cost of setting up a second interview with each of the three best candidates, taken by one of your Qt people, compared with the value of hiring the best one? What's the cost of your time to interview the candidates, given that this interview has no influence on the hiring decision? Just remember that different kinds of programmers have different knowledge at their immediate command, and make sure that your questions are strongly correlated with the kind of programmer you want. On this particular subject, what it proves is that the interviewee has spent time bit-twiddling, possibly in the fairly recent past. On the plus side, that's time they spent programming. On the minus side, that's time they didn't spend writing and learning Qt. I would be concerned if someone didn't know how to check the lsb, and didn't know that for positive values and for 2's complement negative values, the lsb is 1 for odd numbers and 0 for even numbers. That's because I expect programmers to know what a binary representation is. I would also be concerned if someone thought that x & 1 was likely to be better in some way than x % 2, because it means they use a terrible compiler ;-) I wouldn't be too concerned if someone couldn't remember the bit-twiddle for popcount. Slightly more if they couldn't figure out the code for it after you'd given them a heavy hint of one of the simpler ways to do it: "How could I compute the popcount of a 2 bit integer using bit-twiddling? OK, now write a line to do that in parallel for each of the top and bottom 2 bits of a 4 bit integer. OK, now write a 32-bit popcount". A: If you are programming in C, I would say yes. Bit twiddling is not something you do everyday, but something which shows that you understand how the computer handles your data. If you program in a higher level language, I suppose it is less important. A: for an embedded engineer or a software enigineer that will have to cope with talking to specific hardware etc these questions are good. There's a likely chance they will have to write code that fiddles wih bits then. Not sure if this can be solved within exactly 1 minute though, especially not if the engineer in question wants to do it in a generic way. A: My opinion is that every electronics and/or software engineer must know these things. These are the basics of digital computing and computer programming. A: I think this depends on what kinds of embedded systems they'll be working on, and what they'll be doing with them; "embedded" covers a very wide range of hardware. If they'll need to write low-level code or work with small microcontrollers, things like bit twiddling matter more than for higher level code on something bigger like a PC-compatible SBC. However, even when using a more powerful system and not writing low-level code, it's still important to be somewhat familiar with bitwise operations -- at least enough to handle bit flags and the like (at a minimum).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: glassfish and hibernate i saw that my glassfish server has a number of updates available, and i`ve noticed that hibernate 3.5 was one among them. I was wondering why would glassfish use hibernate. Then i have searched a little and i found that glassfish's default persistence implementention is toplink, and some guys tried to switch to hibernate. But again, why ? Is there a way of remove hibernate jar's from my app and put them on the application server so that every app that runs on glassfish can use them. I already use connection pool managed by glassfish and here i can understand the advantages. Can someone explain or point me somewhere where i can find some documentation about that ? Thank you A: According to this, the default persistence provider of glassfish is toplink which now became eclipselink. So, I am not sure about the updates you mentioned. May be hibernate was added to the AS. If you would like to use the jar but have it commonly stored in a repository, may be Maven would be a better choice. This is because, when you have the jar in the AS and not in your development environment, both development and unit testing would become difficult.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show Calendar in IPhone app source as iCal (.ics)file I am planning to create an iPhone application which displays tasks in calendar view with sort options Day, Week and Month view. Those tasks comes from .ics file which will be in web site (server). is it, We have to read that .ics file using our code and connect those tasks to calendar or we can directly set .ics file as a source. Please give me ideas to create this application, thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7579394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c++ code using libnet not compiling I'm trying to compile my libnet script and am getting this error: [root@whyme]# gcc -Wall `libnet-config --defines` mysocket.cc -o mysocket `libnet-config --libs` -lpcap -lnet /tmp/ccUPbuVg.o: In function `main': mysocket.cc:(.text+0x1e): undefined reference to `net_init' mysocket.cc:(.text+0x2a): undefined reference to `net_loadconfig' mysocket.cc:(.text+0x35): undefined reference to `net_detectdrivers' mysocket.cc:(.text+0x40): undefined reference to `net_initdrivers' mysocket.cc:(.text+0x54): undefined reference to `net_openconn' mysocket.cc:(.text+0x83): undefined reference to `net_listen' mysocket.cc:(.text+0xbe): undefined reference to `net_poll_listen' mysocket.cc:(.text+0xd2): undefined reference to `net_closeconn' mysocket.cc:(.text+0xf1): undefined reference to `net_receive_rdm' mysocket.cc:(.text+0x11b): undefined reference to `net_query_rdm' I didn't paste my code because this looks like it's related to linking the objects. A: Could you check what is returned by "libnet-config --libs" ? It might be returning something wrong, thus preventing the linker to find the libnet library. Make sure that the part saying "-L XXXX" points to the directory where libnet library is located. A: I'm able to compile & execute this source file with your exact command (changing only the filenames): https://github.com/repolho/Libnet-1.1-tutorial-examples/blob/master/01_init.c I therefore suspect the problem is in your source after all. Most libnet function names are of the form libnet_[funcname], but in your linker errors I see names of the form net_[funcname]. I also note that you've manually inserted -lnet. On my system, -lnet is the entire output of libnet-config --libs, so if you do need it specifying it manually is redundant. It's not harmful, but you can type fewer characters next time. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: trigger rowcommand event from commandfrield Edit button I have a query regarding GridView Control : I added a commandfield inside my Gridview and set ShowEditButton="True" (By default it trigger RowEditing Event). Can i Trigger RowCommand Event Instead of RowEditing Event. I know i can do it via other way but just got curious whether we can do this way A: No you would need to use a control like ButtonField or LinkButton in order to trigger a custom command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using auto generated id of Hibernate entity object in the equals and hashcode methods Lovely equals and hashcode, all the theory is here and also here I have taken the decision to use the auto-generated id within equals() and hashcode() in a number of my hibernate entity/domain objects. However, a number of websites say you should never do this due to the risk of persisting an object to the database for the first time whilst it is in the process of being compared or using hashcode. My point of view is that in most use cases this is much more unlikely than any other field being changed. The individual domain objects have the id generated once when they are first created, whereas nearly every other field has the opportunity to be altered during normal business processes (even a unique username can be changed ... ). And in many of my domain objects the unique id is pretty much the only suitable field to be considered (Person, Address, Pet, ... Customer etc etc ? Combining fields is a good idea, but never using the auto generated id is, I think, not good advice. Am I missing something else ? A: You should read Equals and HashCode on the Hibernate Community Wiki. The main reason for not using the database identifier in equals, and by implication, hashCode is for dealing with stored, but not persisted, entities. Prior to persistence all you instances are going to be equal, unless you take care to handle that case explicitly. If you know that you're not going to be in this scenario, and you make sure it's well documented, you may well be OK. You can always change the implementations later. A: No, I don't think you're missing anything fundamental. The "root cause" of the problem with using the database ID for equals and hashCode is that a Hibernate-generated ID is stored in a mutable field, and the value of that field changes when Hibernate assigns the ID. Equals and hashCode should be based on immutable state, as described as "pitfall #3" in the Odersky / Spoon / Venners article on writing equals / hashCode methods. This means, among other things, that you cannot add an instance to a Set or compare it to another instance until after it has been persisted, when the hashCode becomes fixed. The only thing you might be missing is how tricky it is for you to keep track of when the ID gets assigned, since it's done automatically by Hibernate. Sure, you might never call setId(someNewId), but you might issue a query that triggers a session flush, and a whole bunch of transient entities unrelated to the query suddenly have their IDs change from null to not-null. Using a business key for equals and hashCode is often recommended by the Hibernate community, but this approach also suffers from the same mutable-until-initialized problem. If your entity is a member of a persistent set which is eager-loaded by Hibernate, then it can be added to a set before its fields are initialized, so a hashCode based on these fields does not work either. See this Hibernate bug report discussing the problem with business key equality. James Brundege recommends assigning the ID in application code to avoid this problem. Lance Arlaus has a similar approach using an object factory which assigns IDs. If you really want to use an auto-generated ID for equals and hashCode, consider using Assert.notNull(id) in your implementations of equals and hashCode to detect coding errors. See also another stackoverflow question with a lot of discussion on the different approaches. A: I came across the equals problem with auto-id-generation because of the fact that I've put my objects into Set once they were created based on new user input. So I did not explictily compare them or something, i've just put them into a Set. At that point it was already fail, because the Set relies on equals()/hashCode() (which again were based on the object id because I had no other option). I then changed it to actually generating and assigning id's myself, which was the far better solution. Please read this article, it explains exactly the problem: dont-let-hibernate-steal-your-identity
{ "language": "en", "url": "https://stackoverflow.com/questions/7579404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: URL routing not working with ASP.NET web forms? I've recently started a web application and decided to use url routing in it (basically just to get some practice with it). The app is .NET4, and I'm using VS2010 SP1 and IIS Express (integrated pipeline). The thing is, when I run the app, routing works fine as long as there's no parameter in the route URL. If there is a parameter, then I get a 404. Here's the relevant code from global.asax.cs: void RegisterRoutes(RouteCollection routes) { routes.Clear(); routes.MapPageRoute("Users_Edit", "users/view/{username}", "~/users/user_detail.aspx", false); routes.MapPageRoute("Users_Create", "users/create", "~/users/user-detail.aspx", false); } void Application_Start(object sender, EventArgs e) { RegisterRoutes(RouteTable.Routes); } The app is running on IIS Express from VS. The virtual folder is /cms. If I go to http://localhost:8888/cms/users/create I see my page as intended. If I go to http://localhost:8888/cms/users/view/Matt I get a 404 error (from ASP.NET not from IIS, so the request is going into the ASP.NET pipeline). I've tried adding the following to web.config, but this didn't make any difference: <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> I've tried changing to Classic mode in IIS Express but that made no difference. Neither did using good old Cassini rather than IIS Express. Any ideas what I'm doing wrong? Cheers, Matt A: There seems to be a typo the actual page name in the non-working route. You have used page_detail.aspx in this route while in working route, you have used page-detail.aspx - notice the underscore vs hyphen. So I believe fixing that should do the trick i.e. routes.MapPageRoute("Users_Edit", "users/view/{username}", "~/users/user-detail.aspx", false);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome : No data received, Safari : Can't open the page I have a web page which allow users to compose news articles. It has a rich text editor too. So someone can copy and paste text from the web. When I put some copied content from wiki to that and once I POST, it throws "No Data Received" error on Chrome. When I check this with Safari it says "Can't open the page". Firefox displays empty page. But when I stop the execution of the mysql insert query it works fine. The issue is there is n issue with the mysql statement too. I extracted the generated sql statement and executed it separately with mysql tool. It works fine. No issue with the queries. I am really stuck here. Could you please help me on this. Thank you. Prasad. Here is the action code: public function articlenewAction() { $form = new Backoffice_Form_ArticleDraft(); if ($this->getRequest()->isPost()) { $formData = $this->getRequest()->getPost(); if ($form->isValid($formData)) { $postData = $_POST; $newArticleID = Classes_Article::createArticle($postData); } } } A: Finally we could go through this. We have upgraded the php version. Let us know if you know any other way to fix this. Prasad.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem while reading contacts with ContactsContract.Contacts.CONTENT_URI I need to search a particular name from ma contacts... for that i gave the selection criteria like this ContactsContract.Contacts.DISPLAY_NAME + " LIKE '"+constraint+"%'" But for apostrophe(')... means ...when i gave apostrophe as constraint an (SQL error )exception is thrown.. for all other special characters , the search is working.. How can we handle constraint apostrophe(')... in search criteria.. boz we can have contact names having apostrophe in it (Eg: Jennifer'lo'pe_z) A: How do I use a string literal that contains an embedded single-quote (') character? The SQL standard specifies that single-quotes in strings are escaped by putting two single quotes in a row. SQL works like the Pascal programming language in the regard. SQLite follows this standard. Example: INSERT INTO xyz VALUES('5 O''clock'); SO, simply for your solution, use '' at the place of '. like if(constraint.contains("'")) constraint = constraint.replace("'", "''"); And then execute your query. This must help you. Happy coding :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UIScrollView + change orientation = messed up subviews (iPad) I want to use a UIScrollView as my main container in the app, enabling me to swipe back and forth between subviews. To achieve this, I created a UIViewController subclass with a UIScrollView IBOutlet: In the viewDidLoad method I construct the sub-pages: for (int i= 0; i< pageCount; i++) { CGRect frame = self.scrollView.frame; frame.origin.x = frame.size.width * i; frame.origin.y = 0; UIWebView* aWebView= [[UIWebView alloc] initWithFrame:frame]; [self.scrollView addSubview:aWebView]; } When launching the app (portrait mode), everything works. That is, the UIWebViews are layed out side by side with the correct dimensions, and I can swipe back and forth between them. When I rotate to landscape, it seems that neither the scrollview size nor the subviews are resized. I don't know what I should do in order to resize the subviews and the scrollview itself, or at what point in code I should do anything, and I cant seem to find any examples for this. Anyone know what to do? [edit] Attempt to adjust sizes as suggested by mahboudz: - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * pageCount, self.scrollView.frame.size.height); for (int i= 0; i< pageCount; i++) { CGRect frame = self.scrollView.frame; frame.origin.x = frame.size.width * i; frame.origin.y = 0; UIWebView* view= [[self.scrollView subviews] objectAtIndex:i]; view.frame= frame; } } This kind of does what I want, but has the following issues: 1) one can see the subviews grow to correct screen size upon changing orientation 2) when the current page is, for example, page 2 of 5 pages, the page is not fully visible after orientation was changed, but is off-screen by like 40 pixels 3) I get strange effects depending on whether the app is launched in portrait or landscape mode (simulator), ill try to explain: When the app is launched in portrait mode: * *The shape/border of the subviews looks messed up/offscreen, see screenshots: http://i53.tinypic.com/21jr76x.png * *when I rotate to landscape, everything looks okay, scrolling works superb. even when I rotate back to portrait, everything is great now: http://i55.tinypic.com/if3iiw.png When the app is launchend in landscape mode: * *I get the same messed up/offscreen glitches as in portrait mode *Switching back and forth between portrait and landscape fixes this for landscape mode *BUT: Portrait mode will have the subviews with the width of the landscape mode, thus subviews are too wide I tried to fix 1) doing the code above in willRotateToInterfaceOrientation however it completely messed up the layout. I fixed 2) by adding the following code to didRotateFromInterfaceOrientation: // update the scroll view to the appropriate page CGRect frame = self.scrollView.frame; frame.origin.x = frame.size.width * self.currentPage; frame.origin.y = 0; [self.scrollView scrollRectToVisible:frame animated:NO]; Note: current page is determined in scrollViewDidScroll I dont have any idea how to fix 3) A: You would need to reset the frame size, content size and the content offset in order to get the subviews in a proper position. CGFloat screenHeight =[UIScreen mainScreen].bounds.size.height; CGFloat screenWidth =[UIScreen mainScreen].bounds.size.width; self.scrollView.frame = CGRectMake(0, 0, screenWidth, screenHeight); self.scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * numberOfPages, self.scrollView.frame.size.height); self.scrollView.contentOffset = CGPointMake(visiblePageBeforeRotation * self.scrollView.bounds.size.width, 0); This code should be placed in the method -(void)willRotateToInterfaceOrientation: (UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration Check as well the answer on this question: Clean autorotation transitions in a paging UIScrollView It has good example named Rotolling for rotating UIScrollView with paging enabled. Hope this helps. P.S: I am facing a problem on repositioning the center of the UIWebView on the rotation. A: You need to implement viewWillRotate/viewDidRotate and make adjustments to our content size and orientation as needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can FoneMonkey be used for testing preinstalled apps or apps for which we dont have source code? Can we use fonemonkey to test preinstalled apps in iphone. if so, can you guide me. or If it is possible to test an app for which i dont have sourcecode, pls guide me. Thank you. A: No, FoneMonkey needs to be compiled with the app, so you need to have the souces
{ "language": "en", "url": "https://stackoverflow.com/questions/7579413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: automatic paste value from clipboard (web base php and javascript) i've browse and search the solution with my problem, but i (still) can't fix my problem from the resource and article that i've search before. I've copy the (text) value into clipboard from (c# form apllication) that i've build before. QUESTION : how can i paste the (text) value in clipboard to textbox in web-apps (i'm using php, html and javascript) ? note : i've set focus to the textbox in web page but i can't still the way to paste value of the clipboard into the textbox. thx anyway. A: I don't think that is possible. You should past the text using your c# application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: my mapView.apk file execute properly on simuletor application start also but map is not show on the simulator while the application execute only the mapView back ground and the logo at the given location is appear. the map is not able to visible. A: Have You created map API key for your PC? If not get the Map API key from here for your PC and use it in your app. Hope this will help you. A: Mostly it happens when : * *you miss to add the INTERNET permission in manifest.xml *you do not have a proper API key. *Internet is not working on your simulator. check these conditions..and if you are using internet behind the proxy , then your AVD cannot load any application that is using the map.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sort a subItems in ListView Can you help me sorting a subitems in listview? I know only on how to sort the 1st column. Here's the code lstVItem.Sorting = SortOrder.Ascending; A: This Microsoft link gives you all the infos you need. And this one can help you too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MySQL update multiple records I have a web page that needs to update multiple records. This page gets all the information and then begins a transaction sending multiple UPDATE queries to the data base. foreach row { Prepare the query Hashtable Item = new Hashtable(); Item.Add("Id", Id); Item.Add("Field1", Field1); Item.Add("Field2", Field2); Item.Add("Field3", Field3); ... } Then we launch the ytransaction DO CHANGES() public void execute_NonQuery_procedure_transaction(string StoredProcedure, List<Hashtable> Params) { using (MySqlConnection oConnection = new MySqlConnection(ConfigurationManager.AppSettings[DB])) { MySqlTransaction oTransaction; bool HasErrors = false; oConnection.Open(); oTransaction = oConnection.BeginTransaction(); try { MySqlCommand oCommand = new MySqlCommand(StoredProcedure, oConnection); oCommand.CommandType = CommandType.StoredProcedure; oCommand.Transaction = oTransaction; foreach (Hashtable hParams in Params) { oCommand.Parameters.Clear(); IDictionaryEnumerator en = hParams.GetEnumerator(); while (en.MoveNext()) { oCommand.Parameters.AddWithValue("_" + en.Key.ToString(), en.Value); oCommand.Parameters["_" + en.Key.ToString()].Direction = ParameterDirection.Input; } oCommand.ExecuteNonQuery(); } } catch (Exception e) { HasErrors = true; throw e; } finally { if (HasErrors) oTransaction.Rollback(); else oTransaction.Commit(); oConnection.Close(); } } } Is there another way to do this or this is the most efficient way? A: It depends on the situation, like if you have multiple row updates or adding new rows or deleting some rows or a combination of these, which modifies the database table then, the efficient way to do this is to have Batch Update... Please go through this link Batch Update Hope this helps... A: it looks fine to me, you could eventually do not clear the Command.Parameters list but just assign the values on following iterations but probably this leads to no visible improvements. pay attention your throw is wrong, in C# don't use throw e; but simply throw;.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby Parallel/Multithread Programming to read huge database I have a ruby script reading a huge table (~20m rows), doing some processing and feeding it over to Solr for indexing purposes. This has been a big bottleneck in our process. I am planning to speed things in here and I'd like to achieve some kind of parallelism. I am confused about Ruby's multithreading nature. Our servers have ruby 1.8.7 (2009-06-12 patchlevel 174) [x86_64-linux]. From this blog post and this question at StackOverflow it is visible that Ruby does not have a "real" multi threading approach. Our servers have multiple cores, so using parallel gem seems another approach to me. What approach should I go with? Also, any inputs on parallel-database-read-feeding systems would be highly appreciated. A: You can parallelize this at the OS level. Change the script so that it can take a range of lines from your input file $ reader_script --lines=10000:20000 mytable.txt Then execute multiple instances of the script. $ reader_script --lines=0:10000 mytable.txt& $ reader_script --lines=10000:20000 mytable.txt& $ reader_script --lines=20000:30000 mytable.txt& Unix will distribute them to different cores automatically. A: Any chance of upgrading to Ruby 1.9? It's usually faster than 1.8.7. It's true that Ruby suffers from having a GIL but if multithreading would solve your problem then you can take a look at JRuby since it supports true threading. Also you better make sure it's the CPU that's the bottleneck because if it's I/O multithreading might not buy you much.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the best way to add logic to delete() on Grails domain class? I need to make changes to other domain classes when an instance of a particular domain class is deleted. What is the best way to do this? I don't want to wait until commit or flush so I don't think the "beforeDelete" callback will help. I would like to "override" delete, do some stuff and call super.delete(): class Foo { Bar bar void delete() { if (bar) bar.foo = null super.delete() -- this doesn't work } } Currently I have named "delete" cancel but would like to call it "delete" but then I cannot call the original delete(). A: To add to what @sbglasius said, here's the link to the docs on GORM events Complete example: class Foo { Bar bar def beforeDelete() { if(bar) { bar.foo = null } } } A: I haven't tried overriding GORM methods myself, but this might give some insight on what's involved: "Overloading" standard GORM CRUD methods I would put the "delete" logic in a service and call that instead: class FooService { def deleteInstance(foo) { if (foo?.bar) { foo.bar.foo = null // might have to call foo.bar.save() here // then foo.bar = null } foo.delete() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access Full Set View from client Couchbase Server 2.0 issue When i go in the couchbase console it shows a partial subset by default, u can show the fullset by clicking on it, this happens trough a link. (Developer view) The weird thing is after publishing the view(Production view), and checking the link there i do get all the objects, but when i try and get them from the client trough client.getView("data","view") i only get the partial subset instead of all objects. I am using the CouchbaseClient in .NET, MVC3. A: The Couchbase .NET client allows you to configure whether you're using development or production views through the client configuration. In the end, all that really does is prepend "dev_" to the view name, but it's part of the configuration rather than part of the code to allow runtime configuration without recompliation. The best approach would be to use the actual design document name you're using within the Web UI. As you may know, you can have both a development and a production version of a design document at the same time. The two can differ, but you can only edit the views in the development design document. Assuming you have the regular name for the design doc which contains the view in your code, you can add switch it to the development mode design doc in your App/Web.config as follows: <couchbase> <documentNameTransformer type="Couchbase.Configuration.DevelopmentModeNameTransformer, Couchbase" /> ... </couchbase> There are some other references on this over on the Couchbase wiki. If you're not seeing the full response expected, and you're sure it's using a production design doc/view, then there may be another issue. Keep in mind, there is a little lag time between inserting/updating a doc and it being available in the view. A: I found the problem, all i had to do was remove the following line from my config file: documentNameTransformer type="Couchbase.Configuration.DevelopmentModeNameTransformer, Couchbase"
{ "language": "en", "url": "https://stackoverflow.com/questions/7579432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A brief guide to extensions, namespaces and assemblies in V1 of Reactive Extensions (Rx) Exploring the latest release of Reactive Extensions, I discover that the different types and extension methods have been split across namespaces and assemblies. I know that I can go looking one by one on MSDN, but what I'd like is a brief overview of the logic of this segregation (I don't mean a justification, but if you're looking for this, try here first). A: Assemblies * *System.Reactive.dll - The core APIs *System.Reactive.Providers.dll - IQbservable interfaces and implementation over objects *System.Reactive.Windows.Forms.dll - Schedulers and integration for WinForms *System.Reactive.Windows.Threading.dll - Schedulers and integration for WPF/Silverlight *Microsoft.Reactive.Testing.dll - Classes for testing Rx- Mocks, Recorders, Virtual schedulers, etc Namespaces * *System.Reactive.Concurrency - Schedulers *System.Reactive.Disposables - Classes for creating and using disposables. (I was sad to see these classes moved into the Rx specific namespace, as they are generally useful) *System.Reactive.Joins - Join matching patterns *System.Reactive.Linq - Combinators and extension methods on IObservable and IQbservable. This is the main namespace for most consumers *System.Reactive.Subjects - Subject implement both IObservable and IObserver and have state *System.Reactive.Threading.Tasks - Interop to the TPL
{ "language": "en", "url": "https://stackoverflow.com/questions/7579433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute a script when xfce session ends Is it possible to run a script/command when the xfce session stops ? A: See http://mail.xfce.org/pipermail/xfce/2012-November/031694.html - There, Erik Habicht suggested creating a wrapper script in /usr/local/bin/xfce4-session (or another dir that precedes the dir where xfce4-session is installed, /usr/bin in your PATH). This way, you do not have to change /usr/bin/X11/xfce4-session, so it can be updated independently. #!/bin/bash # Add your own pre-session logic here /usr/bin/xfce4-session # Add your own logout logic here then $ chmod +x /usr/local/bin/xfce4-session It's not perfect (depends on PATH order) but may be more palatable. (Note: I promoted my comment to an answer.) A: Change the /usr/bin/xfce4-session executable with a shell script which runs the original xfce4-session and your logout script if xfce4-session finished. # mv /usr/bin/xfce4-session /usr/bin/xfce4-session.orig The new /usr/bin/xfce4-session file: #!/bin/bash /usr/bin/xfce4-session.orig echo "my logout script" > /tmp/testfile Don't forget to set the execute permissions: # chmod a+x /usr/bin/xfce4-session (Tested on Debian Squeeze.) A: I'd prefer solution that does not touch system directories or files and will run the logout hook within current user session and its privilledges. below is my solution: create ~/.local/bin/xfce4-session-logout script with the following contents: #!/bin/bash PRELOGOUT=${HOME}/scripts/pre-logout.sh RESULT=RES_`echo -e "logout\nrestart\nshutdown\nsuspend" | zenity --height=250 --list --title "Logout from $USER" --column "What do You want to do?"` case $RESULT in RES_logout) [ -x $PRELOGOUT] && $PRELOGOUT /usr/bin/xfce4-session-logout --fast --logout ;; RES_restart) [ -x $PRELOGOUT] && $PRELOGOUT /usr/bin/xfce4-session-logout --fast --reboot ;; RES_shutdown) [ -x $PRELOGOUT] && $PRELOGOUT /usr/bin/xfce4-session-logout --fast --halt ;; RES_suspend) /usr/bin/xfce4-session-logout --suspend ;; *) exit 1 ;; esac and make it executable: chmod u+x ~/.local/bin/xfce4-session-logout Now, put whatever You need to be executed at logout action to ~/scripts/pre-logout.sh and make it executable chmod u+x ~/scripts/pre-logout.sh after relogin, either menu > logout button or Alt+f3: "logout" will bring simple dialog for leaving the current session Note: pressing Alt+F4 does not work with it, but maybe some black belted xfce4 users will provide some suggestion A: I validated the answer above since it does not involve new code writing. I however found another way to proceed : create a X11 program which would be launched at session startup : it could execute custom scripts when the X session is closed Note : the drawback is that the used scripts could not connect to X windows so this solution may, depending on the need, execute the script too late.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to skip an activity's result for another activity than the subsequent activity in a sequential workflow? I'm with a sequential workflow, say with three activities 1. Get Images 2. Rotate Images 3. Flip Images Now I want something like this, that for the 3rd activity, the input doesn't come from 2nd activity but from the 1st activity. means, in 3rd activity, I want the original images to be flipped, den the rotated images to be flipped. thanks for the help in advance. Regards A: You could place the results of GetImages into a Sequence scoped collection variable, place the results of RotateImages into another Sequence scoped collection variable, then FlipImages could flip both the original images and the rotated images. That sounds to me like it would work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7579439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a fully customized Alert Dialog? Is there a solution to create an Alert Dialog with no borders around? If I create a layout and attach it to the Alert Dialog, I have my layout shown, but it's surrounded by the default dialog borders. Any way to cut them off? Thanks in advance. A: Here is one way (if you don't like this particular example with the green border, scroll below to see a second one I found). Here is another example (this one gives you an example without a border, and one with a border. The explanations are in Japanese, but the code is given for both.) A: Hi if you use your own layout then set this in your styles.xml <style name="Theme.Transparent_layout" parent="android:style/Theme.Dialog"> <item name="android:windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> <item name="android:windowBackground">@android:color/transparent</item> </style> and set this style in your manifest file <activity android:name=".Main" android:theme="@style/Theme.Transparent_layout" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7579441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show super.view - iPhone I've created ViewControllers ABC and XYZ. XYZ inherits from ABC. In the AppDelegate, I add XYZ.view as subView. Now at the click of a button in XYZ I want to display ABC.view on a small portion of screen. I've tried some combinations of the following but nothing works. * *[self.view bringSubviewToFront:super.view]; *[appDelegate.window bringSubviewToFront:super.view]; *[self.view addSubview:super.view]; *[appDelegate.window insertSubview:self.view atIndex:0]; *[appDelegate.window insertSubview:super.view aboveSubview:self.view]; *[super.view setNeedsDisplayInRect:CGRectMake(0, 0, 320, 320)]; A: Super is a keyword that Is used only to invoke the superclass's implementation of a particular method. It does not refer to an actual instance of a class. If you want to create and display a viewcontroller, you have to alloc and init an instance of it, then present it just as you have done with XYZ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to resrtrict resolution in Android Manifest Can anyone simply explain how restrict small resolution for my app. For example, I want that my app will be appropriate for QVGA , WVGA and devices with more resolutions? Thanks in advance. A: Add this to your manifest file: <supports-screens android:smallScreens="false" android:normalScreens="true" android:largeScreens="true" /> Hope this helps. A: Please read this documentation it will help you . http://developer.android.com/guide/topics/manifest/supports-screens-element.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7579446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete characters from textfields,iphone I have textfield and having a number "1234567890" now i have button, on tapping it, it should delete the the number from last. like as in keyboard. but one time tap, should delete one int at a time. I dont want to delete whole number at once, it should just delete a single int, on every single click. How can i implement it. Suggestion are always appreciated A: - (IBAction) deleteCharacter : (id)sender { if ([textField.text length] > 0) { textField.text = [textField.text substringToIndex:[textField.text length] - 1]; } } A: Get the textField string and remove the last character from that.Again show the new string in the textField NSString *str=urTextField.text; urTextField.text=[str substringToIndex:([str length]-1)];
{ "language": "en", "url": "https://stackoverflow.com/questions/7579448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If statement with background colors Okay, I've been trying to get this for almost 4 hours now, and it just won't work. I have a link: <a id="togglecolor" href="#" onclick="ToggleCover();"> Click here to toggle DIV so you can see what I did. </a> And I have a div: <div id="framecover" style="position:absolute; width:97%; height:500px; z-index:100; background-color: transparent;"> </div> I am trying to make a script so the link toggles the background color of the div from transparent to red and back again when you click it again. This is the code I have: $(function() { $('#framecover').css('backgroundColor', "transparent") var framecover = '#framecover' $("a#togglecolor").click(function(){ if ($(framecover).css('backgroundColor') == "transparent") { $(framecover).animate({ backgroundColor: "red" }, "slow"); } else { $(framecover).animate({ backgroundColor: "transparent" }, "slow"); } }); }); Through my testing, I've been able to narrow down to where the problem is. It's on this line: if ($(framecover).css('backgroundColor') == "transparent") Undoubtedly, he problem is above code is the wrong syntax for "if framecover's background-color is transparent". The problem is that I have no clue what the syntax is and I've been scouring the internet for two hours looking for the answer and I can't find it. Note: I do have the jquery color plugin. This code: $(framecover).animate({ backgroundColor: "red" }, "slow"); works fine. It's the if statement that's giving me trouble. A: Assuming you want it to start at transparent (if not just switch them): $("a#togglecolor").toggle(function(){ $(framecover).animate({ backgroundColor: "red" }, "slow"); }, function(){ $(framecover).animate({ backgroundColor: "transparent" }, "slow"); }); A: First this I'd try is to use console.log($('#framecover').css('backgroundColor')) to find out exactly what the background color is at the point of the test (might be none). Copy this and it should work. Second option, check if the background is red, make the transparent background setting part of the else execution A: Have you tried : if (... .css("backgroundColor") == "rgba(0 ,0 , 0, 0)") { ... Works in Chrome but I haven't tried all browsers. jsFiddle here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: comparision of two columns within a single table i have a table alpha ,this contains two columns A And B. I need to find out how many A's are there for B. A B 1 1 2 2 3 3 4 3 5 4 6 7 A: Try grouping : SELECT `B`, COUNT(*) AS `Count` FROM `Alpha` GROUP BY `B` A: try this SELECT COUNT( * ) AS `Items` , `B` FROM `alpha` GROUP BY `b`
{ "language": "en", "url": "https://stackoverflow.com/questions/7579457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: while loop not iterating properly to remove table rows Just trying to remove a table but loop is not removing all rows. I have used alert to be sure it's the right element by id. It does remove some rows but not all, just chunks. console reports: DOM Exception 1,DOM Exception 8 function removeThis(unsetElement) { unsetElement.parentNode.removeChild(unsetElement); } A: While you remove rows, their indices change; you need to do the loop from the top, i.e. i=rowCounter-1; while(i>=0){unsetTable.deleteRow(i);i--;} Yet the better idea is just to purge the whole table; rows will be garbage-collected. A: Another solution could be to use the special -1 index, which deletes the last row. var i = thisTrAry.length; while(i--) { unsetTable.deleteRow(-1); } But if you remove the whole table anyway (in your last line) then there is no need to remove the rows first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: returning fuzzy match percentage in solr query result I've implemented solr/lucene fuzzy match for my system and its working perfectly. I have requirement to display percentage fuzzy match after query sends response back. As an example if my index data is "rushikupadhyay" and if my query is "rushikupadhya"~0.8, I should get exact percentage as part of response like 0.85 or 85%. I want to use percentage result as part of application and perform additional steps based on return value, like if percentage match is 70-80% do X, 80-90% do Y, and > 90% do Z. Any pointers are appreciated. A: Please Note: The guidance found in this post on the Lucene Wiki - ScoresAsPercentages that you may want to review before deciding to go with a purely percentage based logic. However, if you do decide to go with a percentage value, you can get this value by also including the score field in the query response. See the Solr Admin page (Full Interface link) will direct you to /admin/form.jsp In the Fields to Return option it shows, *,score This will return the match score for each document in the result set. However, please note that this is the raw score of the document match and is relative to the maxScore value that is part of the <result> element. So in order to get the true percentage based score for each document, you will need to normalize each documents score against the maxScore by using logic such as (score/maxScore * 100) to get the correct percentage value to display.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: create file with FileStream and apply FileAttributes Is it possible while creating the file with FileStream also apply FileAttributes at the same time? I would like to create file for stream writing with FileAttributes.Temporary file attribute. A: You can use FileOptions.DeleteOnClose as one of parameters. File will be automatically removed after you finish your operations and dispose a stream. A: Ya, surely you can apply FileAttributes also by using File.SetAttributes Method A: Why do you need to do it all at once? * *Just create the file (using File.Create or, if its a temporary file, use GetTempFileName.) *Set the attributes on the newly created file *Open the file using whatever method suits you A: You can do this if you use the Win32 CreateFile method uint readAccess = 0x00000001; uint writeAccess = 0x00000002; uint readShare = 0x00000001; uint createAlways = 2; uint tempAttribute = 0x100; uint deleteOnClose = 0x04000000; new FileStream(new SafeFileHandle(NativeMethods.CreateFile("filename", readAccess | writeAccess, readShare, IntPtr.Zero, createAlways, tempAttribute | deleteOnClose, IntPtr.Zero), true), FileAccess.ReadWrite, 4096, true); private static class NativeMethods { [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern IntPtr CreateFile(string name, uint accessMode, uint shareMode, IntPtr security, uint createMode, uint flags, IntPtr template); } For more information, see the MSDN documentation of CreateFile
{ "language": "en", "url": "https://stackoverflow.com/questions/7579465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Add radioButton in ListView I need to add RadioButton in ListView and indeed I have tried, But the problem that I am getting is that when I click on radio button it get selected wonderfully... but the same time if wish not to select that particular button... it just remains selected. Here I am providing my code: import android.app.ListActivity; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class RadioInCustomListView extends ListActivity { ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String[] names = new String[] { "Issues", "Request for Information", "Contracts", "Purchase Orders", "Change Orders", "Proposals", "Submittals" }; lv = getListView(); lv.setCacheColorHint(Color.TRANSPARENT); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.radio_item, names); //this.setListAdapter (new ArrayAdapter<String>(RadioInCustomListView.this,R.layout.radio_item, names)); setListAdapter(adapter); } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Object o = this.getListAdapter().getItem(position); Toast.makeText(RadioInCustomListView.this, o.toString(), Toast.LENGTH_LONG).show(); } } My xmls: main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ListView android:id="@+android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> radio_item.xml <?xml version="1.0" encoding="utf-8"?> <RadioButton xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:gravity="center_vertical" android:checkMark="?android:attr/listChoiceIndicatorSingle" android:paddingLeft="6dip" android:paddingRight="6dip" /> A: may be this code help you ls.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,list_sexuality)); ls.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How main method called without calling it by classname.mainmethod() This is very basic question, many of us didn't know this answer. In java, to call static methods we have to follow this classname.method();. But when comming to main(), its not been called by classname.main() even though it is static. A: The best way to understand how "main()" is called by JVM is to see how "java" calls your main method. Here is the JNI example explaining the same. mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V"); ... (*env)->CallStaticVoidMethod(env, cls, mid, args); A: Yes it is. The java "interpreter" takes the class name you're giving it, looks for a static main method taking a String array as argument and returning void, and calls this method. The java interpreter probably does this using native code, but that's not important. If, inside a program, you want to call another class's main method, you can. main methods are not special in this regard. The only special thing they have is that they can be the entry point for the java interpreter. A: The main method is invoked by the java interpreter itself when you run the class, without have to add the class names. you can find more detail explaination @ Why is the Java main method static? A: You can call static methods in Java as though they were instance methods but this is considered bad practice. public class Foo { public static void bar() { ... } } ... Foo foo = ... foo.bar(); // this will work Foo.bar(); // but this is better A: It's being called with Class.main() as you have to provide the class containing a main() method, when starting an application. A: But when comming to main(), its not been called by classname.main() even though it is static. How can you say so? I am afraid you have got it wrong. You can call a static method using object,though. Usually you never call main yourself.It is an entry-point for your program and JVM calls it to start the execution of the program. Also this is the reason you need to pass the name of the class when you execute your code. Remember this: java ClassName This is how you execute your program from command line. ClassName here is the name of your Class having the main method. This class name is used by JVM to call your main method e.g, ClassName.main()And all this calling stuff is done using native code C/C++.You might want to google it, in case you want to know exactly how all this works.If this is not exactly what you were looking for, maybe you can explain the question little more. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Procedure returning multiple values I have a database which maintains interactions with my application, a log kinds. I want to generate reports for total interactions per day in a month. What is the best possible way to write a procedure that would return up 30 values, each value representing the count for a day? I am using SQL Server 2005. I retrieve these values in a .NET code, upon which I want to run my algorithm. Thanks. A: Your sql query will look like the following. select top 30 DATEPART(day, InteractionDate) as Day, COUNT(1) as Interactions from logTable group by DATEPART(day, InteractionDate) In .NET you can use SqlDataReader and store values in a List A: Stored procedures often return result sets - what you want here is a simple SELECT statement in your stored procedure. Depending on what technology you are using, you can use a SqlDataReader to get data back into your own structures or SqlDataAdapter to grab it all into a DataSet object. So we've broken it down into two tasks: (1) Write a SELECT to produce the data you want, (2) Use a DR/DA in the app/service to retrieve it. evpo gives a good example of the first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matlab- zero padding How to do this on matlab? zero pad the face image with a five‐pixel thick rim around the borders of the image. show the resulting image. Must be manual codes on script. A: This sounds like homework, so I will just give you a hint: In MATLAB it is very easy to put the content of one matrix into another at precisely the correct place. Check out the help for matrix indexing and you should be able to solve it. A: save this function as create_padded_image.m function padded_image = create_padded_image(image, padding) if nargin < 2 % if no padding passed - define it. padding = 5; end if nargin < 1 % let's create an image if none is given image = rand(5, 4) end % what are the image dimensions? image_size = size(image); % allocate zero array of new padded image padded_image = zeros(2*padding + image_size(1), 2*padding + image_size(2)) % write image into the center of padded image padded_image(padding+1:padding+image_size(1), padding+1:padding+image_size(2)) = image; end Then call it like this: % read in image - assuming that your image is a grayscale image $ image = imread(filename); $ padded_image = create_padded_image(image) A: I realize you want to code this yourself, but for reference, you can use the PADARRAY function. Example: I = imread('coins.png'); II = padarray(I,[5 5],0,'both'); imshow(II) Note this works also for multidimensional matrices (RGB images for example)
{ "language": "en", "url": "https://stackoverflow.com/questions/7579477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Browse Directory option for sftp and ftp Currently I'm doing the functionality for sftp using jsch-0.1.44. I need to add option for the user to browse the directory. So how to get the list of files from the remote server. Is there any other open source exists for this functionality ? Please help me A: This example from jsch examples list shows one way to do this. Look at the code starting from the following line... if(cmd.equals("ls") || cmd.equals("dir")){ A: The ChannelSftp class provides the necessary methods to browse a remote directory. For listing the directory, use channel.ls("."). This returns a vector of LsEntry objects, which you can traverse, print, show in a window, etc. A: You can use Apache Virtual File System. If you are creating GUI application you can use OtrosVfsBrowser or VFSJFileChooser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deadlock in SQL Server 2008 I have two stored procedures, both insert rows into the same table. Once stored procedure call regular time interval and another stored procedure call by user event. Sometimes both stored procedure are called together and at this time deadlock occurs. How can I solve this problem? A: Lock at the beginning of the SP and unlock at the end. http://msdn.microsoft.com/en-us/library/ms187749.aspx and http://msdn.microsoft.com/en-us/library/ms190345.aspx A: You can lock the table at the beginning of your both sprocs. This way there will be no deadlocks because data modification will have to wait until the other sproc finishes. See the following command: select 1 from theTable with (tablock, holdlock) where 1=0; It also needs to be done inside a transaction. The table will be editable when the transaction finishes. A: You might also consider detecting the condition and retrying. Have each procedure back off for a short random amount of time
{ "language": "en", "url": "https://stackoverflow.com/questions/7579502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do i have possibility to develop iphone application in WindowsOS(Win7)? Possible Duplicate: How can I develop for iPhone using a Windows development machine? I am new to iphone applications. My doubt is, can i develop i phone applications in windows platform by installing iphone SDK, emulators etc.. A: Straight and simple Answer = No You can-not ! Apple, wants confine its iphone ecosystem only to Mac OS. Its just that Windows is so prominent in the market so, they have to give away itunes for windows (For Consumers only) But, they have such a good SDK and such a strong hold on iphone market that gives them enough confidence to keep the SDK and the emulator to Mac. One possible work around : You can use Hackintosh ('Hacked Mac OS, to run on normal PC instead of a powerPC') For more info, I found a related answer : Related Question
{ "language": "en", "url": "https://stackoverflow.com/questions/7579503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tailable cursor in mongo db timing out I am trying to create an oplog watcher in ruby. So far ive come up with a small script below. require 'rubygems' require 'mongo' db = Mongo::Connection.new("localhost", 5151).db("local") coll = db.collection('oplog.$main') loop do cursor = Mongo::Cursor.new(coll, :tailable => true) while not cursor.closed? if doc = cursor.next_document puts doc else sleep 1 end end end The problem with this is, after 5 or 6 seconds when it has spit out a lot of data it times out and i get an error C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/connection.rb :807:in `check_response_flags': Query response returned CURSOR_NOT_FOUND. Either an invalid c ursor was specified, or the cursor may have timed out on the server. (Mongo::OperationFailure ) from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ connection.rb:800:in `receive_response_header' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ connection.rb:768:in `receive' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ connection.rb:493:in `receive_message' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ connection.rb:491:in `synchronize' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ connection.rb:491:in `receive_message' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ cursor.rb:494:in `send_get_more' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ cursor.rb:456:in `refresh' from C:/RailsInstaller/Ruby1.8.7/lib/ruby/gems/1.8/gems/mongo-1.4.0/lib/../lib/mongo/ cursor.rb:124:in `next_document' from n.rb:7 from n.rb:6:in `loop' from n.rb:6 What i dont understand is when i m able to see the actual data how can it suddenly say cursor not found. Im pretty new to ruby and any ideas on what direction i must take will be useful for me. A: The solution is that i need to have an exception handling mechanism to capture the exception which is thrown when the cursor reads the last document in a relatively small oplog with an higher number of writes per second. Since the cursor reaches the end of the oplog it would throw an exception that there are no more records. require 'rubygems' require 'mongo' db = Mongo::Connection.new("localhost",5151).db("local") coll = db.collection('oplog.$main') loop do cursor = Mongo::Cursor.new(coll, :timeout => false, :tailable => true) while not cursor.closed? begin if doc = cursor.next_document puts "Timestamp" puts doc["ts"] puts "Record" puts doc["o"] puts "Affected Collection" puts doc["ns"] end rescue puts "" break end end end This now works as the exception is been handled. Thanks to the mongodb-user google group for pointing this out to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to use Google Book API in Android to download/search books I'm new to android and trying to build this application * *As a user, I will be entering some terms in application. Service will search for books relevant to those terms on the internet using Google Book API. It will fetch the information and store in content provider. In case term is already present, then service will check if there is any change in content. In case, there is change, service will notify the user using notification API. *When user starts application, or click on notification, he will be shown the latest relevant books. For this purpose, Activity will directly talk to content provider using content resolver I'm enable to find anything on Google Book API though I got Google Book API docs but how to start or implement them in my program is still unknown to me A: Ok. First just write an application that uses HttpClient to invoke a url and get the data back. Study HttpClient api, and sample apps that use HttpClient to connect to server because thats what you are going to be doing. I would recommend using the REST API, but this is still a style of URL and interaction. Its still fundamentally an HttpClient interaction scenario. So you will need to get a google account for credentials, and download the jar files for the Book API if there is on. create a libs folder in your eclipse android project (definitely use eclipse), use exactly the folder libs to place the jar files for Google API and start coding!
{ "language": "en", "url": "https://stackoverflow.com/questions/7579515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: inserting into an array in foreach I have the following code. I'm doing some work on websites, but sometimes they redirect, and if they do so I want to do the work on the redirected site. BUT I don't want to check all the sites for redirection before doing the work, as there are few of them. So how can I insert it in the loop? I know that I can't insert into string array, but what's the best structure? Probably list, because of insert, although I'm not so keen to hold on to the values, which we have already processed. I'm not proficient in C#. string[] lines = System.IO.File.ReadAllLines(@"my_file_with_urls.txt"); foreach (string line in lines) { Uri default_uri = new Uri(line); Uri response; WebSiteIsAvailable(default_uri, out response); //Do work on the actual link if (!response.Host.Equals(default_uri.Host)){ //I want to run the work on the redirected website } } A: var urisToProcess = new HashSet<Uri>( lines.Where(s => Uri.IsWellFormedUriString(s, UriKind.Absolute)).Select(s => new Uri(s))); var redirectedUris = new HashSet<Uri>(); foreach (var uri in urisToProcess) { Uri response; WebSiteIsAvailable(uri, out response); if(response.Equals(uri)) { // do work on actual URI continue; } while (!response.Equals(uri)) { uri = response; WebSiteIsAvailable(uri, out response); } if(!urisToProcess.Contains(uri)) { redirectedUris.Add(uri); } } foreach (var uri in redirectedUris) { // do work on redirected URI } A: You could try, I havent fully tested it, but. foreach (string line in lines) { Uri default_uri = new Uri(line); Uri response; WebSiteIsAvailable(default_uri, out response); while (!response.Host.Equals(default_uri.Host)) { default_uri = response; WebSiteIsAvailable(default_uri, out response); } //Do work on the actual link as now default_uri contains the working link. } A: You can't insert items in the array or list you are going through with foreach. Instead make a for loop and decrease the index of the loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cross browser W3C compliant semi-transparent background color To set a semi-transparent background I use: background-color: rgba(0, 120, 180, 0.8); For IE, which doesn't support rgba I use a 1x1 png with the same color: background-image: url(http://i53.tinypic.com/2mgtu9e.png); (demo here) Question 1 I know that there is another method for IE which uses filters. Is this method considered as W3C compliant ? Question 2 Say I combine 20 1x1 png images into a single sprite. How could I use this sprite to set an element's background color according to the 7th pixel in the sprite ? A: As others have said, no IE filters are not W3C compliant. They also incur significant overhead and have performance ramifications. Unless I am mistaken when a filter is applied to an HTML element it will be applied to everything in that element including its text. So you'd end up with semi-transparent text too. There may be a way to keep that from happening but I haven't come across it. Also there are times when IE filters don't play well with semi-transparent PNGs as this article mentions. Speaking of PNGs, the idea of using a sprite really only works if you have a specific height or width or both. So this really won't work for what you need, like Merianos Nikos said. Also tiling a 1x1 image is a really terrible idea. I say this because there are performance issues when you do that, especially with IE6. Though IE6 may not be a concern for this, tiling such a small image still causes a performance hit since the browser must draw and redraw each and every one. See this StackOverflow entry. For this situation I would use something like Modernizr which will make rgba available to use in browsers that don't support rgba. After customizing a download for just rgba and a few other things (HTML5 shim, yepnope, and adding CSS classes) the download was 6.1kb. Not a huge hit to make development easier. Update I misspoke when I said that Modernizr enables rgba. It doesn't do that but it will let you know that rgba is enabled in the browser. It will add classes to the html tag that tells you the abilities of the browser. A: Answer #1 This method is not W3C compliant. The way that Internet Explorer uses Filters is not the regular one. Filters are not supported at all from the W3C specification. The filters are Internet Explorer plugins. Answer #2 There is no way to use them. In sprites you can only use images that are not repeated in the background. In example: Say that you have the following sprite x y z r t s u v a if you have now an area that you like to use as a background the image t from your sprite. You can set the very top left side of the div to display the t image, but then when you need to reapeat the background you will start again from x. That means that you will have repeated all the images from the sprite. A: Question 1: CSS3please. The box-gradient shows how to use the MS-filter. To check if valid: W3C CSS validator . I'm getting errors, so I guess it's not considered valid CSS
{ "language": "en", "url": "https://stackoverflow.com/questions/7579520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET MVC Client-Side Validation with a JavaScript Loader Has anyone tried using MVC client-side validation with a JavaScript loader, specifically yepnope.js? I can't get it to work, and I believe it's because it registers the validation code before the necessary JS files have loaded. I can get it working by loading jQuery, jquery.validation, MicrosoftAjax, and MicrosoftMvcValidation normally (i.e., outside of yepnope), but I wonder if anyone has a better solution. Thanks. A: on the completed event of the YepNope please execute the below script where formName will be the name of your form. $(formName).removeData("validator"); $(formName).removeData("unobtrusiveValidation"); $.validator.unobtrusive.parse(formName);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting PDF to txt for right-to-left language I want convert a Persian language PDF file to text file or to a string type variable. I have read all questions on StackOverflow similar to this question, but not found an answer. An example Persian language PDF file is provided here
{ "language": "en", "url": "https://stackoverflow.com/questions/7579525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does any one have a working script of LoadRunner Automation API? Currently I am writing Perl script that creates LoadRunner scenario, execute the test, collect the result, recover the environment and repeat the cycle again with different scenario variables. I don't have a problem creating new scenario, adding generator, adding 2 groups + script + the run-time settings. But I am having a problem with: * *Setting scenario schedule from "Scenario" to "Group". *Setting schedule per group This the snippet of the code: use strict; use v5.10; use Win32::OLE; use Win32::OLE::Enum; use Win32::OLE::Variant; use Data::Dumper; use Win32::OLE::Const 'LoadRunner Automation Library'; use constant False => Variant(VT_BOOL,''); use constant True => Variant(VT_BOOL,1); my $lrEngine = Win32::OLE->new('wlrun.LrEngine') or die "oops\n"; my $lrScenario = $lrEngine->Scenario(); my $rc = $lrScenario->new(0, 1); # do not save previous, Regular vusers based scenario if ($rc != 0) { print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n"; print "lrScenario->new(0, 1):rc: $rc\n"; } # snip-snipped - add generator # snip-snipped - add @groups definition foreach my $group (@groups) { print "scriptName: $group->{scriptName}\n"; my $scriptLocation = $group->{scriptLocation}; my $scriptName = Variant(VT_BSTR|VT_BYREF, $group->{scriptName}); { # add $group->{scriptName} script $rc = $lrScenario->Scripts->Add($scriptLocation, $scriptName); if ($rc != 0) { print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n"; print "lrScenario->Scripts->Add($scriptLocation, $scriptName):rc: $rc\n"; } } ############################################################################# my $groupName = Variant(VT_BSTR|VT_BYREF, $group->{groupName}); { # add $group->{groupName} group $rc = $lrScenario->Groups->Add($groupName); if ($rc != 0) { print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n"; print "lrScenario->Groups->Add:rc: $rc\n"; } $rc = $lrScenario->Groups->Item($groupName)->AddVusers($scriptName, $hostname, 3); if ($rc != 0) { print "Win32::OLE::LastError: ".Win32::OLE::LastError()."\n"; print "lrScenario->Groups->Item($groupName)->AddVusers:rc: $rc\n"; } } ############################################################################# # snip-snipped - change group script run time setting } my $scheduleName = Variant(VT_BSTR|VT_BYREF, 'Schedule123'); my $lrManualScheduleData = $lrScenario->ManualScheduler->AddSchedule($scheduleName, lrGroupSchedule); # Scenario schedule mode if (!$lrManualScheduleData) { say "Win32::OLE::LastError: ".Win32::OLE::LastError(); say "lrScenario->ManualScheduler->AddSchedule:rc: $rc"; } $rc = $lrScenario->ManualScheduler->SetCurrentSchedule($scheduleName); if ($rc != 0) { say "Win32::OLE::LastError: ".Win32::OLE::LastError(); say "lrScenario->ManualScheduler->SetCurrentSchedule:rc: $rc"; } print "\$lrScenario->ManualScheduler->SetScheduleMode($scheduleName, lrGroupSchedule):"; $lrScenario->ManualScheduler->SetScheduleMode($scheduleName, lrGroupSchedule); #LrManualScheduleMode -> lrGroupSchedule = 1, lrScenarioSchedule = 0 say "Win32::OLE::LastError: ".Win32::OLE::LastError(); $lrManualScheduleData->{'InitAllBeforeRun'} = 'True'; $lrManualScheduleData->{'DurationMode'} = 1; $lrManualScheduleData->{'Duration'} = 60 * 60; $lrManualScheduleData->{'RampupBatchSize'} = 1; $lrManualScheduleData->{'RampupMode'} = lrRampupByGroupBatches; $lrManualScheduleData->{'RampupTimeInterval'} = 5; $lrManualScheduleData->{'RampdownBatchSize'} = 1; $lrManualScheduleData->{'RampdownMode'} = lrRampupByGroupBatches; $lrManualScheduleData->{'RampdownTimeInterval'} = 5; $rc = $lrScenario->ManualScheduler->{'ScenarioStartTimeMode'} = 0; # Start scenario without delay #test say "$scheduleName: ".$lrScenario->ManualScheduler->Schedule($scheduleName)->{'Duration'}; # returns 300 A: I have the same problem. Setting those properties and then calling either setschedulemode or setcurrentschedule doesn't seem to work. The only workaround I have found is to use the setscheduledata method passing in xml. You will need to get the current xml for the scheduledata and then change the xml, passing in the modified xml to the setscheduledata method. Hopefully this helps lrManualScheduleData data = engine.Scenario.ManualScheduler.get_Schedule("Schedule 1"); String scheduleXML,errStr; int returncode = data.getScheduleData(out scheduleXML, out errStr); // Manipulate the XML to set whatever schedule you want data.SetScheduleData(scheduleXML, out errStr);
{ "language": "en", "url": "https://stackoverflow.com/questions/7579526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I need Linq Query for this SQL Query "select count(salary) from employee where employeeID = 10 group by salary" --- Its a SQL Query. I need Linq Query which would retrieve me same output..? Please Help me out i am new to Linq A: You should also check : Full aricle : SQL to LINQ ( Visual Representation ) from e in employee where e.employeeid=10 group e by e.Salary into grp select new { Salary = grp.Key, Count = grp.Count() }; A: Your query puzzles me from the functional perspective: You want to count the number of different salaries for one employee? Anyway, i think something like this would do also work (untested) db.Employees.Where(e=>e.id == 10).Select(s=>s.salary).Distinct().Count()
{ "language": "en", "url": "https://stackoverflow.com/questions/7579530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Prevent Multiple entries stored in database? Consider am using java , struts, hibernate and oracle. How can i prevent duplicate entries stored in database. One way is to make field as Unique . For example i am entering country "USA" in jsp page,USA is already available means how can i prevent it. Please let me know. Regards, sara A: You should always indeed put a unique constraint on fields which must stay unique. This will, however, lead to a cryptic exception at commit time. If you want to be more user-friendly, you should check if the entry already exists (using a query) before inserting it, and display a useful and readable error message to the user if the entry already exists. This still allows two concurrent users to check at the same time, then insert at the same time, but it greatly reduces the probability, and the unique constraint makes sure that one of the commits will fail, leaving your database in a consistent state. A: Query your database whether it already contains USA or not. If it does, then don't store it. If not, then do. A: Add a unique index to your database table on the country column. Additionally you can annotate the country attribute of your hibernate object with @Column(unique=true).
{ "language": "en", "url": "https://stackoverflow.com/questions/7579532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebClient DownloadFileAsync Illegal characters in path I am using WebClient.DownloadFileAsync to download files asynchronously to my machine. Occasionally, I end up with URLs which has a double quote on it. For example, see this: http://upload.wikimedia.org/wikipedia/en/d/d3/"Baby"_Palace_Hotel_1906.jpg. DownloadFileAsync throws an "Illegal characters in path" exception when the file name contains double quotes. I am unable to decode the url either since DownloadFileAsync does not accept string as a parameter but only Uri. What would be a good way to handle this situation? A: Weird, the follownig works fine for me: class Program { static void Main() { using (var client = new WebClient()) { client.DownloadFileCompleted += (sender, e) => { Console.WriteLine("finished"); }; client.DownloadFileAsync(new Uri("http://upload.wikimedia.org/wikipedia/en/d/d3/\"Baby\"_Palace_Hotel_1906.jpg"), "test.jpg"); Console.ReadLine(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7579537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Catching MySQL errors I have a very simple development. I was using Pear DB to error catch a query with something along the lines of if(DB::isError($create)) die($create->getMessage()); I'm wondering if there is something similar in mysql? A: Pear DB is Database Abstraction Layer which works with MySQL. MySQL: $res = mysql_query($query); if(mysql_error()) { die('error!:' . mysql_error() ); } A: $res = mysql_query($query) or die(mysql_error());
{ "language": "en", "url": "https://stackoverflow.com/questions/7579538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How create a views showing sponsored user profile field I created a profile field called Sponsor name, who sponsor or introduce him into the website. The sponsor must be a user in the website. A user can sponsor any number of users to the website. When a user wants to register, he must give the sponsor name. I have done it successfully. Now I want to create a view showing a list of sponsored users corresponding to each user. for example: User James sponsor's * *Williams *Perter *John User Williams sponsor's * *Adam *Jimmy Thanks in advance. A: If you want a single page per user, then what you would want to do is to add an argument to your view. Where the argument would be the field you created for the sponsors name, and then in the settings for that argument, you would get the user id or username from the URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7579540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why exec('java -jar file.jar') dont work on browser I am about to go insane. for hours, trying the same and does not work I have the following code: <?php exec('java -jar /home/user/classname.jar --some arguments',$output,$result); works if I run from the command line, but if you get on my server and I try to run just does not work, I have tried with other command and work perfectly as "java -version", ls, mkdir, chmod, cp, date, etc A: the problem is the architecture of the OS, the. jar was compiled in Windows 7 64Bits with 1.6_26 32-bit and the server has Linux x86_64. i compile again .jar files and work fine. "write once, run anywhere." ...of course
{ "language": "en", "url": "https://stackoverflow.com/questions/7579546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }