text
stringlengths
8
267k
meta
dict
Q: Why doesn't my UITextField, created by code, work inside my tableview Cell? I want two cells to log in (User and password). So I run the app, everything is ok but when I click in the UITextField "playerTextField" the program received this signal: "EXC_BAD_ACCESS". :( Do u know why? I've tried and read a lot of different ways and it's like this one how I'am closer to get it. My code: To disappear the keyboard if the button Next/Done is pushed. - (BOOL) textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; } My UITextFields inside the cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *kCellIdentifier = @"kCellIdentifier"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease]; cell.accessoryType = UITableViewCellAccessoryNone; if ([indexPath section] == 0) { playerTextField = [[UITextField alloc] initWithFrame:CGRectMake(110, 10, 185, 30)]; playerTextField.adjustsFontSizeToFitWidth = YES; playerTextField.textColor = [UIColor blackColor]; if ([indexPath row] == 0) { playerTextField.placeholder = @"ejemplo@gmail.com"; playerTextField.keyboardType = UIKeyboardTypeEmailAddress; playerTextField.returnKeyType = UIReturnKeyNext; playerTextField.delegate = self; } else { playerTextField.placeholder = @"Requerida"; playerTextField.keyboardType = UIKeyboardTypeDefault; playerTextField.returnKeyType = UIReturnKeyDone; playerTextField.secureTextEntry = YES; playerTextField.delegate = self; } playerTextField.backgroundColor = [UIColor whiteColor]; playerTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support playerTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support playerTextField.textAlignment = UITextAlignmentLeft; playerTextField.tag = 0; playerTextField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right [playerTextField setEnabled: YES]; //cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:20.0]; cell.textLabel.font = [UIFont fontWithName:@"Futura" size:16.0]; cell.textLabel.textColor = [UIColor darkGrayColor]; cell.textLabel.shadowOffset = CGSizeMake(0.5, 0.5); cell.textLabel.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:10]; [cell.contentView addSubview:playerTextField]; //[playerTextField release]; } } if ([indexPath section] == 0) { // Email & Password Section if ([indexPath row] == 0) { // Email cell.textLabel.text = @"Email"; } else { cell.textLabel.text = @"Contraseña"; } } else { // Login button section cell.textLabel.text = @"Log in"; } return cell; } A: "EXC_BAD_ACCESS" errors occur when you try to access an object which has been deallocated. This means, somewhere, the last retained reference to your UITextField is released. I don't see anything in the visible code which would cause such a problem. * *alloc -- retain 1 *addSubView -- retain 2 *release (you should probably add this back in) -- retain 1 Instruments should help you figure out where the problem occurs. There is an instruments called 'Zombies' which is designed for exactly this purpose. When you reach a EXC_BAD_ACCESS it will show you every place in your code where that object was retained and released. From there you can figure out where you released too many times (or maybe forgot to retain it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7514848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert Unicode Code into SQL I am creating a dictionary table in sqlserver. I have the unicode codes \u0C2D\u0C3E\u0C37 to insert. How to encode them when inserting into sqlserver to show international character. I am using NCHAR as the datatype for that particular column. Thanks K A: As nonnb commented, you can probably just use Unicode literal syntax in your INSERT statements. If for some reason you are unable to use the Unicode literal syntax and must encode a specific code point, use the NCHAR() function. The following example shows both: -- create temp table for this example create table #TestDictionary ( [Key] nchar(10), Value nvarchar(100) ) -- insert dictionary entries for the 3 specific code points mentioned insert into #TestDictionary ([Key],Value) values (nchar(0x0C2D), 'TELUGU LETTER BHA') insert into #TestDictionary ([Key],Value) values (nchar(0x0C3E), 'TELUGU VOWEL SIGN AA') insert into #TestDictionary ([Key],Value) values (nchar(0x0C37), 'TELUGU LETTER SSA') -- If your keyboard allows you to type it into the script directly then it -- is probably easiest to just use unicode literal syntax. insert into #TestDictionary ([Key],Value) values (N'క ', 'TELUGU LETTER KA') -- Non-unicode string literals can also be inserted into NCHAR/NVARCHAR columns insert into #TestDictionary ([Key],Value) values ('A', 'LATIN CAPITAL LETTER A') select * from #TestDictionary Reference and examples for NCHAR() can be found at http://msdn.microsoft.com/en-us/library/ms182673.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7514855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to return JSON from the ruby on rails getting started example I am following this really great tutorial. Now I would like to get the comments for a specific posting as JSON output. Doing this for the posting is easy because it is just to call the .json. But how does it work with the comments? A: So this is mostly sans-code, but the ideas should at least set you in the right direction. To provide comments with their own route, first set up a route for comments in your routes.rb file, then create a show method in the comments controller (similar to the way you set it up for a posting). In the comments controller show method, just render the comment the same way you do for the posting. It is a bit easier to just include comments along with the posting when requesting the json output. In the posts controller show method, use render :json => @posting.to_json(:include => :comment) (substitute @posting for the name of the Post object you find in the show method).
{ "language": "en", "url": "https://stackoverflow.com/questions/7514856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Looking for regex to split on the string on upper case basis Looking for regex solution for following scenaio: I have strings, which i have to split on the upper case basis but consecutive uppercase parts should not get split. For example : if the input is DisclosureOfComparativeInformation O/p should be Disclosure Of Comparative Information But consecutive uppercase should not get split. GAAP should not result in G A A P. How to find the particular pattern and insert space? Thanx A: Try - var subjectString = "DisclosureOfComparativeInformation"; var resultString = Regex.Replace(subjectString, "([a-z])([A-Z])", "$1 $2"); A: Try this regex: [a-z](?=[A-Z]) With this call to replace: regex.Replace(toMatch, "$& ") For more information on the special replacement symbol "$&", see http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx#EntireMatch A: [A-Z]{1}[a-z]+ will split as follows if replaced with match + space DisclosureOfComparativeInformation -> Disclosure Of Comparative Information GAPS -> GAPS SOmething -> SOmething This one may be undesirable alllower -> alllower A: ((?<=[a-z])[A-Z]|[A-Z](?=[a-z])) replace with " $1" In a second step you'd have to trim the string. check out this link also...... Regular expression, split string by capital letter but ignore TLA A: Using regex solutions to look for strings where something is not true tends to become unrecognizable. I'd recommend you go through your string in a loop and split it accordingly without using regexp. A: In Perl this should work: str =~ s/([A-Z][a-z])/ \1/g; The parenthesis around the two character sets save the match for the "\1" (number one) later. A: Split and Join: string.Join(" ", Regex.Split("DisclosureOfComparativeInformation", @"([A-Z][a-z]*)"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7514861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Need some recommendations for WSDL namespace practices to cope with changing company names? As someone who has worked for a company that has changed it's name (and hence domain name) at least three times over the last few years, the practice of namespacing our java code with com.[company].[product].[function] etc has meant frequent refactoring (or just living with odd looking java namespaces). However, we're now publishing WSDL services as well, and they are also namespaced in a similar way. Here, the impact of a domain/company change is much more serious, as we can't change the namespace on a whim. What are some recommendations for namespacing our services? A: Use simple URNs ... ... like urn:OrderService, urn:BookSearchingService, urn:TradingService etc, something that signals what the service is doing. Your company (whatever its name is today) offers such a service (e.g. book searching), and that should be enough (don't stamp the company names all over the place). Adding company name or project name to a public namespace can cause problems such as the one you mention. Sometimes you can refactor and change the names sometimes you can't. In case of a Web Service you will break your clients if you refactor because messages comming from the old clients will not validate against the new namespace. You will have clients on the new namespace and clients on the old one. Repeat this a couple of times and it becomes frustrating remembering which is on what version of the thing... Project name is also problematic. What happens if the company uses a name which is a trademark of another company which sues you and then the law says you can no longer use the name? You have to change the name and in this case you are forced to refactor and make all your clients upgrade to the new namespace. This is not good for business... you loose face. For this reason, use a namespace that identifies what the web service is offering as operations. A: The internets are full of java code with packages that exhibit that old principle: "Ontology recapitulates phylogeny." In other words, they have package names that reflect ancient corporate history. Your goal here is confict-avoidance, first, and marketing second. So, I'd suggest that you register a domain name that is not the company name but is more or less descriptive of the code, and use it. Then, when the inevitable bigger fish comes along, the names are unperturbed. The urn: suggestion is neither here nor there. If someone runs a code generator, whatever URI you use is going to be mapped to a Java package name or a C# name or whatever, and if that collides with some other name, it will be, of course, "the death of the internet as we know it."
{ "language": "en", "url": "https://stackoverflow.com/questions/7514863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Introduce dummy row in a sybase query I need to introduce a dummy row if my query 1 fails to fetch result. select column1,column2,... from <ActualTable> Where condition='abc'... (1) Union select "dummy col1","dummy col2"..... from <dummy table> where col1 NOT IN (select column1 from <ActualTable> where condition = 'abc'..) (2) With the above query if query 1 fetches result query 2 wont. If query 1 has no result then i would get a dummy row. Is there any other way to achieve the same result in Sybase? A: Temp table if the "ActualTable" gives >1 row select column1,column2,... INTO #temp from <ActualTable> Where condition='abc'... (1) IF @@ROWCOUNT = 0 select "dummy col1","dummy col2"..... INTO #tmp from <dummy table> -- #temp will exist now INSERT #temp select column1,column2,... from <AnotherTable> Where condition='abc'... (1) IF @@ROWCOUNT = 0 INSERT #temp select "dummy col1","dummy col2"..... from <dummy table> ... SELECT * FROM #tmp A: Try this: select top 1 * from ( select 0,column1,column2,... from <ActualTable> Where condition='abc'... (1) Union select 1,"dummy col1","dummy col2"..... from <dummy table> order by 1 ) If first query is successful, you will get it, if not, then the second will be returned
{ "language": "en", "url": "https://stackoverflow.com/questions/7514867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check if a particular sheet is the activesheet How to check if particular sheet is an active sheet or not? I want particular functionality to be used for worksheet having name Data. I can check if Data sheet exists or not using following code Dim ws As Worksheet Set ws = Wb.Sheets("Data") If ws Is Nothing Then Else But how to check if Data sheet is an active sheet or not ? is there any thing like If ws Is Activesheet Then UPDATE: I have added following code in the one of the Class module of addin. What i am trying to do is to manage other excel sheets from this addin. I want to call procedure paste_cells if the the active sheet is having name "Data". Public WithEvents App As Application Private Sub App_WorkbookActivate(ByVal Wb As Workbook) MsgBox "Activate" Dim ws As Worksheet Set ws = Wb.Sheets("Data") If ws Is ActiveSheet Then ' if active sheet is having name Data App.OnKey "^v", Procedure:="Paste_cell" 'paste cell is procedure i want to add when active sheet is Data Else App.OnKey "^v" End If End Sub A: You can also check objects (we never know if the user has opened a workbook where the sheet has the same name): Sub test() On Error Resume Next If ActiveWorkbook.Worksheets("Data") Is ActiveSheet Then MsgBox ("ok") On Error GoTo 0 End Sub See MSDN Thanks to brettdj for the reminder about the error handling. [EDIT] Within your code: Public WithEvents App As Application Private Sub App_WorkbookActivate(ByVal Wb As Workbook) MsgBox "Activate" Dim ws As Worksheet On Error Resume Next Set ws = Wb.Sheets("Data") On Error GoTo 0 If Not ws Is Nothing and ws Is ActiveSheet Then ' if active sheet is having name Data App.OnKey "^v", Procedure:="Paste_cell" 'paste cell is procedure i want to add when active sheet is Data Else App.OnKey "^v" End If End Sub A: you should * *use error handling as the sheet may not exist *For an addin you would normally use ActiveWorkbook,ie Dim ws As Worksheet On Error Resume Next Set ws = ActiveWorkbook.Sheets("Data") On Error GoTo 0 If ws Is Nothing Then MsgBox "Data sheet not found" Else If ws.Name = ActiveWorkbook.ActiveSheet.Name Then MsgBox "Data sheet found and is active" Else MsgBox "Data sheet found but is inactive" End If End If A: I would use: If Wb.ActiveSheet.Name = ws.Name Then End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7514868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: document.body.scrollLeft does not trigger as expected in Safari on OSX Lion Safari does not update the document.body.scrollLeft when sliding a finger on Apples magic mouse or on the touchpad. It only triggers when releasing the finger. Try following example in Safari under OSX Lion. It updates as expected in other browsers but works like the swiping on iOS in Safari Lion (seems to triggers on "touchend"). Dragging the scrollbar makes it behave as expected. Scrolling forth and back with the touchpad or Apples magic mouse makes it behave weird. Demo Fiddle It can be solvable by moving the content into a container with width: 100%; height: 100%; overflow-left: scroll; but my problem is that need to get it from the body. Any ideas? A: It seems like Apple has fixed this now, since it now suddenly works for me without changing anything.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect some URLs to https while keeping the rest http As my site links are relative, i'm finding when i am in a https URL the rest of links become https. So i want to use mod_rewrite to force redirect some URIs to https while keeping the rest of the website http. I need something like: 'Redirect actual url to http BUT If is contact.php then https, If is account then https, etc...'. Maybe someone can help me with this matter. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7514872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove programmatically the security protection of a copied file in network directory? i have a file in a network directory and this file it's been previously copied, and i want to operate with this file. But, in Windows Xp, the file have this security protection / block: (sorry it's in italian) I want to programmatically remove this security protection in C#. Thanks in advance! M. A: Open this file for write yourfile.exe:Zone.Identifier and close it, so it gets emptyed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AddThis buttons wont update to include fragment (#Hash Tag) I have these AddThis buttons on my website, and my site uses JS to take a user though an image gallery, when changing an image the URL is updated with the image title in the fragment element, the problem I have is this is not being reflected in the AddThis links. I've tried to get some answers from the AddThis forums, but was pointed at the api documentation and the addthis.toolbox() function, but it doesn't seem to be working out for me, so I thought I'd run it past the experts here. This is my AddThis code on the basic page. <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style addthis_32x32_style"> <a class="addthis_button_preferred_1 add_this_but"></a> <a class="addthis_button_preferred_2 add_this_but"></a> <a class="addthis_button_preferred_3 add_this_but"></a> <a class="addthis_button_preferred_4 add_this_but"></a> <a class="addthis_button_compact add_this_but"></a> <a class="addthis_counter addthis_bubble_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":false};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4e77111e2de880eb"></script> <!-- AddThis Button END --> In my JS script when a user changes the image, I have added this to the function. addthis.toolbox(".addthis_toolbox"); I've also tried this addthis.toolbox(); When running the code, I get no JS errors, but I dont see any updates to the AddThis buttons. you can see the problem here. http://www.martynazoltaszek.com/artpages?nid=30#Rendezvouz This link will open up the site on a particular image called "Rendezvouz" but the nid=30 is actually a differnet image called "Walking by".The problem is shown by AddThis (Facebook) will always link to the Walking by" image. AddThis Gmail appears to be ok, but I dont think this is a factor of the API, as it works with or without the above function call. Thanks in advance. p.s. The reason for using a ?nid GET variable and a Fragment are due to php page load and JS viewing(without page refersh), but this also leaves support for a non JS browser. A: I had a similar issue whilst using hashbangs for a javascript driven site. This code was used because the share buttons wouldn't re-render when content is loaded async. You should be able to take parts of this to fit to your situation. Maybe just the addthis.update() code First I changed the script for addThis to async http://s7.addthis.com/js/250/addthis_widget.js#async=1 Once the DOM has loaded, listen for hashchanges, this is where we will update the addthis share details. You may require additional plugins for this bit to work with older browsers, consider jQuery hashchange event - v1.3 - 7/21/2010 - http://benalman.com/projects/jquery-hashchange-plugin/ Now its all wired up for a hashchange, the next step is to alter addThis. $(function(){ $(window).hashchange(function(){ if($('body').hasClass('addThis')){ addthis.ost = 0; addthis.update('share', 'url', window.location.href); // new url addthis.update('share', 'title', window.document.title); // new title. addthis.ready(); // this will re-render the buttons. } else { addthis.init(); $('body').addClass('addThis'); } }); addthis.init() //As we've changed the addthis to async, you will have to call addthis.init() once the DOM has loaded. }); Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python WMI _wmireg - retrieving values I am trying to retrieve the values inside the Registry Object retrieved using python WMI. import _winreg import wmi c = wmi.WMI(computer="10.31.247.8", user="devuser", password="devpass1!",namespace="root/default").StdRegProv result, names = c.EnumKey ( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName="SYSTEM\ControlSet001\Services\MRxDAV" ) for item in names: print item Output: EncryptedDirectories Parameters Security Enum I want to retrieve the value of the string "ImagePath" present inside the directory HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\MRxDAV. The part I want to retrieve is provided in the image below: A: You need to use the GetStringValue() method instead of EnumKey(): import _winreg import wmi c = wmi.WMI(computer="10.31.247.8", user="devuser", password="devpass1!",namespace="root/default").StdRegProv result, imagePath = c.GetStringValue ( hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName="SYSTEM\ControlSet001\Services\MRxDAV", sValueName="ImagePath" ) print imagePath A: def get_reg(self): # https://msdn.microsoft.com/en-us/library/windows/desktop/aa384911(v=vs.85).aspx HKEY_CLASSES_ROOT = 2147483648 HKEY_CURRENT_USER = 2147483649 HKEY_LOCAL_MACHINE = 2147483650 HKEY_USERS = 2147483651 HKEY_CURRENT_CONFIG = 2147483653 KEY_QUERY_VALUE = 1 # Required to query the values of a registry key. KEY_SET_VALUE = 2 # Required to create, delete, or set a registry value. KEY_DEFAULT_VALUE = 3 # KEY_QUERY_VALUE | KEY_SET_VALUE Default value, allows querying, creating, deleting, or setting a registry value. KEY_CREATE_SUB_KEY = 4 # Required to create a subkey of a registry key. KEY_ENUMERATE_SUB_KEYS = 8 # Required to enumerate the subkeys of a registry key. KEY_NOTIFY = 16 # Required to request change notifications for a registry key or for subkeys of a registry key. KEY_CREATE = 32 # Required to create a registry key. DELETE = 65536 # Required to delete a registry key. READ_CONTROL = 131072 # Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values. WRITE_DAC = 262144 # Required to modify the DACL in the object's security descriptor. WRITE_OWNER = 524288 # Required to change the owner in the object's security descriptor. #c = wmi.WMI(computer="XXX.XXX.XXX.XXX", user="devuser",password="devpass1!",namespace="root/default").StdRegProv c = wmi.WMI(find_classes=False,namespace="default",computer=self.computer).StdRegProv print "Methods: " print str(c) try: subkey = r"SYSTEM\CurrentControlSet\Services\LanmanWorkstations" name = "EnablePlainTextPassword" result, grants = c.CheckAccess(hDefKey = HKEY_LOCAL_MACHINE, sSubKeyName=subkey, uRequired=KEY_DEFAULT_VALUE); print "Access : " + str(grants) #result, value = c.GetStringValue(hDefKey=_winreg.HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=name) #print "HKEY_LOCAL_MACHINE " + str(HKEY_LOCAL_MACHINE) #err, sids = c.EnumKey (hDefKey=2147483650, sSubKeyName=subkey) #for sid in sids: # print sid # https://msdn.microsoft.com/en-us/library/windows/desktop/aa390461(v=vs.85).aspx name = "OtherDomains" subkey = r"SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" err, names, types = c.EnumValues (hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey) for i in range(len(names)): if types[i] == REG_SZ: tipo = "Data Type: String" result, value = c.GetStringValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) elif types[i] == REG_EXPAND_SZ: tipo = "Data Type: Expanded String" result, value = c.GetExpandedStringValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) elif types[i] == REG_BINARY: tipo = "Data Type: Binary" result, value = c.GetBinaryValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) elif types[i] == REG_DWORD: tipo = "Data Type: DWORD" # 32 Bits result, value = c.GetDWORDValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) # 64 Bits #result, value = c.GetQWORDValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) elif types[i] == REG_MULTI_SZ: tipo = "Data Type: Multi String" result, value = c.GetMultiStringValue(hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=subkey, sValueName=names[i]) print names[i] + " = " + tipo + " " + str(value) except Exception as e: print "Erro: ", str(e)
{ "language": "en", "url": "https://stackoverflow.com/questions/7514879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding iOS support to an existing Titanium App I have a titanium mobile project and I had just selected "Android" in the deployment target at the time of creating it. I would now like to add iOS target as well. Is it possible to add it to an existing project or will I have to create a new one? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7514880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Loading jQuery asynchronously in IE causes error - but $.ajax() still runs Scenario: I have some JS code, I want to detect if jQuery exists in the DOM already, if not add it: if (typeof jQuery != 'function') { var sc = document.createElement('script'); sc.type = 'text/javascript'; sc.async = true; sc.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"; sc.onload = function() { App.getTrackers(); }; sc.onreadystatechange = function() { App.getTrackers(); }; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s); } else { App.getTrackers(); } App = { getTrackers: function() { $.ajax({url: "/ajax.php", success: function(data) { console.log(data) }}); } } The onload() is for FF+Webkit; onReadyStateChange() is for IE The issue is with IE, I'm getting this error: '$' is undefined Yet! IE's console returns the contents of ajax.php. So the jQuery function has been executed... somehow. Even though $ was undefined... Does $ not yet exist? Has it yet to be compiled even though the script has been downloaded? A: The ready state has other values than complete, so the event will be triggered at different stages until the code is loaded and completed. Check what the state is in the event handler: sc.onreadystatechange = function() { if (sc.readyState === 'complete') { App.getTrackers(); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/7514882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does CLOS is a weakness in Common Lisp? What I want to mean is if CLOS is a bad practice to the Lisp functional programming way? A: Common Lisp is not a "functional programming" language, it is a "multi-paradigm" programmable programming language. CLOS is less of a bar to readable code than the PROG special form is. Both are useful, in their niches. Hopefully the niche of CLOS is larger than that of PROG.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Select random 3000 lines from a file with awk codes I want to select randomly 3000 lines from a sample.file which contains 8000 lines. I will do that with awk codes or do from command line. How can I do that? A: awk 'BEGIN{srand();} {a[NR]=$0} END{for(i=1; i<=3000; i++){x=int(rand()*NR) + 1; print a[x];}}' yourFile A: Fixed as per Glenn's comment: awk 'BEGIN { a=8000; l=3000 srand(); nr[x] while (length(nr) <= l) nr[int(rand() * a) + 1] } NR in nr ' infile P.S. Passing an array to the length built-in function is not portable, you've been warned :) A: You can use a combination of awk, sort, head/tail and sed to do this, such as with: pax$ seq 1 100 | awk ' ...$ BEGIN {srand()} ...$ {print rand() " " $0} ...$ ' | sort | head -5 | sed 's/[^ ]* //' 57 25 80 51 72 which, as you can see, selects five random lines from the one hundred generated in seq 1 100. The awk trick prefixes each and every line in the file with a random number and space of the format "0.237788 ", then sort (obviously) sorts it based on that random number. Then you use head (or tail if you don't have a head) to get the first (or last) N lines. Finally, the sed will strip off the random number and space and the start of each line. For your specific case, you could use something like (on one line): awk 'BEGIN {srand()} {print rand() " " $0}' file8000.txt | sort | tail -3000 | sed 's/[^ ]* //' >file3000.txt A: If you have gnu sort, it's easy: sort -R FILE | head -n3000 If you have gnu shuf, it's even easier: shuf -n3000 FILE A: I used these commands, and got what I wanted: awk 'BEGIN {srand()} {print rand() " " $0}' examples/data_text.txt | sort -n | tail -n 80 | awk '{printf "%1d %s %s\n",$2, $3, $4}' > examples/crossval.txt which in fact randomly selects 80 lines from the input file. A: In PowerShell: Get-Content myfile | Get-Random -Count 3000 or shorter: gc myfile | random -c 3000 A: In case you only need approximately 3000 lines, this is an easy method: awk -v N=`cat FILE | wc -l` 'rand()<3000/N' FILE The part between the backticks (`) gives the number of lines in the file. A: For a huge file that I didn't want to shuffle, this worked out well and pretty fast: sed -u -n 'l1p;l2p; ... ;l1000p;l1000q' The -u option reduces buffering, and l1, l2, ... l1000 are random and sorted line numbers obtained from R (would be just as good with python or perl).
{ "language": "en", "url": "https://stackoverflow.com/questions/7514896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to add array of object to the list I have an array of object like A[] a; I also have a list of A like List<A> b = new ArrayList<A>(); I am wondering how to add a to b? A: Just use the addAll() method with Arrays.asList() as argument: b.addAll(Arrays.asList(a)); A: Try: b.addAll(Arrays.asList(a)); A: Iterate the array and add each element for( A element : a ) { b.add( element ) } A: Assuming you are adding the contents of a to b, you would want to use Collections.addAll(b, a); A: list.addAll(Arrays.asList()); For example : b.addAll(Arrays.asList("Larry", "Moe", "Curly")); A: List<A> b = new ArrayList<A>(); b.addAll(Arrays.asList(a));
{ "language": "en", "url": "https://stackoverflow.com/questions/7514899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error using QueryExtender with an EntityDataSource - 'FirstName' is not a member of type 'System.Data.Common.DbDatRecord' The following GridView with an EntityDataSource that grabs 3 fields from the Surveyors table (which contains more fields) works, but of course it shows me every Surveyor. <asp:GridView ID="gvwSurveyors" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" DataSourceID="edsSurveyors"> <Columns> <asp:BoundField DataField="FirstName" HeaderText="FirstName" ReadOnly="True" SortExpression="FirstName" /> <asp:BoundField DataField="LastName" HeaderText="LastName" ReadOnly="True" SortExpression="LastName" /> <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" /> </Columns> </asp:GridView> <asp:EntityDataSource ID="edsSurveyors" runat="server" ConnectionString="name=PLSOEntities" DefaultContainerName="PLSOEntities" EnableFlattening="False" EntitySetName="Surveyors" Select="it.[FirstName], it.[LastName], it.[ID]" AutoGenerateOrderByClause="true"> <OrderByParameters> <asp:Parameter DefaultValue="LastName" /> </OrderByParameters> </asp:EntityDataSource> So in order to get the initial page load to not show everything I added the OnSelecting event to the EntityDataSource and have it cancel the query if it is Not a postback. protected void edsSurveyors_Selecting(object sender, EntityDataSourceSelectingEventArgs e) { if (!Page.IsPostBack) e.Cancel = true; } I have two text boxes named txtFirstName and txtLastName that I want the user to be able to search using a SQL query LIKE style. Some reading on the web pointed me toward the QueryExtender. I changed the code to the following: <asp:GridView ID="gvwSurveyors" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" DataSourceID="edsSurveyors"> <Columns> <asp:BoundField DataField="FirstName" HeaderText="FirstName" ReadOnly="True" SortExpression="FirstName" /> <asp:BoundField DataField="LastName" HeaderText="LastName" ReadOnly="True" SortExpression="LastName" /> <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" /> </Columns> </asp:GridView> <asp:EntityDataSource ID="edsSurveyors" runat="server" ConnectionString="name=PLSOEntities" DefaultContainerName="PLSOEntities" EnableFlattening="False" EntitySetName="Surveyors" Select="it.[FirstName], it.[LastName], it.[ID]" AutoGenerateOrderByClause="true" onselecting="edsSurveyors_Selecting"> <OrderByParameters> <asp:Parameter DefaultValue="LastName" /> </OrderByParameters> </asp:EntityDataSource> <asp:QueryExtender ID="qexSurveyor" runat="server" TargetControlID="edsSurveyors"> <asp:SearchExpression SearchType="Contains" DataFields="FirstName"> <asp:ControlParameter ControlID="txtFirstName" /> </asp:SearchExpression> </asp:QueryExtender> So now when I click the button I get the error: 'FirstName' is not a member of type 'System.Data.Common.DbDataRecord' What can I do to allow a Contains? Once it works, I will then added a LastName parameter that does the same. A: I also ran into the same thing when using AdventureWorks as a data source. I had to remove the 'Select=' from my EntityDataSource. For a workaround, I went to my GridView and set AutoGenerateColumns="False". I then manually added each column I wanted to display in the Gridview, e.g. <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" /> <asp:BoundField DataField="SalesPerson" HeaderText="Sales Person" /> <asp:BoundField DataField="CustomerID" HeaderText="Customer ID" /> <asp:BoundField DataField="FirstName" HeaderText="First Name" /> <asp:BoundField DataField="LastName" HeaderText="Last Name" /> <asp:BoundField DataField="CompanyName" HeaderText="Company Name" /> <asp:BoundField DataField="EmailAddress" HeaderText="Email Address" /> <asp:BoundField DataField="Phone" HeaderText="Phone" /> As an additional note, it seems another workaround, albeit programatically, is to apply a LINQ Query to the EntityDataSource using the onquerycreated event. In this case, you don't need to declaratively use the Query Extender supposedly. Full Article Here -> http://msdn.microsoft.com/en-us/library/ee404748.aspx A: I'm currently running into the same issue, I have found so far that if I remove the 'Select=' from the EntityDataSource it works. Apperently you are forced to select all when using the QueryExtender. However, I don't want to return every field in the table and I haven't found a way around this yet. So, does anybody have a workaround?
{ "language": "en", "url": "https://stackoverflow.com/questions/7514902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simplemodal doesn't reopen if I close it in the same event I'm trying to open another simplemodal from a button click event of first simplemodal dialog. Here is what I am trying to do. Below button belongs to the first simple modal. $(".someBtn").click(function () { $.modal.close(); renderSomeContent(); }); function renderSomeContent(){ $("#popupDiv").html(markup); $("#popupDiv").modal(); } Even first simplemodal is also displayed in the same div (popupDiv) which I'm using for the second modal dialog. If I dont close the first modal in button click event it works fine but the modal position, width and height remains same as per the first modal content. This is the reason I want to close it and reopen it so that it adjusts as per the second modal content. Can anybody tell me where I'm doing wrong? A: I couldn't find the solution but I found a workaround to fix the reloading resizing issue. As I mentioned above, if I don't close the current simplemodal and update the content of that simplemodal with some other content and when I call $("#popupDiv").modal() it maintains the height and position of the first simplemodal dialog. Once I fill the modal content I'll get the height and width of the content and update the simplemodal. Below is what I did: $("#popupDiv").html(markup); $.modal.update($("#popupDiv").height(), $("#popupDiv").width()) That's it I don't have to close the simplemodal and just update it with the new dimensions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ant: Converting a path into separate properties I have a folder containing several jar files which should all go to a classpath: <path id="my.classpath"> <fileset dir="/tmp/mylibs" includes="*.jar" /> </path> Now I would like to be able to reference all these jar files as a seperate property, e.g. if I have two jar files foo.jar and bar.jar then I would like to be able to reference them like ${foo.jar} (== /tmp/mylibs/foo.jar) ${bar.jar} (== /tmp/mylibs/bar.jar) Is that somehow possible in Ant? Thanks, Peter A: With help of ant-contrib you can try this: <target name="test"> <ac:for param="file"> <fileset dir="/tmp/mylibs" includes="*.jar"/> <sequential> <antcall target="setImpl"> <param name="file" value="@{file}"/> </antcall> <echo>param: @{file}</echo> </sequential> </ac:for> </target> <target name="setImpl"> <property name="filename" value="${file}" /> <echo>property: ${filename}</echo> </target> For overriding property value (if you need) purpose you can also use ant-contrib A: Ivy has a artifactproperty task which is designed to do this for you. The only catch to this solution is that it assumes you're using ivy to resolve your dependencies and manage your classpath. A: An easy way to get the entire classpath into a single property: <path id="my.classpath"> <fileset dir="/tmp/mylibs" includes="*.jar" /> </path> <property name="classpath.property" refid="my.classpath"/> <echo message="Classpath = &quot;${classpath.property}&quot;"/> I believe this will work in an Eclipse .classpath file. I don't have one in front of me right now. If you have to manipulate it, you can do that via the <concat> task with the filterchains.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to sort(arrange) tables of entity framework database model in Visual studio? I want to sort tables of entity framework database model in visual studio 2008. But I can't find how to accomplish that. But it's possible to "arrange tables" in sql server diagrams for making table relationships more clear. Does visual studio have the functionality(menu or shortcut etc) for that? Edit: Finally I've managed to finish this manually. And I've not found answers on the internet for solving it automatically in visual studio. Tips for relationships between tables: You just put your cursor over the boundary of the link and a table when you want move the "relation" between two tables. You can move the relation as it shows a black diamond icon(not white diamond icon). A: In Visual Studio 2012 right click on the empty space of your diagram in the designer, select Diagram->Layout Diagram.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: redis list items, TTL and ranking by score I would like to sort blog articles by page hits over the past 5000 views. I was experimenting with the following (200, 205, 202 are id's of the blog articles): ZINCRBY blog_hits 1 200 ZINCRBY blog_hits 1 200 ZINCRBY blog_hits 1 200 ZINCRBY blog_hits 1 205 ZINCRBY blog_hits 1 205 ZINCRBY blog_hits 1 202 ZRANGEBYSCORE blog_hits 0 9 WITHSCORES Which will give me the top ten viewed pages. The only problem is the ZINCRBY doesn't seem to have a TTL or a way of ignoring increments that happen more than 5000 increments ago. Is there a way I could use a list, add an entry of the blog id, then LTRIM the list and get a score? If this is the way could you please write a little example? If not, I'd be keen to see how I could best solve this problem. Thanks, Mark A: Try blog_hits_date, and then summarize the week ZINCRBY "blog_hits_09_24_2011" 1 200 TTL "blog_hits_09_24_2011" 3600*24*7 Or move id with hits > 5000 to another list(*blog_hits_over_5000*).
{ "language": "en", "url": "https://stackoverflow.com/questions/7514909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to open Microsoft Office documents in iPhone I do not want any code but want to get reference that how can we open Microsoft Office documents in our iPhone application. Is there any way to edit this documents in iPhone? I just want to know Is this possible or not? Thanks in advance.. A: You can display MS Office documents using UIWebView but editing is not possible (at least not without major effort). A: Displaying: instead of using UIWebView to display the office document, I found the UIDocumentInteractionController supports more formats than UIWebView(for example: docx) while also provides better performance. Plus it has built in interaction menu that allows you to share this document through Email or other 3rd part apps like dropbox. One example of this controller is the built in Email app, which uses UIDocumentInterActionController to display attached files. Apple's document regards to UIDocumentInterActionController https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html How to use: http://mobile.tutsplus.com/tutorials/iphone/previewing-and-opening-documents-with-uidocumentinteractioncontroller/ Editing: Sorry I can't help you with this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Ajax Post Multiple Variables From Form Firstly apologies if this is really simple but I have spent hours trying and quite a lot of Google searches for the information I believe I need to no avail. Ok. So what I have is a form with 14 inputs that is dynamically filled using a get query. The user can then change the contents of the retrieved information and when complete press submit to update our database. The code I was using was working fine using separate pages and a lightbox setup to update the information however I wanted to integrate the update screen into the main page and use ajax to do the update post so to the user the rest of the page is still visible. At present I have the following for my form: <table border='1'> <form id="Update" onsubmit="return false;"> <tr> <th>Query</th> <th>Result</th> <tr/> <tr> <?php while($row = mysql_fetch_array($result)) { ?> <td>Estimating No:</td><td><input name="ID" id="ID" type="text" value="<?php echo $_GET['q']; ?>" /></br></td> </tr> <tr> <td>Date Received:</td><td><input type="text" name="Date_Received" id="Date_Received" value="<?php echo( htmlspecialchars( $row['Date_Received'] ) ); ?>" /><br/></td> </tr> <tr> <td>X Ref:</td><td><input name="Xref" id="Xref" type="text" value="<?php echo( htmlspecialchars( $row['Xref'] ) ); ?>" /><br/></td> </tr> <tr> <td>Project Name:</td><td><input name="Project_Name" id="Project_Name" type="text" value="<?php echo( htmlspecialchars( $row['Project_Name'] ) ); ?>" /><br/></td> </tr> <tr> <td>Location:</td><td><input name="Location" id="Location" type="text" value="<?php echo( htmlspecialchars( $row['Location'] ) ); ?>" /><br/></td> </tr> <tr> <td>Project Type:</td><td><input name="Project_Type" id="Project_Type" type="text" value="<?php echo( htmlspecialchars( $row['Project_Type'] ) ); ?>" /><br/></td> </tr> <tr> <td>Main Contractor:</td><td><input name="Main_Contractor" id="Main_Contractor" type="text" value="<?php echo( htmlspecialchars( $row['Main_Contractor'] ) ); ?>" /><br/> </td> </tr> <tr> <td>Tender Sum:</td><td><input name="Tender_Sum" id="Tender_Sum" type="text" value="<?php echo( htmlspecialchars( $row['Tender_Sum'] ) ); ?>" /><br/></td> </tr> <tr> <td>Tender Return Date:</td><td><input name="Tender_Return_Date" id="Tender_Return_Date" type="text" value="<?php echo( htmlspecialchars( $row['Tender_Return_Date'] ) ); ?>" /><br/></td> </tr> <tr> <td>Jbsr Return Date:</td><td><input name="Jbsr_Return_Date" id="Jbsr_Return_Date" type="text" value="<?php echo( htmlspecialchars( $row['Jbsr_Return_Date'] ) ); ?>" /><br/></td> </tr> <tr> <td>Contact Name:</td><td><input name="Contact_Name" id="Contact_Name" type="text" value="<?php echo( htmlspecialchars( $row['Contact_Name'] ) ); ?>" /><br/></td> </tr> <tr> <td>Contact Number:</td><td><input name="Contact_Tel" id="Contact_Tel" type="text" value="<?php echo( htmlspecialchars( $row['Contact_Tel'] ) ); ?>" /><br/></td> </tr> <tr> <td>Contact Email:</td><td><input name="Contact_Email" id="Contact_Email" type="text" value="<?php echo( htmlspecialchars( $row['Contact_Email'] ) ); ?>" /><br/></td> </tr> <tr> <td>Project Status:</td><td><input name="Status" id="Status" type="text" value="<?php echo( htmlspecialchars( $row['Status'] ) ); ?>" /><br/></td> </tr> <tr> <td></td><td><input type="submit" onClick="sendUpdate()" /></td> </tr> </form> Now my problem. After a lot of searching I have found a piece of code that seems to work however it will only work with one parameter. As you can see I need to post 14 in one go so it is no good as is. I have tried many combinations to try and get it working but to no avail. The code is: <script> function sendUpdate() { new Ajax.Request("MenuUpdate1.php", { method: 'post', postBody: 'ID='+$F('ID'), onComplete: showResponse }); } function showResponse(req){ $('MenuUpdate').innerHTML= req.responseText; } </script> What I really need to know is how I can adapt the code above to allow me to post the additional 13 input boxes. Any help would be much appreciated and if you need me to clarify anything please ask. Thanks in advance Alan A: Prototype excels at these sorts of operations. For reference see Ajax.Updater and Form.serialize. function sendUpdate() { new Ajax.Updater({success: 'MenuUpdate'}, 'MenuUpdate1.php', { parameters: Form.serialize('Update', true) }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7514911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a Decision Tree Chart I am Using R to create a decision tree but need a web base control that will allow be to plot the tree. I have all of the node info but need to plot. Is there any open source tool that will allow me to do this? I prefer python or a javascript control. Thanks A: Plot your decision tree to a PNG or JPG, save it to a file, serve it via your Webserver. If I remember correctly the code would be something like this: jpeg('rplot.jpg') plot(x,y) dev.off() A: While I was searching for ways to plot graphs with JS, I came across D3. I haven't used it yet, but it looked promising. A: I am using JavaScript InfoVis toolkit that offers support for variety of tree visualizations and beyond. Of course, it means that you'll need a browser to run this but it works pretty well. As for Python, use it to map your tree structure to InfoVis json format for trees.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WCF REST 4.0 ,not accessible I have created a WCF REST web service with no SVC and successfully deployed on IIS7.5 ,Win2008 server box . I can access the service URL http://172.29.132.209:9999/TestService/CheckGet/sdfsds/response.xml from the Server machine ..using both ServerName ,Server Ip or localhost .It works . But when i try this URL on client machine , it does not work I.E says "Internet Explorer cannot display the webpage". What could be the potential isssue .?pls. help A: Could be a number of things. Try it in a proper browser like firefox then stick fiddler up and see what the traffic looks like.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Compare a single image with multiple images in matlab? I would like to compare a single image (probably jpeg formats) with multiple images in matlab and when the images matches with one of the multiple images i would like to output that image file name. A: % the basic image that you are trying to find the_image = imread('compare_image.jpg'); % list of images you are trying to compare to % go through each image end
{ "language": "en", "url": "https://stackoverflow.com/questions/7514918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How does quads get rendered as lines in wireframe mode? People have been telling me that "GPU renders triangles only". But how do you explain GPU rendering a quad with 4 lines only in the wireframe mode, shouldnt it be rendering it with 5 lines since GPU cannot understand quads ? On the other hand, how can i emulate quads in the future where GL_QUADS is banned ? do i need a shader for it, do i need to generate new array of lines for each object and i cant just simply switch from GL_FILL to GL_LINE ? A: Lines are something different than filled primitives. When switching to glPolygonMode(…, GL_LINE) whenever a filled primitive is started (GL_TRIANGLES, GL_QUADS), OpenGL won't sent commands for filled primitives, but lines between the vertices of the filled primitive. So GL_TRIANGLES translates to tupled of 3 GL_LINES, GL_QUADS translates to tuples of 4 GL_LINES. GL_POLYGON is translated to a GL_LINE_LOOP. Of course those translations don't happen in terms of OpenGL, but the OpenGL driver will send commands to the GPU that are equivalent to what would have been sent; also there are some subtle differences between GL_LINE polygon mode and sending actual lines, most notably the evaluation of the edge flag. A: I din't understand your question fully but from what I understood here is the answer. There are 2 concepts 1. Interpolation Used for figuring out which pixels are to be drawn on a line. 2. Rasterization Used for figuring out what properties (colors, texture etc.) to be assigned to the pixels lying inside a triangle. GPU can raster only triangles and interpolate only lines. So when you are in a wireframe model only interpolation of the boundary of polygons is done. But when we are in solid geometry model along with interpolation we also raster the polygon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails with Underscore.js Templates I was trying to use underscore.js templates for templating in a rails 2.3 app which does not have jammit as an asset packager. Here is the simple Template: <script type="text/template" id="q-template"> <div class="current-body"> <span class="q-index"><%= title %></span> <span class-"q-text"><%= body %></span> </div> </script> Rails tries to parse these as erb variables and throws an ArgumentError. How do I get underscore templates to play nicely with rails in this case? Where am I going wrong? A: Use some other delimiters instead of <%= %>. For example, to use mustache-style brackets {{= }} (interpolate) and {{ }} (evaluate), add this somewhere to your javascript: _.templateSettings = { interpolate: /\{\{\=(.+?)\}\}/g, evaluate: /\{\{(.+?)\}\}/g }; A: If you don't want to change the template settings across your entire project... Escape the ERB tags: <%= becomes <%%= <script type="text/template" id="q-template"> <div class="current-body"> <span class="q-index"><%%= title %></span> <span class-"q-text"><%%= body %></span> </div> </script> Note that the closing tag is still %>, not %%>. Side note - I also tried outputting using a heredoc. The following code runs successfully but outputs a bunch of erb source code that gets caught between the heredoc commands. <script type="text/template" id="q-template"> <%= <<-heredoc %> <div class="current-body"> <span class="q-index"><%%= title %></span> <span class-"q-text"><%%= body %></span> </div> heredoc </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7514922", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Dynamically setting div id in JavaScript or jQuery How to set the div id dynamically? Here is my code: <div id="q1"></div> <div id="q2"></div> <div id="q3"></div> <div id="q4"></div> <div id="q5"></div> Now I want to set the q4 div id to q1 something like that in JavaScript. How can I do that in JavaScript or jQuery? I have tried this. document.getElementById("q4").id = "q1"; document.getElementById("q2").id = "q5"; but it is saying that the object is null or undefined. Thanks. chakri. A: Using jquery: set dynamically one by one: var idCount = 1; $('div').each(function() { $(this).attr('id', 'q' + idCount); idCount++; }); to rearrange what you want: $('div#q4').attr('id', 'q1'); $('div#q2').attr('id', 'q5'); A: $('#q1').attr('id', 'q4') it soulde work I think... EDIT: If it still doesnt work try put this before </body>: <script> $(document).ready(function(){ $('#q1').attr('id', 'q4') }); </sript> A: First of all, you are giving the id to an element an id which is already given to some element before, that's not a right thing to do you can't have more than one id in your DOM. Anyway the code would be something like var element = document.getElementById('q4'); element.setAttribute('id', 'q7'); if(document.getElementById('q7').innerHTML = "All is well") alert(document.getElementById('q7').innerHTML); //to check if the new id has been set correctly Fiddle http://jsfiddle.net/kmSHB/ A: Your code is fine, which means that if it's failing, you're probably running the JavaScript before those elements have been defined in the DOM. Try moving the script block to below those elements (e.g., the bottom of the page), or place your code in a DOM load/ready handler. Edit: not sure why this is being down voted, but whatever. If you want to do this in jQuery while waiting for the DOM ready event, this should work: $(function() { $('#q4').attr('id', 'q1'); $('#q2').attr('id', 'q5'); }); Please note that the important part here isn't the fact that setting the id is done in jQuery or vanilla JavaScript - the important part is that we're waiting until the DOM is ready for manipulation. A: Your code works fine. Except that after that you will have 2 divs with the same id. So you will run to problems if you try to get q1 again. A: Try this.. var divid = document.getElementById('q1'); divid.id = 'q5'; A: In JavaScript var yourElement = document.getElementById('originalID'); yourElement.setAttribute('id', 'yourNewID'); In jQuery $('#originalID').attr('id', 'yourNewID'); JSFiddle example A: in jQuery you could do this: $('#q4').attr('id', 'q1'); However, note that that will now leave you with invalid markup, as you can't use the same ID more than once in a document.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Generate audio bell in terminal using Python How can I generate audio bell in xterm type terminal? A: print("\a") # Python 3 or print "\a" # Python 2 See the docs. A: For a simple beep, print "\a". The Control Codes are listed on this page, these are all the characters that should make a terminal perform an action. A: Simple, print the bell character. In Python: print('\a') From bash shell: echo $'\a' Note that on some terminals, the bell can be disabled. In others, the bell can be replaced with a visual bell in the shape of a flashing screen background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: UITextView and data detector types - how to find out that external modal view controller is opened / closed when the link is long tapped? in my specific situation I have an email link in UITextView, so that when user long taps on this link, an Action Sheet provided by iOS is opened, where you can e.g. create new contact with this email address and so on. This action opens another external (provided by iOS) modal view controller similar to Contacts app, but it is opened within our application, on top of current view controller. I'd like to know when my view controller is covered by this external modal view controller and when it becomes visible again, because I need it to control opening / hiding the keyboard (and do some more). Unfortunately I've found no events being fired in this situation, no delegate methods of UITextView, viewWill/DidAppear/Disappear is not called either. I've even tested using my own UIApplication subclass and overriding -(BOOL)openURL:(NSURL *)url method, but it is only called if URL is tapped (like: short tap on http link to open it in Safari, short tap on phone number to call etc.), so it is not called in my situation (creating new contact with email address). So far I have no solution, I'd greatly appreciate any ideas. A: Your view controller should be receiving viewWillDisappear: and viewDidDisappear: and their counterparts. If you receive this shortly after a tap in your text view then it is not unreasonable to assume the user has triggered a system modal view controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Solr lucene and "similar" keywords I'm still a relative newbie with Solr Lucene, and I have noticed an interesting "problem" with a search I performed. If I do a basic search for "responsive", I also get results that contains the word "responsible". I suppose this is OK, but the problem is the result with the keyword I was looking for (responsive) appears BELOW the result that contain the keyword I was NOT looking for! (responsible). Granted, the result with "responsible" has more keyword matches, but the fact remains I did not search for this. I like this alternative word/synonym feature, but is there a setting I should look for to make sure results with the actual search keyword are ranked higher than the alternatives? Many thanks in advance, much appreciated. Seb A: The stemmer you have in the fields seems to be stemming responsive & responsible to the same root. Solr does not out of box rank the actual matches more than the alternatives. If you want the actual search words to be ranked higher than the alternatives, you would need to maintain both stemmed and unstemmed versions of the field, and add more weight to the unstemmed version than the stemmed versions. A: which ranking algorithm is it using? you must modify the ranking algorithm function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mysql order by using search string i have a mysql query like: select * from employee where name like '%ani%' I want my results to be order by starting with ani for eg. my results should be comming as: {anil,anirudha,rani, ...} starting with ani first and then followed by other characters. Can anybody please help me on this. A: Something like select * from employee where name like '%ani%' order by locate('ani', name) asc, name asc Should do the trick ... (sort by position of the substring in the whole string) A: You can possibly use a union to achieve this: select * from employee where name like 'ani%' order by name union select * from employee where name like '%ani%' and not name like 'ani%' order by name A: I am not entirely sure exactly what you are looking for. If you would like to just order the results of that query by name: select * from employee where name like '%ani%' order by name asc; A: select * from employee where name like '%'+'ani'+'%' order by if(SUBSTRING(name, 1, length('ani'))= 'ani', 0,1), name for mssql server repalce if with case when with the syntax provided, is easy to replace 'ani' with any value you want
{ "language": "en", "url": "https://stackoverflow.com/questions/7514933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Business Objects & Ole I can create simple program to connect to BO using another application using ole automation such as: var bob = createObject('BusinessObjects.Application'); bob.visible = true; bob.interactive = true; bob.loginas ('Login', 'pass' ...); var doc = bob.documents'; var zed = doc.open('file.rep'); ... etc. but is it possible to already write the SQL query in the application that connects to the BO universe and extract the data etc... (without having to invoke any already authored rep file)? The thing is I want to be able to completely manipulate BO through the external application. Alternatively if it's not possible, another option may be to connect to a BO universe and perform SQL queries there, is it possible to dispatch an SQL query to a BO universe using something like ODBC connectivity? Thanks A: Have you checked the SimbaEngine ODBC SDK 8.1 ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7514934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unsupported operand type(s) for *: 'NoneType' and 'Decimal' I have a django app that manages VAT. For instance, it can calculate the VAT for all sales from the European Union. vat = purchases[0].vat.vat eu_sales = Sale.objects.filter(country_type='2') eu_amount = (eu_sales.aggregate(price = Sum('amount'))['price']) * vat/100 However, today I copyied my files to another machine. Then I received an error unsupported operand type(s) for *: 'NoneType' and 'Decimal' I realised that I was getting this error because there is no eu_amount value stored yet. In overwords, there is no vale for eu_amount so it cannot multiply to a decimal value. Here is what I have in my template {{eu_amount}} Is there way to filter this template tag? I want to say something like if value the value is None, (or Null) then its 0. A: You could try to use a default value like this. eu_amount = (eu_sales.aggregate(price = Sum('amount'))['price']) or 0 * vat/100 But the cleanest way is probably to test if your Sum returns nothing, then to display some kind of warning message, because this should'nt happen. A: Change the line vat = purchases[0].vat.vat to vat = purchases[0].vat.vat or 0 A: You mean this? {% if item %} something {% else %} something different {% endif %} Taken from https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs I'm nearly sure, I've seen this .vat.vat somewhere lately ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7514943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to turn on logging for AWT I have a performance problem that makes mouse events stack up in a strange way. My profiling tool says that the AWT thread is very occupied all the time. I wonder if there is some smart way (e.g. setting some value in a properties file or something) to make the AWT thread spit out detailed log messages about what it is doing. A: You can use AspectJ to 'annotate' method calls. However it very likely makes more sense to use a profiler. Or the "the profiler" that comes with your JDK. A: I do not know who this log will be informative. I have just tried to look for usage of logger into AWT classes and did not see anything. But I probably have other idea for you. Connect to event queue using Toolkit.getDefaultToolkit().addAWTEventListener(listener, eventMask). Print events to log file. Probably you will see what kind of events take more time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Shorthand for conditional statements I am looking for a way to write something like this: if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { } In a shorthand way like below, which does not work of course: if (product.Category.PCATID != 10 | 11 | 16) { } So is there shorthand way at all to do something similar ? A: Yes - you should use a set: private static readonly HashSet<int> FooCategoryIds = new HashSet<int> { 10, 11, 16 }; ... if (!FooCategoryIds.Contains(product.Category.PCATID)) { } You can use a list or an array or basically any collection, of course - and for small sets of IDs it won't matter which you use... but I would personally use a HashSet to show that I really am only interested in the "set-ness", not the ordering. A: You could use an extension method: public static bool In<T>(this T source, params T[] list) { return list.Contains(source); } And call it like: if (!product.Category.PCATID.In(10, 11, 16)) { } A: not exactly a shortcut, but maybe the right thing for you. var list = new List<int> { 10, 11, 16 }; if(!list.Contains(product.Category.PCATID)) { // do something } A: Well... I think a shorthand version would be if(true), because if PCATID == 10, it is != 11 and != 16, so the whole expression is true. The same goes for PCATID == 11 and for PCATID == 16. And for any other number all three conditions are true. ==> You expression will always be true. The other answers are only valid, if you really meant this: if (product.Category.PCATID != 10 && product.Category.PCATID != 11 && product.Category.PCATID != 16) { } A: You could do something like that: List<int> PCATIDCorrectValues = new List<int> {10, 11, 16}; if (!PCATIDCorrectValues.Contains(product.Category.PCATID)) { // Blah blah } A: if (!new int[] { 10, 11, 16 }.Contains(product.Category.PCATID)) { } Add using System.Linq to the top of your class or .Contains generates a compile error. A: Make it simple with switch: switch(product.Category.PCATID) { case 10: case 11: case 16: { // Do nothing here break; } default: { // Do your stuff here if !=10, !=11, and !=16 // free as you like } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7514949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: About shift operator in C++ I am looking at big code base in C++. There is line mentioned as below int capacity( ) const { return ( 1 << theTrees.size( ) ) - 1; } Here theTrees is vector<int> theTrees What is statement 1 << theTrees.size( ) likely trying to achieve? Assume we have tree size of 25 elements. A: If your question is about C++: 1<< is usually thought of as "2 to the *N*th power." If your question is about data structures theory: a binary tree of height n has up to 2^i nodes per level, for up to 2^n - 1 nodes total. (but you should have tagged it that way) A: In binary, 1 is: 1 If we shift it left by one, 1 << 1 then we have: 10 Which is decimal 2. So shifting << 25 means we get: 10000000000000000000000000 Which is: 33554432 Similar to how in decimal if we shift left by one, we multiply by 10, doing so in binary multiplies by 2. So we get 2^25 essentially. A: It computes two to the power of theTree.size() minus 1 A: I think in this case the size is actually the number of levels. Assuming you have a balanced binary tree this is the number of elements in the tree (if its full). For example a tree with only the head has 1 << 1 -1 = 1 possible nodes where as a full tree with 3 levels has 1 << 3 - 1 = 7 nodes (the head its two children and the children's four children) A: A left shift by n is basically multiplying by 2 to the nth power. Whenever you have 1 << n you're just calculating the nth power of 2. E.g.: 1 << 0 = 1 1 << 1 = 2 1 << 2 = 4 1 << 3 = 8 Etc. I suspect theTrees.size() returns not the number of elements in the tree but the height of the tree (number of levels), because that's the only way this makes sense. Given a full binary tree, the number of nodes is 2^N - 1, where N is the height of the tree. E.g., a tree with three levels (n = 3) can hold 2^3 - 1 = 7 nodes. Check it: The first level has one, the second has two and the third has four. 1 + 2 + 4 = 7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Spring Web MVC: How to use a ResponseEntity in the view class, not the controller? Using Spring Web MVC, I would like to use a ResponseEntity to send bytes back to the client. For example, I could do this: @RequestMapping(value = "/getMyBytes", method = RequestMethod.GET) public ResponseEntity< byte[] > handleGetMyBytesRequest() { // Get bytes from somewhere... byte[] byteData = .... HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType( MediaType.IMAGE_PNG ); responseHeaders.setContentLength( byteData.length ); return new ResponseEntity< byte[] >( byteData, responseHeaders, HttpStatus.OK ); } But now the controller itself decides, how the data will be presented to the client. Shouldn't that not be the job of the view? So my question is, when I have this view class: public class DemoView extends AbstractView { @Override protected void renderMergedOutputModel( Map< String, Object > model, HttpServletRequest request, HttpServletResponse response ) throws Exception { bytes[] byteData = model.get( "byteData" ); // ??? } } How must the view code look like, when I want to use a ResponseEntity there? Or does it make no sense to use ResponseEntity in the view class, and if yes, why? Thanks a lot for your help! A: In your AbstractView you can simply use the HttpServletResponse object to set the HTTP response status and write the byte[] array to the output stream: response.setStatus(status); response.getOutputStream().write(byteData);
{ "language": "en", "url": "https://stackoverflow.com/questions/7514952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selecting unique rows when doing a join Fist a little background: I'm using Rails 3.0.7, Postgres 9.0 and MetaWhere/MetaSearch 1.0.4 I have a very frustrating problem with getting the unique records when querying the my database. I have 3 models as follows: class Car < ActiveRecord::Base has_many :sellers, :through => :adverts, :uniq => true has_many :adverts, :dependent => :destroy end class Seller < ActiveRecord::Base has_many :cars, :through => :adverts, :uniq => true has_many :adverts end class Advert < ActiveRecord::Base belongs_to :car, :autosave => false belongs_to :seller, :autosave => false end So far so good. Now what I want to do is, to find all cars, that is Fiat Panda´s (:brand, :model_name attributes on car). This is going just fine. But if I want some information from sellers table joined in as well, the problems start to show - I'm getting duplicate cars!!! What I do is the following: Car.includes(:adverts, :sellers).where(:brand >> 'Fiat', :model_name >> 'Panda', :sellers => [:kind >> 'Dealer']) Now you could argue, that this is not possible, because "how should the db know which :kind to chose from all the sellers connected to each car?" But I don't care, because they are all the same, so it doesn't matter if it's the first or if it's the last seller it's taking the attributes value from. If I do a .debug_sql, I get the following: SELECT cars.*, sellers.*, adverts.* FROM cars LEFT OUTER JOIN adverts ON adverts.car_id = cars.id LEFT OUTER JOIN adverts sellers_cars_join ON cars.id = sellers_cars_join.car_id LEFT OUTER JOIN sellers ON sellers.id = sellers_cars_join.seller_id WHERE cars.brand = 'Fiat' AND cars.model_name = 'Panda' AND sellers.kind = 'Dealer' Of cause this gives me duplicates, it gives perfect sense - but how can I solve it? - cause it's not what I want. I can see two possible solutions to this: First If I could somehow in a rails-like way get it to execute SELECT DISTINCT(cars.id), cars.*, sellers.*, adverts.* FROM cars LEFT.... It seems that it would give me the right thing. Second As you can see, I have added a :uniq => true to the associations, but this would, as far as I can see only work in my example, if I stated from sellers and asked for cars like this: Seller.includes(:adverts, :cars).where(:cars => [:brand >> 'Fiat'], :cars => [:model_name >> 'Panda'], :kind >> 'Dealer') But I'm not sure about this at all! And what about metawhere/metasearch - I'm fearing that it's interfering in this as well. A: includes performs a LEFT OUTER JOIN, which indeed creates duplicates. If you don't need to access to each @car.seller after your query (n+1 query issue), just use joins instead : Car.joins(:sellers). where(:cars => {:brand => 'Fiat', :model_name => 'Panda'}, :sellers => {:kind => 'Dealer'}) joins performs an INNER JOIN, so you shouldn't get duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Pickling from multiple threads in Python I have a python program with multiple threads. Each thread detects events, which I would like to store somewhere so that I can read them in again (for testing). Right now, I'm using Pickle to output the events, and each thread outputs to a different file. Ideally, I would only use one output file, and all the threads would write to it, but when I try this, it looks like the various threads try to write their output at the same time, and they don't get pickled properly. Is there a way to do this? A: seems like a good place to use a Queue. * *Have all your event detection threads put items on a shared Queue. *Create another thread to get items from the queue, and write/pickle/whatever from this thread. from the Queue docs: "The Queue module implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Queue class in this module implements all the required locking semantics. It depends on the availability of thread support in Python; see the threading module." A: Yes, with threading.Lock() objects. You create a lock before creating all your threads, you give it to the method that is responsible of saving/pickling items, and this method should acquire the lock before writing into the file and releasing it after. A: You could create a lock and acquire/release it around every call to pickle.dump(). A: The logging module has a Rlock built into its Handlers. So you could logging as normal (just create a handler to log to a file.) A: Here is an example using threading.Lock(): import threading import pickle picke_lock = threading.Lock() def do(s): picke_lock.acquire() try: ps = pickle.dumps(s) finally: picke_lock.release() return ps t1 = threading.Thread(target=do, args =("foo",)) t2 = threading.Thread(target=do, args =("bar",)) p1 = t1.start() p2 = t2.start() inpt = raw_input('type anything and click enter... ')
{ "language": "en", "url": "https://stackoverflow.com/questions/7514958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: SQL query compare and get info based on two tables I have two tables. Contacts and groupcontacts. I want all contacts from group x listed. Table A Tablename : contacts Fields : crmcListId crmcId Table B Tablename: contactgroups Fields : crmcgrId crmcgrContactId crmcgrGroupId Field crmcgrID = crmListID Field crmcID = crmContactID I want all contacts from table a belonging to group x to list. From table contactgroups where crmcgrGroupID = x A: Do something like : SELECT c.* FROM Contacts c WHERE c.ID IN (SELECT ContactID FROM groupcontacts) OR with a join : SELECT c.* FROM Contacts c INNER JOIN groupcontacts gc ON c.ID = gc.ContactID You can then add a WHERE clause to select the IDs for a specific group. A: Since it's not entirely clear what your tables look like, I'm going to take a shot in the dark here: Select * From Contacts c inner join GroupContacts gc on gc.ContactID = c.ContactID where gc.GroupID = x Just subsitiute x for the real group id
{ "language": "en", "url": "https://stackoverflow.com/questions/7514963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django - how to create a file and save it to a model's FileField? Here's my model. What I want to do is generate a new file and overwrite the existing one whenever a model instance is saved: class Kitten(models.Model): claw_size = ... license_file = models.FileField(blank=True, upload_to='license') def save(self, *args, **kwargs): #Generate a new license file overwriting any previous version #and update file path self.license_file = ??? super(Request,self).save(*args, **kwargs) I see lots of documentation about how to upload a file. But how do I generate a file, assign it to a model field and have Django store it in the right place? A: Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view. Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc). Django 1.4.1 Python 2.7.3 #Model class MonthEnd(models.Model): report = models.FileField(db_index=True, upload_to='not_used') import csv from os.path import join #build and store the file def write_csv(): path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv') f = open(path, "w+b") #wipe the existing content f.truncate() csv_writer = csv.writer(f) csv_writer.writerow(('col1')) for num in range(3): csv_writer.writerow((num, )) month_end_file = MonthEnd() month_end_file.report.name = path month_end_file.save() from my_app.models import MonthEnd #serve it up as a download def get_report(request): month_end = MonthEnd.objects.get(file_criteria=criteria) response = HttpResponse(month_end.report, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename=report.csv' return response A: You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile.save(). Basically, a field declared as a FileField, when accessed, gives you an instance of class FieldFile, which gives you several methods to interact with the underlying file. So, what you need to do is: self.license_file.save(new_name, new_contents) where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.core.files.File or django.core.files.base.ContentFile (see given links to manual for the details). The two choices boil down to: from django.core.files.base import ContentFile, File # Using File with open('/path/to/file') as f: self.license_file.save(new_name, File(f)) # Using ContentFile self.license_file.save(new_name, ContentFile('A string with the file content')) A: It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc. Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin. You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name. Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField: import os from django.core.files import File with open(filepath, 'rb') as fi: self.my_file = File(fi, name=os.path.basename(fi.name)) self.save()
{ "language": "en", "url": "https://stackoverflow.com/questions/7514964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "153" }
Q: Problems in running MakeFile I am trying to learn/use inject_and_interpose project. I am facing problems with make file. When I try to execute make file on terminal, I get following error message. i686-apple-darwin10-gcc-4.2.1: ?=: No such file or directory i686-apple-darwin10-gcc-4.2.1: gcc: No such file or directory i686-apple-darwin10-gcc-4.2.1: no input files ARCH: Can't find any plists for ARCH i686-apple-darwin10-gcc-4.2.1: no input files ./Makefile: line 3: findstring: command not found ./Makefile: line 3: ifeq: command not found ARCH: Can't find any plists for ARCH ./Makefile: line 5: endif: command not found ./Makefile: line 7: all:: command not found ./Makefile: line 9: testlib.dylib:: command not found i686-apple-darwin10-gcc-4.2.1: no input files ARCH: Can't find any plists for ARCH ./Makefile: line 10: -dynamiclib: command not found ./Makefile: line 11: tester:: command not found i686-apple-darwin10-gcc-4.2.1: no input files ./Makefile: line 12: -O3: command not found ./Makefile: line 13: testputs:: command not found i686-apple-darwin10-gcc-4.2.1: no input files ./Makefile: line 14: -o: command not found ./Makefile: line 15: clean:: command not found rm: tester: is a directory Can somebody please explain me what changes I have do to run this make file properly? Or Am I doing anything wrong? A: Makefiles are not intended to be run by sh or friends. You invoke it by running $ make in the directory the makefile is in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenVG on wince: nothing painted on screen (example application Star.exe) Has anyone got the openvg example (star.exe) running on a wince target successfully? I’ve tried it but failed – nothing was painted on screen except for an empty window. Below is what I’ve done for it. Environment: * *Qt 4.7.4 *Wince 6.0 *An SDK with both OpenGL and OpenVG support. (OpenVG version 1.1) Steps: * *Open "Visual Studio 2005 Command Prompt", configure Qt with command: configure -openvg -platform win32-msvc2005 -xplatform wince60DbAu1300-qt46-mipsii-msvc2005 *Set environment variables for wince. *Run "nmake" *Copy files needed to the same folder on my target. Below is the file tree in the folder: * *star.exe *QtCored4.dll *QtGuid4.dll *QtOpenVGd4.dll *msvcr80d.dll *Run star.exe -graphicssystem OpenVG Results: The window is created and shown, but nothing in it. The content is empty and transparent. Update: I was trying to debug this issue, and I found that the application Star.exe is failing to load OPenVG libs. How do I find out the reason why the app is not able to load OpenVG libs? A: solution:- Could figure out the problem. My application was not able to find the graphics libs which are loaded at run time. the graphics libs has to be in "graphicssystems" folder in star app folder, and the graphics libs can be copied from "QTROOT\plugins\graphicssystems\" folder. And might have to specify command line arguments "-graphicssystems OpenVG" while launching the application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making 'isinstance' work with decorators How does the Python isinstance function work internally? Is there anything I can do to alter its results, like define a special function inside a class or something? Here's my use case: class Decorator: def __init__(self, decorated): self._decorated = decorated def __call__(self): return self._decorated() @Decorator class Foo: pass f = Foo() # How can I make this be true? isinstance(f, Foo) Decorator acts almost like a mixin, except a mixing wouldn't be appropriate here. Is there any way I can make the above code work? I should also note that the isinstance line also gives the following error:     isinstance(f, Foo) TypeError: isinstance() arg 2 must be a type or tuple of types A: How about the following: def Decorator(decorated): class Dec(decorated): def __call__(self): print 'in decorated __call__' return decorated.__call__(self) return Dec @Decorator class Foo(object): def __call__(self): print 'in original __call__' f = Foo() # How can I make this be true? print isinstance(f, Foo) With the above code: * *isinstance(f, Foo) works; *f() calls the decorated method which then forwards to the original method. The basic idea is to make sure that the decorated Foo is still a class, and to also make sure that the decorated Foo is a subclass of the original Foo. P.S. The purpose of all this is not entirely clear to me; it might be that metaclasses are a better way to achieve what you're trying to do. A: The problem is that Foo in your example isn't a class. This code: @Decorator class Foo: pass is equivalent to: class Foo: pass Foo = Decorator(Foo) Which means that Foo is an instance of class Decorator. Because Foo is not a clas or type, isinstance complains. A: When decorating a class, it's often useful or desirable to for the decorated return value to also be type; The most obvious way of achieving this is to have the decorator construct and return a new class directly. That functionality is already handled by metaclasses; In fact, metaclasses are a bit more powerful than decorators, since you get to describe the new class before a decorated class has even been constructed. Another option is to return the same object that was passed in; but with some changes. That's a better use for decorators, since it works well when you nest decorators. Since you're modifying the behavior when Foo() is used, then you probably want to modify Foo's __init__, which might look like this: >>> def Decorator(cls): ... assert isinstance(cls, type) ... try: ... old_init = cls.__init__.im_func ... except AttributeError: ... def old_init(self): pass ... def new_init(self): ... # do some clever stuff: ... old_init(self) ... cls.__init__ = new_init ... return cls ... >>> @Decorator ... class Foo(object): ... def __init__(self): pass ... >>> @Decorator ... class Bar(object): ... pass ... >>> f = Foo() >>> isinstance(f, Foo) True A: You can't get type of the object that Foo returns without calling Foo. isinstance complains about its second argument because it is an instance - in you case instance of Decorated. Although you think of Foo like a class but actually it is just a callable object and it is not a class. Maybe the next will help you to rethink/solve your problem: >>> isinstance(f, Foo._decorated) True
{ "language": "en", "url": "https://stackoverflow.com/questions/7514968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Html entities form JSON In my ifone App, i have called a php page to get contents, it returns JSON format,but the response contains Html entities like &quot;.How i convert these entities to unicode.Any methods or libraries in objective C. help is highly appreciated, Shihab. A: For your problem you can use SBJSON class and will get result in the dictionary json by following code NSString *stringResponse = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; SBJSON *jsonParser = [SBJSON new]; NSMutableDictionary *json = [jsonParser objectWithString:stringResponse error:NULL];
{ "language": "en", "url": "https://stackoverflow.com/questions/7514973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mobile cookie htaccess I have a mobile site and a desktop site. I have set up automatic redirection for mobile users if they access the desktop site. But unfortunately I need them to access the full site as well, if they prefer. I have set up a cookie in the .htaccess file, how do i check to see if the cookie has been set so they can access the full site? Haven't found a clear answer. Code: #redirect RewriteCond %{HTTP_HOST} !^m\.stage.sunjournal\.com$ RewriteCond %{HTTP_USER_AGENT} "android|iPhone|blackberry|ipad|iemobile|operamobile|palmos|webos|googlebot-mobile" [NC] RewriteRule ^(.*)$ http://m.stage.sunjournal.com/$1 [L,R=302,CO=mobile:yes:m.stage.sunjournal.com:0:/] A: Add this kind of rewrite condition for your rule: RewriteCond %{HTTP_COOKIE} mobile=yes This will allow rule to execute if cookie with the name mobile and value of yes is present (to be more precise, that pattern will match any cookie name that ends with mobile (e.g. notmobile) and value that starts with yes (e.g. yesSir)). If you need this to be more precise (exact match only) -- you have to check how raw cookie look like and adjust pattern accordingly. But as long as you have unique cookie name and value this will not be required. A: Mark -- In the reference link you provided, the cookie is set to destroy itself after the user has exited their session. This is because the lifetime of the cookie was never specified. For more information about this, go to the official documentation for mod_write. BDUB, I would suggest you check out that link that Mark provided. I'm running into issues setting the new cookie, because if a cookie is set for mobile=0, my cookie mobile=1 is not set. I have seen this in my RewriteLogs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7514997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to download data from an ASP.Net webpage to an Excel file? I need to download the data in a table and also a picture to an excel spreadsheet. I am currently able to create the excel spreadsheet on the website, but how do I get the data into the spreadsheet? protected void btn_ExcelDownload_Click(object sender, EventArgs e) { string path = Server.MapPath(""); path = path + @"\Resources\MessageStatus.xlsx"; string name = Path.GetFileName(path); Response.AppendHeader("content-disposition", "attachment; filename=" + name); Response.ContentType = "Application/msword"; Response.WriteFile(path); Response.End(); } A: I had done this using this class void WriteToXls(string fromfilePath, string targetFileName) { if (!String.IsNullOrEmpty(fromfilePath)) { HttpResponse response = HttpContext.Current.Response; response.Clear(); response.Charset = "utf-8"; response.ContentType = "text/xls"; response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName)); response.BinaryWrite(File.ReadAllBytes(fromfilePath)); response.End(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is the mysql_close() necessary? Possible Duplicate: close mysql connection important? in the php manual, there say : Using mysql_close() isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution. does it mean that we actually don't need to colse the php connect in a script? so the code below <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); ?> will be more performanece than the below code? <?php $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); mysql_close($link); ?> A: It is not necessary but a good thing to do is close your connection before you start sending data to the user so it does not stay open for nothing (the time for the client to download your page, which depending on his latency can take some time). heavy work on the data you got from the database. A: First: No, it isn't strictly necessary in all cases. However it is good practice, and there are times when it is necessary. I would suggest always closing any connection which you open. Even if you are confident that it isn't necessary, future changes to your code may change that, at which point you might find yourself struggling to find the bug. To answer your second question: No, there will be zero performance benefit to be gained from not closing a connection. In the best case scenario it will be closed automatically for you, but this still involves closing it, so it doesn't save you any time whatsoever. In the worst case scenario, not closing a database connection can result in your application running out of available connections, which will obviously hurt your site quite lot.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: To have image name stored in SD card of android emulator I am having images in SD card and from there i am able to retrieve them and display them in my gallery. Now i wanted to display the name of that particular image only using Toast. Can any one tell me how can I do that??? My code is as follow package com.example.Gallery; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.AdapterView.OnItemClickListener; import android.widget.TextView; import android.widget.Toast; public class HelloGallery extends Activity { private TextView Text; private List<String> ReadSDCard() { List<String> tFileList = new ArrayList<String>(); //It have to be matched with the directory in SDCard File f = new File("/sdcard/pictures/"); File[] files=f.listFiles(); if(files != null)//to check whether an image is present in that file or not { for(int i=0; i<files.length; i++) { File file = files[i]; //to check the type of file and according allowing the files to display String curFile=file.getPath(); String ext=curFile.substring(curFile.lastIndexOf(".")+1, curFile.length()).toLowerCase(); if(ext.equals("jpg")||ext.equals("gif")||ext.equals("png")) /*It's assumed that all file in the path are in supported type*/ tFileList.add(file.getPath()); } } else { Text =(TextView)findViewById(R.id.text); Text.setText("THERE IS NO IMAGE IN THE cARD MOUNTED INTO DEVICE"); } return tFileList; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView imageView = (ImageView)findViewById(R.id.image1); Gallery g = (Gallery) findViewById(R.id.gallery); String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { final List<String> SD = ReadSDCard(); g.setAdapter(new ImageAdapter(this, SD)); //to saw image with image view g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { //to get a image file String imageInSD = SD.get(position); String imagename = imageInSD.intern(); Toast.makeText(HelloGallery.this, imagename, Toast.LENGTH_SHORT).show(); //to display image in image view Bitmap bitmap = BitmapFactory.decodeFile(imageInSD); imageView.setImageBitmap(bitmap); } }); } else { Text =(TextView)findViewById(R.id.text); Text.setText("THERE IS NO EXTERNAL CARD MOUNTED IN THE DEVICE"); } } public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; private Context mContext; private List<String> FileList; public ImageAdapter(Context c, List<String> fList) { mContext = c; FileList = fList; TypedArray a = obtainStyledAttributes(R.styleable.Theme); mGalleryItemBackground = a.getResourceId( R.styleable.Theme_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return FileList.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); Bitmap bm = BitmapFactory.decodeFile( FileList.get(position).toString()); i.setImageBitmap(bm); i.setLayoutParams(new Gallery.LayoutParams(150, 100)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setBackgroundResource(mGalleryItemBackground); return i; } } } A: you should use this code to open gallery: Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"SelectPicture"),50); After selecting image from gallery ,control goes to OnActivityResult. then add this code to OnActivityResult: public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == 50) { Uri selectedImageUri = data.getData(); String selectedImagePath = getPath(selectedImageUri); Toast.makeText(this,selectedImagePath,Toast.LENGTH_LONG).show(); } } } i hope this help you
{ "language": "en", "url": "https://stackoverflow.com/questions/7515026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Audio queue starts failed I have encountered that while streaming song with AudioStreamer following error occured: Audio queue start failed. err: hwiu 1752656245 this error occured in the following code err = AudioQueueStart(audioQueue, NULL); if (err) { [self failWithErrorCode:AS_AUDIO_QUEUE_START_FAILED]; return; } where audioQueue is object of AudioQueueRef. What to do to prevent going into if condition?? What could be the error? I am using AudioStreamer example of github? A: Did you refer to this links? Second one is most interesting. Audio queue start failed AudioQueue fails to start http://s272.codeinspot.com/q/881582 Try if you have referred to it. This may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't turn off buffering in Perl using $|=1; I am writing to two files, one a log using a Log_message function and the other within my file_write function writing to OUT and I want to write it line by line and not be buffered so that it writes line by line and not all in one go at the end of the script. I have read about buffering and making the filehandle hot but can't get my code to work. In this example I have added the $|=1; just before the foreach loop but it still writes in one go. Am I doing something really dumb? I have enclosed my entire script further down if that helps. #----------------------------------------------- sub file_write { #----------------------------------------------- open OUT, ">>$OUT" or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); Log_message ("\n$DATE - $TIME - INFO - Opened the output file"); my $total = scalar keys %{ $doc->{ resource } }; Log_message ("\n$DATE - $TIME - INFO - Found: " . $total . " resources"); #printf "resources: %s\n", scalar keys %{ $doc->{ resource } }; $|=1; #And I have also tried: #use IO::Handle; #STDOUT->autoflush(1); foreach ( keys %{ $doc->{ resource } } ) { #print OUT $doc->{ resource }->{ $_ }->{ id }, "\n"; my $ID = $doc->{ resource }->{ $_ }->{ id }, "\n"; Log_message ("\n$DATE - $TIME - INFO - Found: " . $ID); my $testurl = "http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID; print OUT "$testurl\n"; sleep 1; } And the entire script # !c:/Perl/bin/Perl.exe #----------------------------------------------- #Modules #----------------------------------------------- use XML::Simple; use LWP; use Data::Dumper; $Data::Dumper::Indent = 1; $Data::Dumper::Sortkeys = 1; use strict; use warnings; #----------------------------------------------- #Declare variables #----------------------------------------------- my $script = "LiveContent Auto Cache Script"; # Name of the script my $version = "Version 0.1"; #my $pubId = "COMP-20110922XXXX"; my $pubId = "LiveContentDoc"; my $OUT = "output.txt"; my $LOG = "cacher-log.log"; # Location of log file my $DATE; # Date in form 2001-sep-01 my $DATENR; # Date in form 2001-01-09 my $TIME; # Time in form 12:04:03 my $txtmesg = ""; my $resource; my $xs; my $doc; #################################### ########### Main Program ########### #################################### error_logger(); # Open Log file and time stamp it request_url(); #Open the xml url and read it in file_write(); #write the contents of the xml url to a file #----------------------------------------------- sub request_url { #----------------------------------------------- my $useragent = LWP::UserAgent->new; my $request = HTTP::Request->new( GET => "http://digitalessence.net/resource.xml" ); #my $request = HTTP::Request->new( GET => "http://dronlineservices.letterpart.com/web/content.xql?action=index&lang=en&pub=" . $pubId ); $resource = $useragent->request( $request ); $xs = XML::Simple->new(); $doc = $xs->XMLin( $resource->content ); } #----------------------------------------------- sub file_write { #----------------------------------------------- open OUT, ">>$OUT" or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); Log_message ("\n$DATE - $TIME - INFO - Opened the output file"); my $total = scalar keys %{ $doc->{ resource } }; Log_message ("\n$DATE - $TIME - INFO - Found: " . $total . " resources"); #printf "resources: %s\n", scalar keys %{ $doc->{ resource } }; use IO::Handle; STDOUT->autoflush(1); foreach ( keys %{ $doc->{ resource } } ) { #print OUT $doc->{ resource }->{ $_ }->{ id }, "\n"; my $ID = $doc->{ resource }->{ $_ }->{ id }, "\n"; Log_message ("\n$DATE - $TIME - INFO - Found: " . $ID); my $testurl = "http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID; print OUT "$testurl\n"; # my $browser = LWP::UserAgent->new; # $browser->timeout(240); # $browser->env_proxy; # $browser->agent('Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'); # my $response = $browser->get($testurl); # if ($response->is_success) { # print "\n############################\n"; # print "$testurl\n"; # print "\n############################\n"; # print $response->decoded_content; # print the response out # } # else { # my $error = $response->status_line; # Log_message ("\n$DATE - $TIME - WARN - Can't load $ID because: $error"); # die $response->status_line; # } #my $loadrequest = $ua->get('http://dronlineservices.letterpart.com/web/content.xql?action=doc_html&lang=en&pub=" . $pubId . "&docid=" . $ID'); sleep 1; } Log_message ("\n$DATE - $TIME - INFO - Written the output file"); #close(OUT) or Log_message ("\n$DATE - $TIME - WARN - Failed to close the Output file"); Log_message ("\n$DATE - $TIME - INFO - Closed the output file"); } #----------------------------------------------- sub error_logger { #----------------------------------------------- time_stamp(); # Run Time stamp sub open LOG, ">>$LOG" or die ("could not open log file <$LOG>"); # Open Log File Log_message ("\n$DATE - $TIME - -----------------------------------------\ \t"); Log_message ("\n$DATE - $TIME - INFO - Start of Application\ \t"); Log_message ("\n$DATE - $TIME - INFO - $script\ \t"); Log_message ("\n$DATE - $TIME - INFO - $version\ \t"); Log_message ("\n$DATE - $TIME - -----------------------------------------\ \t"); } #------------------------------------------------------------- sub Log_message { #------------------------------------------------------------- time_stamp(); # Run time_stamp every time the log is written to my($mesg) = @_; print LOG $mesg if $LOG; # Print to log file print $mesg; # Print to Screen $txtmesg = $mesg; #print "\nLOGGING: $txtmesg\n"; } #----------------------------------------------- sub time_stamp { #----------------------------------------------- my($Sec,$Min,$Hour,$Day,$MonthNr,$Year) = localtime(time()); my $Month=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$MonthNr]; $Sec = sprintf("%02d",$Sec); $Min = sprintf("%02d",$Min); $Day = sprintf("%02d",$Day); $MonthNr = sprintf("%02d",++$MonthNr); $Year = 1900 + $Year; $DATE = "$Year-$Month-$Day"; $DATENR = "$Year-$MonthNr-$Day"; $TIME = "$Hour:$Min:$Sec"; } # end sub A: You forgot to select the handle first. select( (select(OUT), $| = 1)[0] ); A: use IO::Handle; OUT->autoflush(1); But it is better to use lexical filehandles: use IO::Handle; open my $outfh, ">>", $OUT or Log_message ("\n$DATE - $TIME - ERROR - Could not create filelist.doc \t"); $outfh->autoflush(1);
{ "language": "en", "url": "https://stackoverflow.com/questions/7515029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Pyglet: equivalent of pygame.Rect I am contemplating migrating from pygame to pyglet (main reason: move from Python to Pypy). However, I found no rectangle collision tools in the pyglet doc, while I use pygame.Rect quite often. Do you know how pyglet deals with rectangle collision (maybe with OpenGl funcs, but I do not know them) ? Thanks A: Pyglet doesn't not have this system. You will have to implement it on your own. You could possibly import just pygame's rect and use it within pyglet. Pyglet is only an opengl interface, not a game toolkit. (this was a hurdle for me way back when, but you'll get over it. stick with it, pyglet is the right direction to go from pygame)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get rid of the console window I have tried to make a simple MessageBox using this code: #include <windows.h> int main() { MessageBox(NULL, "Hello", "Message Box", MB_OKCANCEL); } But upon building this in the Dev-C++ IDE with the MinGW toolchain, I get a console window popping up behind the MessageBox. Is there a way to get rid of this console window? A: Yes, compile for the "windows" subsystem. Here are instructions for performing this task on multiple IDEs. A: * *Don't use Dev-C++; use a decent IDE instead. *Compile for the WINDOWS subsystem, instead of the CONSOLE one. Even braindead Dev-C++ should have option for that (the entry point should be called WinMain — see any introduction to Windows programming). A: Here you go #include <Windows.h> int main() { HWND hwnd; AllocConsole(); hwnd = FindWindowA("ConsoleWindowClass", NULL); ShowWindow(hwnd, 0); MessageBox(NULL, "Hello", "Message Box", MB_OKCANCEL); ShowWindow(hwnd, 0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: change android system-wide displayed stuff Is it possible on android that we change the displayed things on screen, out of our program? For example put a color filter on screen (system-wide, not only an specific app), or zoom, and maybe rotate? thanks. A: I found it finally! this app uses an activity and sets a transparent image to its background (the crystal leaks!) and puts that in top layer of the screen. I guess it, I'm not sure, but probably it is true, because when screen shows leaks and volume buttons pressed, screen does not show them, because they both are dialog activities. Of course it is just a guess!
{ "language": "en", "url": "https://stackoverflow.com/questions/7515036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby GuardFile - Why does the process restart twice I have a Guard setup (Ruby gem that reacts to filesystem events - https://github.com/guard/) that compiles coffee files to Javascript and also restarts the node.js server on changes to relevant js files. Here is my Guardfile from my project directory: guard 'process', :name => 'SPCRM Server', :command => 'node --debug server/js/app.js' do watch(%r{^server/js/.+\.js$}) end guard 'coffeescript', :input => 'app/coffee', :output => 'app/js' guard 'coffeescript', :input => 'server/coffee', :output => 'server/js' When I change a relevant .coffee file (so that a server/js/ file is updated) the process is restarted twice. Modifying by hand a server/js/*.js file and it is only restarting once (as expected) leading me to believe it does two passes for some reason. Here is the output running with guard -d debugger listening on port 5858DEBUG (19:30:26): Guard::CoffeeScript#run_on_change with ["server/coffee/app.coffee"] DEBUG (19:30:26): Hook :run_on_change_begin executed for Guard::CoffeeScript DEBUG (19:30:26): Command execution: command -v nodejs 2>/dev/null DEBUG (19:30:26): Command execution: command -v node 2>/dev/null DEBUG (19:30:26): Command execution: command -v /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc 2>/dev/null DEBUG (19:30:26): Command execution: command -v js 2>/dev/null DEBUG (19:30:26): Command execution: command -v cscript 2>/dev/null Compile server/coffee/app.coffee Successfully generated server/js/app.js Stopping process SPCRM Server Stopped process SPCRM Server Starting process SPCRM Server Started process SPCRM Server DEBUG (19:30:27): Hook :run_on_change_end executed for Guard::CoffeeScript DEBUG (19:30:27): Guard::Process#run_on_change with ["server"] DEBUG (19:30:27): Hook :run_on_change_begin executed for Guard::Process Stopping process SPCRM Server Stopped process SPCRM Server Starting process SPCRM Server Started process SPCRM Server DEBUG (19:30:27): Hook :run_on_change_end executed for Guard::Process debugger listening on port 5858 My knowledge of Ruby is limited so whilst I have read the FAQs, examples, wikis, rubydocs I still none the wiser. It would seem that after the first match the rules cascade and then are applied again. My expectation would be this: * *Update file in my editor and save server/coffee/app.coffee *Guard recognizes this and the Guard-Coffeescript plugin overwrites server/js/app.js *Guard recognizes server/js/app.js has changed and Guard-Process restarts node server. Can anyone help me solve this minor annoyance or enlighten me on how Guard is processing my Guardfile/FS events? This is using fresh Ruby 1.9 (installed via Homebrew), latest Guard and plugins, including the fs event gem, on Mac OX Lion.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do http authentication in android I am using following code public void executeHttpGet() throws Exception { dialog = new ProgressDialog(this); dialog.setCancelable(true); // set a message text dialog.setMessage("Loading..."); // show it dialog.show(); BufferedReader in = null; HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); String url= "http://newdev.objectified.com/morris/interface/mobile.php?method=dealerLogin&username=alixxxxxxxx&password=jamali"; request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader (new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); Toast.makeText(this, page, Toast.LENGTH_LONG).show(); // dialog.dismiss(); } Now I want to do http authentication on this ,please help? A: It should look like this: HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); String url= "http://newdev.objectified.com/morris/interface/mobile.php?method=dealerLogin&username=alixxxxxxxx&password=jamali"; String login = "alixxxxxxxx"; String pass = "jamali"; client.getCredentialsProvider().setCredentials(new AuthScope("newdev.objectified.com", 80), new UsernamePasswordCredentials(login, pass)); request.setURI(new URI(url)); HttpResponse response = client.execute(request); A: For http authentication the Authenticator class is your friend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hash map in ruby? I'm trying to get this object, passed via AJAX: Parameters: {"status"=>{"1"=>["14", "1"], "2"=>["7", "8", "12", "13"]}} into something like: 14 -> 1 1 -> 1 7 -> 2 over which I can iterate. What's the most elegant way of achieving this? A: flat_inverse = {} parameters["status"].each { |key, values| values.each { |v| flat_inverse[v] = key } } flat_inverse # {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} #or more functional Hash[*parameters["status"].map { |k, vs| vs.zip([k] * v.length) }.flatten] A: Couple other variants, using product: input.map{|k,v| Hash[v.product([k])]}.inject(&:merge) # => {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} Hash[input.map{|k,v| v.product([k])}.flatten(1)] # => {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} A: input = {"1"=>["14", "1"], "2"=>["7", "8", "12", "13"]} output = Hash[*input.map{|k,l|l.map{|v|[v,k]}}.flatten] => {"14"=>"1", "1"=>"1", "7"=>"2", "8"=>"2", "12"=>"2", "13"=>"2"} output.each {|k,v| puts "#{k} -> #{v}"} 14 -> 1 1 -> 1 7 -> 2 8 -> 2 12 -> 2 13 -> 2
{ "language": "en", "url": "https://stackoverflow.com/questions/7515059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: read cookie value in jquery I have called one php page inside the iframe I have stored some values in cookies.I want to read that cookies values from that page to other page. I used jQuery to read cookie. var value = $.cookie('artname'); 'artname' is the cookie name. But it displaying null value because cookies path is different,path is "/v/abcfile/frontend/". But the path for the other cookies on the page i am trying to get is "/. I tried with this: top.jQuery.cookie('artname'); Its still showing me the same. how can I get value of cookie? A: just use the path property $.cookie("example", { path: '/' }); http://www.electrictoolbox.com/jquery-cookies/ cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7515061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How should I deal with null objects in a using block? Given a situation like this: using (var foo = CreateFoo()) { if (foo != null) { // do stuff } } I would like to avoid the nested if. Sadly, the obvious solution is not possible because break does not work with using: using (var foo = CreateFoo()) { if (foo == null) { break; } // do stuff } Is there a pattern to still avoid the additional indentation caused by the if != null? A: If you have sufficient control over the class returned from CreateFoo() you could just implement a Null Object and return this instead of the actual NULL value A: I favor small clearly named methods: public void DoWhatEver() { using (var foo = CreateFoo()) { if (foo == null) return; //DoWhatEver } } A: Introduce a helper method that takes a lambda. So your code becomes: UsingIfNotNull(CreateFoo(), foo => { //do stuff }); which has the indentation you want. The definition of UsingIfNotNull is: public static void UsingIfNotNull<T>(T item, Action<T> action) where T : class, IDisposable { if(item!=null) { using(item) { action(item); } } } A: This is just a style issue ... code is fine. Are you really that worried about indents? Here's another way to lose the indents anyway ... public void DoWhatEver() { using(var foo = CreateFoo()) { DoStuffWithFoo(foo); } } private void DoStuffWithFoo(Foo foo) { if(foo == null) return; //DoWhatEver } A: In that sort of generic sense, I believe I would wrap the using in a try...catch block and throw an exception if the object was null, but that's a personal preference. A: It's an ugly hack, but it avoids the additional identation: do using (var foo = CreateFoo()) { if (foo == null) { break; } // do stuff } while (false); (No, I don't recommend to do this. This is just a proof-of-concept to show that it's possible.) If possible, I would suggest to refactor your code instead: using (var foo = CreateFoo()) { if (foo != null) { doSomethingWith(foo); // only one line highly indented } } A: Personally I would probably leave the code as you've posted it. However, since you asked (and at the risk of exposing myself to downvotes to this often-maligned language feature), you could always use "goto": using (var foo = CreateFoo()) { if (foo == null) { goto SkipUsingBlock; } // do stuff } SkipUsingBlock: // the rest of the code... A: C# compiler treats using(var foo = CreateFoo()) statement in: try { var foo = CreateFoo(); } finally { ((IDisposable) foo).Dispose(); } If your method CreateFoo return not disposable object - do not use using at all. In other case you can write: try { var foo = CreateFoo(); //do stuff like foo.SomeMethod (if foo == null exception will be thrown and stuff will not be done) } finally { ((IDisposable) foo).Dispose(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: c#: Distance from point to a line segment (in longitude and latitude) I have a position (A) in longitude and latitude. I have a line segment with start (B) and end (C) points in longitude and latitude. What I am trying to calculate is the shortest distance from A to line B<->C. In other words the distance from A to the closest point (on line BC) in meters. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Jquery to enable/disable a drop down list on checking/unchecking a check box in Ruby I am new to ruby and jQuery as well. I have a drop down list which should be enabled/disabled on checking/unchecking a check box.It would be of great help if someone could help with the jQuery for this. thanks, Ramya. A: Try this: $(document).ready(function(){ $("#yourCheckBoxId").change(function(){ if($(this).attr("disabled").length) { $("#yourDropDownId").removeAttr("disabled"); } else { $("#yourDropDownId").attr("disabled", "disabled"); } }); }); (untested) A: Recent versions of jquery support .prop method. example: $("#dropdownid").prop("disabled", "true")
{ "language": "en", "url": "https://stackoverflow.com/questions/7515071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between web.config and normal xml file for storing application settings I have an application which have some specific settings like erroremailid, maxcapcount etc. I am storing these values in appsetting block. Can anybody tell me which will be better (performance wise) between following two options: 1. Storing settings in web.config 2. Storing settings in normal xml file and then reading them Some articles specifying the performance difference will also be good. Thanks Ashwani A: The point is not about performances, why do you think the .NET framework would be any faster in reading one xml file vs another one? The way .NET works is that certain settings (not only the appSettings section) are retrieved from the application configuration file which is web.config for ASP.NET and exefile.exe.config for executable applications. in executables like windows forms applications you can also save settings from the app at runtime in the config file but in ASP.NET even if the APIs being the same will let you call the save method, the web.config will not be updated as it's opened as readonly because every time it is changed IIS restarts the web application. there is no way to imagine that putting some other custom settings in another separated XML file would be any slower or any faster, the advantage vs the web.config would be that you can edit such xml file anytime without the web app to restart as it would happen anytime you save changes in web.config. still. .NET will get the appSettings from web.config so you can put in another file only other kind of settings and then you have to read those settings yourself by hand, not sure if you can instruct the ConfigurationManager to read from another file. There are many other sections inside the web.config that are taken by other parts of the application and if you would move them somewhere .NET would not automatically take those for you, for example the default SMTP Server. A: you have several classes already at your disposal that allow you to read settings from your web.config. if you choose to use your own xml file you will have to write the code to read the values yourself (not that it is particularly difficult, though) performance wise, the web.config values are read once and strored in memory (again, you could do this yourself if you implement your own class to read settings from your xml) therefore it's fast. the other difference is that asp.net detects changes to the web.config file automatically and loads them again when this happens. so potentially you can point your app, for example, to a different database at runtime w/o recycling the application. and the application will pick up the changes immediately w/o you recycling the app manually. A: webconfig for settings that are not going to change (Can use built in methods to make them update on the fly though). If you have a lot of settings that are being changed, then storing as a seperate XML would be a better solution, since you can update them on the fly. EDIT: After finding some new information it is possible to use webconfig settings on the fly as well using built in methods. (See Icarus's answer)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: get html value on checkbox click from a table using jquery I am creating a dynamic table like below on page load after fetching data from database <table border="1" id="tableView"> <thead> <th></th><th>ID</th><th>Name</th><th>Description</th><th>Active</th><th>Release Date</th> </thead> <tbody> <% for(int i=0;i<result.size();i++) { %><tr><td><input class="tablechkbox" type="checkbox"/></td><% String[] row=pi.getResults(result,i,params); for(int j=0;j<row.length;j++) { %><td class="viewa"><%out.print(row[j]);%></td><% } %></tr><% } %> </tbody> </table> This is what I am doing to fetch ID column. Please help me fetch any specific column $('#tableView tbody tr').live('click', function (event) { if ($('input.tablechkbox', this).is(':checked')) { alert(this.innerHTMl()); /*$('.viewa', this).each(function() { alert(this.innerHTMl()); });*/ } }); Below is my jsp page screenshot A: alert($(this).find("td:eq(1)").html()); should work A: Consider storing the row Id in your row using an HTML5 data- attribute (the prefix allows you to define arbitrary attributes that are "legal"): String[] row = pi.getResults(result, i, params); %> <tr data-id="<%=row[0]%>"> <td><input class="tablechkbox" type="checkbox" /></td> That way, you can grab the Id directly from the clicked row: $('#tableView tbody tr').live('click', function (event) { if ($('input.tablechkbox', this).is(':checked')) { var id = $(this).data("id") You can use $(this).attr("data-id") in older versions of jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript XOR Encrypt | PHP XOR Decrypt I am looking for a simple and lightweight method of encrypting a string with javascript then decrypting with PHP after it's been sent in a header. With code for both JS and PHP parts. There is no need for security as it's merely a means to obscure the string in the header. XOR seems to be the best/lightest way. There are plenty of examples with incomplete answers. The easiest answer seems to be the required PHP to decode this answer of the JS part: Simple Javascript encrypt, PHP decrypt with shared secret key Open to any other lightweight methods. A: If you XOR it, chances are you'll end up with invalid characters in your headers. If you don't need security, what is wrong with good ol' base64_encode()/base64_decode()? There are plenty of Javascript equivalent codes out there...
{ "language": "en", "url": "https://stackoverflow.com/questions/7515078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ClickOnce Single vs Multiple Solutions Deployment I've been trying to create deployment for a VSTO Word solution. I have two projects: an add-in and a template. I opt for ClickOnce as auto-updates will be implemented later on. I created separate ClickOnce installers for both the add-in and template. But the drawback with that one is the add-in must know where the template will be installed since the two projects will be working together closely. I looked around MSDN and saw the article in deploying multiple office solutions in a single ClickOnce deployment. See below for links: http://msdn.microsoft.com/en-us/library/dd465290.aspx http://blogs.msdn.com/b/vsto/archive/2009/05/20/deploying-multiple-office-solutions-in-a-single-installer.aspx I followed through the steps and tested the installation. The two projects are installed under one location but the template is not there. I modified the installer project to include the template and now it is being copied to the directory upon installation. When I open the template through code from the add-in, it produces an error and says it cannot find the VSTO of the template. I checked the installation folder and there are no VSTOs there. I tried publishing the Template project as a stand-alone. The installation is okay and when I open the template, it is able to load the VSTO properly from the installation folder ClickOnce used. I'm confused as to what I'm doing wrong. At the same time, is there any other difference I should know when putting two Office projects under one ClickOnce deployment, particularly Template type projects. I've read somewhere that ClickOnce does not go well with Template project types.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delphi cctalk protocol to implement a coin acceptor I want to integrate a coin acceptor into my Delphi 7 Application. This specific coin acceptor uses the ccTalk protocol. I've been looking for a ccTalk library which I can use from delphi. Any of you guys know of any ccTalk libraries out there? Thanks I think I must use a comport component, here some code procedure TForm1.Button_OpenClick(Sender: TObject); begin try if ComPort.Connected then ComPort.Close else ComPort.Open; except ShowMessage('Connection error !'); exit; end; end; procedure TForm1.Button_SettingsClick(Sender: TObject); begin ComPort.ShowSetupDialog; end; procedure TForm1.Button_SendClick(Sender: TObject); var Str: String; begin Str := Edit_Data.Text; if NewLine_CB.Checked then Str := Str + #13#10; try ComPort.WriteStr(Str); except ShowMessage('Comunication error !'); exit; end; end; procedure TForm1.ComPortRxChar(Sender: TObject; Count: Integer); var Str: String; begin ComPort.ReadStr(Str, Count); Memo.Text := Memo.Text + Str; end; If I call Button_SendClick with string "000 000 001 245 010" nothing happens .... Here's the device protocol manual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cross Threading between UI and Background Thread I've written a program that allows the user interface thread to access a populated array at almost any time. This array is populated by a separate background worker thread within an object. What will happen when the user interface thread accesses this array? Will it automatically lock it down before accessing it? I'm writing my code in managed C++/CLI. A: Array is not locked automatically. If it is accessed from multiple threads, it is your responsibility to provide synchronization. Another way is to serialize array update from a worker thread(s) through Control.BeginInvoke call - in this case array is accessed/changed only from UI thread, and synchronization is not needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the differences between Intel TBB and Microsoft PPL? I'm planning to start "playing" with task-based parallelism for a cross-platform project. I wanted to use Intel Threading Building Blocks. I'm starting with Windows and Visual Studio. As I just want to prototype for the moment, I'm thinking about "playing" only on windows, then have enough knowledge to use the library on all compatible platforms. I've learned that since VS2010, Microsoft provide a similar library, Parallel Processing Library, that have (almost) the same interface than Intel TBB. Some sources suggest, including TBB's team blog, that they build it together and that it's the same library. However its not really explicit because it's often suggested that there are minor differences between the two libraries. So, what are those differences, if any? Should I start directly with last stable ITBB or is it low-risk to just play with Microsoft PPL in prototypes and use ITBB on the cross-platform "real" project? A: TBB is a superset of PPL (as in VS2010), so it provides all PPL API plus its own APIs that PPL does not have. Note that namespace Concurrency in VS2010 also contains APIs of Concurrency Runtime (ConcRT, on top of which PPL is built), Asynchronous Agents and etc. TBB does not have most of that, though it has some (e.g. critical_section). As an alternative to Asynchronous Agents, the recent version of TBB features the new flow graph API. In theory, to switch from PPL to TBB, you just need to replace a path from where you take ppl.h (with TBB, the header comes in <tbbdir>/include/tbb/compat) and of course link with the TBB DLL. However in this case you will be limited to PPL API. To use the "extra" TBB API that does not exist in PPL (such as parallel_pipeline, parallel_reduce, concurrent_priority_queue and other), you need to work with TBB from the very beginning.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Using signed assembly causes TargetInvocationException In order to get a SQL CLR assembly to work in UNSAFE mode, I had to sign the assembly with a key. Another project in my solution references that assembly to use some of its functionality. During a runtime, when a call to a function inside a signed assembly is made, a TargetInvocationException is thrown with the following message: Could not load file or assembly 'MyAssembly, Version=12.2.1.3, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Is there a way to have .NET load the right assembly/by pass the exception? Edit: After running fusion on the main assembly, it appears that it tries to load MyAssembly twice each time with a different publickeytoken. The first load succeeds, but the second fails. And the error message references the publickeytoken of the failed load. Why is trying to do it twice? Here is the text of the error: The operation failed. Bind result: hr = 0x80131040. No description available. Assembly manager loaded from: C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll Running under executable C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer20.exe --- A detailed error log follows. === Pre-bind state information === LOG: DisplayName = MyAssembly, Version=12.3.2.148, Culture=neutral, PublicKeyToken=5ad1afbaab228075 (Fully-specified) LOG: Appbase = file:///C:/inetpub/wwwroot/MySolution converted to 2010/MyApplication/ LOG: Initial PrivatePath = C:\inetpub\wwwroot\MySolution converted to 2010\MyApplication\bin LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\8365e84e LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\8365e84e LOG: AppName = d8cf427a Calling assembly : (Unknown). LOG: This bind starts in default load context. LOG: Using application configuration file: C:\inetpub\wwwroot\MySolution converted to 2010\MyApplication\web.config LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config. LOG: Post-policy reference: MyAssembly, Version=12.3.2.148, Culture=neutral, PublicKeyToken=5ad1afbaab228075 LOG: GAC Lookup was unsuccessful. LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/8365e84e/d8cf427a/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/Temporary ASP.NET Files/root/8365e84e/d8cf427a/MyAssembly/MyAssembly.DLL. LOG: Attempting download of new URL file:///C:/inetpub/wwwroot/MySolution converted to 2010/MyApplication/bin/MyAssembly.DLL. LOG: Assembly download was successful. Attempting setup of file: C:\inetpub\wwwroot\MySolution converted to 2010\MyApplication\bin\MyAssembly.dll LOG: Entering download cache setup phase. LOG: Assembly Name is: MyAssembly, Version=12.3.2.148, Culture=neutral, PublicKeyToken=7a45b8ac095ea0f9 WRN: Comparing the assembly name resulted in the mismatch: PUBLIC KEY TOKEN ERR: The assembly reference did not match the assembly definition found. ERR: Setup failed with hr = 0x80131040. ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated. Thanks! A: PublicKeyToken=null It is looking for an assembly without a strong name. You need to update the assembly reference (remove and add it again) and rebuild the project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to delete two TreeNode at same time I have a TreeView and I want to remove 2 nodes of it at the same time. node.Remove(); This will delete the node, but after this code the next node will automatically selected. Is there a way to prevent that? Or better soloution for me will be deleting the next node right after its pervious node is deleted. You may ask why. In my program every pair of nodes are necessery for doing something. so If I delete one of them, TreeView control will jump to next member of that pair and because the last one is deleted, all my codes goes wrong since it can not find that node anymore. Please let me know if you need more info. A: Ok, I was lucky...My node texts are ending in "_1"and "_2" for each pair of nodes so I came up with this soloution: if (fileText.EndsWith("_1")) { selectedFile.NextNode.Remove(); selectedFile.Remove(); } else { selectedFile.PrevNode.Remove(); selectedFile.Remove(); } A: With simple tree view and a simple context menu this works for me if (tvwACH.SelectedNode.Text == "Child") { tvwACH.SelectedNode.NextNode.Remove(); tvwACH.SelectedNode.Remove(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bundler invalid sequence in US-ASCII Since upgrading my to using ruby 1.9.2 I've seen these kind of errors a lot using bundler (on Mac): Using aasm (2.3.1) from git://github.com/rubyist/aasm.git (at master) .../specification.rb:733: in `gsub': invalid byte sequence in US-ASCII (ArgumentError) My previous workaround was to not use the git source but that's not a workable workaround for all situations. From what I've read online you need to ensure that all your locales are set, but running locale I got this: LANG="en_GB.us-ascii" LC_COLLATE="en_GB.us-ascii" LC_CTYPE="en_GB.us-ascii" LC_MESSAGES="en_GB.us-ascii" LC_MONETARY="en_GB.us-ascii" LC_NUMERIC="en_GB.us-ascii" LC_TIME="en_GB.us-ascii" LC_ALL= I tried doing export LC_ALL="en_GB.us-ascii" to fill in that last one and running bundler again but that didn't fix the issue. A: You may correct this error writing this export LC_ALL="en_US.UTF-8" to your ~/.profile, ~/.bash_profile or similar. It works like a charm. A: The sequence is invalid in the US-ASCII locale because it's a UTF-8 character. The most likely fix is to set your LANG to something like "en_GB.UTF-8".
{ "language": "en", "url": "https://stackoverflow.com/questions/7515106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Override Ninject binding locally inside a test method to bind mock objects I have the following problem, I want to use Ninject in my unit tests. My thoughts about this were like this: 1) Define a global binding schema inside a module to bind my fake objects that I use inside the tests 2) When using a mock object bind it locally inside the test I didn't find a way to locally override the binding configuration, my idea is I locally create a mock object with expectations and I want the kernel.Get() method to return an object that has all the binding in place except that each tests adds a local mock object inside a test with expectations, this sounds to me to be readable and maintainable, as I only override 1 binding per test, the objects are mocks so they can't be configured inside the module as the test context is unknown How can I accomplish this, I am using c# and nunit. If my methodology is wrong I would like to hear the right one. A: I have the same problem and I understand that it's not the good way to do but on my side, I do integration tests; not unit tests. Here is my solution: Kernel.Rebind<TypeToBind>().ToConstant(Mock.Object); Where Kernel is the object that you used to create the binding. TypeToBind is the type that you want to inject dependency. Mock.Object is the object that you have previously setup. Again, I know that it's not very cool but while working on legacy code where unit tests are hard to insert, this could be a salvation to have a good safety net. A: You shouldn't use your IoC container to create the object you want to test in your unit tests. Instead create it manually using new and pass a mock/stub object for each constructor argument. A: I think using IoC framework for tests is the perfect way to do it. In fact, that is why IoC existed in the first place and then frameworks came. Guice(google's java injection DI framework) actually supports this feature where you pass in the Module with the production bindings and then pass in a TestModule that can override certain bindings with mockobjects and then you can test away. We have been doing this and it has been very clean for a long time now in java. I am getting into myself just now to try to have my tests rebind stuff yet keep the rest of the bindings.... There are also frameworks like AtUnit where you are supposed to be using the DI framework to test the objects and NOT use the new keyword at all.(unfortunately, I don't see a port of that framework to C# land yet :( ). NOTE: The reason this is desirable as when people add a new binding in production module and then use it in one of my system under test classes, it doesn't fail with nullpointer exceptions because an interface was not bound in the test. people keep adding and the test keeps working. In my opinion, you should only use the keyword "new" with dtos and such these days and all biz logic should be wired up with DI making it easy to add tests now or at a later point as well pretty easily(though I like to add tests first myself).
{ "language": "en", "url": "https://stackoverflow.com/questions/7515109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Create SQL INSERT Script with values gathered from table I need to create a INSERT script in order to insert in another database the same data. If in SQL Server I select "Script table as > INSERT To" I can easily recreate the skeleton for the INSERT statement. However since I have several records to migrate, I would prefer to avoid having to insert the values manually. Therefore is there any way to "automatically" get the INSERT script with also the values (coming from the target table) filled in? I know this could be done with SSIS, but I am wondering whether it would be possible as well with a quicker solution. A: Use the free SSMS tools pack to "generate insert statements"? Or in SSMS (don't have it on this PC to confirm) the export wizards allows you to "script data" too A: It will depend on the data types, because you need to conditionally enclose string values in quotes or cast numeric values as strings. You also need to deal with problem characters: SELECT 'INSERT INTO dbo.DestinationTable(col1, col2, col3) SELECT ' + CONVERT(VARCHAR(12), col1) + ',' + '''' + REPLACE(col2, '''', '''''') + ''',' + '''' + REPLACE(col3, '''', '''''') + ''';' FROM dbo.SourceTable; Vyas has a pretty complex stored procedure for this purpose. Of course you can do this much easier by just saying: INSERT INTO OtherDatabase.dbo.DestinationTable(col1, col2, col3) SELECT col1, col2, col3 FROM dbo.SourceTable; In other words, you don't need to "script" an insert, you can just run it... A: You can do this with SSMS. 1 - Right-click your database in Object Explorer. 2 - Select Tasks/Generate Scripts... 3 - On the Set Scripting Options page, click the Advanced button and make sure Types of data to script is set to Data only. The resulting script will have a USE DATABASE statement at the top. Change this to the database you would like to insert the data into. A: use the INSERT INTO ... SELECT format: http://blog.sqlauthority.com/2007/08/15/sql-server-insert-data-from-one-table-to-another-table-insert-into-select-select-into-table/ A: @RedFilter, your solution is working like a charm for less data SIZE. In my case, When I tried to open the Exported sql file, I faced the OutOfMemoryException. The file size is around 4GB. In order to get the data from that file, I tried BCP(Bulk Copy Program) approach. Hope that would be help full for someone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }
Q: what's the best return type for Select LINQ I'm just getting started with LINQ and C# and I'm unsure what's the recommended return type for a LINQ statement that returns a bunch of records. I found the following two notations that work both when linking the data to a gridview. Which approach should I use in what situation? public object SelectAll() { var query = from p in dc.Products select new { p.pk_product_id, p.product_name, p.product_price_kg }; return query; } public IQueryable<Product> SelectAll2() { var query = from p in dc.Products select p; return query; } A: You don't want to return object. I wonder where you have seen this. IQueryable<T> or IEnumerable<T> is the preferred way. A: If this method only gets called as the SelectMethod of a GridView, then it doesn't matter. The GridView code will be checking at execution time exactly what kind of data it's been given, and deciding what to do with it on the basis of what it is. Strong-typing the method doesn't make any difference to the GridView. If you're going to be consuming this method from your own code, then use the most specific type that makes sense. A: If you are building reusable data access code (and not just a query for a specific form or control) then you should take a look at repository patterns - have a look here. In this case you would want to return strongly typed entities from the query (and not objects from the result of an anonymous class) PS : you can shorten SelectAll2 to return dc.Products.AsQueryable();
{ "language": "en", "url": "https://stackoverflow.com/questions/7515115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automatic destruction of static object Why doesn't C++ create/destroy a static member of a template type. Observe the following example: #include <iostream> struct Dump { Dump() { std::cout << "CTOR" << std::endl; } ~Dump() { std::cout << "DTOR" << std::endl; } }; template <typename T> struct X { static Dump dump; }; template <typename T> Dump X<T>::dump; struct A : X<A> { }; int main() { A a; return 0; } I would have expected that on execution I see the string CTOR followed by DTOR. While I don't. What am I missing here? It has something to do with dump being the member of a template type, but that's as far as I get. A: I found something in § 14.7.1 Implicit instantiation. 1/ [...] The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, scoped member enumerations, static data members and member templates. [...] It goes on in the second note: 2/ Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist. Therefore, unless you use it, it should not be instantiated. This is not an optimization, just Standard [n3092] conformance. A: It is not instantiated, unless used. This works : int main() { A a; (void) a.dump; } Also, fix the compilation error : template <typename T> Dump X<T>::dump; A: Members of class templates are only instantiated if they are needed; in this case, nothing refers to the static member, so it is not instantiated, even if the class template itself is. You'll find that putting the statement X<A>::dump; somewhere will cause the member to be instantiated and an object created and destroyed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to access an Array Controller from App Delegate? I have a simple Core Data based Cocoa app that uses an ArrayController to display model objects (employees). Two buttons allow for adding and deleting employees. The add button is wired with bindings to the insert: action of the Array Controller however the delete button is wired to a confirmDelete method in the App Delegate, which shows a modal confirmation dialog. How do I get access in the confirmDelete method of the App Delegate to the Array Controller to remove the selected object from the Array Controller (and the underlying store)? A: You can simply do like this- * *Bind array controller to app delegate *In confirmDelete method, add this line after checking your conditions : [yourArrayController remove:nil]; Hope this helps :) ---- Edit ---- Please be sure to save the context after performing deletion, otherwise it will not be reflected in persistent store. ie. after this line: [yourArrayController remove:nil]; Add this line: NSError *error = nil; if(![self.managedObjectContext save:&error]){ NSLog(@"Some Useful Message!"); } Generally, this code is used in - applicationShouldTerminate: , which automatically saves it to persistent store, when application quits. A: Why is your application's delegate showing such a dialog, anyway? That's not a responsibility of the application's delegate. I suggest moving that, and anything else that isn't part of that object being the application's delegate, to another object. In my applications, that's usually the object that owns the window, the array controller, and anything else in that nib, and is owned (created in applicationWillFinishLaunching: and released in applicationWillTerminate:) by the application's delegate. Cleaning up your object graph is almost always the solution to any “how do I get to object A from object B?” question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB.NET 2.0 - StackOverflowException when using Thread Safe calls to Windows Forms Controls I have a Windows Forms app that, unfortunately, must make calls to controls from a second thread. I've been using the thread-safe pattern described on the http://msdn.microsoft.com/en-us/library/ms171728.aspx. Which has worked great in the past. The specific problem I am having now: I have a WebBrowser control and I'm attempting to invoke the WebBrowser.Navigate() method using this Thread-Safe pattern and as a result I am getting StackOverflow exceptions. Here is the Thread-Safe Navigate method I've written. Private Delegate Sub NavigateControlCallback(ByRef wb As WebBrowser, ByVal url As String) Private Sub AsyncNavigate(ByRef wb As WebBrowser, ByVal URL As String) Try If wb.InvokeRequired Then Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate) callback(wb, url) Else wb.Navigate(url) End If Catch ex As Exception End Try End Sub Is there a Thread-Safe way to interact with WinForms components without the side effect of these StackOverflowExceptions? A: This is the problem: If wb.InvokeRequired Then Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate) callback(wb, url) Else On the second line of the If block, you're just calling AsyncNavigate again. Directly. Resursively. With no marshalling to a UI thread. You should be using Invoke or BeginInvoke: If wb.InvokeRequired Then Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate) wb.BeginInvoke(callback(wb, url)) Else (Side-note: please don't swallow exceptions like that...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7515127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSURLConnection. I need a help saving data received I'm starting a NSURLConnection and I need to save data received from internet. In the - (void)connectionDidFinishLoading:(NSURLConnection *)connection I need to save data with different name using the original url as name of the data... How Can get this info (url) in the connectionDidFinishLoading using async request? If it is not possible can suggest me some other ways to do what I asked? Thanks Paolo A: *NOW ASIHTTPRequest Library is No Longer supported by the author so its good to start adopting some other libraries * I would suggest you use ASIHTTP request. I have been using this for a long time. The below code sample is for downloading data from a url asynchronously. - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request { // Use when fetching text data NSString *responseString = [request responseString]; // Use when fetching binary data NSData *responseData = [request responseData]; } - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; } UPDATE: - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; __block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setCompletionBlock:^{ // Use when fetching text data NSString *responseString = [request responseString]; // Use when fetching binary data NSData *responseData = [request responseData]; //here you have access to NSURL variable url. }]; [request setFailedBlock:^{ NSError *error = [request error]; }]; [request startAsynchronous]; } Try using GCD in ASIHTTP. Here inside the block you'll have access to the variable url. A: ** Answer valid only pre-iOS5. Since iOS5 Apple introduced the -originalRequest method that allows to avoid any further subclassing for this special purpose. In general Apple introduced the the NSURLConnection class so many improvements that it makes no longer necessary to subclass NSURLConnection unless non-trivial behaviours are required ** You can subclass NSURLConnection by adding an extra property called NSURL originalURL and then start it. When the delegate finish method is executed you can retrieve this property and do the rest of the job. * E.g. (I will show relevant parts, don't copy and paste please): MyURLConnection.h @interface MyURLConnection:NSURLConnection { @property (nonatomic,retain) NSURL *originalURL; } @end MyURLConnection.m @implementation MyURLConnection @synthesize originalURL; In your calling class: MyURLConnection *myConnection = [[MyURLConnection alloc] initWithRequest:myRequest delegate:myDelegate]; myConnection.originalURL = [request URL]; [myConnection start]; and finally in the delegate: - (void)connectionDidFinishLoading:(NSURLConnection *)connection { MyURLConnection *myConn = (MyURLConnection)connection; NSURL *myURL = myConn.originalUrl; // following code }
{ "language": "en", "url": "https://stackoverflow.com/questions/7515128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Bean validation & password confirmation, email exist I am using bean validation with annotations in my JSF project. I was wondering, how to create annotations for password confirmation and how to validate that an email doesn't exist in database? A: This kind of validation is not really applicable on entities. User entities do not hold double password fields, instead they hold just a single password field. Also entities do not necessarily hold an email field with a value which do not exist in the DB. You would end up with false errors whenever you want to edit an existing entity. I suggest you to do this validation in the view side, right before the entity is to be persisted in the DB. In JSF you can use Validator for this. You can find examples of a password confirmation validator in the answers on this question: How validate two password fields by ajax?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xcode warning "-method 'imagePath' not found (return type defaults to 'id' " Hi I have this weird warning in my iphone app: -method 'imagePath' not found (return type defaults to 'id' It's giving me this warning on the following line: UIImage *image = [UIImage imageNamed:[_occasion imagePath]]; Here is my Occasion class header: #import <Foundation/Foundation.h> @interface Occasion : NSObject { NSString *_title; NSDate *_date; NSString *_imagePath; } @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSDate *date; @property (nonatomic, retain) NSString *imagePath; + (id)occasionWithTitle:(NSString *)title date:(NSDate *)date imagePath:(NSString *)imagePath; - (id)initWithTitle:(NSString *)title date:(NSDate *)date imagePath:(NSString *)imagePath; @end The weird thing is I'm getting this warning only on the (imagePath property of Occasion, while the other 2 properties are working fine namely: [_occasion date] and [_occasion title] I dunno why is it complaining the method is not found while it is a property and it does exist. A: I finally found the solution. I imported the Occasion.h file in MyFile.m since I was using the forward declearation @class Occasion.h only in MyFile.h. It's still weird though cuz in AnotherFile.h only @class Occasion.h was enough without the import in the AnotherFile.m
{ "language": "en", "url": "https://stackoverflow.com/questions/7515145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User defined resources folder in an included jar to be built same as the android res folder to generate a new R.java class My problem statement being, there is a android project x and my project y. i want to add some classes from my project and some resource files to add as a jar in project x. Basically i do not want the creater of project x to write or add anything else except my jar. I want to keep a different "Myres" folder in this included jar. This Myres folder is similar to the "res" folder in an Android application. And have "Myres" folder to be built same as the res folder and get the generated java class , the R.java class that has resources both from res and Myres folder. Last option that i see is write some piece of runnable code that will directly place the resources files from my jar to the project x res folder(and is this one possible). please note that there will not be any name clashes between the files. A: You'll need to create a library project. If you don't want to provide the source code, you can build a jar file and include that in your library project. There's no other easy way to include the \res files outside of a library or copying them into the second app. They can't be included in a jar afaik. Some details on libraries http://developer.android.com/guide/developing/projects/projects-eclipse.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7515146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get a String value from a SQL query in Grails? I need to return a String value so I can build a object from another app via Restful. Part of my code the following snippet follows: def searchProductionOrder (String sequentialNumber) { def sql = Sql.newInstance(dbUrl, user, pwd, driverName) String idProdOrder = sql.execute(""" SELECT production_order.idProdOrder FROM production_order production_order WHERE production_order.sequential_number LIKE ${sequentialNumber} """).toString(); String url = ":8080/app2/api/productionOrder/"+idProdOrder // call to Restful service return Order } But the String url is always interpreted (and I printed it for testing) as: url: :8080/app2/api/productionOrder/true I need the idProdOrder String to return its value, not a boolean value. How can I do so? Thanks in advance, A: Instead of doing execute which will always return a Boolean do something like the following def searchProductionOrder (String sequentialNumber) { def sql = Sql.newInstance(dbUrl, user, pwd, driverName) String idProdOrders = sql.rows(""" SELECT production_order.idProdOrder FROM production_order production_order WHERE production_order.sequential_number LIKE ${sequentialNumber} """) if(idProdOrders.size()==1) { String url = ":8080/app2/api/productionOrder/"+idProdOrders[0].idProdOrder // call to Restful service return Order } else { //You have either no results from the query or more then 1 so do something } } If you wanted to make sure you did something for each result you could use the sql.eachRow as well. The documentation is here. Only thing to double check is the name of the entry it returns I'm not sure what it will do since you do production_order.idProdOrder
{ "language": "en", "url": "https://stackoverflow.com/questions/7515152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SUMIF when the range is a range of dates Here's what I want to do. I have the following table: And another one that looks like this: Here's what I want to do. A SUMIF .. the range is the A column in the first table (picture 1) ...but the problem is here... the criteria is that I want the day in that date to be equal with the number in the 2nd table... and then I want to sum from column D. I tried the formula but it didn't work. Could you help me with this situation? Thanks! A: Use this =SUMPRODUCT((DAY(A1:A50)=A1)*(B1:B50)) Where A1:A50 range of dates A1 the day to find B1:B50 The range of values to SUM []´s A: You can also use an array formula: =SUM(IF(DAY(Sheet1!$A$1:$A$11)=Sheet2!A2,Sheet1!$D$1:$D$11,0)) Enter the formula text with Ctrl+Shift+Enter. A: "the criteria is that I want the day in that date to be equal with the number in the 2nd table" As a date consists of a day AND month, year, just to provide a day as parameter isn't enough. If your intention is e.g. to get a total "per day in the current MM/YY"YYY you know what to do - create two fields for the YYYY and MM you want to look at in the table header. Basically there is nothing wrong with using dates in a SUMIF directly, like in =SUMIF($A$1:$A$15,DATE(2011,9,F1),$B$1:$B$15) because at the end a date is a number. Alternatively you may use a Pivot table which aggregatees by day whatever date you have in the list, and you can sort/filter on any key field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate - Two different transaction will commit successfully I am using two different database. I am using two different session for delete records from both database. The code is below: try{ Session session1 = factory.getSession(); Transaction trn1 = session1.beginTrn(); session1.delete(foobar); trn1.commit(); Session session2 = jbomContext.getGrahpSession(); Transaction trn2 = session2.beginTrn(); session2.delete(box);`enter code here` trn2.commit(); }catch(Exception e){ trn1.rollback(); trn2.rollback(); } Here, the problem is if the error is occurred in transaction2 i couldn't rollback the transaction1.I have some idea about two phase commit. but i need to rollback the transaction if exception will happen both transaction. A: You cannot rollback tr1 (if tr2's commit fails) as tr1 will be already committed by then. At least I dont see a native way of doing this in hibernate. What you can probably do is to use distributed transaction (JTA datasource) if you are on a full blown Java EE App Server or can enable it by some other means (something like this and Spring's JtaTransactionManager).
{ "language": "en", "url": "https://stackoverflow.com/questions/7515160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Visual Basic 2010 HMAC SHA1 i got a code to convert a string to a hmac sha1 encyption. However, i cant get it to work. Here is my code: Public Shared Function HashString(ByVal StringToHash As String) As String Dim myEncoder As New System.Text.UTF32Encoding Dim Key() As Byte = myEncoder.GetBytes("thisismykey") Dim Text() As Byte = myEncoder.GetBytes(StringToHash) Dim myHMACSHA1 As New System.Security.Cryptography.HMACSHA1(Key) Dim HashCode As Byte() = myHMACSHA1.ComputeHash(Text) Return Convert.ToBase64String(HashCode) End Function When i run the function like this: TextBox1.Text = HashString("thisismystring") I get 04p075DKS2Suw9jGQKC5Q7mYjvI= in the textbox. What i should get is c2bc9dd26b76d5b61a40ac788220eef0b26cb2bb Anyone has any idea on how to solve this? Please help :) A: I found the solution. I just converted the byte to a string, made it to lower and replaced - with nothing. See my code below :) Public Function HashString(ByVal StringToHash As String, ByVal HachKey As String) As String Dim myEncoder As New System.Text.UTF8Encoding Dim Key() As Byte = myEncoder.GetBytes(HachKey) Dim Text() As Byte = myEncoder.GetBytes(StringToHash) Dim myHMACSHA1 As New System.Security.Cryptography.HMACSHA1(Key) Dim HashCode As Byte() = myHMACSHA1.ComputeHash(Text) Dim hash As String = Replace(BitConverter.ToString(HashCode), "-", "") Return hash.ToLower End Function Example Usage: TextBox1.Text = HashString("thisismystring", "thisismykey") Thanks for your help :) A: Your 04p075DKS2Suw9jGQKC5Q7mYjvI= is in Base64. Your c2bc9dd26b76d5b61a40ac788220eef0b26cb2bb is in hex. You need to convert one into the other format so you can compare them correctly. ETA: I checked, the two don't match, your hex gives me wryd0mt21bYaQKx4giDu8LJssrs= in Base64. I suspect the problem may lie with using UTF32 encoding, this is very unusual. UTF8 or UTF16 are much more common. Try UTF8 first. A: correction depuis maj EXCEL, pour faire du mD5, il faut copier coller le code ci-dessous Option Explicit Private Const HP_HASHVAL = 2 Private Const HP_HASHSIZE = 4 Private Const PROV_RSA_FULL As Long = 1 Private Const ALG_CLASS_HASH = 32768 Private Const ALG_TYPE_ANY = 0 Private Const ALG_SID_MD2 = 1 Private Const ALG_SID_MD4 = 2 Private Const ALG_SID_MD5 = 3 Private Const ALG_SID_SHA1 = 4 Private Const CRYPT_NEWKEYSET = &H8 Private Const CRYPT_VERIFYCONTEXT As Long = &HF0000000 Enum HashAlgorithm MD2 = ALG_CLASS_HASH Or ALG_TYPE_ANY Or ALG_SID_MD2 MD4 = ALG_CLASS_HASH Or ALG_TYPE_ANY Or ALG_SID_MD4 MD5 = ALG_CLASS_HASH Or ALG_TYPE_ANY Or ALG_SID_MD5 SHA1 = ALG_CLASS_HASH Or ALG_TYPE_ANY Or ALG_SID_SHA1 End Enum Private Declare Function CryptAcquireContext Lib "Advapi32" Alias "CryptAcquireContextA" (ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, ByVal dwProvType As Long, ByVal dwFlags As Long) As Long Private Declare Function CryptReleaseContext Lib "Advapi32" (ByVal hProv As Long, ByVal dwFlags As Long) As Long Private Declare Function CryptCreateHash Lib "Advapi32" (ByVal hProv As Long, ByVal Algid As Long, ByVal hKey As Long, ByVal dwFlags As Long, ByRef phHash As Long) As Long Private Declare Function CryptDestroyHash Lib "Advapi32" (ByVal hHash As Long) As Long Private Declare Function CryptHashData Lib "Advapi32" (ByVal hHash As Long, pbData As Any, ByVal dwDataLen As Long, ByVal dwFlags As Long) As Long Private Declare Function CryptGetHashParam Lib "Advapi32" (ByVal hHash As Long, ByVal dwParam As Long, pbData As Any, pdwDataLen As Long, ByVal dwFlags As Long) As Long Public Function HashString(ByVal Str As String, Optional ByVal Algorithm As HashAlgorithm = MD5) As String On Error Resume Next Dim hCtx As Long Dim hHash As Long Dim lRes As Long Dim lLen As Long Dim lIdx As Long Dim abData() As Byte lRes = CryptAcquireContext(hCtx, vbNullString, vbNullString, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) If lRes <> 0 Then lRes = CryptCreateHash(hCtx, Algorithm, 0, 0, hHash) If lRes <> 0 Then lRes = CryptHashData(hHash, ByVal Str, Len(Str), 0) If lRes <> 0 Then lRes = CryptGetHashParam(hHash, HP_HASHSIZE, lLen, 4, 0) If lRes <> 0 Then ReDim abData(0 To lLen - 1) lRes = CryptGetHashParam(hHash, HP_HASHVAL, abData(0), lLen, 0) If lRes <> 0 Then For lIdx = 0 To UBound(abData) HashString = HashString & Right$("0" & Hex$(abData(lIdx)), 2) Next End If End If End If CryptDestroyHash hHash End If End If CryptReleaseContext hCtx, 0 If lRes = 0 Then MsgBox Err.LastDllError End If End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/7515164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checkbox, unselect and select What I want is when checkbox1 is selected both checkbox labelled 1 will get selected and background will be removed here is the fiddle for eg if i select checkbox1 it should select both checkbox labelled checkbox1 A: The problem is that searching for ID $("#somethin") is not possible to select more than one element. IF you search for class, then your example works.. well, with some minor changes :) $(document).ready(function() { $('input[type=checkbox]').change(function(){ var pos; pos = this.id; // global hook - unblock UI when ajax request completes $(document).ajaxStop($.unblockUI); if($(this).prop("checked")) { $("."+pos).parent().removeClass("highlight"); $("."+pos).prop('checked', true) //ajax to add uni } else { //ajax to remove uni $("."+pos).parent().addClass("highlight"); $("."+pos).prop('checked', false) } }); }); A: You can't have multiple DOM elements with the same id. See this fiddle for a working example, but it's not as generic as you may need. A: Select multiple elements using class. You can try this.. <script language="javascript" type="text/javascript"> $(function () { $("#checkbox1").click(function () { $('.case').attr('checked', this.checked); }); }); </script> and your html code will be like below <div> <table> <tr> <td><input type="checkbox" id="checkbox1" class="highlight"/></td> <td>Item1</td> <td>value</td> </tr> <tr> <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td> <td>Item2</td> <td>value</td> </tr> </table> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7515167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: a question about expect and tcl I have a question about expect/tcl, I expect the following expect "class room: classroom 1" send "classroom" send "classroom" will return "class room: classroom 1" but this does not match, because the expected matching become class room: classroom 1: how to handle the ":" in expect? A: First piece of advice for developing an expect program: before you spawn use this command exp_internal 1 That will show you what expect sees, and you can see how it does and does not match your expected patterns. Next, you can specify regular expressions for your patterns with expect -re {^pattern$}. The default pattern mode is glob-style matching, which is documented in Tcl's string match command. Tcl regular expressions are documented here. Do you want to code this: send "classroom\r" expect -re {class room: classroom 1:?} A: expect will match any substring send "hello" expect "he" That will match. Where is the second ":" coming from in yours?
{ "language": "en", "url": "https://stackoverflow.com/questions/7515174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC Contrib Portable areas and static content I have followed a couple of guides on how to serve static content from a portable area but with no luck. I have two projects, a web project and a class library (which serves as my portable area). In my portable area (lets call it 'MyArea' for namesake) I have a Content folder with three folders inside that, Scripts, Styles, Images. In the Scripts folder I have a simple js file as an embedded resource ('Hello.js'). My understanding is that the RegisterDefaultRoutes method called by RegisterArea creates routes for these which map to the following urls: directory /Areas/AreaName/Content/Images maps to the URL /AreaName/Images directory /Areas/AreaName/Content/Styles maps to URL /AreaName/Styles directory /Areas/AreaName/Content/Scripts maps to URL /AreaName/Scripts My layout view (_layout.cshtml) (which is in my web project which imports the MyArea project as a project reference) has the following in the head: <script src="@Url.Content("~/MyArea/Scripts/Hello.js")" type="text/javascript"></script> However, inspecting this returns a 404 so I must be doing something wrong I have also followed the guides below with no luck http://geekswithblogs.net/michelotti/archive/2010/04/13/mvc-portable-areas-enhancement-ndash-embedded-resource-controller.aspx http://groups.google.com/group/mvccontrib-discuss/browse_thread/thread/b5f9c77f3a7523ff What am I doing wrong? Thanks very much. A: Ok... so it was me doing something silly. I didn't follow the proper naming conventions, my Content folder was located in: Project -> Content Whereas it should have been in Project -> {areaname} -> Content (i.e. Project -> MyArea -> Content) It works now, Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7515177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upgrade to PHP5 on Plesk 8.0: is my webhost full of it? I asked my host to upgrade from an old PHP4 version to the latest PHP version available 5.x.x (?) and they told me I need to pay for a new server because they can't upgrade to PHP5 on Plesk 8.0. My question is: shouldn't they be able to upgrade Plesk on the current server and then upgrade to PHP5? A: I found this answer on google.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find the difference of 2 values for the 2 latest dates Say I have the following data: Client Date Money 31CDAAFE-93BA-4666-AE6D-2253059990BB 2011-08-31 200000000.00 31CDAAFE-93BA-4666-AE6D-2253059990BB 2011-07-31 198000000.00 31CDAAFE-93BA-4666-AE6D-2253059990BB 2011-04-31 108000000.00 Is there an easy way to find the difference between the amounts (Money) for the latest and second latest record? So for this data set the answer would be: 31CDAAFE-93BA-4666-AE6D-2253059990BB 2011-08-31 2000000.00 I basically need to return the 1st record with the client and date and the difference between the 2. Note there are multiple clients, dates and money and if there is only one date for a client I can just return the amount. I've got as far as ranking the data but can't for the life of me figure out how to end up the result in one row...am I missing something obvious? SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY Date DESC) AS Sequence FROM MyTable A: ;WITH aCTE AS ( SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY [Date] DESC) AS rn FROM MyTable ) SELECT T1.Client, T1.Money - ISNULL(T2.Money, 0) FROM aCTE T1 LEFT JOIN aCTE T2 ON T1.Client = T2.Client AND T2.rn = 2 WHERE T1.rn = 1 Note: this covers where there is no "previous" row A: You can try this: WITH CTE AS ( SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY Date DESC) AS Sequence FROM MyTable ) SELECT A.Client, A.[Money] - B.[Money] MoneyDifference FROM (SELECT * FROM CTE WHERE Sequence = 1) A INNER JOIN (SELECT * FROM CTE WHERE Sequence = 2) B ON A.Client = B.Client A: You have most of the work done. All that's left to do is to wrap your statement into a WITH statement, JOIN with itself and retain all rows where Sequence = 1. Note that clients with only 1 record will not be shown. I assume that is the most logical thing to do. You should change the INNER JOIN to a LEFT OUTER JOIN if my assumption is wrong. Using WITH ;WITH q AS ( SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY Date DESC) AS Sequence FROM MyTable ) SELECT q1.Client , q1.Date , q1.Money - q2.Money FROM q q1 INNER JOIN q q2 ON q2.Client = q1.Client AND q2.Sequence = q1.Sequence + 1 WHERE q1.Sequence = 1 Equivalent statement without WITH As you indicate in comments that you should read up on using WITH statements, in essence, the WITH statement in the example * *shortens the statement *makes it more readable *makes it more maintainable. Note that in this example, there is no recursion involved (usually associated with WITH statements) SELECT q1.Client , q1.Date , q1.Money - q2.Money FROM ( SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY Date DESC) AS Sequence FROM MyTable ) q1 INNER JOIN ( SELECT Client, Date, Money, ROW_NUMBER() OVER (PARTITION BY Client ORDER BY Date DESC) AS Sequence FROM MyTable ) q2 ON q2.Client = q1.Client AND q2.Sequence = q1.Sequence + 1 WHERE q1.Sequence = 1 A: I would break it down into two embedded sub-queries: One to find the row with the maximum date, the other to find the row with the maximum date not equaling the date of the first query, the join those queries on 1=1 (since you're getting one row from each), then get the difference in the overall query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Core Data Errors 1600 and 133020 I think I'm coming to my wits end with this. I'm working on an app that executes and api call and then stores the response within Core Data. I'm also pretty n00b at iphone development, so if my question could use more information, please let me know. It seems like whenever I run the app, and the API is called for the first time, it works fine, but when it updates the data already in core data, I get either error 130020 or 1600. I looked up what they are: 1600 - NSValidationRelationshipDeniedDeleteError 133020 - NSManagedObjectMergeError From what I read a 1600 can occur when a deleteRule is set to deny, but each of my relationship delete rules are set as nullify in the data model. And I have no idea what to do at all about 133020. The other interesting thing to note is that there doesn't seem to be any logic (that I can determine) as to when these errors pop up. One time it could be 1600, one time 133020, and another time it could be absolutely nothing, for the same operation within the same sequence. If someone could give me some pointers as to what I can look at, or even how I can try to debug this, I would appreciate it greatly. I pasted below 2 sections of the code which seem to consistently cause at least one of the errors: - (void)updatePhotoAlbumsForGroup:(NSNumber *)gid notifyRegistrant:(id <APRegistrant>)registrant { NSManagedObjectContext *context = [[self newContextWithSharedCoordinator] autorelease]; [self registerObserver:registrant selector:@selector(managedObjectContextDidSave:) forDidSaveNotificationFromContext:context]; APGroup *group = [APCoreDataRequests fetchGroupWithGID:gid inContext:context]; // Download and create new albums [self queueBlock:^{ NSArray *drupalAlbums = [_drupalRequests getPhotoAlbumsForGroup:gid]; if ([drupalAlbums count]) { [self refreshPhotoAlbumsForGroup:group withDrupalAlbums:drupalAlbums inContext:context]; // Save any changes dispatch_async(dispatch_get_main_queue(), ^{ [self saveContext:context]; }); } }]; } And here is the refreshphotoalbumsforgroup function that is called above: /** Uses the drupal albums to create new albums, update existing ones, and delete dead ones. */ - (void)refreshPhotoAlbumsForGroup:(APGroup *)group withDrupalAlbums:(NSArray *)drupalAlbums inContext:(NSManagedObjectContext *)context { NSMutableArray *newDrupalAlbums = [NSMutableArray arrayWithArray:drupalAlbums]; NSMutableArray *existingAlbumsToDelete = [NSMutableArray array]; // Update existing albums and collect albums to be deleted and created if (group.photoAlbums) { for (APPhotoAlbum *album in group.photoAlbums) { BOOL deleteAlbum = YES; for (NSDictionary *drupalAlbum in drupalAlbums) { NSNumber *aid = [drupalAlbum objectForKey:kGetPhotoAlbumsAIDKey]; if (aid) { if ([aid isEqualToNumber:album.aid]) { deleteAlbum = NO; // Update existing album NSString *title = [drupalAlbum objectForKey:kGetPhotoAlbumsTitleKey]; if (title) album.title = title; NSString *repPhotoURL = [drupalAlbum objectForKey:kGetPhotoAlbumsRepresentativePhotoURLKey]; if (repPhotoURL) album.representativePhotoURL = repPhotoURL; NSNumber *numPhotos = [drupalAlbum objectForKey:kGetPhotoAlbumsNumberOfPhotosKey]; if (numPhotos) album.numberOfPhotos = numPhotos; NSNumber *dateNum = [drupalAlbum objectForKey:kGetPhotoAlbumsModificationDateKey]; if (dateNum) album.modificationDate = [NSDate dateWithTimeIntervalSince1970:[dateNum doubleValue]]; NSNumber *radioactivity = [drupalAlbum objectForKey:kGetPhotoAlbumsRadioactivityKey]; if (radioactivity) album.radioactivity = radioactivity; [newDrupalAlbums removeObject:drupalAlbum]; break; } } else { [newDrupalAlbums removeObject:drupalAlbum]; } } if (deleteAlbum) { [existingAlbumsToDelete addObject:album]; } } } // Delete albums for (APPhotoAlbum *album in existingAlbumsToDelete) { [context deleteObject:album]; } // Create and add new albums NSMutableSet *currentAlbums = [NSMutableSet setWithSet:group.photoAlbums]; for (NSDictionary *drupalAlbum in newDrupalAlbums) { NSNumber *aid = [drupalAlbum objectForKey:kGetPhotoAlbumsAIDKey]; APPhotoAlbum *album = [APCoreDataRequests fetchPhotoAlbumWithAID:aid inContext:context]; // Set album properties NSString *title = [drupalAlbum objectForKey:kGetPhotoAlbumsTitleKey]; if (title) album.title = title; NSString *repPhotoURL = [drupalAlbum objectForKey:kGetPhotoAlbumsRepresentativePhotoURLKey]; if (repPhotoURL) album.representativePhotoURL = repPhotoURL; NSNumber *numPhotos = [drupalAlbum objectForKey:kGetPhotoAlbumsNumberOfPhotosKey]; if (numPhotos) album.numberOfPhotos = numPhotos; NSNumber *dateNum = [drupalAlbum objectForKey:kGetPhotoAlbumsModificationDateKey]; if (dateNum) album.modificationDate = [NSDate dateWithTimeIntervalSince1970:[dateNum doubleValue]]; NSNumber *radioactivity = [drupalAlbum objectForKey:kGetPhotoAlbumsRadioactivityKey]; if (radioactivity) album.radioactivity = radioactivity; [currentAlbums addObject:album]; } group.photoAlbums = [NSSet setWithSet:currentAlbums]; } A: Try setting the mergePolicy of your managed object context, e.g. to NSMergeByPropertyObjectTrumpMergePolicy. It defaults to NSErrorMergePolicy which always causes a validation error in case multiple contexts edit the same object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OLAP - levels have the same name I have the following Hierarchy: <Dimension name="Locations"> <Hierarchy hasAll="true" allMemberName="All Locations" primaryKey="loc1Id" uniqueKeyLevelName="loc1Id"> <Table name="OLAP_Budget"/> <Level name="location1" column="location1" uniqueMembers="true"/> <Level name="location2" column="location2" uniqueMembers="true" hideMemberIf="IfBlankName"/> <Level name="location3" column="location3" uniqueMembers="true" hideMemberIf="IfBlankName"/> </Hierarchy> The problem: "location1" is exit through different fiscal Year and has different children in each fiscal year. I displayed "fiscalYear" dimension in column but when i choose to display values of a specific fiscalYear it display all children overall the fiscalYears. How can i solve this problem ? Thanks in Advance A: Well, SSAS does not know what the relationship between years and locations is - and it is not supposed to. Typically, you'd have data for some combinations and the only way (other than placing Year and Location in the same dimension and building a user-defined hierarchy, which I would not advise as it sounds wrong), is to write your query with NON EMPTY. In example: SELECT { [Measures].[Some Measure]* [Date].[Calendar].[Year].&[2011] } ON 0, { [Location].[Location 1].Members } ON 1 FROM [Some Cube] shows all Locations on rows, regardless whether they have data against them or not. However, if you modify it to: SELECT { [Measures].[Some Measure]* [Date].[Calendar].[Year].&[2011] } ON 0, NON EMPTY { [Location].[Location 1].Members } ON 1 FROM [Some Cube] Then you get locations which have data in 2011. This way you could get the result you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Join same table twice on different key I have a two tables accounts and subs. The first table has id and the second table has fields id, requester_account_id, grabber_account_id I want the count of how many sub requests an account made, and how many grabs he did (based on if the requester_account_id/grabber_account_id is populated with his id) In one query output: +------------+----------------+-----------------+ | account_id | subs_requested | subs_grabbed | +------------+----------------+-----------------+ | 1 | 4 | 3 | | 3 | 2 | 1 | +------------+----------------+-----------------+ A: Use something like select accounts.id, count(distinct s1.id) as num_req, count(distinct s2.id) as num_grab from accounts left join subs as s1 on accounts.id = s1.requester_account_id left join subs as s2 accounts.id = s2.grabber_account_id group by accounts.id The trick is to use table subs twice: subs as s1 and subs as s2, every time joined by different field.... Note regarding efficiency: I'm not sure but I believe this solution is faster than the subquery solution, not tested it though (at least it won't be slower). I always prefer left join over subquery whenever possible. A: This should work: SELECT a.account_id, (SELECT COUNT(*) FROM subs WHERE requester_account_id=a.account_id) AS subs_requested, (SELECT COUNT(*) FROM subs WHERE grabber_account_id=a.account_id) AS subs_grabbed FROM accounts a A: As I understand what you're looking for, it would be something like this: select a.id as account_id, count(distinct sr.id) as requests, count(distinct gr.id) as grabs from accounts a left outer join subs sr on sr.requester_account_id = a.id left outer join subs gr on gr.grabber_account_id = a.id On occasion, I have experienced weirdness with MySQL when doing aggregate functions on left joins, so here's another way: select a.id as account_id, (select count(distinct sr.id) from subs sr where sr.requester_account_id = a.id) as requests, (select count(distinct gr.id) from subs sr where gr.grabber_account_id = a.id) as grabs from accounts a A: You can join the subs table only once if you want (not sure this performs better) select acc.id sum(if(sub.requester_account_id = acc.id, 1, 0)) as req, sum(if(sub.grabber_account_id = acc.id, 1, 0)) as grab from subs sub, accounts acc where sub.requester_account_id = acc.id or sub.grabber_account_id = acc.id group by acc.id
{ "language": "en", "url": "https://stackoverflow.com/questions/7515202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use an NSFetchedResultsController without a UITableView What I want to do is select from my core data entity and effectively group by the date attribute. So it will return something like this: NSDictionary results { NSDate 01/01/2011 => NSArray { NSManagedObject obj1, NSManagedObject obj2, NSManagedObject obj3 } NSDate 02/01/2011 => NSArray { NSManagedObject obj4 } NSDate 03/01/2011 => NSArray { NSManagedObject obj5, NSManagedObject obj6 } } I hope that makes sense. I don't know if I'm even using the right class. I have heard/read that using the sectionNameKeyPath:@"date" helps with splitting a table view into sections. I don't want to do this, I just want to be able to access the sections in an array/dictionary structure. Can you give me an example of how to use this? Its different from the usual: NSArray *results = [context executeFetchRequest:...] I'm used to... Thank you A: You can use a NSFetchedResultsController without a UITableView. Take a look at the sectionIndexTitles property. That returns an array of sections based on your sectionNameKeyPath. In your case, it should return an array of NSDates. You could then use the objectAtIndexPath method to access the records in each group and build an array of records to load into your dictionary. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7515210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: git show commit in beyond compare I would like to see a specific commit in Beyond Compare or any other separate diff tool while viewing it via git show. I tried looking at help of git show/difftool/config but couldn't find anything. Does anyone know how it can be done? I've looked at Git Diff with Beyond Compare and configured Beyond Compare for git difftool but I also want to use it as tool from git show A: Once you have a diff tool set up, like the awesome p4merge, you can do this: git diff HEAD HEAD~1 Works like a charm. Similarly if you want to see the commit before that, you can do: git diff HEAD~1 HEAD~2 A: I managed to use git difftool to see commits that I normally used to see via git show. git show $commit translates to git difftool $commit^ $commit. The above command shows difference between commit's parent ($commit^) and commit. All this is of course after configuring Beyond Compare with difftool. A: You can also create an alias "showtool" to wrap the call to git difftool: set +o histexpand git config --global alias.showtool "!sh -c 'if [ -z \$1 ]; then REVISION="HEAD"; else REVISION="\$1"; fi; git difftool \$REVISION~ \$REVISION' -" .. then you can execute: git showtool 81e945b .. or just git showtool .. as a shortcut for git difftool 81e945b~1 81e945b to show the changes introduced in 81e945b using the configured difftool, or in the second case git difftool HEAD~1 HEAD A: This worked for me nicely, to show the diff of the last commit git difftool HEAD~ HEAD For other commits you can replace HEAD with commit hash eg: git difftool 1234ABCD~ 1234ABCD A: I think that git show is based on the tool set in the GIT_PAGER variable. I don't use Beyond Compare but i think that you can try something like this: $ GIT_PAGER='bc3' git show <whatever> Maybe you should fill the GIT_PAGER variable with some additional parameter that allows bc3 process the input. There are more suitable ways to persist the pager. This question can give you more tips about how to do it. A: Based on @javabrett answer I have created https://github.com/albfan/git-showtool to support commands like $ git showtool -y :/my\ commit\ message
{ "language": "en", "url": "https://stackoverflow.com/questions/7515213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Grails JSON/XML generation fails I have some code in my Controller that's throwing some unknown exceptions to me, can someone give me a hint of what is going on? see the code below: class FooController { static allowedMethods = [save: "POST", update: "POST", delete: "POST"] def xmlList = { render Foo.list() as XML } def jsonList = { render Foo.list() as JSON } //... } when I try to generate the JSON in the middle of it(the strangest part of it...) I get the following stacktrace: [http-8080-2] [tenant 122] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /project/foo/jsonList Stacktrace follows: org.codehaus.groovy.grails.web.json.JSONException: Misplaced key. at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.convertAnother(JSON.java:161) at grails.converters.JSON.value(JSON.java:198) at grails.converters.JSON.render(JSON.java:133) at grails.converters.JSON.render(JSON.java:149) at com.foo.FooController$_closure2.doCall(FooController.groovy:18) at com.foo.FooController$_closure2.doCall(FooController.groovy) at java.lang.Thread.run(Thread.java:662) when I try to generate the xml, I get the following error on the screen: This page contains the following errors: error on line 1 at column 68: Encoding error Below is a rendering of the page up to the first error. and the following stacktrace: [http-8080-2] [tenant 122] ERROR errors.GrailsExceptionResolver - Exception occurred when processing request: [GET] /project/foo/xmlList Stacktrace follows: java.lang.NullPointerException at grails.converters.XML.getElementName(XML.java:130) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.convertAnother(XML.java:173) at grails.converters.XML.render(XML.java:113) at grails.converters.XML.render(XML.java:256) at com.foo.FooController$_closure1.doCall(FooController.groovy:14) at com.foo.FooController$_closure1.doCall(FooController.groovy) at java.lang.Thread.run(Thread.java:662) here is my Foo.groovy: @MultiTenant class Foo { String name String description List modules = new ArrayList(); static belongsTo = [something : Something] static hasMany = [anything : Anything] static mapping = { table 'foo' version false // version is set to false, because this isn't available by default for legacy databases id generator:'identity', column:'id' sort "name" description sqlType: "text" tenantId column:'tenant_id' } static constraints = { something(blank:false) name(size:1..100, blank:false, unique:['tenantId','project']) description() } @Override String toString() { return name } } Grails version -> 1.3.7 I'm new to grails, forgive me if I'm asking something newbieish, but I'm in real trouble here... A: I can't try your code at the moment so I try to suggest you a workaround: def jsonList = { def foos = Foo.list() render(contentType:"text/json") { foos { for(f in foos) { foo(name: f.name, description: f.description) } } } } And the same for your xmlList controller method. Let me know if that works for you. A: This is the work around that I am using. def foos = Foos.findAll() def array = [] for (Foo acc : foos) { def data = new Foo(id: acc.id, bar : acc.bar) array << data } render array as JSON
{ "language": "en", "url": "https://stackoverflow.com/questions/7515218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the new JNDI names (esp. ConnectionFactory) I upgraded to JBoss 7.0.1 and we are using the following JNDI lookup to get a connection to a HornetQ message queue. InitialContext jndiContext = new InitialContext(); QueueConnectionFactory qf = (QueueConnectionFactory) jndiContext.lookup( "ConnectionFactory" ); This results in a NameNotFoundException when used with JBoss 7. I have also tried the following: * *java:jms/ConnectionFactory *java:env/ConnectionFactory .. and some others. But I think guessing won't get me far. How do I get the new JNDI names that are not logged in the console (like my EJB beans)? Kind regards, Sebastian A: Try java:jboss/ConnectionFactory Did not test it, but would give that a try, since https://docs.jboss.org/author/display/AS7/How+do+I+migrate+my+application+from+AS5+or+AS6+to+AS7 says: Unqualified relative names like "DefaultDS" or "jdbc/DefaultDS" should be qualified relative to "java:comp/env", "java:module/env", or "java:jboss/env", depending on the context. Correction and edit: Had a look at my installation and correct is: java:/ConnectionFactory as it is defined in domain.xml also. A: Solved it: The whole HornetQ part was deactivated by default in JBoss 7. Had to copy the corresponding part from the standalone-preview.xml to standalone.xml and move everything from META-INF/hornetq-jms.xml to the JBoss config. Now I have the ConnectionFactory configured like this: <jms-connection-factories> <connection-factory name="InVmConnectionFactory"> <connectors> <connector-ref connector-name="in-vm"/> </connectors> <entries> <entry name="ConnectionFactory"/> </entries> </connection-factory> </jms-connection-factories> and I can use it by doing this JNDI lookup: QueueConnectionFactory qf = (QueueConnectionFactory) jndiContext.lookup( "java:/ConnectionFactory" ); This is caused by a bug in the JMS configuration of JBoss 7. Seems to be fixed in 7.0.1, used that version, didn't notice any fix - however, the above configuration works.
{ "language": "en", "url": "https://stackoverflow.com/questions/7515220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }