text
stringlengths
8
267k
meta
dict
Q: How can I stop my Windows console application triggers beeps when displaying binary data I wrote a windows console application that receives binary data from a third party provider. For Debug and logging purposes, I display the binary data on the output (the console). Unfortunately when the character 7 is displayed it triggers a beep. Here is a code that can trigger it: int main(int argc, char** argv) { char c = 7; std::cout << c; } My question is simple, is there a way to disable the beeps ? Thanks A: You could unplug the beeper in your computer. If that is not an option: If you have a method debug(String s) that outputs the string s, you could replace character 7 by something else to avoid the beep. Another way would be to output the text in hexadecimal form. A: There is a lot of other values that will trigger weird things (depending on what terminal you use). You should check each char with isprint before outputting it. Better yet is a function like: void memdump( std::ostream& o, const void* data, size_t len ) { const unsigned char* ptr = static_cast<const unsigned char*>(data); for( size_t i = 0; i < len; i += 16 ) { o << std::setw(8); o << std::setfill('0'); o << std::hex << i << ' '; size_t to = std::min(len,i+16); for( size_t j = i; j < to; ++j ) { o << ' '; o << std::setw(2); o << std::setfill('0'); o << std::hex; o << (unsigned)ptr[j]; if( (j+1) % 8 == 0 ) { o << ' '; } } o << " "; for( size_t j = to; j < i+16; ++j ) { o << " "; if( (j+1) % 8 == 0 ) { o << ' '; } } for( size_t j = i; j < to; ++j ) { if(isprint(ptr[j])) { o << ptr[j]; } else { o << '.'; } if( (j+1) % 8 == 0 ) { o << ' '; } } o << '\n'; } o << std::dec; } A: A way to disable the beeper (at a Windows command line): net stop beep It should disable beeps temporarily. If you want the full effect (re-applies on reboot) type this: sc config beep start= disabled A: char c = 7; is a BELL according to ASCII if you want to display the 7 then you need to wrap it in single quotations marks (or how they are called: char c = '7'; If you don't want to display a 7 then you need to remove the character 0x07 or replace it with (for example with '') (http://www.asciitable.com/) A: Select a code page that interprets the character 7 as a glyph instead of a control character. See my other answer for details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: error with fetching tweets after refresh First of all i want to apologize if this is the most basic question ever! I'm not that good with php but i'm learning. I can't find a solution or even understand why it's going wrong all the time. I do want to know why this is happening I'm trying to get the two latest tweets from a twitter account. I don't want to use massive (existing, i know) classes or codes which i don't understand. So i tried the following myself: $timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries"; $data = file_get_contents($timeline); $tweets = new SimpleXMLElement($data); $i = 0; foreach($tweets as $tweet){ echo($tweet->text." - ".$tweet->created_at); if (++$i == 2) break; } When i first ran this code i got the text from my tweets, but when i refreshed the page i sometimes get the following error: Warning: file_get_contents(http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /path/to/file on line 88 Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /public/sites/www.singledays.nl/tmp/index.php:89 Stack trace: #0 /public/sites/www.singledays.nl/tmp/index.php(89): SimpleXMLElement->__construct('') #1 {main} thrown in /path/to/file on line 89 Lines 88 & 89 are these: $data = file_get_contents($timeline); $tweets = new SimpleXMLElement($data); Really weird. Sometimes it work, sometimes not. Does anybody know this issue and/or a solution? And why does the error seem to occur randomly (Allthough it;s now erroring for a while allready)? Thanks! A: $timeline = "http://twitter.com/statuses/user_timeline.xml?screen_name=Mau_ries"; $data = @file_get_contents($timeline); if($data){ $fh = fopen("cache/".sha1($timeline),"w"); fwrite($fh, $data); fclose($fh); }else{ $fh = @fopen("cache/".sha1($timeline),"r"); $data = ""; while(!feof($fh)){ $data = fread($fh, 1024); } fclose($fh); } if(!$data) die("could not open url or find a cache of url locally"); $tweets = new SimpleXMLElement($data); $i = 0; foreach($tweets as $tweet){ echo($tweet->text." - ".$tweet->created_at); if (++$i == 2) break; } There as every one has said debugging you should really cache the results in files and if it fails to download then use the cache the above code will do it for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.Net MVC Routing: How to catch the root of a website? In my global.asax I have three routes: //MemberHome is supposed to handle urls like http://localhost/johndoe routes.MapRoute( "MemberHome", // Route name "{username}", new { controller = "PublicMember", action = "Index", username = "username" } ); //Home is supposed to catch http://localhost/ routes.MapRoute( "Home", "" ); // the default way of doing things.. routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); The problem is, I can get them to work separtely (just home or just MemberHome) But when they are both activated its either Home or MemberHome which gives me a 404 resource not found.. Any idea how I can get this work? A: You need to set the first part of the route to something distinct. Eg: routes.MapRoute( "MemberHome", // Route name "MemberHome/{username}", new { controller = "PublicMember", action = "Index", username = "username" } ); or: routes.MapRoute( "Default", "Home/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); That way they will be distinct. Whichever one is given the fixed part of the route should come first, as otherwise the route handler will match the wildcard one first...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Server Task Scheduler needs files to be in System32 folder? I have made a C# console application which needs 2 config files for booting. When I run it from cmd window it runs fine-finds the 2 config files(which are placed within the exe produced directory). However,when using the Windows server task scheduler i get an excpetion - " Could not find file 'C:\Windows\system32\field.config' " I tried to use a bat file for the task but same issue occurs-task scheduler tries to find the files in System32 direcory. Placing the two config files within System32 direcory is a workaround but is there any other way? Googled for similar issues but no information at all. Any help is mutch appriciated. A: I know this is old but figured I'd put my finding here incase anyone stumbles on this. On Properties>Action, it seems to be the "Start in (optional)" field on the action edit screen where you type the directory you want the working directory to be located. A: With no actual code to look at, let me make an educated guess. Within your application, you are trying to open those files with paths relative to the executable (say: field.config). When you set the scheduled task, you are not properly configuring the working directory; then the application is executed with System32 as the working directory and that's why it looks for the files there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to convert image which mode is "1" between PIL and numpy? I'm new to image processing with Python and met a strange problem. For example I have a 2*2 black-white bitmap image which pixels are following: black white white black Use PIL and convert it to numpy: >>> import Image >>> import numpy >>> im = Image.open('test.bmp') >>> im <BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x95A54EC> >>> numpy.asarray(im) array([[ True, True], [False, False]], dtype=bool) >>> What puzzles me is the order of pixel in the array. Why not [[True, False], [False, True]]? Thanks. UPDATE: the bitmap is here: http://njuer.us/clippit/test.bmp A: It looks like there are some bugs with converting to/from numpy with the 1 mode. If you convert it to L first, it works fine: >>> im <BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x17F17E8> >>> im2 = im.convert('L') >>> numpy.asarray(im2) array([[ 0, 255], [255, 0]], dtype=uint8) Also, if you try and convert a bool numpy array to PIL, you get strange results: >>> testarr = numpy.array([[True,False],[True,False]], dtype=numpy.bool) >>> testpil = Image.fromarray(testarr, mode='1') >>> numpy.asarray(testpil) array([[False, False], [False, False]], dtype=bool) However, the exact same thing with uint8 works fine: >>> testarr = numpy.array([[255,0],[0,255]], dtype=numpy.uint8) >>> Image.fromarray(testarr) <Image.Image image mode=L size=2x2 at 0x1B51320> >>> numpy.asarray(Image.fromarray(testarr)) array([[255, 0], [ 0, 255]], dtype=uint8) So I would suggest using L as an intermediate datatype and then converting to 1 before saving if you need to save it in that format. Something like this: >>> im <BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x17F17E8> >>> im2 = im.convert('L') >>> arr = numpy.asarray(im2) >>> arr array([[ 0, 255], [255, 0]], dtype=uint8) >>> arr = arr == 255 >>> arr array([[False, True], [ True, False]], dtype=bool) Then to convert back: >>> backarr = numpy.zeros(arr.shape, dtype=numpy.uint8) >>> backarr[arr] = 255 >>> backarr array([[ 0, 255], [255, 0]], dtype=uint8) >>> Image.fromarray(backarr).convert('1') <Image.Image image mode=1 size=2x2 at 0x1B41CB0>
{ "language": "en", "url": "https://stackoverflow.com/questions/7597525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Adding WPF ListView Items Dynamically I'm looking for examples or help to create a WPF listview of files. <ListView Margin="10,10,0,13" Name="ListView1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200"> I Load my files with this method : private void AddFiles_Click(object sender, RoutedEventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = true; if (ofd.ShowDialog() == true) { string[] filePath = ofd.FileNames; string[] safeFilePath = ofd.SafeFileNames; } } What should I do now ? ListView1.Items.Add(...) don't seems to work. In fact I can't find ListView1 from my cs code. I found info here A: I would recommend to use DataBinding for display items in ListView you should bind the ObservableColliction files; with your ListView ItemSource property and when you add or remove files in collection on the ListView items will be updated automaticaly for example look at this article A: Simple, * *Store your file(name)s in a list (ObservableCollection) in your ViewModel *Databind the ListView.ItemSource to that collection *Add/Remove/Change files in the Collection, not in the Listview If you're not using an explicit ViewModel, use your WindowClass as such. A: as a quick and dirty way you can assign the collection of files directly to the ItemsSource property of the ListView ListView1.ItemsSource = safeFilePath; in the XAML you can add an ItemTemplate to customize the visualization of the single files
{ "language": "en", "url": "https://stackoverflow.com/questions/7597532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: whats the difference between jQuery UI and nyroModal for creating a modal box I'm totally new to javascript and trying to figure out which jQuery plugin best suits my needs. I've looked at a few and tried to implement them and basically found that UI plugin works the best but even though you can play about with the theme it doesn't look nice and plain like I want it. NyroModal on the other hand looks right but I can't get my form to submit when it's inside a modal. I've found out that it might have something to do with using an ajax call but I haven't a foggy idea what thats all about. All I know is my form submits fine using UI but nothing at all happens which I click submit in NyroModal. So whats the difference? Why does one allow you to submit a form but the other doesn't? thanks in advance :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7597536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TFS 2010 Queries for work item hierarchies with multiple levels I've build up a hierarchical structure of all my work items with excel - all my work items are now organized in multiple levels. User Story 1 |-- Task 1 | -- -- Sub Task 1 | -- -- -- Bug 1 | -- -- Sub Task 2 | -- -- -- Bug 2 | -- -- -- Sub Sub Task 3 | -- -- -- -- Bug 4 ... But how can I access all items under a certain work item (e.g., "All under Task 1") and visualize the results in a somehow hierarchical way? Is this possible with TFS 2010 and VST 2010? Or do I need some third-party tools to get e.g., "All my Bugs for Sub Task 2" or "All Tasks for User Story 1"? Thank you Konrad A: In general you need to construct Work Item Queries in VS that have "Type of Query" equal to "Tree of Work Items". To obtain a list of Bugs for Sub Task 2: New Query of type "Tree of work items" with Work Item = Sub Task 2 & linked work items Type = Bug To obtain a list of Tasks under UStory 1: New Query of type "Tree of work items" with Work Item = User Story 1 & linked work items Type = Task For an external tool: See here for a nice codeplex-solution that generates DGML - trees of Work Items.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JQuery - improving my function I have a client who uses a WYSIWYG editor to create new website pages. The problem is that sometime the WYSIWYG editor put in empty p tags <p>&nbsp;</p> This was causing havoc with the layout so i wrote a little function to remove these empty tags $('p') .filter(function() { return $.trim($(this).text()) === '' }) .remove() The problem now is that when a image is inserted into the wysiwyg editor it get's included in a p tag and my function removes it from the screen. Can either my function be updated to allow images or can I just search for and remove empty p tags??? Thanks in advance James A: You can use the :empty pseudo-selector to only select elements that have no children: $("p:empty").remove(); However, if you have p elements with white-space and nothing else they will not be removed (because :empty treats text nodes as children). So you may want to remove white space (using .trim) from your p elements before running the above. The problem with your current method is that tags like img do not contain any text, so your filter function thinks a p element containing only an img element should be removed. A: You could make your filter also ensure that there are no child elements: $('p').filter(function() { var $this = $(this); return !$this.children().length && $.trim($this.text()) === ''; }).remove() A: $('p').not(':has("img")') .filter(function() { return $.trim($(this).text()) === '' }) .remove() JS Fiddle demo. A: How about this $('p').each(function(){ if($(this).html() == "&nbsp;"){ $(this).remove(); } }); Demo: http://jsfiddle.net/krVBd/ A: Just fix WYSIWYG, if it is javascript, if not, then fix at backend not frontend. A: You can try using div tags around the blocks you want removed such as . In your jQuery statement you can then call based off the div id instead of all paragraphs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio 2010 Database Project Deploy to Different Environments I've got a Database project which works fine for my local MSSQL 2008 database. It has a script under scripts/post-deployment that inserts standing data configuration into a settings table, and other tables. I've got 1 file for each table, e.g. a Setting.sql file to insert data into the Settings table. The settings will be different depending on the database I deploy to. How can I script this? Basicaly I would like to be able to have say 2 files, Prod.Setting.sql and Dev.Setting.sql and VS 2010 would use the appropriate script depending on what database (environment) I am deploying to. A: Completely doable but there two options and a few steps involved. You can have a complete duplicate set of scripts, one for each configuration. Or, you can have one set of scripts, the contents of which take into account the configuration you are using. I'll go with the first, and I'll keep it simple. Create two solution configurations, or use Debug and Release if you like. I'll use these for the example. For each configuration, create a new .sqlcmdvars file. Database_Release.sqlcmdvars Database_Debug.sqlcmdvars Switch your solution configuration to each and in the database project properties change the variables file drop down to point at the corresponding file you created. In each of those files you can define variables to be used during deployment. Create a new variable in each one $(DeploymentConfiguration) And set its value in each one to either Debug or Release Then in any of your Pre or Post deployment scripts you can do something like so: IF '$(DeploymentConfiguration)' = 'Debug' BEGIN PRINT 'Executing Debug deployment' :r .\Debug\SomeNeededScript.sql END IF '$(DeploymentConfiguration)' = 'Release' BEGIN PRINT 'Executing Release deployment' :r .\Release\Anotherscript.sql END
{ "language": "en", "url": "https://stackoverflow.com/questions/7597553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: External JS in simplemodal Iam successfully loading an external html-code in a modal window. But there is a JS in this external code, which i need to execute. I do not know in advance, which JS comes with external code. So I can not take advantage of onShow method. How can I execute the code that comes with an external html? FOR EXAMPLE I need to bind submit function to form wich comes with external html
{ "language": "en", "url": "https://stackoverflow.com/questions/7597557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: grep using a character vector with multiple patterns I am trying to use grep to test whether a vector of strings are present in an another vector or not, and to output the values that are present (the matching patterns). I have a data frame like this: FirstName Letter Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6 I have a vector of strings patterns to be found in the "Letter" columns, for example: c("A1", "A9", "A6"). I would like to check whether the any of the strings in the pattern vector is present in the "Letter" column. If they are, I would like the output of unique values. The problem is, I don't know how to use grep with multiple patterns. I tried: matches <- unique ( grep("A1| A9 | A6", myfile$Letter, value=TRUE, fixed=TRUE) ) But it gives me 0 matches which is not true, any suggestions? A: Have you tried the match() or charmatch() functions? Example use: match(c("A1", "A9", "A6"), myfile$Letter) A: To add to Brian Diggs answer. another way using grepl will return a data frame containing all your values. toMatch <- myfile$Letter matches <- myfile[grepl(paste(toMatch, collapse="|"), myfile$Letter), ] matches Letter Firstname 1 A1 Alex 2 A6 Alex 4 A1 Bob 5 A9 Chris 6 A6 Chris Maybe a bit cleaner... maybe? A: Good answers, however don't forget about filter() from dplyr: patterns <- c("A1", "A9", "A6") >your_df FirstName Letter 1 Alex A1 2 Alex A6 3 Alex A7 4 Bob A1 5 Chris A9 6 Chris A6 result <- filter(your_df, grepl(paste(patterns, collapse="|"), Letter)) >result FirstName Letter 1 Alex A1 2 Alex A6 3 Bob A1 4 Chris A9 5 Chris A6 A: This should work: grep(pattern = 'A1|A9|A6', x = myfile$Letter) Or even more simply: library(data.table) myfile$Letter %like% 'A1|A9|A6' A: Not sure whether this answer has already appeared... For the particular pattern in the question, you can just do it with a single grep() call, grep("A[169]", myfile$Letter) A: In addition to @Marek's comment about not including fixed==TRUE, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6". You also mention that there are lots of patterns. Assuming that they are in a vector toMatch <- c("A1", "A9", "A6") Then you can create your regular expression directly using paste and collapse = "|". matches <- unique (grep(paste(toMatch,collapse="|"), myfile$Letter, value=TRUE)) A: Take away the spaces. So do: matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE)) A: Based on Brian Digg's post, here are two helpful functions for filtering lists: #Returns all items in a list that are not contained in toMatch #toMatch can be a single item or a list of items exclude <- function (theList, toMatch){ return(setdiff(theList,include(theList,toMatch))) } #Returns all items in a list that ARE contained in toMatch #toMatch can be a single item or a list of items include <- function (theList, toMatch){ matches <- unique (grep(paste(toMatch,collapse="|"), theList, value=TRUE)) return(matches) } A: Using the sapply patterns <- c("A1", "A9", "A6") df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9")) name Letters 1 A A1 2 Ale A2 3 Al A9 4 lex A1 5 x A9 df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ] name Letters 1 A A1 4 lex A1 3 Al A9 5 x A9 A: Another option would be using the syntax like '\\b(A1|A9|A6)\\b' as the pattern. This is for regular expressions word boundary which comes in hand for example if Bob had the letters for example "A7,A1", when using that syntax, you can still extract the row. Here is a reproducible example for both options: df <- read.table(text="FirstName Letter Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6", header = TRUE) df #> FirstName Letter #> 1 Alex A1 #> 2 Alex A6 #> 3 Alex A7 #> 4 Bob A1 #> 5 Chris A9 #> 6 Chris A6 with(df, df[grep('\\b(A1|A9|A6)\\b', Letter),]) #> FirstName Letter #> 1 Alex A1 #> 2 Alex A6 #> 4 Bob A1 #> 5 Chris A9 #> 6 Chris A6 df2 <- read.table(text="FirstName Letter Alex A1 Alex A6 Alex A7,A1 Bob A1 Chris A9 Chris A6", header = TRUE) df2 #> FirstName Letter #> 1 Alex A1 #> 2 Alex A6 #> 3 Alex A7,A1 #> 4 Bob A1 #> 5 Chris A9 #> 6 Chris A6 with(df2, df2[grep('A1|A9|A6', Letter),]) #> FirstName Letter #> 1 Alex A1 #> 2 Alex A6 #> 3 Alex A7,A1 #> 4 Bob A1 #> 5 Chris A9 #> 6 Chris A6 Created on 2022-07-16 by the reprex package (v2.0.1) Please note: if you are using R v4.1+, you can use \\b, otherwise use \b. A: I suggest writing a little script and doing multiple searches with Grep. I've never found a way to search for multiple patterns, and believe me, I've looked! Like so, your shell file, with an embedded string: #!/bin/bash grep *A6* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6"; grep *A7* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6"; grep *A8* "Alex A1 Alex A6 Alex A7 Bob A1 Chris A9 Chris A6"; Then run by typing myshell.sh. If you want to be able to pass in the string on the command line, do it like this, with a shell argument--this is bash notation btw: #!/bin/bash $stingtomatch = "${1}"; grep *A6* "${stingtomatch}"; grep *A7* "${stingtomatch}"; grep *A8* "${stingtomatch}"; And so forth. If there are a lot of patterns to match, you can put it in a for loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "173" }
Q: Saving output using FMOD without playback I need to implement a playback of separate audio files in N channels, files may play sequentially or in parallel. I need to implement it on Android. Timeline: |file a...|file d....|file b...|......|file k|.... |.....|file g|file c..|file p.|.... I'm thinking two options, one being FMOD to decompress files and play them simultaneously. I have researched and FMOD seems to fit well and much easier than manually playing this using an AudioTrack. However, I can't understand if FMOD would allow us to save the entire merged output without playing it through. I know that using solution here we can redirect output to a wav file, but is it possible to just create a final output instantly and save it using FMOD? Or will I have to manually merge PCMS into one stream after all.. Thanks. A: An important question here is why you need to save the files out, if it's possible to do this offline then it would be a lot simpler. If you must record the concatenation of several files (including others played in parallel), it is quite possible with FMOD. One way would be to use wave-writer-nrt output mode, which allows you to output a wav file based on FMOD playsound calls in faster than realtime. Another way is to use a custom DSP to access the data stream of any submix as it plays, useful if you want other sounds actually playing at the same time. Another is simply create the sound objects, then use Sound::lock to access the PCM data, which you could concatenate yourself to a destination. Keep in mind all the sounds would need to be the same sample rate and channels, otherwise you would need to do processing. Also keep in mind you cannot do this for parallel sounds unless you want to mix the audio yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create assembly with permission_set safe I'm trying to deploy a .NET assembly to SQL Server 2008 R2 database, but I'm just hitting this error: Deploy error SQL01268: .Net SqlClient Data Provider: Msg 6509, Level 16, State 31, Line 1 An error occurred while gathering metadata from assembly 'Assembly' with HRESULT 0x80004005. Now the tricky part is that I've made sure that the framework version is correct, and I have a separate trivial CLR database project from which I add and test things to see if I can isolate the issue (I can't). I've even written a tool which uses Mono.Cecil and PEVerify to ensure that I adhere to the programming model restrictions that apply to CLR projects in the database. I'm obviously missing something but I don't know how to debug this, why can't SQL Server just tell me why it fails? Isn't there something I can do to get more verbose output why SQL Server rejects the assembly? A: Can you paste the CREATE DDL statements please? Did you write the CREATE statement yourself? It looks like you may have used the auto-deploy from Visual Studio. Try it manually. Please give details on the assembly, does it access external data? A: After two days of debugging this is what I did. Drawing from experience I used Cecil to rewrite the assembly, cancelling out methods by just replacing all method bodies with simply throw new NotImplementedException ignoring all constructors (initialization is a bit tricky and just can't just kill the method body of a constructor). After doing this the assembly was installed successfully. I didn't know what was the problem but I knew it had something to do with code. This was my assumption all along. To find the actual method, I used a binary search. I replaced half of the methods in the assembly and if the error was not there I went left, otherwise right as long as I had a problem until I found the smallest set of methods that were responsible for the error. Given that it was more than 2000 methods and I took about 1-2 seconds to test each configuration, it saved a lot of time. I managed to zero down on a single method rather easily and here it is (from what I could tell of my findings, this had to be in a generic class as well). class Hashtable<K, V> { IEnumerable<KeyValuePair<K, V>> GetEnumerator() { var hashtable = new Hashtable(); return hashtable .Cast<DictionaryEntry>() .Select(x => new KeyValuePair<K, V>((K)x.Key, (V)x.Value)) .GetEnumerator(); } } Nothing in this code really results in any IL that's invalid, even though there's plenty of transformations applied by the compiler. If you put this in a database CLR assembly it will reject the assembly with an access denied error with without any further information. Eventually, I'm gonna file this as a bug with Microsoft, the error message should not be access denied and furthermore this code is actually allowed because it doesn't do anything which isn't allowed under the safe permission set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change HTML Textbox layout Hi i would like to know how to change the text box in HTML to just a line rather than a box because i am trying to make a webpage look like a PDF form and for a neat outlook i would like to change the text box design to just a long line so the user can type his name or whatever the field requires him to do.. A: You'll probably want a more specific selector, but this should make a reasonable starting point: input { border-style: none; border-bottom: solid black 1px; } A: You mean to display a <textarea> as an <input type="text">? In html, i assume, via <textarea cols="" rows="1"> or via CSS styling the width and height of the element A: For single lines of input, I'd use a <input type="text" />, which actually is the default type and can be abbreviated to just <input /> (I'm assuming xhtml in these examples).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Default role mapping when creating a MSSQL Server database Is it possible to set up a default set of role mappings for Microsoft SQL Server (2008 R2 for instance) that apply to subsequent databases? Example: Whenever I create a new database on the server, I want it to map db_owner to a login group called Group_A and db_datareader to a group called Group_B. The databases are created by a 3rd party application, so doing it in the CREATE statement is not enough. What I hope for is to set a default behaviour for the server itself. A: Every new database is created as a copy of the model database on the SQL server. So when you do the mapping the the MODEL db every new DB should replicate that. I haven't tried that with roles and groups but you can try it and let me know whether it works...
{ "language": "en", "url": "https://stackoverflow.com/questions/7597573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# MSI install with Windows server 2003 - no distribution data available I got an msi (default visual studio installer) to distribute my application that works perfectly on all systems, except on Windows server 2003. A user tries to install the msi from the active directory, but a message is prompted stating that there is no distribution data available. At the office, I can't reproduce the error, and I really have no clue on where to look for the origin of this problem, so any hints or idea's are very welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android accessing asset file I want to access a text file located under assets from a class that would do some processing on that file and is invoked in my Activity. The code I am using is: AssetManager assetManager = getAssets(); InputStream instream = assetManager.open("file.txt"); this works fine if used in an Activity class but how to make it work in a plain java class? Edited JamesBlack - because if i pass the inputstream then the following code won't work for (int i = 0; i < gestureNumbers.size(); i++) { BufferedReader bf = new BufferedReader(new InputStreamReader(instream)); // possible error here while ((line = bf.readLine()) != null) { ... } } Even if the gestureNumbers.size() > 1 then the while loop is executed only once and then it equals null once it read the file once. When the following code works but I can't open the file in plain java class, it works in activity class and I don't want to have too much code in one class. for (int i = 0; i < gestureNumbers.size(); i++) { InputStream instream = assetManager.open("BSL_Word_POS.txt"); BufferedReader bf = new BufferedReader(new InputStreamReader(instream)); // possible error here while ((line = bf.readLine()) != null) { ... } } A: You have to pass the context to that java class to access the asset folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Solaris - My process listening on all the interfaces but other processes listening on localhost:6011 My server program is designed to listen on all the interfaces and it is listening working also. One strange behavior is happening. It means port conflict with sshd process. Because I need to make my application and sshd to listen on same port range.(ex: 6000 - 6100) MyProg code: MyPort = 6011; #if TARGET_HAS_IPV6_SUPPORT /* IPv6 socket */ { struct addrinfo *ai = NULL; r = ipw_getaddrinfo("::", NULL, AF_INET6, SOCK_STREAM, IPPROTO_TCP, AI_PASSIVE, &ai); if (r == 0) { Create_listen_socket(&ai, IpcMyPort); } } #endif { struct addrinfo ailocal = { 0 }; struct sockaddr_in sin = { 0 }; sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); ailocal.ai_family = AF_INET; ailocal.ai_socktype = SOCK_STREAM; ailocal.ai_protocol = IPPROTO_TCP; ailocal.ai_flags = AI_PASSIVE; ailocal.ai_addrlen = sizeof(struct sockaddr_in); ailocal.ai_addr = (struct sockaddr *)&sin; Create_listen_socket(&ailocal, MyPort); } Create_listen_socket(struct addrinfo *ai, unsigned int MyPort) { SOCKET fd = INVALID_SOCKET; while (ai != NULL) { fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (fd == INVALID_SOCKET) { Exit() break; } switch (switch (sa->sa_family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)sa; sin->sin_port = htons((unsigned short)port); } break; #if TARGET_HAS_IPV6_SUPPORT case AF_INET6: { struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa; sin6->sin6_port = htons((unsigned short)port); } break; #endif } if (ipw_bind(fd, ai->ai_addr, ai->ai_addrlen) < 0) { exit(); Break; } else { r = ipw_listen(fd, IPC_MAX_LISTEN_COUNT); } ai = ai->ai_next; } } Following is the output of "sudo lsof -i -P | grep :60" :: :: :: sshd 23038 fin22495 11u IPv4 0x60026f7c740 0t0 TCP localhost:6011 (LISTEN) myProg 23108 root 4u IPv6 0x60026e46000 0t0 TCP *:6011 (LISTEN) myProg 23108 root 5u IPv4 0x6002658e3c0 0t0 TCP *:6011 (LISTEN) If you see, the sshd daemon is listening on same port 6011 but on local host interface. but my program is listening on *.6011. How to make sure myProg listening on "localhost:6011" along with *:6011 and if already some process is listening on "localhost:6011" how to detect it. It happens in Solaris. Please let me know your views. Thanks, Naga A: I'm not sure what you have done here because sshd should normally be listening on port 22, not 6011. The first process opening the port will get exclusive access. There are good, security-related reasons for this being so. See the tcp(7P) manpage for details - look for SO_REUSEADDR and SO_EXECLBIND. A: If you see, the sshd daemon is listening on same port 6011 but on local host interface. but my program is listening on *.6011. How to make sure myProg listening on "localhost:6011" along with *:6011 and if already some process is listening on "localhost:6011" how to detect it. It happens in Solaris. Your application's port numbers conflict with ports used by ssh X-forwarding. Change your port numbers and be done with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Python how to add headers for a file after gzip before writing it I am trying to open a javascript file, read it, gzip it and then write it back to another file.. able to do all that.. but how can set the "Content-Encoding : gzip" before writing the compressed content... here is the code: import os, sys, mimetypes, zipfile, gzip, cStringIO from optparse import OptionParser def main(): parser = OptionParser(usage='usage: %prog [options] src_file destination_file') parser.add_option('-x', '--expires', action='store_true', help='set far future expiry for all files') (options, args) = parser.parse_args() if len(args) != 2: parser.error("incorrect number of arguments") name = os.path.normpath(args[0]) des_file = os.path.normpath(args[1]) try: s_file = open(name, 'r') content = s_file.read() compressed = cStringIO.StringIO() gz = gzip.GzipFile(filename=name, mode='w', fileobj=compressed) gz.write(content) gz.close() s_file.close() o_file = open(des_file, 'w') ## ## BEFORE WRITING THE CONTENT INTO A FILE HOW WE ADD THE Content-Encoding ## o_file.write(compressed.getvalue()) o_file.close() except (IOError, os.error), why: print 'Failed to read the file', filename, '\n Exception:', why A: That is usually determined by whatever is serving the file. Your job is usually limited to setting the correct file name extension (.gz in this case) when you create the file and configuring the server properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript/JQuery bouncing text off left and right sides of a div I want text to bounce of the left and right sides of a div tag (#header). It works fine when it bounces of the right, then goes back and hits the left. The problem is that after it hits the left and starts to go right again it never hits the right side. It just keeps going and the window scrollbar appears. It appears as soon as it hits the left side. It seems that the div tag. var finishedGoingRight = false; setInterval(function() { slideText(); }, 10); function slideText(){ if(!finishedGoingRight){ $('#header h1').css("right","-=1"); }else{ $('#header h1').css("left","-=1"); } if($('#header h1').css("right") == "20px"){ finishedGoingRight = true; } if($('#header h1').css("left") == "485px"){ finishedGoingRight = false; } } Hope I explained it clearly :) A: Debugging your code revealed that $('#header h1').css("right") always equals "auto", unless you've set it explicitly somewhere. This works: http://jsfiddle.net/7z3a3/1/ var finishedGoingRight = false; setInterval(function() { slideText(); }, 10); function slideText() { if (!finishedGoingRight) { $('#header h1').css("left", "+=1"); } else { $('#header h1').css("left", "-=1"); } if ($('#header h1').position().left >= $('#header').width()-$('#header h1').width()) { finishedGoingRight = true; } else if ($('#header h1').position().left <= 0) { finishedGoingRight = false; } } A: Here's my solution using animate: JS: var inner = $('#inner'), widthInner = inner.width(), outer = $('#outer'), widthOuter = outer.width(); function animateRight() { inner.animate({ left: widthOuter - widthInner }, 1000, function() { animateLeft(); }); } function animateLeft() { inner.animate({ left: 0 }, 1000, function() { animateRight(); }); } animateRight(); HTML <div id="outer"><h2 id="inner">Inner</h2></div> CSS div, h2 { border: 1px solid black; } #outer { width: 300px; height: 200px; } #inner { margin-top: 75px; width: 50px; position: relative; } http://jsfiddle.net/rHEQA/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7597588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I pass parameter Just for examples machineId = 150018; paper = raphel('canvas_container', 15, 20); rect = paper.rect().attr({.....}); rect.node.ondblclick = function() { window.open("graph.php?mach_id=" + id); } Question: How can I pass machineId value to id; I need the result is to open new window with url http://localhost/graph.php?mach_id=150018; code from duplicate question function showUtilization(machineId, rectUtil, txtResult, txtMCName, rectCover) { for (i = 0; i < machineId.length; i++) { $.ajax({ url: 'ajax/getonemachineinfo.php', data: { id: machineId[i] }, dataType: 'text', async: false, success: function(data) { results = data.split(','); status = results[0]; utilize = results[1]; // Machine Name switch (status) { case '0': var colorCode = "#FF0000"; break; case '1': var colorCode = "#33CC33"; break; case '2': var colorCode = "#808080"; break; } txtMCName[i].attr({ fill: colorCode }); // utilization rectUtil[i].attr({ width: (utilize * conversionFactor())/100 }); if (utilize <= 30) { var colorAttr = [{ fill: "#FF0000" }]; } else if ((utilize > 30) && (utilize <= 60)) { var colorAttr = [{ fill: "#FFFF00" }]; } else if (utilize > 60) { var colorAttr = [{ fill: "#33CC33" }]; } rectUtil[i].attr(colorAttr); txtResultAttr = [{ text: utilize + '%'}]; txtResult[i].attr(txtResultAttr); txtResult[i].attr(colorAttr); rectCover[i].node.ondblclick = function() { window.open("graph.php?mach_id=" + machineId[i]); } } }); } } (2 A: What's wrong with this: window.open("graph.php?mach_id=" + machineId); If the (unexplained) problem is that you need to save the value of machineId at the time the ondblclick handler is defined rather than using its value at the time the handler is executed, you need a closure: (function (id) { rect.node.ondblclick = function() { window.open("graph.php?mach_id=" + id); } })(machineId); UPDATE: OK, based on the new code you posted I can see I was on the right track with the closure idea above. The problem is that your event handlers try to use the i index at some point in the future at which time i equals whatever value it had when the loop ended. You need something like this: function showUtilization(machineId, rectUtil, txtResult, txtMCName, rectCover) { for (var index = 0; index < machineId.length; index++) { (function(i){ $.ajax({ // all of your other code here, where anytime it // uses i it will be using the parameter of the // anonymous function rather than the loop counter // (which I've renamed to "index" to avoid confusion // with "i") }); })(index); } } I've changed the loop to use a counter called index, which is passed in to an anonymous function that is immediately executed. Your existing code, i.e., everything that you have inside the $.ajax({ }); call goes inside that anonymous function. When your success and ondblclick handlers are executed at some point in the future they will use the i from their own closure rather than the loop index. A: machineId is scoped globally already, so it will be available for use directly in the ondblclick action. Also, you should add the var keyword before the machineId declaration. var machineId = 150018; paper = raphel('canvas_container', 15, 20); rect = paper.rect().attr({.....}); rect.node.ondblclick = function() { window.open("graph.php?mach_id=" + machineId); } A: What if you change the code to machineId = 150018; paper = raphel('canvas_container', 15, 20); rect = paper.rect().attr({.....}); rect.node.ondblclick = function() { window.open("graph.php?mach_id=" + machineId); } That is, instead of id, just pass along machineId. A: Just change id to machineId and your code would work as it is, since you are creating an another function which has access to variables within the scope. More explanation on closures and scopes
{ "language": "en", "url": "https://stackoverflow.com/questions/7597589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: how to create a filter system? i have a database like this prod_id prod_name catogory_1 catogory_2 catogary_3 now i want place my filter like this <slect id="filter for cat 1"> <option vlaue="all">all</option> <option vlaue="caps">Caps</option> <option vlaue="shoose">shoose</option> <option vlaue="cloths">cloths</option> <option vlaue="bags">bags</option> </slect> <slect id="filter for cat 2"> <option vlaue="all">all</option> <option vlaue="mens">mans</option> <option vlaue="womens">wonens</option> <option vlaue="babys">babys</option> </slect> <slect id="filter for cat 3"> <option vlaue="all">all</option> <option vlaue="large">Larg</option> <option vlaue="midum">midum</option> <option vlaue="small">small</option> </slect> <div id="display_prod_list"> here goes the list </div> my function <?php function display_product() { $query = mysql_query("SELECT `pord_id` AS `id`, `prod_name` AS `name`, `catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`, `catogory_3` AS `catogory_3` FROM `porducts`"); $products = array(); while(($rows = mysql_fetch_assoc($query))!== false) { $products[] = $rows; } return $pruducts; } ?> this function returns all products i want to change this function to return only filtered products how can i do that? please help me. can i do this with php or i have to use jquery or something. please tell me the best way to filter my products thanks A: I don't know if this is about what you asking for, but hope it helps. Use a WHERE clause on your MySQL query, for example: SELECT `pord_id` AS `id`, `prod_name` AS `name`, `catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`, `catogory_3` AS `catogory_3` FROM `porducts` WHERE catogory_1 = 'caps' AND catagory_2 = 'babys'; You could build your query condition in this way: $conditions = array(); $condition_string = ''; if ($catagory_1 != 'all') { $conditions[] = "catagory_1 = $catagory_1 "; } if ($catagory_2 != 'all') { $conditions[] = "catagory_2 = $catagory_2 "; } if ($catagory_3 != 'all') { $conditions[] = "catagory_3 = $catagory_3 "; } if ($conditions) { $condition_string = ' WHERE '. implode($conditions, ' AND '); } $sql = "SELECT `pord_id` AS `id`, `prod_name` AS `name`, `catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`, `catogory_3` AS `catogory_3` FROM `porducts` $condition_string "; A: Just PHP A standard HTML form that sumbits to the php script which executes query based on the filter values when the submit button is pressed. The use the SQL WHERE clause to narrow down your results to products that match the criteria. eg. WHERE catogory_1 = 'caps' AND catagory_2 = 'babys'; You will also need to put some logic in the php to prevent you from querying for a category when the filter value is 'all', as you can effectively ignore those categories. Then output your results. PHP & jQuery You could use jQuery to populate the products part of the page with only the products that match the category filters when a filter is changed rather than reloading the page. A ajax request is made to the a php script that queries based on the current filters. For example, all products are shown when your page loads at first then the "filter for category 1" is changed to "caps", using jQuery to detect a change event on the filter an ajax call to a php script that would run the following query. SELECT `pord_id` AS `id`, `prod_name` AS `name`, `catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`, `catogory_3` AS `catogory_3` FROM `porducts` WHERE catogory_1 = 'caps'; Then build your HTML based on the results and this is sent back as the ajax response and you should use it to replace the current HTML for the products.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Copy data from remote MySQL server I have two MySQL servers on different location. I would like to copy some data from one table on one server to another server. And that process is automated and executed scheduled. Is it possible to do it with php? A: You will need to create a cron job. The job can execute a php script. Just google it A: Yes with provisos... * *you will need access to both servers on the MySQL port (through the firewall) *you'll need the users set up in the database (in the relevant mysql tables) to give read/write permissions *you'll need a Cron job to perform the scheduling
{ "language": "en", "url": "https://stackoverflow.com/questions/7597595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XmlSerializer constructor with XmlTypeMapping and XmlRootAttribute arguments I'd like to prefetch in C#, the XmlTypeMapping of a known set of class types to speed up XML deserialization of them while instantiating a new XmlSerializer as XmlReflectionImporter.ImportTypeMapping (happening during XmlSerializer contruction on a class type) is quite time consuming and seem to happen at each XmlSerializer construction. In addition the xml content I am parsing forces me to use XmlRootAttribute argument to set the xml root element name to parse as it is not always the same. To achieve that, I can use the XmlSerializer(Type, XmlRootAttribute) constructor to deserialize my object. However I would also like to benefit from the prefetch XmlTypeMapping and I can't see any XmlSerializer constructor like : XmlSerializer( XmlTypeMapping, XmlRootAttribute ) or something close. How could I achieve that? Any help would be greatly appreciated! Thanks. A: The built-in cache is not used on any of the constructors that accept an XmlRootAttribute. Your best bet is to use the constructor that accepts a single XmlTypeMapping parameter: public XmlSerializer(XmlTypeMapping xmlTypeMapping) And to wrap it in your own constructor that accepts a XmlRootAttribute, and constructs the XmlTypeMapping from it using XmlReflectionImporter: public class CachedRootXmlSerializer : XmlSerializer { private static Dictionary<int, XmlTypeMapping> rootMapCache = new Dictionary<int,XmlTypeMapping>(); private static XmlTypeMapping GetXmlTypeMappingFromRoot(Type type, XmlRootAttribute xmlRootAttribute) { XmlTypeMapping result = null; int hash = 17; unchecked { hash = hash * 31 + type.GUID.GetHashCode(); hash = hash * 31 + xmlRootAttribute.GetHashCode(); } lock (rootMapCache) { if (!rootMapCache.ContainsKey(hash)) { XmlReflectionImporter importer = new XmlReflectionImporter(null, null); rootMapCache[hash] = importer.ImportTypeMapping(type, xmlRootAttribute, null); } result = rootMapCache[hash]; } return result; } CachedRootXmlSerializer(Type type, XmlRootAttribute xmlRootAttribute) : base(GetXmlTypeMappingFromRoot(type, xmlRootAttribute)) { } } Enjoy!
{ "language": "en", "url": "https://stackoverflow.com/questions/7597599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Database design: how to effectively manage about 4000 databases with mysql It sounds crazy, but i started a data intensive project[collecting online store inventories] which later grew to be very big. I currently have about 2000 users and each user has about 100 tables. So in essence, i created the system so that each user had his own mysql database and hosted it on a dedicated server. The problem is, the server becomes very slow and breaks due to the pressure and connections. Is there a tool i can use to optimize the db? or i should redesign to only 1 database, which will mean redesigning the whole system? I need an advice and help A: 4000 databases for one system?! Wowzer, did you invent Google? I'd definitely say that you need to redesign that setup - unless your 'system' is actually database hosting and each user has paid for a private db, of course. Nothing wrong with having multiple discrete databases, but 2-per-user is the wrong approach. The 'right' approach will depend entirely on what your system is meant to do. You mention everyone has a dedicated server too - this should prevent contention issues for other users. Are you sure it's not shared hosting? A: Nine times out of ten, when someone structures an application database this way (segmenting identical data into different databases, or even into different tables) it's a mistake based on an unnecessary attempt to pre-optimize the system. But without more information we cannot tell whether: * *This is one one of the nine times it's a mistake, or the tenth time, when it's an appropriate design. *Whether the number of connections is what's causing the performance problems you see (which would be solved by switching to a single database) or something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving the url anchor in a werkzeug request I have a DAV protocol that stores out-of-band data in the url anchor, e.g. the ghi in DELETE /abc.def#ghi. The server is a Flask application. I can see the request come in on the wire via tcpdump, but when I look at the werkzeug Request object (such as url() or base_url()), all I get back is /abc.def. The #ghi has been stripped out. Is there a method that returns this information, or do I have to subclass Request to handle this myself? If so, is there an example I can use as an inspiration? A: I ran into the same problem. Facebook authentication API returns the access token behind a hash appended into the redirection url. In the same way, Flask's request.url drops everything in the URL behind the hash sign. I'm also using Flask so I think you can use my brute-force workaround using Javascript's window.location.href to get the full URL. Then, I just extracted the piece that I needed (the access token), put it into a redirection URL where I can pass the access token as an argument to the receiving view function. Here's the code: @app.route('/app_response/<response>', methods=['GET']) def app_response_code(response): return ''' <script type="text/javascript"> var token = window.location.href.split("access_token=")[1]; window.location = "/app_response_token/" + token; </script> ''' @app.route('/app_response_token/<token>/', methods=['GET']) def app_response_token(token): return token In case you manage(d) to do this within Werkzeug, I'm interested to know how. A: From Wikipedia (Fragment Identifier) (don't have the time to find it in the RFC): The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the server So Flask - or any other framework - doesn't have access to #ghi. A: You can do this using flask.url_for with the _anchor keyword argument: url_for('abc.def', _anchor='ghi')
{ "language": "en", "url": "https://stackoverflow.com/questions/7597603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Adding in javaScript I am trying to create a reverse heading app and have gotten the subtraction part of it to work but when I punch in 30 for example instead of pumping out 210 degrees it pumps out 30180. My code is below and I would love some suggestions on how to fix this. if(convertFromValue > 360){ paraGraph.innerHTML = 'Please enter a number between 1 and 360'; } else { if(convertFromValue > 180) { paraGraph.innerHTML = convertFromValue - 180 ; } else { paraGraph.innerHTML = convertFromValue + 180 ; } } } A: JavaScript gives preference to strings around the + operator. You have to explicitly make sure that the values are really numbers: paraGraph.innerHTML = parseInt(convertFromValue, 10) + 180; That may or may not be the right thing for your application. There are other common shortcuts to converting strings to numbers. Of course you probably want to check for errors too, because if the string is coming from an input field it might not be (or look like) a number at all. A: Try convertFromValue = parseInt(convertFromValue, 10); before you start checking conditions and adding. A: You are adding integers to string values, which equates to concatenating the strings together. Use parseInt() convertFromValue = parseInt(convertFromValue, 10); if(convertFromValue > 360) { paraGraph.innerHTML = 'Please enter a number between 1 and 360'; } else { if(convertFromValue > 180) { paraGraph.innerHTML = convertFromValue - 180 ; } else { paraGraph.innerHTML = convertFromValue + 180 ; } } A: paraGraph.innerHTML = parseInt(convertFromValue) + 180 ; A: All the answers about needing to use parseInt are correct. This is just a sneaky alternative approach using the + operator to coerce a String to a Number: paraGraph.innerHTML = +convertFromValue + 180
{ "language": "en", "url": "https://stackoverflow.com/questions/7597606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Access the property of an object within an object? I have a custom "brain" class that has a custom "recipe" object as one of it's properties. The recipe class has four "ingredient" objects as properties. If I try and do: brain.myRecipe.ingredient1 = myIngredient; self.displayLabel.text = brain.myRecipe.ingredient1.ingredientName; The label is blank (although I get no errors) but if I do Ingredient * temp = myIngredient; self.displayLabel.text = temp.ingredientName; That one works... Are you not able to drill down through properties like that with the dot operator? Thanks! A: Yes, you can do that with the dot operator. Most likely one of those properties is nil. A: Check if brain is not nil. If not : Check myrecipe and ingredient1 properties ? Are they set on retain ? If not, put retain. Check @synthesize for both. Aren't there any type mistake so their name would not match the one set fo the properties and the ivars ? If there are mistakes (lokk ate upper/lowercases), correct. I also guess that Ingredient inherits from NSObject (at least) and have [super init] on the begining of its init method ? If not, do you class inherit NSObject, and init it first. If nothing works... then, just put some more code. How do you want us to solve your problem with such a little piece of code ? You should have something like : Brain : NSObject { MyReceipe* receipe; } @property (nonatomic, retain) MyReceipe* receipe; MyReceipe : NSObject { Ingredient* ingredient1; } @property (nonatomic, retain) Ingredient* ingredient1; Ingredient : NSObject { NSString* ingredientName; } @property (nonatomic, retain) NSString* ingredientName; in all the .m, add @synthsize the_property_name and an init method like - (id) init { self = [super init]; if (!self) return nil; self.the_ivar = nil; (or whatever you want) return self; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPad takes three touch for JavaScript click event I have problem with iPad. I use 3 function in JavaScript for anchor tag, onmouseover, onmouseout, onclick. But when I test it on the iPad then for first touch it trigger onmouseover, and then it takes two another touch for execute onclick event. That means it take total three touch for click event. Generally it has to take only two touch for it. Why is it so? A: To fully support Mobile devices with their Touch Screens you can't use the mouse events... you need to change to touch events http://ross.posterous.com/2008/08/19/iphone-touch-events-in-javascript/ Another way is to divide the code using a mobile Framework, like jQTouch, jQMobile, etc... They support Mouse Events and Touch Events right out of the box. After you make your code support for Touch Events, even Drag and Drop will work nicely Drag and drop on iPad
{ "language": "en", "url": "https://stackoverflow.com/questions/7597616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android web view selection I would like to show on the device's screen only this , without all the other unnecessary stuff , from this web page. This is my code so far... package com.nextlogic.hellowebview; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; public class HelloWebView extends Activity { /** Called when the activity is first created. */ WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl("http://golfnews.no/nyheter.php?a=2013"); } } Could you please help me ? It would be much appreciated. Thanks. A: What you will need is a HTML Parser such as JSOUP. A great parser i use it for alot of projects. This will allow you to parse only specific content, Such as the image url from your webpage, and then retrieve it to a bitmap and set it to a imageview(Best to use an asynctask for this) and then you can use tags to retrieve the text. Let me know if you need help with this. EDIT: How to parse your Webpage with jsoup: Document doc = Jsoup.parse("http://golfnews.no/nyheter.php?a=2013").get(); Elements article-text = doc.select(div.article); //just to verify. System.out.println(article-text.text()); TextView TextArticle = (TextView)findViewById(R.id.YOURTEXTVIEW); TextArticle.setText(article-text.text()); //OR String article = article-text.text(); TextArticle.setText(article); Try this out. EDIT: How to add external jar's
{ "language": "en", "url": "https://stackoverflow.com/questions/7597625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a Rails way or a gem to get related entries from HABTM to the same object? Well, I have a table with images, each image is tagged with a HABTM relation through a join table. What I want to do is show related images in the page the image is being shown, by matching images with the same tags. Can this be done efficiently with the current join table or I should generate joins between images in another table each time a new image is created? A: I recommend you consider switching to using has_many :items, :through => :link_table It's become the new standard and it's a great approach because you get more flexibility 'baked in' and the structure is also ready for easy expansion and growth without major rework, e.g. adding new attributes is very easy. 'new attributes' are frequently date fields. So you can add the regular timestamps fields (created and updated) and people also find other date fields like 'completed_on', 'authorized_on', 'terminated_on', 'activated_on', 'sold_on', etc. useful, depending on the application use cases. class Image < ActiveRecord::Base has_many :image_tags has_many :tags, :through => :image_tags end class ImageTag < ActiveRecord::Base belongs_to :image belongs_to :tag end class Tag < ActiveRecord::Base has_many :image_tags has_many :images, :through => :image_tags end You will still see a lot of examples of HABTM and it does still work. There are certainly cases where it may still make sense to use it but as HMT does them anyway, KISS says use 'one way'.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Heroku REST api Call in java can we connect to heroku using webservices or anything else . i want to set up an integration in java which should login in ito heroku and run my application.? A: There is an out-dated doc on the Heroku REST APIs that will give you the basic idea. Unfortunately the most up-to-date reference is the Heroku command-line client source code - which is in Ruby. A: If you want to build an HTTP client in Java, Jersey (Oracle's JAX-RS Reference implementation) is a good choice. It's client library is very similar to the client library that will be in standardized in JAX-RS 2.0. With Jersey, you are also not limited to Java's build in HTTP connector but can plug in the (much better) Apache HTTP client connector. (All described in the Jersey docs) http://jersey.java.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/7597632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Name spaces in c++ and c Not that I would ever write the code like the following in my professional work, the following code is legal and compiles without warnings in c++ and c: #include <stdlib.h> typedef struct foo { int foo; } foo; foo * alloc_foo () { return (struct foo*) malloc(sizeof(foo)); } struct foo * alloc_struct_foo () { return (foo*) malloc(sizeof(struct foo)); } foo * make_foo1 (int val) { foo * foo = alloc_struct_foo (); foo->foo = 0; return foo; } struct foo * make_foo2 (int val) { struct foo * foo = alloc_foo(); foo->foo = 0; return foo; } What makes this legal and unambiguous in C is section 6.2.3 of the C standard: 6.2.3 Name spaces of identifiers If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers (label names; tags of structures, unions, and enumerations; members of structures or unions; and ordinary identifiers). Note that thanks to label names living in their own name spaces, I could have made the code even more obfuscated by using a label foo somewhere. Add the following and the code does not compile: int foo (foo * ptr) { return ++ptr->foo; } So, two questions, one related to C and C++ and the other, C++. * *C/C++ question: Why can't I define the function foo? It seems I should be able to define the function foo; function names and variable names are "ordinary identifiers". But if I add that last little bit of code I get error: redefinition of 'foo' as different kind of symbol. Question: foo * foo; is perfectly legal, so why isn't int foo (foo*); legal? *C++ question: How does this work at all in C++? The meaning of "name space" takes on a rather different meaning on in C++ than in C. I can't find anything in the C++ standard that talks about the C concept of name spaces, which is what makes the above legal in C. Question: What makes this legal in C++ (chapter and verse preferred)? A: foo * foo; is perfectly legal, so why isn't int foo (foo*); legal? Because there already is a type named foo in the same declaration context as your function. You cannot have a type and a function of the same name in the same scope. How does this work at all in C++? Because you are allowed to hide names in nested scopes. When you declare foo * foo, the first foo refers to the type. The second foo declares a variable -- at that point, the type foo is hidden. Try declaring foo * baz after foo * foo, it should fail. struct foo {}; void test() { foo * foo; // first `foo` is the type, second `foo` is the variable foo * baz; // first `foo` is the variable } A: In C++11 3.3.1/4 says that in a declarative region all declarations of a name must refer to the same entity (or an overload set). There's an exception that allows you to use a class name for a set of function names (so foo() hides class foo) but this doesn't apply if you have a typedef (which you do). Try it with the typedef struct foo foo omitted in C++. A: This doesn't work in C++ either ... the problem is that the pre-processor for gcc/g++ is looking for __cplusplus, not cplusplus. Therefore you pre-processor statements #if defined FOO && ! defined cplusplus #undef FOO #endif do not work correctly. A: Because there is already function foo() it's a default constructof for struct foo typedef struct foo { int a; foo(int val) :a(val) {} } foo; int foo(int value) { cout << value <<endl; } void main() { foo foovar = foo(50); // constructor foo or function foo? } There are no such things as constructors in C. Edit specially for Alan Stokes: typedef struct foo { int a; foo(int val, double val2) :a(val) { cout << val2 << endl; } } foo; int foo(int value, double val2) { cout << value << val2 << endl; } void main() { some_random_func(foo(50, 1.0)); // constructor foo or function foo? }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Getting null values when trying to parse an XML using XPATH in Java When running this code in Eclipse I get only null values: String recordsAsXML = "<vGVC:Row xmlns:vGVC=\"urn:com.versai:Bacon:GetViewContentsResponse.v1.0\"><vGVC:Column><vGVC:Value>aaa0</vGVC:Value><vGVC:ObjectName>2ff31656-b10c-11e0-99f6-e01321378d2a</vGVC:ObjectName></vGVC:Column><vGVC:ModifiedAfterQuery>false</vGVC:ModifiedAfterQuery></vGVC:Row>"; DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(recordsAsXML)); Document doc = builder.parse(is); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//vGVC:Value/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } I'm trying to extract the "aaa0" value. Could you please help me understand what I'm doing wrong? Thanks in advance, Michal. A: You should use namespace context to let XPath know about your namespace, for example like this: xpath.setNamespaceContext(new NamespaceContext() { @Override public Iterator<?> getPrefixes(String namespaceURI) { return null; } @Override public String getPrefix(String namespaceURI) { return "vGVC"; } @Override public String getNamespaceURI(String prefix) { return "urn:com.versai:Bacon:GetViewContentsResponse.v1.0"; } }); This should be done before calling evaluate, and if you have more than one namespace to handle, you can add them all in one implementation and use if statements to return the right prefix/URI. More details in the javadocs here: http://download.oracle.com/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7597644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Preventing styles of html elements created by firefox plugin getting overridden by the sites stylesheet I am injecting some html + css into every page from my firefox plugin. But this styles is sometimes getting overridden by the style sheet. I want to stop this behavior. I know this can be solved by some css tricks. Adding !important for instance. But is there a way available in firefox or xul to do this easily? A: Using !important alone is not enough, the webpage could do the same and still override your styls. You can use the Stylesheet Service to register a user stylesheet. If you then use !important then web pages will no longer be able to override your styles. Note that user stylesheets are always global and apply to all webpages as well as browser's own XUL documents. You can restrict them to particular webpages using @-moz-document. A: #MEGA_PLUNGIN a {} #MEGA_PLUNGIN span {} #MEGA_PLUNGIN div {} #MEGA_PLUNGIN table {} ... Not the best solution but right... A: To me, this is one case where you would certainly use !important. That said, you can try to use specificity to ensure your styles are being set. So, make sure that you are targeting the elements are precisely as possible, in order to override those styles that are not as specific. For instance, if you have this structure <body> <div> <h1 class="something"> <a href> The site's styles may target h1.something a{ You should aim to do this body div h1.something a{ which is more specific and would override the above styles. The other thing you might be able to do is append your styles just before the </head>, which would make them appear last in the cascade, and, if they are equal, will be applied.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Powershell custom cmdlet formatting output I am writing my first custom CMDLet in powershell 2.0. I have encoutered a problem with custom formatting temaplate xml being not used in my cmdlet. Here is my formatting file: <Configuration> <ViewDefinitions> <View> <Name>abc</Name> <ViewSelectedBy> <TypeName>ExtractServicesCmd.ServiceInfo</TypeName> </ViewSelectedBy> <TableControl> <TableHeaders> <TableColumnHeader> <Label>ServiceName</Label> <Width>12</Width> <Alignment>right</Alignment> </TableColumnHeader> </TableHeaders> <TableRowEntries> <TableRowEntry> <TableColumnItems> <TableColumnItem> <PropertyName>ServiceName</PropertyName> </TableColumnItem> </TableColumnItems> </TableRowEntry> </TableRowEntries> </TableControl> </View> </ViewDefinitions> </Configuration> Everything goes fine, Format is successfully registering (I checked it using Get-FormatData command) with proper type. But when executing my commandlet it still uses default formatting. I even tried to force using my formatter by piping "| Format-Table -View abc" but it says - cannot find view with name abc! What is going on? I tried Get-FormatData and analyzed entries - my ViewDefinition is present there with proper view name! Thanks for reading. A: What does $x.GetType().FullName where $x is an instance of you type return? (Ie. this sounds like PSH is failing to match the type name.) Note the type name will match the exact type of the object being formatted, or a base type of the object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I exclude/ disallow field in Validator in Spring I have 2 forms * *Add Book (addBook.jsp) and It's controller (AddBookController.java) *Edit Book(editBook.jsp) and It's controller (EditBookController.java) Book.java is bean class for both views. I have same UI for editBook.jsp and addBook.jsp. I have created org.springframework.validation.Validator (BookValidator.java) for add book same Validator can be use for EditBookController.java But in AddBookController when user is entering Book information user must enter unique bundle number. I have some validations for Unique bundle number on BookValidator. This validations must not work while user EditBook. I want to exclude / disallow field for validations while book edit. I have done binder.setDisallowedFields(new String[] {"bundleNumber"}); but not helped me. Please suggest me How i can re use validator ? A: It sounds like you need two validators. Perhaps the more specific one can be a subclass of the more general one. The template method pattern may help here with different, overridable methods for each piece of validation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FOP warning:line 1 of a paragraph overflows the available area by more than 50 points Just to make sure I would like to share my understanding of FOP vre 1.0 with you, FOP uses a automated line breaking algorithm i.e when data overflows the width of a table cell,FOP looks for white space in the data and if it finds a white space,then it wraps the data that overflows from the nearest white space into next line of that cell. But what if the data don't has a white space,then then FOP is not able to wrap data. This is the problem I'm facing. I write this code. <fo:table-cell border="solid"> <fo:block hyphenate="true" language="en" wrap-option="wrap"> <xsl:value-of select="welcomeMsg"></xsl:value-of> </fo:block> </fo:table-cell> but it overflows from table cell,instead of wraping because the welcomeMsg is a long string with no white spaces in between.I need the welcomeMsg to be wrapped inside table cell. A: Apache FOP implements the Unicode UAX #14 algorithm for line breaking. So, if a word (or loooong number) cannot be broken and therefore overflows a table-cell, it's because of that algorithm. The usual work-around is to insert zero-width spaces (&#x200B;) into fields that you know could cause overflows. This can easily be done via XSLT. See also: How to force wrap on table entries
{ "language": "en", "url": "https://stackoverflow.com/questions/7597663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Play .wav files on Android phone I need to complete an app on an Android phone that plays back four sound files when four separate buttons are pressed. The trouble I have is that the sound files are .wav files. They are also stereo files. I need to play them on the Android phone uncompressed and in stereo. My understanding is that .wav can not be played on Android phones as it is uncompressed and that I will need to convert the file format but I have not had any luck that way. Any ideas? Thanks!! A: Android certainly can open/play WAV files. Use android.media.MediaPlayer to play them, as you'd do for mp3 or other format. A: See the following list for a complete reference of supported media formats: http://developer.android.com/guide/appendix/media-formats.html Wave is supported, PCM/WAVE 8- and 16-bit linear PCM (rates up to limit of hardware) WAVE (.wav) A: From Android 4.0.1 Android supports Wave (.wav) formats, you can access 8bit or 16 bit audio files in .wav format
{ "language": "en", "url": "https://stackoverflow.com/questions/7597667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Deprecated API Android and Iphone I am making application which is using a deprecated API. I have to submit it on Apple and Android App Store next month. In this case, is there any chances to reject the application from app Store of Iphone And Android. A: Don't use a deprecated API. Almost nobody deprecates something without providing an alternate means to accomplish the same task. Use the documentation to discover these alternatives, and adjust your code accordingly. What happens if iOS 5 comes out tomorrow, for instance, and all of a sudden your code breaks on those devices. You'll be scrambling to fix it. Fix it now while you have some time. A: Android should not be a problem due to the fact that they won't look at your code. Apple will probably check your code and if they see it, they will most likely tell you that you are using deprecated API, but I don't think they will reject it if it is working flawlessly with it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSOperation to all run consequently I have program that is crashing somewhere not really visible to programmer. It may have something to do with memory management but it definitively has something to do with multiple threads and more than 200 notification observers... I would like to know if that kind of starting derived NSOperation object would ensure that all operations are being executed consequently as normal execution on one thread? [operation start]; [operation waitUntilFinished]; A: I think what you're looking for is operationQueue.maxConcurrentOperationCount = 1 and then add all your operations to the NSOperationQueue. They will be executed serially, one after another. A: No, it starts the operation and then blocks the calling thread until it is done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Transferring serialized objects with jboss much faster than transferring byte arrays? Following scenario: I have a java client with 40 threads. Each thread has its own bean instance and each thread calls its beans method 100 times. I'm confused about the results of this test because sending objects turned out to be a lot faster than sending byte arrays or integer arrays. Sending a single integer value is still fastest, though. The size of both arrays in this test was 1. Size 2048 was neither slower nor faster. map, data, panel, maprecord and field are classes with quite a lot of properties. How can this be? static: created once, server always returns same instance dynamic: created everytime the beans method is called sessions: 40 repetitions: 100 transactions: 4000 send bytes ( static ) transactions/s: 1047.3947 time: 3.819 send ints ( dynamic ) transactions/s: 11976.048 time: 0.334 send int arrays ( static ) transactions/s: 1114.5166 time: 3.589 send map with 30 fields ( static ) transactions/s: 4613.6104 time: 0.867 send map, created from panel ( dynamic ) transactions/s: 221.50847 time: 18.058 send data, containing a map created from a maprecord ( dynamic ) transactions/s: 5797.1016 time: 0.69 My javax.ejb.EJBObject: ... public byte[] getByteArrayForPerformanceTest() throws java.rmi.RemoteException; public Map getMapForPerformanceTest() throws java.rmi.RemoteException; public Data getConverseDataForPerformanceTest() throws java.rmi.RemoteException; ... The UserSessionBean: ... private static byte[] byteArrayForPerformanceTest = new byte[1]; public byte[] getByteArrayForPerformanceTest() throws java.rmi.RemoteException { return UserSessionBean.byteArrayForPerformanceTest; } ... A: Well your Collections, Maps, and arrays are all serializable, as well as the primitives. It's more likely that JBoss uses standard Java serialization to send/receive these instances between remote entitites. If you wan't an explanation as to why one thing goes faster than other, then why don't you serialize both those instances to separate files and see which one is bigger. Especially with collections and maps you can't know how many objects (especially arrays) are created under the hood when you instantiate them. Note that for these you can controll to some point the initial sizes of the underlying arrays. A: You don't say what is under the hood here but you might for example be serializing your objects to byte arrays then sending those and JBoss is serializing them, so two serialization step.s
{ "language": "en", "url": "https://stackoverflow.com/questions/7597673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I stop Coldfusion from converting query column names to upper case? When I select data from a MySQL table using the cfquery tag in ColdFusion 8, the column names are all converted to uppercase even though I've stored them in camelCase in the database table. Is there a way to make ColdFusion respect the case of the column names? The reason I'm asking is because I'm returning the query result as a JSON object and I don't want to use upper case property names on the JavaScript side as I reserve that naming convention for constants. A: queryName.getMetaData().getColumnLabels() return an array of query column label with original case from query A: Use getMetaData on the query object. It returns an array of columns showing the same case you used in the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: "Dead Store" Warning in Xcode I am getting a dead store warning when I analyze my project but the project does not crash. Here is what I am doing NSString *graphUrl = nil; if ([graphArray count] == 1) { objTrial = [graphArray objectAtIndex:0]; graphUrl = @"http://chart.apis.google.com/chart?cht=s:nda&chf=bg,s,FFFFFF&chs="; graphUrl = [graphUrl stringByAppendingString:@"&chd=t:"]; graphUrl = [graphUrl stringByAppendingString:objTrial.highValue];// get the dead store error here } else { //someother operation is done and a value is loaded to aURL } I get a dead store warning as mentioned in the code.. How can I prevent this? It would be great if someone could help me out in this A: The warning is telling you that the store that you do in the first line gets thrown away (i.e assigning an empty string to the variable and then reassigning it afterwards without using the original value). Just change the first line to the following and the warning should go away: NSString *aUrl; Edit: you should change the line where you use it also: aURL = [aValue copy]; A: "dead store" means something that's not used, or rather something useless. You get it when you have a variable defined that you never do anything with. So, the Analyzer tells you that you have wasted some storage. Here you haven't used the aUrl object after assigning it. It won't cause any problems other than a few bytes of wasted memory. Of course if it's a large object that could be more. Perhaps someone could chip in with knowledge of compilers, as compiler optimization might take care of dead stores in any case. A: Dead Store is a value that is assigned but never used. There is nothing to worry about it. But if you can't control yourself from worrying ;-) you can change your code to, NSString aUrl = nil; if ([anArray count] == 1) { // a value is store in aValue // then that value is appended to aURL aURL = [aURL stringByAppendingString:aValue]; } else { aUrl = @""; //someother operation is done and a value is loaded to aURL }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting headers when using jQuery Form Plugin I'm using JQuery Form Plugin and I'm not sure how to set headers. I want to be able accomplish something like this: $.ajax({ url: "/url", data: post, type: "POST", beforeSend: function(jqXHR) { jqXHR.setRequestHeader("foo", "bar"); }, }) but the beforeSubmit event dosn't pass the jqXHR object for manipulation. Any ideas? A: The following code works for me. $('#myForm').ajaxSubmit({ headers: { "foo": "bar" } }); A: As it turns out, the options object you send to the form plugin actually passes the options to the $.ajax method. Therefore you can use the native before send function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can XDebug track separately the time spent for profiler calls? I am using XDebug as a profiler for a PHP application. I have run into a situation where XDebug changes severely the results in such a degree that they are useless. Here a simplified example to demonstrate the problem: function foo(){ $x = 1; } function bar(){ foo(); } Test A: $t0 = microtime(true); for ($i = 0; $i < 1000000; $i++) foo(); echo microtime(true) - $t0; Test B: $t0 = microtime(true); for ($i = 0; $i < 1000000; $i++) bar(); echo microtime(true) - $t0; So, these are the results I am getting (in seconds): profiler | profiler > profiler disabled | enabled > results -------------------------------------------------------------------- output | output > total time time in foo() time in bar() Test A 0.159 | 12.199 > 12.245 0.110 - (not called) Test B 0.233 | 25.399 > 25.578 0.104 11.068 The increased execution time is expected because of the extra calls to the profiler. The slight variation between the microtime-based output and the profiler results is also expected. I have repeated the tests several times, and the results are always similar. From the results taken from Test B with the profiler disabled, we can say that the script spends about 0.159 seconds in foo() and 0.074 seconds in bar(). It is evident that time spent in bar() is less than the time spent in foo(). However, when I analyze the results of the profiler (with qcachegrind), the time shown as spent in bar() (= 11.068 seconds) is ridiculously higher than the time in foo() (=0.104 seconds). There is a possible explanation for this: each time a function call is made, the profiler runs some extra code to keep track of the time spent in the call. I believed that it excluded this extra time from the results, but apparently it does not. [EDIT] As a result, the profiler says that bar() takes more time than foo() in this program, which is not the case as we have measured with the profiler disabled. It's not even close! The relative results (the percentage of time taken by each function) are totally wrong. This should not be expected, because, if this is the case, the profiler can not indicate which function takes most of the time. Although the absolute times are expected to have (big) differences, the relative times should not have. [/EDIT] This renders the results unusable. Any code that is more modular (with more function calls, wrappers, objects etc.) is severely penalized, although it is not that slower! So the question is: Is there any way to tell XDebug to ignore or track separately the extra time spent for the profiler calls? A: It is known that xdebug behaves like that and actually no news. Sorry, obviously this is news to you, and I don't want to say everybody needs to know that. As an explanation: xdebug does the whole job, from beginning to end, dumping/metricating everyhing as announced. This comes with a price (how couldn't it?). If you need to pick metrics in an isolated context within your script, you should not run xdebug. Or as your question shows: You're trying to profile xdebug with xdebug switched on (with PHP code!). That won't really work, you can't profile a PHP compiled C extension with PHP user-code, or at least I won't trust that much. Imagine the lib is changing the behaviour of the interpreter, that same interpreter your profiling code is running on. If you really need to profile a specific part of your code isolated, xdebug is just not the tool of choice. Look for xhprof or maybe in a real life environment Pinba. A: you are not supposed to expect the profilers results to be the same as normal opperation, it is inposseble(or you have to slow down opperation whith is not desireble) but still the times in de profiler are verry usefull for example you can see that altrug the scripexcution taks longer the results are (some wat) cosistent with scale using profilers is usefull to pointout problem spots, but ther results cannot be the same as reallife is to mutch optimized(at least with xdbug) A: Definitely give xhprof a try. Seems less prone to errors. Not to knock Xdebug. A: Unfortunatelly, it is not possible. I am no longer using XDebug as a profiler and I suggest that nobody should use it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Rails 3.1, jQuery: Append data to a form before sending it out I read this issue in jquery-rails because I want to add some data to the form before sending it out. The instructions seemed pretty simple: Hook onto before:send and do what you will to the form. I did it this way: form.live "ajax:before", () -> form.data('params', sortableList.nestedSortable('serialize')) console.log "data we're sending along: " + form.data('params') # here I see the data I want to append to the form The POST though doesn't contain any of that data I added to data-params: Started POST "/admin/site/nav_items/render_event_response?source=menu_item_tree&type=submit" for 127.0.0.1 at 2011-09-29 20:48:11 +0800 Processing by Admin::Site::NavItemsController#render_event_response as JS Parameters: {"authenticity_token"=>"sV8eEMpIVicbmT0nAfDdChgpRMyI5yR/N6m5VLk3+/Q=", "source"=>"menu_item_tree", "type"=>"submit"} User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1 ...snip... Did I understand that issue wrong? How do I go about appending data to the form before sending it out? Thanks! A: Look at the issue you are refering to You're missing the critical part. ajax:before callback accepts 3 parameters, one of which you should be editing editing. Your code should look like this (probably... I haven't tested it) form.live "ajax:before", (event,xhr,settings) -> settings.data('params', sortableList.nestedSortable('serialize'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7597700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Data not refreshing when using actionscript to assign dataprovider My problem is when I assign the dataprovider for a spark list using actionscript it does not automatically update the list. example: I have a list: < s:List id="fiterList" allowMultipleSelection="true" width="100%" height="100%"/> and I use actionscript to assign the dataprovider: filterList.dataProvider = model.ADEPTList; (where model.ADEPTList is an ArrayCollection) When I use an event to update model.ADEPTList the data does not show up in the list. HOWEVER, if I instead declare the dataprovider in the MXML like this: < s:List id="filterList" allowMultipleSelection="true" width="100%" height="100%" dataProvider="{model.ADEPTList}"/> When the event updates model.ADEPTList it DOES show up in the list. Why is this and how can I get the list to update when assigning the dataprovider using actionscript? Thanks A: That's because that's only an assignment, you're not binding your list's dataProvider to model.ADEPTList. You have to read more about flex binding mechanisms. In AS3 you could use: BindingUtils.bindProperty(filterList,"dataProvider",model,"ADEPTList");
{ "language": "en", "url": "https://stackoverflow.com/questions/7597702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: DirectoryServices filter and methods I'm trying to get a list of all users in an OU/DC from AD. This is what I came up with: $erroractionpreference = "SilentlyContinue" function Get-GroupMembers { $filter = "(&(objectCategory=person)(objectClass=user))" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.Filter = $filter $colResults = $objSearcher.FindAll() foreach ($member in $colResults) { $member } } get-GroupMembers If I change the filter to $filter = "(&(objectCategory=person)(objectClass=user)("OU=Admin Accounts,DC=admin")) Nothing returns. Why is this? I would also like to display certain values (if the accounts is active or disabled etc) but if I pipe $member to gm, I get nothing. Any help would be greatly appreciated. A: If you want to search a specific OU, you can set it as the root of your searcher object: $objOU = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Admin Accounts,DC=admin") $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objOU You can also control the scope of your search. Here are the two most relevant options for you: # Option 1: Return only users in the 'Admin Accounts' OU $objSearcher.SearchScope = "OneLevel" # Option 2: Return users in the 'Admin Accounts' OU or any level beneath it $objSearcher.SearchScope = "SubTree" Unless you override the search root and scope, you'll get the default of performing a SubTree search against the root of your current domain. You can find more detailed information in this TechNet article: * *Searching Active Directory with Powershell Edit: As uSlackr noted, your DC component does look fishy. I left it intact for my example, but an incomplete/malformed base object name will botch your search regardless of the method you use. A: The DC component is not complete. It should look something like this: $filter = "(&(objectCategory=person)(objectClass=user)("OU=Admin Accounts,DC=myco,dc=com")) but the dc=admin,dc=com should translate from the AD domainname in this example "admin.com" which doesn't seem right This is much easier with the Microsoft AD cmdlets. get-aduser -filter * -searchbase "ou=test,dc=mycom,dc=com" Information on downloading and using the cmdlets is available on TechNet A: You can try use the Quest ActiveRolesManagement Shell for ActiveDirectory downloadable from here: http://www.quest.com/downloads/ The package is freeware and is the more accurate cmdlets for Active Directory management from powershell.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: $(window).scrollTop tied to $(window).scroll() event acting oddly I'm trying to trigger a function when the window is scrolled more than a certain number of pixels. Here's my code: $(window).scroll(function(){ if( $(this).scrollTop() >= 100 ) { someFunction(); } else { someOtherFunction(); } }); It kinda works, but there's either a delay of around 2-4 seconds after scrolling before the function(s) are fired or else the functions aren't triggered at all. Tried it out in Safari / Chrome. Don't know if that helps or not! A: It works using jQuery 1.6.1 + mousewheel / scrollbar in Chrome15/Safari5.1/FF7 on OSX. What are you doing in those two functions? For testing, I put a simple alert() in someFunction and nothing in someOtherFunction. Remember that one of those functions is executed every time the scroll-event fires unless you stop it once it was called... e.g. someFunction is called a lot after you scrolled below the 100px line. John Resig: It's a very, very, bad idea to attach handlers to the window scroll event. A: The code looks fine and works for me. As Wolfram says, it's rarely a good idea to attach handlers directly to the scroll event, as this fires a lot and can bring the user's system to a crawl. I'd recommend using Ben Alman's jquery throttle/debounce plugin. A: If you're scolling by holding in the click-button instead of using the scroll wheel, I believe the event won't fire until you release the click-button. Have you considered running a loop that checks the scrollTop instead? EDIT: I just check an old project of mine using window scroll event, and it runs perfect with the same event. I asume you have this script of yours wrapped inside: $(function() { // code });
{ "language": "en", "url": "https://stackoverflow.com/questions/7597712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UITableViewCell unselectable while its accessoryView is selectable I want to have a UITableViewCell that is not selectable while its accessory view (a UISwitch in my case) is editable. The issue is that I have two other cells of which one needs to remain active; this is very similar to the following image of the Time/Date selector from the iOS calendar app: http://www.theiphoneblog.com/images/stories/2009/01/photo.jpg I cannot post the image due to being a new user. Note that in this view the "All-day" cell cannot be selected but its UISwitch can be changed, while one of "Starts" and "Ends" cells must remain selected. I've tried both: [cell setUserInteractionEnabled:NO]; [cell.contentView setUserInteractionEnabled:NO]; The first one works but does not allow the switch to be changed whereas the second does not work, it allows one of the top cells to be deselected which I do not want to happen. A: Implement in delegate method - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if ([selectablePaths contains:indexPath]) { // cell selected selectedPath = indexPath; }else { [tableView deselectRowAtIndexPath:indexPath animated:NO]; [tableView selectRowAtIndexPath:selectedPath animated:YES scrollPosition:UITableViewScrollPositionNone]; } } And enable user interaction for all cells.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Putting files in emulator external storage, prior to app starting Using the emulator, with external storage attached, I would like to emulate what happens when the application starts up and certain files are already present in the relevant directory on ext storage. Is the external storage actually located on my machine, after enabling it in the AVD? Or should I be creating the files with some temporary, throw away code? Or should I just test on a real device? What is best practice for this scenario? A: The sdcard.img is in the avd folder (~/.android/avd). If you are using Linux or OSX you can mount it, manipulate the files inside, and unmount it. Probably there's a program in Windows that let you do the same. As an alternative, you can start the emulator and then manipulate the sdcard content using adb push/pull or DDMS. A: The easiest way of creating the SDCard contents, would be to create the files that you need on your machine and then using the DDMS Perspective in Eclipse you can select your emulator in the Devices panel on the left, and then choose the FileExplorer tab on the right. There is a folder named sdcard which contains the SDCard contents. By using the controlls on the right upper-side you can create folders inside the SDCard and by you can also Push files on the emulators SDCard. As @dtmilano said, you can also achieve the same thing using Command Prompt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select with grouping in range From Table A B _______________ 1 A 3 B 6 C 7 C 8 X 9 Y 15 Z 16 R 17 t 23 T 43 e How to bring this result: Range A Count B _________________ 1-10 6 11-20 3 21-30 1 31-40 1 This could be done using loop: Select Count (* ) from TableA where b between @a and @b But I would like to do it without using any loop is it possible? A: Try this: SELECT Cast(((A / 10) * 10 + 1) as varchar(100)) + '-' + Cast(((A / 10) * 10 + 10) as varchar(100)) AS 'Range A', Count(*) as 'Count B' FROM TableA GROUP BY A / 10
{ "language": "en", "url": "https://stackoverflow.com/questions/7597723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I order fields using an ORACLE select when my strings can contain wildcard characters I have the following ORACLE table and data: create table test_table (field1 varchar2(20)); insert into test_table values ('aaa.bbb.ccc.dd'); insert into test_table values ('aaa.bbb.c*c.dd'); insert into test_table values ('aaa.bbb.ccc'); insert into test_table values ('aaa.b*b.ccc'); insert into test_table values ('aaa.bbb'); insert into test_table values ('a*a.bbb'); insert into test_table values ('aaa'); insert into test_table values ('bbb.ccc.dd.ee'); insert into test_table values ('bbb.ccc.dd'); insert into test_table values ('bbb.ccc'); insert into test_table values ('bbb'); I'd like to do a table select which will retrieve the records in the following order: aaa.bbb.ccc.dd aaa.bbb.c*c.dd aaa.bbb.ccc aaa.b*b.ccc aaa.bbb a*a.bbb aaa bbb.ccc.dd.ee bbb.ccc.dd bbb.ccc bbb In my inserts above the records are obviously already in the right order but they won't normally be. If I run the following select: select field1 from test_table order by field1; I get the output: a*a.bbb aaa aaa.b*b.ccc aaa.bbb aaa.bbb.c*c.dd aaa.bbb.ccc aaa.bbb.ccc.dd bbb bbb.ccc bbb.ccc.dd bbb.ccc.dd.ee How do I write a SELECT statement to get my desired order ? A: select field1 from test_table order by substr(field1, 1,1), replace(field1, '*', substr(field1, instr(field1, '*')-1, 1)) desc, instr(field1, '*') ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7597728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you achieve case-insenstive search/indexing on thinking-sphinx or flying-sphinx? Have had a look through the documentation and wasn't able to clarify this easily.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597729", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: binding data to a usercontrol i've a userControl (watch the screenshot): I would like to know how can i bind data to this control. 1) i want to drag & drop this usercontrol to a form 2) i wish to decide which table from my database should be used 3) the datagrid (the grey control at bottom) should be automatically binded to the datasource which points to the table i wish to use 4) the detail Tab at the usercontrol should be automatically filled with label + textbox for each field of the table i wish to use My Question is.. how can i realize this? Any ideas? greets A: 1) When you build your project, your UserControl is displayed in the VisualStudio's Toolbox, so you can drag&drop it on your forms wherever you want it. 2) Expose DataSource of your DataGridView, for example in some property of your UserControl: public BindingSource MyDataGridViewDataSource { get { return MyDataGridView.DataSource; // or you can skip 'get' if you don't need it } set { MyDataGridView.DataSource = value; } } 3) ...or if you want column names, use property that gets/sets DataTable (remember to Fill it first http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx): private DataTable _myDataTable = new DataTable(); public DataTable MyDataTable { get { return _myDataTable; } set { _myDataTable = value; BindingSource bs = new BindingSource(); bindingSource1.DataSource = value; MyDataGridView.DataSource = bs; // 4) fill your labels somewhere here string tablename = value.TableName; foreach (DataColumn col in value.Columns) Console.WriteLine("{0}\t{1}", col.ColumnName, col.DataType); } } It is not a complete solution, but it's a place to start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert distinct values SQL Server I'm trying to insert unique values into a table from a View. I have a table as below: the "fromView" has no unique constraint in passport id | passport | name | surname | address 1 44543 John Smith xxxxx 2 10001 Mike Thomps avasfa 3 10001 Mike Thomps avasfa 4 10001 Mike Thomps avasfa 5 14221 Robert Martinez lkjij3 my "toTable" has the same data structure but with a unique constraint in passport column. my insert query is this: INSERT into toTable (id, passport, name, surname, address) SELECT (id, passport, name, surname, address) FROM fromView a WHERE passport IS NOT NULL AND NOT EXISTS (SELECT * FROM toTable b WHERE b.passport = a.passport) but this give me the error below: Cannot insert duplicate key row in object 'toTable' with unique index 'toTable_Passport_Unique'. So, I Don't know how to insert unique values into my table. Thanks in advance A: You can get a list of all passports with multiple entries by running this query: Select Passport, Count (*) NumEntries From fromTable Group by Passport Having Count (*) > 1 Then you have to decide what to do with these duplicate rows. Run the following query to see the full row for these duplicates: Select * From fromTable Where Passport In ( Select Passport, Count (*) NumEntries From fromTable Group by Passport Having Count (*) > 1 ) Order by Passport Let's say you decide to go with the newest row inserted for each passport (meaning the Id would be the highest), this query will give you the data you need. Select T1.* From fromTable T1 Where Id In ( Select Max (Id) Id From fromTable Group by Passport ) You can insert using INSERT into toTable (id, passport, name, surname, address) Select T1.* From fromTable T1 Where Id In ( Select Max (Id) Id From fromTable Group by Passport ) A: insert into toTable (id, passport, name, surname, address) select id, passport, name, surname, address from ( select *, row_number() over(partition by passport order by id) as rn from fromTable ) as T where rn = 1 A: If we can assume that for the same passport, we will have the same name, surname, and address, and we only want the most recent (highest) id then try, INSERT INTO toTable (id, passport, name, surname, address) SELECT max(id), passport, name, surname, address FROM fromTable --optional WHERE clause in case there's already data in toTable: WHERE passport NOT IN (SELECT to.passport from toTable [to]) GROUP BY passport, name, surname, address A: insert into toTable (id, name, surname, addr, passport) select testA1.id, testA1.name, testA1.surname, testA1.addr, testA1.passport from fromTable as testA1 right join (select min(id) AS distinctID, passport from fromTable group by passport) as testA2 on testA2.distinctID = testA1.id
{ "language": "en", "url": "https://stackoverflow.com/questions/7597735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python - Reading BLOB type from SQLite3 DB This is a follow on from: Python - Converting Hex to INT/CHAR I now have a working solution for converting the stored hex value of an IP from an sqlite3 db into a readable and usable format. However up until now I have been testing by copying and pasting the values directly from a sqlite3 db viewer. I have been trying to poll the db with a script to lookup that information however I have discovered that it apparantly stores blob data into a buffer which isn't instantly human readable. For example, the IP 192.168.0.1 is stored as blob type under the field ip as X'C0A80001' Since I worked from a copied and pasted example into my code I have constructed code to strip the X' and ' from the hex to be able to then convert it. What I cannot get is that value from the database (X'C0A80001' <- this value that I can view with a db manager). Searching I found http://eli.thegreenplace.net/2009/05/29/storing-blobs-in-a-sqlite-db-with-pythonpysqlite/ which showed an example of reading blobs to and from a sqlite db but their methods didn't work. They displayed the error; print row[0], str(row[1]).encode('hex') IndexError: tuple index out of range I am fairly new to Python so apologies if I am missing something basic but any pointers or code examples anyone has to help me get my head around this would be appreciated. EDIT: Doh, didn't paste the code from the above example; c = conn.cursor() c.execute('select ip from item where name = ' + "\'" + host + "\'") for row in c: print row[0], str(row[1]).encode('hex') It may be my understanding thats really off here as to why I can't read it back the way I want to UPDATE: Using the below answer I modified my code to; rows = c.execute('select ip from item where name= ' + "\"" + host + "\"") for row in rows: print str(row[0]).encode("hex") A: After checking the link, it seems the most likely explanation is an empty row. On line 29 you set up a for loop to go over the results of a query. In python this means you have a list: [item,item2,item3] and each time you go through the loop, your row variable points to the next item. Within the loop, you are checking the contents of the current item. Each of these items is a tuple which suppposedly has at least two entries. But if any of those items don't have an entry for row[0] or row[1] then you will get an index out of range exception. You haven't posted enough code to make determining why this occurred feasible, but to get the code running I'd suggest this: for row in cur.execute("select * from frames"): try: print row[0], str(row[1]).encode('hex') except IndexError, e: print "IndexError: {0}".format(e) That will continue across your entire query result, even if some of them are bad. Edit: I just saw your update, and your problem is that c does not hold the contents of your query. c.execute('select ip from item where name = ' + "\'" + host + "\'") returns a list, which you ignore. The original example works because you get the list in the for loop, and so it's an anonymous variable only within the loop context. To fix your code: c = conn.cursor() rows = c.execute('select ip from item where name = ' + "\'" + host + "\'") for row in rows: print row[0], str(row[1]).encode('hex')
{ "language": "en", "url": "https://stackoverflow.com/questions/7597736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the purpose of Looper and how to use it? I am new to Android. I want to know what the Looper class does and also how to use it. I have read the Android Looper class documentation but I am unable to completely understand it. I have seen it in a lot of places but unable to understand its purpose. Can anyone help me by defining the purpose of Looper and also by giving a simple example if possible? A: Looper allows tasks to be executed sequentially on a single thread. And handler defines those tasks that we need to be executed. It is a typical scenario that I am trying to illustrate in this example: class SampleLooper extends Thread { @Override public void run() { try { // preparing a looper on current thread // the current thread is being detected implicitly Looper.prepare(); // now, the handler will automatically bind to the // Looper that is attached to the current thread // You don't need to specify the Looper explicitly handler = new Handler(); // After the following line the thread will start // running the message loop and will not normally // exit the loop unless a problem happens or you // quit() the looper (see below) Looper.loop(); } catch (Throwable t) { Log.e(TAG, "halted due to an error", t); } } } Now we can use the handler in some other threads(say ui thread) to post the task on Looper to execute. handler.post(new Runnable() { public void run() { //This will be executed on thread using Looper. } }); On UI thread we have an implicit Looper that allow us to handle the messages on ui thread. A: A Looper has a synchronized MessageQueue that's used to process Messages placed on the queue. It implements a Thread Specific Storage Pattern. Only one Looper per Thread. Key methods include prepare(),loop() and quit(). prepare() initializes the current Thread as a Looper. prepare() is static method that uses the ThreadLocal class as shown below. public static void prepare(){ ... sThreadLocal.set (new Looper()); } * *prepare() must be called explicitly before running the event loop. *loop() runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop() method dispatches the Message to its target handler *quit() shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special message Looper can be programmed in a Thread via several steps * *Extend Thread *Call Looper.prepare() to initialize Thread as a Looper *Create one or more Handler(s) to process the incoming messages *Call Looper.loop() to process messages until the loop is told to quit(). A: Life span of java Thread is over after completion of run() method. Same thread can't be started again. Looper transforms normal Thread into a message loop. Key methods of Looper are : void prepare () Initialize the current thread as a looper. This gives you a chance to create handlers that then reference this looper, before actually starting the loop. Be sure to call loop() after calling this method, and end it by calling quit(). void loop () Run the message queue in this thread. Be sure to call quit() to end the loop. void quit() Quits the looper. Causes the loop() method to terminate without processing any more messages in the message queue. This mindorks article by Janishar explains the core concepts in nice way. Looper is associated with a Thread. If you need Looper on UI thread, Looper.getMainLooper() will return associated thread. You need Looper to be associated with a Handler. Looper, Handler, and HandlerThread are the Android’s way of solving the problems of asynchronous programming. Once you have Handler, you can call below APIs. post (Runnable r) Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached. boolean sendMessage (Message msg) Pushes a message onto the end of the message queue after all pending messages before the current time. It will be received in handleMessage(Message), in the thread attached to this handler. HandlerThread is handy class for starting a new thread that has a looper. The looper can then be used to create handler classes In some scenarios, you can't run Runnable tasks on UI Thread. e.g. Network operations : Send message on a socket, open an URL and get content by reading InputStream In these cases, HandlerThread is useful. You can get Looper object from HandlerThread and create a Handler on HandlerThread instead of main thread. The HandlerThread code will be like this: @Override public void run() { mTid = Process.myTid(); Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); mTid = -1; } Refer to below post for example code: Android: Toast in a thread A: This answer has nothing to do with the question, but the use of looper and the way people created the handler and looper in ALL the answers here are plain bad practice (some explanations are correct though), I have to post this: HandlerThread thread = new HandlerThread(threadName); thread.start(); Looper looper = thread.getLooper(); Handler myHandler = new Handler(looper); and for a full implementation A: What is Looper? Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no such queue, e.g. simple thread does not have any queue. It executes once and after method execution finishes, the thread will not run another Message(Runnable). Where we can use Looper class? If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for creating a queue in the thread. For example, while writing an application that downloads files from the internet, we can use Looper class to put files to be downloaded in the queue. How it works? There is prepare() method to prepare the Looper. Then you can use loop() method to create a message loop in the current thread and now your Looper is ready to execute the requests in the queue until you quit the loop. Here is the code by which you can prepare the Looper. class LooperThread extends Thread { public Handler mHandler; @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } } A: You can better understand what Looper is in the context of the GUI framework. Looper is made to do 2 things. * *Looper transforms a normal thread into something run continuously until Android app is running. *Looper provides a queue where jobs to be done are enqueued. As you may know, when an application is launched, the system creates a thread of execution for the application, called “main”, and Android applications normally run entirely on a single thread by default the “main thread”. But main thread is not a secret, special thread. It's just a normal thread similar to one you can create with new Thread(), which means it terminates when its run() method returns! Think of below example. public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); } } Now, let's apply this simple principle to Android apps. What would happen if an Android app runs on a normal thread? A thread called "main" or "UI" or whatever starts your application and draws all UI. So the first screen is displayed to users. What now? The main thread terminates? No, it shouldn’t. It should wait until users do something, right? But how can we achieve this behavior? Well, we can try with Object.wait() or Thread.sleep(). For example, main thread finishes its initial job to display first screen, and sleeps. It awakes, which means interrupted, when a new job to do is fetched. So far so good, but at this moment we need a queue-like data structure to hold multiple jobs. Think about a case when a user touches screen serially, and a task takes longer time to finish. So, we need to have a data structure to hold jobs to be done in first-in-first-out manner. Also, you may imagine, implementing ever-running-and-process-job-when-arrived thread using interrupt is not easy, and leads to complex and often unmaintainable code. We'd rather create a new mechanism for such purpose, and that is what Looper is all about. The official document of Looper class says, "Threads by default do not have a message loop associated with them", and Looper is a class "used to run a message loop for a thread". Now you can understand what it means. To make things more clear, let's check the code where the main thread is transformed. It all happens in ActivityThread class. In its main() method, you can find below code, which turns a normal thread into something that we need. public final class ActivityThread { ... public static void main(String[] args) { ... Looper.prepareMainLooper(); Looper.loop(); ... } } and Looper.loop() method loop infinitely and dequeue a message and process one at a time: public static void loop() { ... for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } ... msg.target.dispatchMessage(msg); ... } } So, basically, Looper is a class that is made to address a problem that occurs in the GUI framework. But this kind of need can also happen in other situations as well. Actually, it is a pretty famous pattern for multi-thread applications, and you can learn more about it in "Concurrent Programming in Java" by Doug Lea(Especially, chapter 4.1.4 "Worker Threads" would be helpful). Also, you can imagine this kind of mechanism is not unique in Android framework, but all GUI framework may need somewhat similar. You can find almost same mechanism in Java Swing framework too. A: Android Looper is a wrapper to attach MessageQueue to Thread and it manages Queue processing. It looks very cryptic in Android documentation and many times we may face Looper related UI access issues. If we don't understand the basics it becomes very tough to handle. Here is an article which explains Looper life cycle, how to use it and usage of Looper in Handler Looper = Thread + MessageQueue A: What is Looper? FROM DOCS Looper Looper Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped. * *A Looper is a message handling loop: *An important character of Looper is that it's associated with the thread within which the Looper is created *The Looper class maintains a MessageQueue, which contains a list messages. An important character of Looper is that it's associated with the thread within which the Looper is created. *The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because someone could not invent a better name *Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches. How it works? Creating Looper A thread gets a Looper and MessageQueue by calling Looper.prepare() after its running. Looper.prepare() identifies the calling thread, creates a Looper and MessageQueue object and associate the thread SAMPLE CODE class MyLooperThread extends Thread { public Handler mHandler; public void run() { // preparing a looper on current thread Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here // this will run in non-ui/background thread } }; Looper.loop(); } } For more information check below post * *What is the relationship between Looper, Handler and MessageQueue in Android? *Android Guts: Intro to Loopers and Handlers *Understanding Android Core: Looper, Handler, and HandlerThread *Handler in Android *What Is Android Looper? *Android: Looper, Handler, HandlerThread. Part I. *MessageQueue and Looper in Android A: Handling multiple down or upload items in a Service is a better example. Handler and AsnycTask are often used to propagate Events/Messages between the UI (thread) and a worker thread or to delay actions. So they are more related to UI. A Looper handles tasks (Runnables, Futures) in a thread related queue in the background - even with no user interaction or a displayed UI (app downloads a file in the background during a call). A: I will try to explain the purpose of looper class as simple as possible. With a normal thread of Java when the run method completes the execution we say the thread has done it's job and thread lives no longer after that. what if we want to execute more tasks throughout our program with that same thread which is not living anymore? Oh there is a problem now right? Yes because we want to execute more tasks but the thread in not alive anymore. It is where the Looper comes in to rescue us. Looper as the name suggests loops. Looper is nothing more than an infinite loop inside your thread. So, it keeps the thread alive for an infinite time until we explicitly calls quit() method. Calling quit() method on the infinitely alive thread will make the condition false in the infinite loop inside the thread thus, infinite loop will exit. so, the thread will die or will no longer be alive. And it's critical to call the quit() method on our Thread to which looper is attached otherwise they will be there in your system just like Zombies. So, for example if we want to create a background thread to do some multiple tasks over it. we will create a simple Java's thread and will use Looper class to prepare a looper and attach the prepared looper with that thread so that our thread can live as longer as we want them because we can always call quit() anytime whenever we want to terminate our thread. So our the looper will keep our thread alive thus we will be able to execute multiple tasks with the same thread and when we are done we will call quit() to terminate the thread. What if we want our Main thread or UI thread to display the results computed by the background thread or non-UI thread on some UI elements? for that purpose there comes in the concept of Handlers; via handlers we can do inter-process communication or say via handlers two threads can communicate with each other. So, the main thread will have an associated Handler and Background thread will communicate with Main Thread via that handler to get the task done of displaying the results computed by it on some UI elements on Main thread. I know I am explaining only theory here but try to understand the concept because understanding the concept in depth is very important. And I am posting a link below which will take you to a small video series about Looper, Handler and HandlerThread and I will highly recommend watching it and all these concepts will get cleared with examples there. https://www.youtube.com/watch?v=rfLMwbOKLRk&list=PL6nth5sRD25hVezlyqlBO9dafKMc5fAU2&index=1 A: Simplest Definition of Looper & Handler: Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into this pipe from any other threads. Details in general wording: So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler. The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread). Example: A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background. Read more here about Looper and Handler and the definition of Pipeline Thread: Android Guts: Intro to Loopers and Handlers A: Understanding Looper Threads A java Thread a unit of execution which was designed to perform a task in its run() method & terminate after that: But in Android there are many use cases where we need to keep a Thread alive and wait for user inputs/events for eg. UI thread aka Main Thread. Main thread in Android is a Java thread which is first started by JVM at the launch of an app and keeps on running till the user choose to close it or encounters unhandled exception. When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. Now point to note here is although main thread is Java thread yet it keeps on listening to user events and draw 60 fps frames on screen and still it wont die after each cycle. how is it so? The answer is Looper Class: Looper is a class which is used to keep a thread alive and manage a message queue to execute tasks on that thread. Threads by default do not have a message loop associated with them but you can assign one by calling Looper.prepare() in the run method and then call the Looper.loop(). Purpose of Looper is to keep a Thread alive and wait for next cycle of input Message object to perform computation which otherwise will get destroyed after first cycle of execution. If you want to dig deeper how Looper manage Message object queue then you can have a look at source code of Looperclass: https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/Looper.java Below is an example of how you can create a Looper Thread and communicate with Activity class using LocalBroadcast class LooperThread : Thread() { // sendMessage success result on UI private fun sendServerResult(result: String) { val resultIntent = Intent(ServerService.ACTION) resultIntent.putExtra(ServerService.RESULT_CODE, Activity.RESULT_OK) resultIntent.putExtra(ServerService.RESULT_VALUE, result) LocalBroadcastManager.getInstance(AppController.getAppController()).sendBroadcast(resultIntent) } override fun run() { val looperIsNotPreparedInCurrentThread = Looper.myLooper() == null // Prepare Looper if not already prepared if (looperIsNotPreparedInCurrentThread) { Looper.prepare() } // Create a handler to handle messaged from Activity handler = Handler(Handler.Callback { message -> // Messages sent to Looper thread will be visible here Log.e(TAG, "Received Message" + message.data.toString()) //message from Activity val result = message.data.getString(MainActivity.BUNDLE_KEY) // Send Result Back to activity sendServerResult(result) true }) // Keep on looping till new messages arrive if (looperIsNotPreparedInCurrentThread) { Looper.loop() } } //Create and send a new message to looper fun sendMessage(messageToSend: String) { //Create and post a new message to handler handler!!.sendMessage(createMessage(messageToSend)) } // Bundle Data in message object private fun createMessage(messageToSend: String): Message { val message = Message() val bundle = Bundle() bundle.putString(MainActivity.BUNDLE_KEY, messageToSend) message.data = bundle return message } companion object { var handler: Handler? = null // in Android Handler should be static or leaks might occur private val TAG = javaClass.simpleName } } Usage: class MainActivity : AppCompatActivity() { private var looperThread: LooperThread? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // start looper thread startLooperThread() // Send messages to Looper Thread sendMessage.setOnClickListener { // send random messages to looper thread val messageToSend = "" + Math.random() // post message looperThread!!.sendMessage(messageToSend) } } override fun onResume() { super.onResume() //Register to Server Service callback val filterServer = IntentFilter(ServerService.ACTION) LocalBroadcastManager.getInstance(this).registerReceiver(serverReceiver, filterServer) } override fun onPause() { super.onPause() //Stop Server service callbacks LocalBroadcastManager.getInstance(this).unregisterReceiver(serverReceiver) } // Define the callback for what to do when data is received private val serverReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val resultCode = intent.getIntExtra(ServerService.RESULT_CODE, Activity.RESULT_CANCELED) if (resultCode == Activity.RESULT_OK) { val resultValue = intent.getStringExtra(ServerService.RESULT_VALUE) Log.e(MainActivity.TAG, "Server result : $resultValue") serverOutput.text = (serverOutput.text.toString() + "\n" + "Received : " + resultValue) serverScrollView.post( { serverScrollView.fullScroll(View.FOCUS_DOWN) }) } } } private fun startLooperThread() { // create and start a new LooperThread looperThread = LooperThread() looperThread!!.name = "Main Looper Thread" looperThread!!.start() } companion object { val BUNDLE_KEY = "handlerMsgBundle" private val TAG = javaClass.simpleName } } Can we use Async task or Intent Services instead? * *Async tasks are designed to perform a short operation in background and give progres & results on UI thread. Async tasks have limits like you cant create more than 128 Async tasks and ThreadPoolExecutor will allow only upto 5 Async tasks. *IntentServices are also designed to do background task for a little longer duration and you can use LocalBroadcast to communicate with Activity. But services get destroyed after task execution. If you want to keep it running for a long time than you need to do hecks like while(true){...}. Other meaningful use cases for Looper Thread: * *Used for 2 way socket communication where server keep on listening to Client socket and write back acknowledgment *Bitmap processing in background. Pass the image url to Looper thread and it will apply filter effects and store it in tempe rory location and then broadcast temp path of image. A: I try to give an example in Kotlin. Here is below the code example. Firstly we need to instantiate variable handler from the Handler(the provided looper instead of the default one) which ask for mainthread (Looper.getMainLooper()). The function getAllCourses() need to return LiveData so we use handler.postDelayed() to be added to the message queque and run after x amount of millisecond specified in constant SERVICE_LATENCY_IN_MILLIS. Please feel free to elaborate more wording to my explanation to give more clarity. class RemoteDataSource private constructor(private val jsonHelper: JsonHelper) { private val handler = Handler(Looper.getMainLooper()) companion object { private const val SERVICE_LATENCY_IN_MILLIS: Long = 2000 @Volatile private var instance: RemoteDataSource? = null fun getInstance(helper: JsonHelper): RemoteDataSource = instance ?: synchronized(this) { RemoteDataSource(helper).apply { instance = this } } } fun getAllCourses(): LiveData<ApiResponse<List<CourseResponse>>> { EspressoIdlingResource.increment() val resultCourse = MutableLiveData<ApiResponse<List<CourseResponse>>>() handler.postDelayed({ resultCourse.value = ApiResponse.success(jsonHelper.loadCourses()) EspressoIdlingResource.decrement() }, SERVICE_LATENCY_IN_MILLIS) return resultCourse }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "527" }
Q: Draggable element covers another one when moving back Currently I'm having a small problem with the demo at http://jsfiddle.net/nivea75ml/yCnh5/. Whenever I drag a pink box from the list to the grey area and later move it back, it covers another one in the same list. How can this behaviour be avoided? A: Droppable and sortable $('#draggableList').sortable({ receive: function(event, ui) { var item = $('.ui-draggable-dragging'); item.removeAttr("style"); item.removeAttr('class'); item.addClass('draggable'); } }); var $tab_items = $("#droppable").droppable({ //accept: ".draggable", hoverClass: "ui-state-hover", drop: function(event, ui) { var item = $(this); var olditem = $(".draggable.ui-sortable-helper").clone(); if (olditem[0] != null) { olditem.removeAttr('class'); olditem.addClass('dragged'); olditem.css({ 'position': 'absollute', 'top': ui.offset.top, 'left': ui.offset.left }); olditem.draggable({ connectToSortable: "#draggableList", helper: "original", revert: 'invalid' }); ui.draggable.remove(); $('#droppable').append(olditem).show("slow"); } }, out: function(event, ui) {} }); http://jsfiddle.net/yCnh5/25/
{ "language": "en", "url": "https://stackoverflow.com/questions/7597743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linking a single file from another git repository How do you link a single file from another git repository to your own repository? I don't want the full repository, just a single file. Using git submodule seems like the right route to go, but it wants to grab the whole thing. A: Considering that the unit of work for git is a repository (or more precisely a repository content), I don't think you can easily integrate one file. If you don't need its history, you could consider simply copy it in your repo. But if you do need the history, then some git filter-branch (as in "git: How to split off library from project? filter-branch, subtree?") are in order. That seems a lot of effort for just one file though. In theory, "git: symlink/reference to a file in an external repository" suggests a solution combining submodule and symlink. (from Pavel Šimerda) $ git submodule add /url/submodule/<reponame> $ ln -s <reponame>/path/to/<linked_file> $ git add .gitmodules <linked_file> $ git commit -m "add a symbolic link to <linked_file> with the respective submodule" Since 2011 (original answer above), Gavriel reports in the comments that: * *When I checkout the main repo, the linked file is not a symlink, but instead the file content is "<reponame>/path/to/<linked_file>". In other words git commits the symlink's target as file content *But the basic idea works. I use "submodule/path/to/file" instead of "file" and it works
{ "language": "en", "url": "https://stackoverflow.com/questions/7597748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "78" }
Q: Mismatched parentheses: a quick way to find them? I just rearranged a very large JavaScript file. I now get "Unexpected end of input." Somewhere in those hundred of functions, one has lost (or gained) a bracket. What's the quickest way to find it? A: A good trick when missing a brace in eclipse is to go to the final brace in the source module and double-click it. That will highlight all the way back to what it THINKS is the matching open brace. Where it highlights back to is invariably the START of where the problem is, so skip that open brace and go to the next one and start double-clicking open braces and you will usually find where the brace is missing pretty quickly. I learnt that the hard way with a source code file of 20,000+ lines of code and getting hundreds of errors without the slightest indication as where the real problem was as the errors started appearing thousands of lines earlier in the code. A: Re-format the file using something that indents well. Look for something that's too far to the left. A: Try the Esprima parser. It comes with a syntax validator that will give you the line number of each error. npm install --global esprima esvalidate path/to/file.js outputs path/to/file.js:915: Unexpected token ) A: Minimize the nesting of functions. It reduces the quality of the code (maintainability-wise).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Changing Properties of a Slowly Changing Dimension Transformation in SSIS I have a problem with changing the properties of the SCD transformation in SSIS 2005. I can define all the properies and mappings the first time i edit the transformation and its working. But when i open the property editor of the component again, it has forgotten all the entered configuration like the mappings of the table columns and the settings of the columns. I even have searched in the generated XML for the settings but have not found anything meaningful. SSIS has definitly stored the components configuration somewhere because its working fine until i open the editor. I have searched the web but with no luck yet. Does anybody know where the settings are stored respectively how to force the components editor/assistant to not forget all my settings? A: The SCD WIZARD in SSIS is not an editor, it is a wizard. That is one of its biggest drawbacks. It doesn't remember any configuration. Every time you use the wizard, it starts again from the beginning and recreates all of the object it uses to do the slowly changing dimension. If you want an SCD component that will remember the setting between uses, you should probably use the excellent tool by Todd McDermid: DimensionMerge SCD Component A: I have had this problem too for almost 2 weeks crawling through the net to find the solution.I finally found a way out. With the xml definition of the SCD component, specifically : <dwd:DtsComponentDesignTimeProperty> <dwd:key xsi:type="xsd:string">50 SCDMetadata</dwd:key> <dwd:value xsi:type="xsd:string">&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;SCDWizardMetadata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;ConnectionID&gt;{8F2DCF5E-0FC4-4CF4-AF30-87548F5C74A3}&lt;/ConnectionID&gt; It is IMPORTANT that the the content of the tag dwd:value is on same line as the tag itself. If there is a line break, the SCD wizard will not load your settings. I know, its wired. Also the values with the dqd:key should be seperated by a tab. The most important is that the content of the dwd:value start on same line. Hope this helps someone out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reflecting Across Serialized Object To Set PropertyChanged Event I have a object that is created through deserialization of some XML. I used Visual Studio's tool to generate the XSD from the vendor mockup XML. Then using the XSD tool I got classes from them. I set the XSD tool so that it would make the generated classes be INotifyPropertyChanged. Now I'm trying to display this object in a "tab" on my WPF application. I want a "dirty" indicator whenever someone makes a change. The issue is that this object, being generated classes from generated XSD is not the prettiest structure. The display for this object is does not mimic its data structure. I thought of creating display objects (not using MMVM ATM) and using those to bind my changes to and then persist those changes to the object as a data object. I would essentially just throw out my current display to do this since I'm now just adding a check for if there were edits. My thought is to reflect across the object and set the PropertyChanged event for every property I come across (walking through the graph of objects and properties). My reflection fu is failing me and I'm also probably making some short-sighted mistakes. Here is the code I've written thus far: void SetupPropertyChanged(INotifyPropertyChanged component) { component.PropertyChanged += CAMConfig_PropertyChanged; Type componentType = component.GetType(); foreach (PropertyInfo info in componentType.GetProperties()) { Type[] types = info.PropertyType.FindInterfaces((a, b) => { return a.ToString() == b.ToString(); }, typeof(INotifyPropertyChanged)); bool isINotify = types.Contains(typeof(INotifyPropertyChanged)); if (isINotify) this.SetupPropertyChanged((INotifyPropertyChanged)info.GetValue(component, new object[] { })); } } I think I'm running into Observable collection property type issues as its throwing an exception when I'm traversing my object. It also just hit me that I don't know if this object structure would have circular references. Can someone help me work out this code so that I can traverse the object graph. Right now I'm not too concerned about the possibility of circular references, but if a solution presents itself that prevents that situation it would be very, very helpful! Based on Karel's answer I've created this "helper" class: public static class NotifyPropertyChangedHelper { public delegate void ChangeOccuredHandler(object sender); public static void SetupPropertyChanged(INotifyPropertyChanged component, ChangeOccuredHandler changedHandler) { SetupPropertyChanged(new List<object>(), component, changedHandler); } static void SetupPropertyChanged(IList<object> closed, INotifyPropertyChanged component, ChangeOccuredHandler changedHandler) { if (closed.Contains(component)) return; // event was already registered closed.Add(component); //adds the property that is to be processed //sets the property changed event if the property isn't a collection if (!(component is INotifyCollectionChanged)) component.PropertyChanged += (sender, e) => { changedHandler(sender); }; /* * If the component is an enumerable there are two steps. First check to see if it supports the INotifyCollectionChanged event. * If it supports it add and handler on to this object to support notification. Next iterate through the collection of objects * to add hook up their PropertyChangedEvent. * * If the component isn't a collection then iterate through its properties and attach the changed handler to the properties. */ if (component is IEnumerable<object>) { if (component is INotifyCollectionChanged) { //((INotifyCollectionChanged)component).CollectionChanged += collectionHandler; ((INotifyCollectionChanged)component).CollectionChanged += (sender, e) => { changedHandler(sender); }; } foreach (object obj in component as IEnumerable<object>) { if (obj is INotifyPropertyChanged) SetupPropertyChanged(closed, (INotifyPropertyChanged)obj, changedHandler); } } else { foreach (PropertyInfo info in component.GetType().GetProperties()) { var propertyValue = info.GetValue(component, new object[] { }); var inpc = propertyValue as INotifyPropertyChanged; if (inpc == null) continue; SetupPropertyChanged(closed, inpc, changedHandler); } } } } A: Keep a list of properties (components) for which you've already registered the event and make your function recursive. And you can cast component to INotifyPropertyChanged directly. void SetupPropertyChanged(IList<object> closed, INotifyPropertyChanged component) { if(closed.Contains(component)) return; // event was already registered closed.Add(component); component.PropertyChanged += CAMConfig_PropertyChanged; foreach (PropertyInfo info in componentType.GetProperties()) { var propertyValue = info.GetValue(component, new object[] { }); var inpc = propertyValue as INotifyPropertyChanged; if(inpc == null) continue; this.SetupPropertyChanged(closed, inpc); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get last sent HTTP request android I am trying to send a GET request to the web server from the android device, the server is having digest authentication enabled, I am able to authenticate using following sort of code, HttpHost host = new HttpHost(urlObj.getHost(), -1, null); CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(scope, creds); HttpContext credContext = new BasicHttpContext(); credContext.setAttribute(ClientContext.CREDS_PROVIDER, cp); Now my problem is every time when I call httpClient.execute() function it first send request without authentication header and then second time with proper headers. So is there any way I can instruct HttpClient to send authentication details by default? One way is to store the last sent request but, I am also not able to get the last sent request. Any suggestion on this? Thanks in advance. A: You may use HttpURLConnection to save all the params you need. I use it and display my source code here. url_connection is defined like that private HttpURLConnection url_connection; // WebService Connection url_connection= (HttpURLConnection) new URL(your_url_server).openConnection(); url_connection.setRequestMethod("POST"); url_connection.setDoInput(true); url_connection.setDoOutput(true); ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7597764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extending parent routing when extending bundles In Symfony2 (2.0.3) I have a BetaBundle that is set as the parent of a AlphaBundle. Is it possible to override some routes while still keeping the parent originals routing definition ? I have tried importing the parent routing.yml inside the child routing.yml file but it naturally result in a circular reference exception. Is there any standard way to achieve this using yml and files named routing.yml in the same relative path ? A: When you override your AlphaBundle anything that uses the @AlphaBundle shortcut will look in @BetaBundle first. The only way I've found to solve this kind of problem is to have the extending bundle (BetaBundle) quit using the @ shortcut, and include your AlphaBundle's route using it's path. As an alternative you could try renaming your BetaBundle's route file so that it doesn't override AlphaBundle's file, and then configure your app/config/routing.yml to include your BetaBundle's renamed routing file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cakephp model alias works, but view doesn't show I read your answer about cakephp model alias and I did on my model what you wrote, I debuged my view and it list what I want, but it doesn't show the list on the respective field, do you have any idea what is wrong? My model: 'ResponsavelManutencao' => array( 'className' => 'Operador', 'foreignKey' => 'responsavel_manutencao_id', 'conditions' => '', 'fields' => '', 'order' => '') My controller: function add( $responsavelManutencao = $this->Dentista->ResponsavelManutencao->find('list'); $this->set(compact('responsavelManutencao'));) My view: echo $this->Form->input('responsavel_relacionamento_id', array( 'class' => 'field text small', 'empty' => '', 'after' => 'Funcionario responsavel por manter o contato comercial.')); debug($responsavelRelacionamento); A: I guess there is something wrong with the CakePHP singular/plural rules for your language. I think you should name your view variable "responsavelRelacionamentos" for it to work. However, the safest way to accomplish your goal without inflection magic would be: echo $this->Form->input('responsavel_relacionamento_id', array( 'options' => $responsavelRelacionamento, 'class' => 'field text small', 'empty' => '', 'after' => 'Funcionario responsavel por manter o contato comercial.' ));
{ "language": "en", "url": "https://stackoverflow.com/questions/7597770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why google analytics need to be load dynamically? Why i need to use: <script type="text/javascript" charset="utf-8"> //<![CDATA[ var _gaq = _gaq || []; _gaq.push( ['_setAccount', 'xxxxxxxxxx'] ); _gaq.push( ['_trackPageview'] ); _gaq.push( ['_trackPageLoadTime'] ); (function() { var ga = document.createElement( 'script' ); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName( 'script' )[0]; s.parentNode.insertBefore( ga, s ); })(); //]]> </script> instead of <script type="text/javascript" src="http://www.google-analytics.com/ga.js"></script> <script type="text/javascript" charset="utf-8"> //<![CDATA[ var _gaq = _gaq || []; _gaq.push( ['_setAccount', 'xxxxxxxxxx'] ); _gaq.push( ['_trackPageview'] ); _gaq.push( ['_trackPageLoadTime'] ); //]]> </script> A: So it can load asynchronous with the rest of the page. Previously, the GA code would block other content from loading as when JavaScript is downloaded and parsed it prevents the rest of the page from loading. When it is asynchronous, it doesn't do this. That results is faster page loading speeds and more accurate tracking.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Console.WriteLine different ways of writing Confusion in a really a basic question: I have seen in many books, they use use Console.WriteLine as: int i = 12; Console.WriteLine("MyVariable value is {0}", i); Instead of int i = 12; Console.WriteLine("MyVariable value is" + i); Is there any difference between them? A: in your example, practically not. However, the first case can easily be extended to do Console.WriteLine("MyVariable value is {0} and myothervar is {1}", i, j); which could be a little cumbersom with the second approach. A: Check out the answer in this thread. In a simple case it doesn't really matter, but there are performance considerations if you are doing this in a large loop or something. A: Maybe this will help someone in the future. There is now a 3rd method(Interpolation) and it is the cleanest of them all! They are all just different ways of writing the same thing. int i = 12; // Interpolation Method- Req. C# 6 or later [Cleanest] Console.WriteLine($"MyVariable value is {i}"); // Concatenation Method (from VB days) Console.WriteLine("MyVariable value is " + i); // Format Method (from C days) Console.WriteLine("MyVariable value is {0}", i); A: I believe you see the string concatenation in books for beginner because it is simple. String formatting needs to be explained before it can be used in such simple example. String concatenation is much simple and may already have been taught at that point in the book (even if not, it is simple enough to learn by example). I can see how C programmers might be confused by the format syntax when encountering it for the first time. When attempting to extend it to two variables they might think it needs to be written as so: int numA = 3; int numB = 5; Console.WriteLine("numA is {0} and numB is {0}", numA, numB); Thinking it would be similar to C's printf where {0} is equivilant to %d: printf("numA is %d and numB is %d", numA, numB); They would of course be surprised to have varA be printed twice. Or they may be frustrated of not knowing the equivalent of %s when trying to Console.WriteLine a string. String concatenation, on the other hand, has fewer pitfalls and can be more easily extended by beginners. Of course it is more cluttered but also more powerful, power that may be confusing in a book introducing someone to C# since string formatting syntax can grow quite complex: Console.WriteLine("numA is {0,17:$00.00####}", numA); The above example also illustrates the difference between concatenation and string formatting. They are different, but for simple usages like the one you made, it makes little difference. A: Your specific case will not, for more information http://msdn.microsoft.com/en-us/library/ms228362.aspx Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7597772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Does reactive extensions support rolling buffers? I'm using reactive extensions to collate data into buffers of 100ms: this.subscription = this.dataService .Where(x => !string.Equals("FOO", x.Key.Source)) .Buffer(TimeSpan.FromMilliseconds(100)) .ObserveOn(this.dispatcherService) .Where(x => x.Count != 0) .Subscribe(this.OnBufferReceived); This works fine. However, I want slightly different behavior than that provided by the Buffer operation. Essentially, I want to reset the timer if another data item is received. Only when no data has been received for the entire 100ms do I want to handle it. This opens up the possibility of never handling the data, so I should also be able to specify a maximum count. I would imagine something along the lines of: .SlidingBuffer(TimeSpan.FromMilliseconds(100), 10000) I've had a look around and haven't been able to find anything like this in Rx? Can anyone confirm/deny this? A: With Rx Extensions 2.0, your can answer both requirements with a new Buffer overload accepting a timeout and a size: this.subscription = this.dataService .Where(x => !string.Equals("FOO", x.Key.Source)) .Buffer(TimeSpan.FromMilliseconds(100), 1) .ObserveOn(this.dispatcherService) .Where(x => x.Count != 0) .Subscribe(this.OnBufferReceived); See https://msdn.microsoft.com/en-us/library/hh229200(v=vs.103).aspx for the documentation. A: This is possible by combining the built-in Window and Throttle methods of Observable. First, let's solve the simpler problem where we ignore the maximum count condition: public static IObservable<IList<T>> BufferUntilInactive<T>(this IObservable<T> stream, TimeSpan delay) { var closes = stream.Throttle(delay); return stream.Window(() => closes).SelectMany(window => window.ToList()); } The powerful Window method did the heavy lifting. Now it's easy enough to see how to add a maximum count: public static IObservable<IList<T>> BufferUntilInactive<T>(this IObservable<T> stream, TimeSpan delay, Int32? max=null) { var closes = stream.Throttle(delay); if (max != null) { var overflows = stream.Where((x,index) => index+1>=max); closes = closes.Merge(overflows); } return stream.Window(() => closes).SelectMany(window => window.ToList()); } I'll write a post explaining this on my blog. https://gist.github.com/2244036 Documentation for the Window method: * *http://leecampbell.blogspot.co.uk/2011/03/rx-part-9join-window-buffer-and-group.html *http://enumeratethis.com/2011/07/26/financial-charts-reactive-extensions/ A: I wrote an extension to do most of what you're after - BufferWithInactivity. Here it is: public static IObservable<IEnumerable<T>> BufferWithInactivity<T>( this IObservable<T> source, TimeSpan inactivity, int maximumBufferSize) { return Observable.Create<IEnumerable<T>>(o => { var gate = new object(); var buffer = new List<T>(); var mutable = new SerialDisposable(); var subscription = (IDisposable)null; var scheduler = Scheduler.ThreadPool; Action dump = () => { var bts = buffer.ToArray(); buffer = new List<T>(); if (o != null) { o.OnNext(bts); } }; Action dispose = () => { if (subscription != null) { subscription.Dispose(); } mutable.Dispose(); }; Action<Action<IObserver<IEnumerable<T>>>> onErrorOrCompleted = onAction => { lock (gate) { dispose(); dump(); if (o != null) { onAction(o); } } }; Action<Exception> onError = ex => onErrorOrCompleted(x => x.OnError(ex)); Action onCompleted = () => onErrorOrCompleted(x => x.OnCompleted()); Action<T> onNext = t => { lock (gate) { buffer.Add(t); if (buffer.Count == maximumBufferSize) { dump(); mutable.Disposable = Disposable.Empty; } else { mutable.Disposable = scheduler.Schedule(inactivity, () => { lock (gate) { dump(); } }); } } }; subscription = source .ObserveOn(scheduler) .Subscribe(onNext, onError, onCompleted); return () => { lock (gate) { o = null; dispose(); } }; }); } A: I guess this can be implemented on top of Buffer method as shown below: public static IObservable<IList<T>> SlidingBuffer<T>(this IObservable<T> obs, TimeSpan span, int max) { return Observable.CreateWithDisposable<IList<T>>(cl => { var acc = new List<T>(); return obs.Buffer(span) .Subscribe(next => { if (next.Count == 0) //no activity in time span { cl.OnNext(acc); acc.Clear(); } else { acc.AddRange(next); if (acc.Count >= max) //max items collected { cl.OnNext(acc); acc.Clear(); } } }, err => cl.OnError(err), () => { cl.OnNext(acc); cl.OnCompleted(); }); }); } NOTE: I haven't tested it, but I hope it gives you the idea. A: Colonel Panic's solution is almost perfect. The only thing that is missing is a Publish component, in order to make the solution work with cold sequences too. /// <summary> /// Projects each element of an observable sequence into a buffer that's sent out /// when either a given inactivity timespan has elapsed, or it's full, /// using the specified scheduler to run timers. /// </summary> public static IObservable<IList<T>> BufferUntilInactive<T>( this IObservable<T> source, TimeSpan dueTime, int maxCount, IScheduler scheduler = default) { if (maxCount < 1) throw new ArgumentOutOfRangeException(nameof(maxCount)); scheduler ??= Scheduler.Default; return source.Publish(published => { var combinedBoundaries = Observable.Merge ( published.Throttle(dueTime, scheduler), published.Skip(maxCount - 1) ); return published .Window(() => combinedBoundaries) .SelectMany(window => window.ToList()); }); } Beyond adding the Publish, I've also replaced the original .Where((_, index) => index + 1 >= maxCount) with the equivalent but shorter .Skip(maxCount - 1). For completeness there is also an IScheduler parameter, which configures the scheduler where the timer is run.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Kentico CMSListMenu not displaying enough levels of the tree? I have a kentico CMSListMenu which contains 4 levels at it deepest, i want to display the menu as a nested list down the left hand side of my content, this works fine for 3 levels but i cant get the 4th level to display. I have this working on another site using the exact same code so i must be missing something, these are the menu expressions i have tried using: <cc1:CMSListMenu ID="CMSTreeMenu1" runat="server" Path="/{0}/{1}/{2}/%" DisplayHighlightedItemAsLink="True" DisplayOnlySelectedPath="true" Indentation="0" MaxRelativeLevel="5" /></cc1:cmslistmenu> <cc1:CMSListMenu ID="CMSTreeMenu1" runat="server" Path="/Products---Solutions/%" DisplayHighlightedItemAsLink="True" DisplayOnlySelectedPath="true" Indentation="0" MaxRelativeLevel="5" /></cc1:cmslistmenu> do i need to set this somewhere else? perhaps somewhere inside of kentico to output so many levels down? Any help would be greatly appreciated, this has been causing me problems for days A: I believe that the CMS List Menu only displays cms.Page (Menu Item) documents by default. If you're trying to display other types of documents, make sure you set that in the menu properties. A: Try setting DisplayOnlySelectedPath="false" to see if it displays everything as you expect it to under the menu.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL Server - Getting job history details We use the below mentioned Stored Procedure to get the history of our JOBS SELECT --sysjobhistory.server, sysjobs.name AS job_name, CASE sysjobhistory.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' ELSE '???' END AS run_status, CAST( Isnull(Substring(CONVERT(VARCHAR(8), run_date), 1, 4) + '-' + Substring(CONVERT(VARCHAR (8), run_date), 5, 2) + '-' + Substring(CONVERT(VARCHAR( 8), run_date), 7, 2), '') AS DATETIME) AS [Run DATE], Isnull(Substring(CONVERT(VARCHAR(7), run_time+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_time+1000000), 4, 2 ) + ':' + Substring(CONVERT(VARCHAR(7), run_time+1000000), 6, 2), '') AS [Run TIME], Isnull(Substring(CONVERT(VARCHAR(7), run_duration+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_duration+1000000), 4, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_duration+1000000), 6, 2), '' ) AS [Duration], Isnull(Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 2, 2) + ':' + Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 4, 2 ) + ':' + Substring(CONVERT(VARCHAR(7), run_time+run_duration+1000000), 6, 2), '') AS [Total TIME], sysjobhistory.step_id, sysjobhistory.step_name, sysjobhistory.MESSAGE AS Msg FROM msdb.dbo.sysjobhistory INNER JOIN msdb.dbo.sysjobs ON msdb.dbo.sysjobhistory.job_id = msdb.dbo.sysjobs.job_id WHERE sysjobhistory.run_date <= Datepart(yyyy, @dateparam) * 10000 + Datepart(mm, @dateparam) * 100 + Datepart ( dd, @dateparam) AND sysjobs.name = @JobName --remove this line if you want to show all jobs for the specified day But can anyone advise how to get error details if the job has failed for example (we are looking for this information which we can view thru log viewer) Date 29/09/2011 07:57:04 Log Job History Step ID 5 Server Job Name Step Name extract Duration 00:02:13 Sql Severity 0 Sql Message ID 0 Operator Emailed Operator Net sent Operator Paged Retries Attempted 0 Message (Need this error message also to come) A: you can use the following script to grab the details of each step..first you have to get the failed job's job_id and pass to msdb.dbo.sp_help_jobhistory stored procedure. I got this script by running trace while doing the activity on job activity monitor. I hope this helps you on what you are looking for To find STEP level messages, look at the message column where step_id <> 0 These records actually provide useful error messages. declare @tmp_sp_help_jobhistory table ( instance_id int null, job_id uniqueidentifier null, job_name sysname null, step_id int null, step_name sysname null, sql_message_id int null, sql_severity int null, message nvarchar(4000) null, run_status int null, run_date int null, run_time int null, run_duration int null, operator_emailed sysname null, operator_netsent sysname null, operator_paged sysname null, retries_attempted int null, server sysname null ) insert into @tmp_sp_help_jobhistory exec msdb.dbo.sp_help_jobhistory @job_id = '329cac18-328d-499b-9216-593244d164b0', --change this job_id according to your requirement @mode='FULL' SELECT tshj.instance_id AS [InstanceID], tshj.sql_message_id AS [SqlMessageID], tshj.message AS [Message], tshj.step_id AS [StepID], tshj.step_name AS [StepName], tshj.sql_severity AS [SqlSeverity], tshj.job_id AS [JobID], tshj.job_name AS [JobName], tshj.run_status AS [RunStatus], CASE tshj.run_date WHEN 0 THEN NULL ELSE convert(datetime, stuff(stuff(cast(tshj.run_date as nchar(8)), 7, 0, '-'), 5, 0, '-') + N' ' + stuff(stuff(substring(cast(1000000 + tshj.run_time as nchar(7)), 2, 6), 5, 0, ':'), 3, 0, ':'), 120) END AS [RunDate], tshj.run_duration AS [RunDuration], tshj.operator_emailed AS [OperatorEmailed], tshj.operator_netsent AS [OperatorNetsent], tshj.operator_paged AS [OperatorPaged], tshj.retries_attempted AS [RetriesAttempted], tshj.server AS [Server], getdate() as [CurrentDate] FROM @tmp_sp_help_jobhistory as tshj ORDER BY [InstanceID] ASC
{ "language": "en", "url": "https://stackoverflow.com/questions/7597775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Adding environment variables using java program and able to see when I open environment tab from My Computer I want to write java program which adds environment variables and when I open environment tab from MyComputer,then I should be able to see that... This is what I have tried,but it gives java.lang.unsupportedexception Map env = System.getenv(); env.put("abc", "pqr"); And One more try is below,it is not giving any error...But I can not see any value added when I open environment variables tablenter code here from My Computer.But When i sysout "env" variable it gives me all paths including myone also...But I need same thing to be shwon in environment variables tab... ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe","/c","set"); Map env = processBuilder.environment(); env.put("abc", "pqr"); Please help me guys...Thanks in Advance... A: There are two ways. The first one is to call the Windows API to change/set the environment variable. You must look for the right Windows API function and call it from Java. However calling any Windows API from Java is a topic on its own. The second way is to call the setx.exe program with the correct arguments to set environment variables. Check the manual of the setx.exe program how to use it (and when it is installed) to set your environment variables. In both ways you obviously restrict your Java program to run on Windows systems only.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load ajax data NOT in a div or other element first of all, sorry for my bad english, I speak spanish. Well, I need some help in this case: I made a microsoft excel POI report using java, this report is in a servlet that I call when do a clic in a href, por example: <a href="ServeletReport">Report</a> Until here, all ok, but I need to call this report using an event (it could be .load()) from jQuery, but this event only works assigning the data result to a div or other element. I not need assign the result to any element because my report is generated and open through in excel, if I assign it to a div, in this div appears rare simbols. I need too add a loading imagen until my report is ready and opened. I have a bad code, please I need some help. $("#mylink").click(function(){ $("#contenidoo").empty().html('<img src="images/loading-icon.gif"/>'); $("#result").load("ServletReport"); }); I not need to put the result in a div $("#result"), I dont need to put the result in any place, I want to do clic and wait until my report is generated but viewing the loading image. A: use the jquery .ajax function instead of .load: http://api.jquery.com/jQuery.ajax/ A: Use jQuery ajax() or get() http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.get/ A: You can use the .get method to fire an HTTP GET request to the server, and use a callback function to do something once it has completed: $("#mylink").click(function() { $("#contenidoo").empty().html('<img src="images/loading-icon.gif"/>'); $.get("ServletReport", function() { $("#contenidoo").empty(); //Remove the image you appended above }); }); A: I found this very useful: $("#mylink").click(function() { $("#contenidoo").empty().html('<img src="images/loading-icon.gif"/>'); $.get("ServletReport", function() { $("#contenidoo").empty(); //Remove the image you appended above }); }); But I dont want to put the result in any place, and using the method above the reslult of my servlet (my excel doc) is not opened. I think its lacking some little thing. I hope your help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create Polygon on Google Map By dragging mouse I am first time using Google Map.. I have to add the Google Map in my web application with following functionality. * *User can create polygon on the Map by using Mouse. *Then the values of polygon's Lat/Lon will be saved in the Database. *Like wise he can create multiple polygons but with the restriction that any polygons should not be overlapped. Please help me on it.. Thaks in advance A: As far as rendering the polys I would consider using a open source tool kit that already does that . Open Layers is a nice javascript library that works with Google Maps enables you to draw overlays and collect lat lon information, etc. As far as the database entries and overlapping issues see the comments on your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Report Viewer using multiple reports Within vb.net we've got a report that works great it has it's header/footer details then then a table in the middle which repeats data and all of that is fine. But what the client wants now is for another button named 'Print Individual' and this will print the same report but instead of the repeated data within the table for each of those rows to be a single row on a page with the same header/footer. So for example on the first report if there is one page with 5 rows of details the 'Print Individual' report will print the same but have 5 pages and 1 row per report. If that makes sense :-) Obviously if I can do it where we use the same report instead of maintaing two reports would be good, as the report has a lot of information on it. Any ideas? A: I ended up creating a new report and using the list box tool.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing an outer array in php I have some functions that deal with data provided in array format. These functions all do the same job, so I would like to merge them into a single function. The problem is, each of them receives arrays with different depths: one-, two- and three-dimensional arrays are used and, in some future implementations, even four-dimensional arrays may be used. In any case, the significant and necessary data are always in the two innermost arrays, so I need to get rid of the outer arrays until I have only the innermost two-levels. My doubt is not simply how to do it, but how to do it elegantly and efficiently, as I find my current method rather clumsy. Current method: function add() { $data = func_get_args(); if(count($data)>0) { if(is_array($data[0])) { if(is_array($data[0][0])) { foreach($data[0] as $row) { $this->items[] = $row; } } else { $this->items[] = $data[0]; } } else { $this->items[] = $data; } } } Some use examples: $list->add('one', 'two', 'three', 'four', 'five'); $list->add($data_from_DB_in_array_format); $list->add( array( array('one', 'two', 'three', 'four', 'five'), array('six', 'seven', 'eight', 'nine', 'ten') ) ); $list->add( array( array( array('one', 'two', 'three', 'four', 'five'), array('six', 'seven', 'eight', 'nine', 'ten') ) ) ); As the data is recovered via func_get_args(), everything is put inside an extra array. The result must be something like this: array( array('one', 'two', 'three', 'four', 'five'), array('six', 'seven', 'eight', 'nine', 'ten') ); A: There is only one way you can achieve this, and it is with recursiveness and a little array function magic. It is probably not your exact solution but should get you started, if you need more help buzz me: <?php $data = array( 'test1' => array( 'test2' => array( 'test3' => array( 'test4' => array( 1, 2, 3 ), 'test5' => array( 4, 5, 6 ), 'test6' => array( 7, 8, 9 ), ) ) ) ); function returnLast2Levels($item){ if(is_array($item) && is_array(reset($item)) && is_array(reset(reset($item)))){ //This $item has more than 2 levels, delve deeper return returnLast2Levels(reset($item)); }elseif(is_array($item) && is_array(reset($item)) && !is_array(reset(reset($item)))){ //This $item has 2 levels deep of array return $item; } } var_dump(returnLast2Levels($data));
{ "language": "en", "url": "https://stackoverflow.com/questions/7597785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the newest value from a column with conditions I have a table in Excel which has the columns: * *Date *Person Name *Amount (£) The table is used to record when people pay me money. Typically, I can get more than one person paying me on the same day. Also, the same person will pay me on many days over the course of time. Records are added to the bottom of the table so the ordering will be on date but no further ordering on name or amount. Using formulas, is there a way I can retrieve the most recent amount for a specific person? If this is too complicated or not possible then I can settle for the following work around: Add a 4th column to the table called "Last". This will display TRUE if it is the last entry for a specific person, FALSE if it is not. A: It felt like there should be a fairly straight-forward answer to this but I found it quite a head scratcher so was interested to see an answer. Having done some googling I came across a solution posted on a dedicated excel site (view here). [NB - look under the header 'Arbitrary Lookups'] Applying it to your example, suppose your data is in A1:C10 and in cell D2 you want to type a name and return the most recent payment in cell D3: 1 Date Name Amt EnterName 2 20 Jul Bob 50 <enter name here> 3 13 Sep Susan 20 = enter formula here (see below) 4 06 Jan Xavier 100 In cell D3 enter the following as an array formula (i.e. type in formula and then press CTRL + SHIFT + ENTER =INDEX($B$2:$C$10,SMALL(IF(OFFSET($B$2:$C$10,0,0,ROWS($B$2:$C$10),1)=$D$2, ROW(OFFSET($B$2:$C$10,0,0,ROWS($B$2:$C$10),1))-ROW(OFFSET($B$2:$C$10,0,0,1,1) )+1, ROW(OFFSET($B$2:$C$10,ROWS($B$2:$C$10)-1,0,1,1))+1),COUNTIF(OFFSET($B$2:$C$10,0,0,ROWS($B$2:$C$10),1),$D$2)),2) It would recommend checking out the link I provided if you want more detail. For clarity, I have merely adapted the formula (changed cell references) from the link provided. A: Here's one way to do it based on an answer I gave in a previous SO post. =INDEX($C$1:$C$19,MATCH(MAX(IF($B$1:$B$19="PersonNameHere",$A$1:$A$19,0)),IF($B$1:$B$19="PersonNameHere",$A$1:$A$19,""))) Where A is the Date column, B is the Person Name column, and C is the Amount column. You must enter this as an array formula by pressing Ctrl+Shift+Enter. A: I can't see right here an easy way to do it in only one formula. If you have your data from A2 to C11. You can add this formula on the 4th column (let say in cell D2): {=MAX(IF($B$2:$B$11=B2,$A$2:$A$11,0))} This is an array formula you have to validate with Ctrl-Shift-Enter This will tell you what is the last date for the current person. And then find the last amount with another column (let say in cell E2) and use this formula: =INDEX($C$2:$C$11,MATCH(D2,$A$2:$A$11,0)) [EDIT] I've just tried to combine the formulas into one and that simply works: {=INDEX($C$2:$C$11,MATCH(MAX(IF($B$2:$B$11=B2,$A$2:$A$11,0)),$A$2:$A$11,0))} and this is still an array formula. Alas, @Excellll was smarter (and faster) and gave the solution at first shot
{ "language": "en", "url": "https://stackoverflow.com/questions/7597788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Form_for generates resource path ending with '.1' I have a resource called :school and when I call form_for(@school) it generates the form action: /school.1 I'm new to all this so any clues as to why it's doing that would be much appreciated. Sleep deprived and heading for a deadline in 3 hours, arrrggg! Thanks :) routes.rb: resource:school school.rb: <%= form_for(@school, :url => school_path) do |f| %> <% if @school.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@school.errors.count, "error") %> prohibited this school from being saved:</h2> <ul> <% @school.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :name %><br /> <%= f.text_field :name %> </div> <div class="field"> <%= f.label :address1 %><br /> <%= f.text_field :address1 %> </div> <div class="field"> <%= f.label :address2 %><br /> <%= f.text_field :address2 %> </div> <div class="field"> <%= f.label :address3 %><br /> <%= f.text_field :address3 %> </div> <div class="field"> <%= f.label :town %><br /> <%= f.text_field :town %> </div> <div class="field"> <%= f.label :county %><br /> <%= f.text_field :county %> </div> <div class="field"> <%= f.label :postcode %><br /> <%= f.text_field :postcode %> </div> <div class="field"> <%= f.label :local_authority_id %><br /> <%= f.collection_select :local_authority_id, LocalAuthority.all, :id, :name %> </div> <% if current_user.person.primary_user? %> <div class="field"> <%= f.label 'Are you happy for us to send you regular updates about VRH?' %><br /> <%= f.check_box :allow_contact %> </div> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %> A: by using the singular resource method you are telling rails that only one of these objects exist, in your routes file I think you need to change your resource :school to... resources :schools If however you do want only one school then I think you will need to add the url option to form_for... <% form_for(@school, :url => school_path) %> Proposed solution for follow up questions... I think what you need will be something like this... # routes.rb resources :users do resources :schools end resources :schools # app/controllers/schools_controller.rb class SchoolsController < ApplicationController def new @user = User.find(params[:user_id]) @school = @user.build_school end def create @user = User.find(params[:user_id]) @school = @user.build_school(params[:school]) if @school.save # success... else # fail... end end def edit @school = School.find(params[:id]) end def update @school = School.find(params[:id]) if @school.update_attributes(params[:school]) # success else # fail end end end # app/views/schools/new.html.erb <%= form_for([@user, @school]) do |f| %> <!-- fields go here --> <% end %> # app/views/schools/edit.html.erb <%= form_for([@user, @school]) do |f| %> <!-- fields go here --> <% end %> A: I just had a similar issue with a singular profile resource in my routes.rb file: resource :profile It took me a few hours to find a solution so I decided to share it to save someone else the trouble. I had to remove the "(.:format)" part of the route (shown when running "rake routes"), by specifying a specific format: constraints :format => "html" do resource :profile end I also had to add the :url option to form_for tags: <% form_for(@profile, :url => profile_path) %> and that worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSScrollView Background Texture Is there any way that one can use the NSScrollView background texture that is used in Safari from within other applications? I know how to get the NSScrollView to display a pattern, I just need to know if there is a named image for the texture and what the name is? Or, if there isn't a named image, where I can find something similar? A: This is a bit off-topic, I think, since it's not "how to use a background texture in NSScrollView" but "where can I find a similar graphic"? But you'd only know that if you knew it wasn't a system-supplied texture. :-) This is a custom graphic and is not available via the system. You'll need to create your own, license someone else's or find one that is free for commercial use. Search the web for "linen background" or "linen texture" etc. If you have Photoshop, there are tutorials out there for creating your own Mac-like linen pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show full stack trace on eclipse? I'm using Eclipse to debug a Java application. Somewhere in the code I get an exception and the stack trace: Caused by: java.io.EOFException: The connection has been reset while reading the header at com.gemstone.gemfire.internal.cache.tier.sockets.Message.fetchHeader(Message.java:583) at com.gemstone.gemfire.internal.cache.tier.sockets.Message.readHeaderAndPayload(Message.java:599) at com.gemstone.gemfire.internal.cache.tier.sockets.Message.read(Message.java:542) at com.gemstone.gemfire.internal.cache.tier.sockets.Message.recv(Message.java:1029) at com.gemstone.gemfire.cache.client.internal.AbstractOp.attemptReadResponse(AbstractOp.java:158) at com.gemstone.gemfire.cache.client.internal.AbstractOp.attempt(AbstractOp.java:363) at com.gemstone.gemfire.cache.client.internal.ConnectionImpl.execute(ConnectionImpl.java:229) at com.gemstone.gemfire.cache.client.internal.pooling.PooledConnection.execute(PooledConnection.java:321) at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.executeWithPossibleReAuthentication(OpExecutorImpl.java:646) at com.gemstone.gemfire.cache.client.internal.OpExecutorImpl.execute(OpExecutorImpl.java:108) ... 11 more How do I get the whole stack instead of the ... 11 more? A: the answers above are not accurate, every time the stack show the words "caused by" it means that the exception went through one or multiple methods until it was caught, and then thrown again. This could happen many many many times, the stack trace is not a loop, it is a single direction, so no, the stuff at the top does not relate to the stuff at the bottom, the most important part IS at the bottom, that is the root of the exception, so if you would have: Exception in class main: blah blah blah ...lines of code... caused by FileNotFoundException ...lines of code... caused by: MalformedURLException ...lines of code... caused by: NullPointerException then you would not want to focus so much on the FileNotFoundException, but you would want to focus more on the NullPointerException. Like say you had a properties file with a file name in it. If accidentally used mykey, to find the property "myKey", then the propertiesResource would return a null, that would then get thrown all the way through all the lines of code (hopefully) to your application where the last catch block is. . . wich, at this piont, it would be "wrapped" not as a nullException, but as a FileNotFoundException. . . A: We might be diverging from the actual problem he's facing. I was having similar problem and it turns out I had my Limit console out put box check marked. After I removed it I was able to see the full stack trace. Steps: Right click on console || ctrl + click if mac go to preferences and follow the above instructions A: You have the entire stack. This is only part of a stack trace. Directly before this was another piece. Look at the bottom lines of this one, and the top lines of the previous one. You'll see them match up. The stack trace began with a section that doesn't begin with "Caused by". The "Caused by" exception is hiding parts of the stack trace that are verbatim copies of stack trace entries in its parent. In other words, Java doesn't show the entire stack up to main() for every cause - it just shows what you haven't seen already. See the Throwable.printStackTrace() documentation. The "Caused by" is filled when you provide a cause when creating a Throwable. Look at the constructors for it. This is done when a piece of code catches a low-level exception and then wants to rethrow it as a different exception class. A: I think it means that the Exception was caught and packaged into another 11 times before printStackTrace was called. Try and figure out the output of the following program for better understanding: public class PrintStackTrace { public static void main(String[] args) { try { level1(); } catch (Exception e) { e.printStackTrace(); } try { level2(); } catch (Exception e) { e.printStackTrace(); } } static void level2() throws Exception { try { level1(); } catch (Exception e) { throw new Exception(e); } } static void level1() throws Exception { try { throwingMethod(); } catch (Exception e) { throw new Exception(e); } } static void throwingMethod() throws Exception { throw new Exception("throwingMethod"); } } A: As Ed says, it is showing the entire stack, but leaving out information that you've already seen. See Throwable#printStackTrace() Quoting from there: Note the presence of lines containing the characters "...". These lines indicate that the remainder of the stack trace for this exception matches the indicated number of frames from the bottom of the stack trace of the exception that was caused by this exception (the "enclosing" exception). This shorthand can greatly reduce the length of the output in the common case where a wrapped exception is thrown from same method as the "causative exception" is caught Often an exception is wrapped; created with another exception as the cause: try { // something which causes an Exception } catch (Exception e) { throw new SpecificException("help", e); } In this case, displaying the stacktrace will create the ... 11 more that you see. A: I have never seen that, but try this public void problemFunction(){ try{ //your code catch(Exception ex){ ex.printStackTrace(); } } or public void problemFunction(){ try{ //your code } catch(Exception ex){ System.out.println(ex); StackTraceElement[] arr = ex.getStackTrace(); for(int i=0; i<arr.length; i++){ System.out.println(arr[i].toString()); } } } A: There is a vmargs option -XX:-OmitStackTraceInFastThrow which might help in some situations. A: To simplify the accepted answer let us consider a simple notation. Exception in main …… At A At B At C Caused by …. AT P At Q AT R AT A - > { THIS ONE IS REPEATED , But slightly with line number changes } . MISSING 2 MORE { THOSE 2 ARE NOTHING BUT B AND C .} Caused by … At X At Y At P - > { THIS ONE IS REPEATED , But slightly line number changes } Missing 5 More ( Those 5 are nothing but Q,R, ,A,B,C ) Hence you have the entire stack. But MAKE SURE CHECK BOX FOR “limit console output” is NOT checked under run/debug drop down --> console in eclipse preferences. You can use the following code to get more clarity. try { // code causing exception } catch(Exception ex){ Throwable exThrowable=ex; while(exThrowable!=null) { System.out.println(exThrowable); StackTraceElement[] arr = exThrowable.getStackTrace(); for(int i=0; i<arr.length; i++){ System.out.println(arr[i].toString()); } exThrowable=exThrowable.getCause(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7597797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "47" }
Q: Flex 4.5 arrange gui components I am using IFrame and adding it dynamically, and it hides a new Alert.show and a previously made TitleWindow. How do I arrange it to go back or to make that Alert or window on top of all ? A: I'm guessing you're using the mx:HTML component to display some HTML. I got the same issue in my project, IFrame objects always display on top of everything. An efficient workaround is to draw the hide the HTML component and display a bitmap snapshot of it instead. That way, the Alert or any popup will display on top of it. Here's how I did it private var _snapshotImage:Bitmap; private function toggleSnapshotMode(htmlVisible:Boolean):void { if(!htmlVisible) { var bitmapData:BitmapData = new BitmapData(htmlLoader.width,htmlLoader.height,false); bitmapData.draw(htmlLoader,null,null,null,null,true); _snapshotImage = new Bitmap(bitmapData); _snapshotImage.x = htmlLoader.x; _snapshotImage.y = htmlLoader.y; html.addChildAt(_snapshotImage,0); } else { html.removeChild(_snapshotImage); } html.htmlLoader.visible = htmlVisible; } A: Unfortunately, you can't, as they are parents of different view heirachy's. The Popup is managed by the SWF, and is a child of the application's display list. The IFrame is managed by the HTML, and is a child of the DOM. ie: + HTML Page | | +---IFrame | +---SWF (Flex Application) | +--- System Manager | | | +---- Popup's // <---- Your Popup is here +--- Application Unfortunately there's no solution here that I'm aware of, you'll need to either display the popup within the IFrame, or remove the IFrame to show the popup.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simulate push view animation inside UIView I have a single UIView with some labels that display attributes from objects inside an array. I'm using gesture recognizers to change the current element in the array and hence the text in the labels. My question is how do I mimic a push animation without actually pushing a new view controller. Thanks for your help. A: Have you tried to use the UIView class methods for animation? For example this could help: + (void)animateWithDuration:(NSTimeInterval)duration animations:(void (^)(void))animations In the animations block you could move one view out and another in. A: Thats simple way to use CGAffineTransformMakeTranslation to move any view from X axis to Y axis using UIViewAnimation. Before using this transition set your object frame to some x,y axis(0,0) and pass your x and y to move from. [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.4]; CGAffineTransform transform = CGAffineTransformMakeTranslation(x,y); YOUR ViewOBJECT.transform=transform; [UIView commitAnimations];
{ "language": "en", "url": "https://stackoverflow.com/questions/7597803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drupal trimmer causes nested div's I work with views. A view manages the display of some text. I checked under REWRITE RESULTS the Trim this field to a maximul length-box and alsoo the Trim only a word-box and Add an eclips...-box. Where the pages used to look like this: <div class="test"></div> <div class="test"></div> <div class="test"></div> <div class="test"></div> now it's like this: <div class="test"><div class="test"><div class="test"><div class="test"></div></div></div></div> Is this a (known) Drupalbug or what am I doing wrong here? A: Try toggeling "Strip HTML tags". It did work for me! A: How many characters are you restricting the field to? If it is trimming the closing 's from the field and trying to output <div class="test"><div class="test"><div class="test"><div class="test"> Then it maybe that either Firefox is closing the divs by itself or it may be that the views trim function tries to tidy the HTML up before outputting it - and it has to guess where the divs should be closed and unfortunately for you, it's guessed wrong by closing them all at the end of string. Your best option is to either get the view to strip the HTML before trimming, or display it untrimmed. Trimming HTML to a fixed length can cause all kinds of strange issues if you chop off the ends.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BizTalk UDDI Services Installation Is it possible to install UDDI Services for BizTalk ESB Toolkit on Windows 7 32-bit? A: Only the dev tools and SDK for UDDI can be installed on Windows 7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight | Correct way to do exception handling Hello All, I would like to know how to handle the exception in the Silverlight ? Since it is the code which runs at Client side , So if some exception happens in the client nor related to web service . So should I show user friendly message and again make a call to the server and store the exception details there. Is it the correct approach ? If not please suggest a better one Regards, Phani A: The standard seems to be to expose a method in your webservice (such as logEvent(exception ex)) and handle it the same way you would any other .NET error. The Silverlight Integration Pack for Enterprise Library apparently provides for a lot more support for error logging too, so that may be worth a look, though I haven't used it myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook login in android WebView I'm developing an android app with phonegap and html5. Can anyone tell me how to implement Facebook login button. Also I need to know, how to implement share on wall functionality. I tried using facebook phonegap plugin, but no success. A: You can check the "Hackbook" example provided with the SDK sources. https://github.com/facebook/facebook-android-sdk/blob/master/examples/Hackbook/src/com/facebook/android/LoginButton.java
{ "language": "en", "url": "https://stackoverflow.com/questions/7597811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image showing as blank in Rails 3.1 on Production (Heroku) I recently updated my Rails to 3.1. Here's a part where I added: <%= asset_path('logo_symbol.png') %> This renders /assets/logo_symbol.png which works perfectly fine in development environment. However, when i push the code to production on heroku, it shows a broken image, with the url: assets/logo_symbol-135ddc8db2c9b59f032bed7db520137a.png. I am guessing the new name is for the reason of some optimization. It is however interesting to note that when I go to the assets/logo_symbol-135ddc8db2c9b59f032bed7db520137a.png url on production, I see a blank page, but when I change that url to anything random, like adding numbers to it, it shows a page not found. So clearly it is finding something on that url. It also shows a blank page when I go to /assets/logo_symbol.png directly on production/heroku. If this is any help, heroku does not precompile successfully when I push the code and heroku's documentation says that there is currently no work around for that issue. Any help in this will be greatly appreciated. My guess is that it has something to do with some configuration related to environments. I am attaching contents of my application.rb, development.rb and production.rb files here are the contents of my production.rb file # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send #config.action_mailer.default_url_options = { :host => 'localhost:3000' } #config.action_mailer.default_url_options = { :host => 'localhost:3000' } config.action_mailer.delivery_method = :smtp # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true end module ActiveAdmin class Reloader def attach! end end end and here are the contents of my development.rb file # Settings specified here will take precedence over those in config/application.rb # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the webserver when you make code changes. config.cache_classes = false # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send #config.action_mailer.default_url_options = { :host => 'localhost:3000' } #config.action_mailer.default_url_options = { :host => 'localhost:3000' } config.action_mailer.delivery_method = :smtp # Print deprecation notices to the Rails logger config.active_support.deprecation = :log # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin # Do not compress assets config.assets.compress = false # Expands the lines which load the assets config.assets.debug = true end module ActiveAdmin class Reloader def attach! end end end Here are the contents of my production.rb file # Settings specified here will take precedence over those in config/application.rb # The production environment is meant for finished, "live" apps. # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Specifies the header that your server uses for sending files config.action_dispatch.x_sendfile_header = "X-Sendfile" # For nginx: # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # If you have no front-end server that supports something like X-Sendfile, # just comment this out and Rails will serve the files # See everything in the log (default is :info) # config.log_level = :debug # Use a different logger for distributed setups # config.logger = SyslogLogger.new # Use a different cache store in production # config.cache_store = :mem_cache_store # Disable Rails's static asset server # In production, Apache or nginx will already do this config.serve_static_assets = false # Enable serving of images, stylesheets, and javascripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false #config.action_mailer.default_url_options = { :host => 'ha1.heroku.com' } config.action_mailer.delivery_method = :smtp # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Compress JavaScripts and CSS #config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to Rails.root.join("public/assets") # config.assets.manifest = YOUR_PATH config.assets.js_compressor = :uglifier config.assets.css_compressor = :scss I have compared my config files with the rails documentation for 3.1 and seems like I have all the defaults needed. However I am still seeing no image. Any help will be much appreciated A: Remove this line from production.rb: config.action_dispatch.x_sendfile_header = "X-Sendfile" You should also align the settings in your config files with those in section 9 of the pipeline guides. Sendfile headers contain information for the upstream webserver of where to find the file (on the file system) to serve it. This removes the load from the backend (Rails/Sprockets). When sendfile is on the HTTP response contains no body (it is zero length) which is why you see nothing. On heroku the nginx servers do not have access to the application filesystem, so this won't work. See this note on the Heroku dev site re sendfile. If you are using heroku, this document outlines the best options for using the pipeline effectively. A: You need to do two things to resolve it. First, change these two lines from false to true in production.rb file. config.assets.compile = true config.assets.digest = true Second, if you've syntax like this for your images background: url("imgo.jpg") Change it to background: image-url("image.jpg") I hope it does your job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Handling NoneType when using addition Im trying to add some values up but some of the values have a NoneType value. Now I looked at this question but I need some help. Im hoping someone can explain to me how I can get this to work with django. Here is my for loop in my views.py: next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year) for inv in next_il: total_m2 += inv.maturity_amount Now inv.maturity_amount is the value I'm trying to handle that has NoneType. Any suggestions would be greatly appreciated. Thanks. Steve A: for inv in next_il: total_m2 += inv.maturity_amount or 0 And may be you should set default=0 for maturity_amount field. And it's better to use DB aggregation here: from django.db.models import Sum total_m2 = Investment.objects.filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year).aggregate(Sum('maturity_amount')) A: Two choices that occur to me. next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year) for inv in next_il: total_m2 += 0 if inv.maturity_amount is None else inv.maturity_amount I actually like this better: next_il = Investment.objects.all().filter(plan = plan).order_by('financial_institution').filter(maturity_date__year=next_year) for inv in next_il: try: total_m2 += inv.maturity_amount except TypeError: log.warning( "Null maturity amount" )
{ "language": "en", "url": "https://stackoverflow.com/questions/7597817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In App Billing managed and unmanaged state for product I am very new to android.. I am working on In App billing.. My question is what is the main purpose of Managed and Unmanaged state while adding the In App product.. Can any one tell me what is the use of managed state and what is the use of unmanaged state.. A: As of Version 3 of Google's IAP Billing API this has changed. Both consumable (multiple purchase) and non-consumable items are "managed". Tf you want to use Version 3 of their API, all purchases must be created as "managed". You can then decide if the item should be consumed later. Here's a link to their docs: http://developer.android.com/google/play/billing/api.html#consumetypes A: The main difference between managed and un-managed is that a managed purchase can only be bought once and is tied to the Google account that purchases it. Un-managed purchases can be bought multiple times and are intended for consumable items. For more information, please see the Choosing a Purchase Type section of the Google in-app billing documentation. A: UnManaged could be something like "Buy 50 points" The 50 points would then be added to your account and you would store this on your accounts server, therefore the Android Market no longer needs to know that you purchased this product i.e. it will not remember your purchase and you can purchase it multiple times. Managed could be "Buy this song" In this scenario you do not have a server to record that they bought the song and so every time they reinstall you can query the market to see they bought the song and it will not let you download it more than once. Managed is aimed at one time downloads then you 'own that object'. UnManaged is for multiple downloads of the same thing to 'top something up'. A: UnManaged could be something like "Buy 50 points" The 50 points would then be added to your account and you would store this on your accounts server, therefore the Android Market no longer needs to know that you purchased this product i.e. it will not remember your purchase and you can purchase it multiple times. Managed could be "Buy this song" In this scenario you do not have a server to record that they bought the song and so every time they reinstall you can query the market to see they bought the song and it will not let you download it more than once. Managed is aimed at one time downloads then you 'own that object'. UnManaged is for multiple downloads of the same thing to 'top something up'. Least thats my understanding. Version 3 has the concept of 'consumables' and it works inline with the above. All products are managed but you can 'consume' a product. i.e. "Buy 50 points" will give the user fifty managed points, the user will not be allowed to purchase that item again until you consume that product. Therefore you can make unmanaged products by consuming instantly, or managed products by consuming when the user has "used" that product (i.e. never call consume for buying a song).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Programmatically accessing a view that is defined in a fragment's XML in Android I'm in the process of making an Android 3 app that has a tab-based navigation. Being quite new to Android I searched for tab tutorials and found a few different approaches, out of which an implementation based on Fragments + ActionBar seemed to be the best. I followed these tutorials http://www.abelski.com/courses/android3ui/actionbar.pdf (the last few slides) and http://www.youtube.com/watch?v=gMu8XhxUBl8 (same lesson in video format) ...and got to the point where the tabs show up, I can switch between them OK, and simple TextViews inside them show up fine. Now, problems arise when I want one of the tabs to have a spinner widget that is defined in the fragment's XML file and populate it with items that are defined in the strings.xml file. When I try to access the spinner with getViewById() from the onCreate() method I always get a null value as a result. As I understand it, to fix this I need to somehow declare the XML of the fragment (similarly like main layout has been done with setContentView(R.layout.main)) so that getViewById() knows where to look for the spinner (Eclipse's autocomplete finds it already though). However, I'm at complete loss how to do this, since none of the tutorials tackled the scenario where you want to modify the XML-based Fragments' contents inside the code. The main.xml looks like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/fragment_placeholder"></LinearLayout> </LinearLayout> tab1_fragment.xml like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout> and onCreate method like this: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ActionBar ab = getActionBar(); ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab newAuditTab = ab.newTab().setText(R.string.tabheader_new_audit); Fragment newAuditFrag = new FragmentTabNewAudit(); newAuditTab.setTabListener(new TabListener(newAuditFrag)); ab.addTab(newAuditTab); //and the same for other tabs Spinner spinner = (Spinner) findViewById(R.id.spinner1); // this returns null ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.cell_array, android.R.layout.simple_spinner_item); //cell_array is defined in strings.xml adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); } Accessing the views that are defined in main.xml via R.id works fine, so in this case the problem isn't related to Eclipse's auto-importing of the R class, I think. I guess I could define the spinner programmatically to get around the issue, but there is probably a more elegant solution to this, I hope. I can't see the Android big picture well enough yet to quite know where to look. A: As the spinner is not a child of the Activity itself, findViewById can not find it. As the spinner is a child of the fragment, you might try: Spinner spinner = (Spinner)newAuditFrag.getView().findViewById(R.id.spinner1); However, I'm not sure when the view for a fragment is created, so getView() might also return null that that point in your code. You could then try to move the code into onResume, which is called after onCreate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: In DDD where to save generated files by user? I have the following architecture in my project: UI -> Application -> Domain -> Infrastructure (4 tier) I need to allow user to upload a image, where the better place to keep the files generated by the user? In a folder in UI project? Update: Here's my folder structure: Thanks for answer, but I want to know too where to save the physic file. Update 2: My app is a CMS and these images are content generated by user. A: Let the Infrastructure handle those details. If there needs to be any sort of validation or business rules, then just deal with it like regular data, because that is all it is. The only difference is you are probably saving this data in a different place, but that is an implementation detail. Later on, you might want store those files in the database, or in version control... still implementation details that can be abstracted away into the infrastructure layer. Update: Ok, where to physically save the file on the drive. If it were me, would not store them mixed in with my code, because that seems like it could get complicated quickly. Say you wanted to start storing these files in version control, now you are mixing code in one version control system with data in another all in the same place. I would probably pick a place at least a little separated from your code: Two thoughts: Venus.Application Venus.Domain Venus.Infra Venus.Tests Venus.UI.Web Venus.Files (or Data) Or Venus.Application Venus.Domain Venus.Infra \Files (or Data) Venus.Tests Venus.UI.Web I did do something like for uploading user xml files, and I did save the files in a folder like the second one, and it worked out alright for a while, but then I decided that those files were better off stored in the database as text then written out only when needed to be exported. A: I think it depends on the character of the image files being uploaded. What is their intended use, how long do they need to be stored. For short-term images that don't need to be around for very long, TEMP is a splendid location for them. If they are meant to be long-term / permanent files, then you need to think about how they fit into your domain model. If your domain is centered around working with users' images, then perhaps they deserve a place in your Domain folder (bear in mind you can't forget about the security aspects of copying a user-uploaded file to a location not publicly accessible from the webserver, but I'm assuming you're taking care of that). However, if these images aren't so critical to the domain, and perhaps they are being used to beautify / customize the user's web experience, then perhaps they belong somewhere in the UI folder. DDD is about designing a solution that models the problem domain as closely as possible; you should know your domain best, use your best judgment. A: In terms of where to physically store them, I'd personally store them in the database by storing them as binary in one of the binary data types provided by the database. You could simply have an Image property on your object/DTO that you convert to bytes when saving. In my experience keeping all user data in the database rather than using physical files is much less hassle because you don't have to worry about unique file names, permissions, and moving servers/ deployment etc is easier because it's all contained in the database which you can backup and move about with ease.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Background of the Image created from Bitmap I am trying to create a signature component where the user can write his signature on the view and the resulting bitmap being saved as an image. I am able to achieve this successfully. But my issue is that the background color is of the image being saved is always transparent. In my onDraw method i do the following: @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.GREEN); canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint); canvas.drawPath(mPath, mPaint); } and while writing to the file system i do the following: fOut = new FileOutputStream(file); mBitmap.compress(Bitmap.CompressFormat.PNG,100, fOut); fOut.flush(); fOut.close(); The view on the device while capturing the signature is as shown in the image below: After the bitmap is written to the file system the image is as below: Could some one kindly help me with this. I would like me image to have the same background as the canvas. Thanks in advance. A: From your question it seems like you want to save the entire view as a bitmap instead of the path object. To do this you can simply save the DrawingCache of the view as a Bitmap. myView.buildDrawingCache() Bitmapt b = myView.getDrawingCache() fOut = new FileOutputStream(file); mBitmap.compress(Bitmap.CompressFormat.PNG,100, fOut); fOut.flush(); fOut.close();
{ "language": "en", "url": "https://stackoverflow.com/questions/7597821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP variables inside a variable I have an error somewhere in this line of code, if I take "by" off the line it works fine. $msg = 'An Order has just been submitted on CID, Number' . $_POST['orderNumber']'by' .$name; Can anyone spot my mistake? A: I would advise you to utilize one of PHPs core language features. PHP supports variable interpolation in double quoted strings. That's much simpler than the cumbersome string concatenation: $msg = "An Order has just been submitted on CID, Number $_POST[orderNumber] by $name"; Note that as special exception no array key quotes are to be used there for simple arrays. (Other examples see the manual http://php.net/manual/en/book.strings.php) Also note that you should actually escape (see htmlspecialchars) incoming $_POST or $_GET variables, if they are to be used for output again. A: Yes, you never concatenate $_POST['orderNumber'] and 'by' properly (via the . operator). $msg = 'An Order has just been submitted on CID, Number ' . $_POST['orderNumber'] . ' by ' . $name; // Notice the . (and a few spaces) A: you forgot to concatenate 'by'. Just add the concatenation . infront of 'by' A: You for got the . $_POST['orderNumber'] . 'by' A: Try this $msg = 'An Order has just been submitted on CID, Number'.$_POST['orderNumber'].'by'.$name;
{ "language": "en", "url": "https://stackoverflow.com/questions/7597822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tool for dropdown I am creating tool for dropdownlist using For each item as Listitem in Dropdown1.items item.attributes.add("title",item.text) Next How can convert this to linq ? Thanks, A: DropDownList1.Items.OfType<ListItem>().ToList().ForEach(item => item.Attributes.Add("title", item.Text));
{ "language": "en", "url": "https://stackoverflow.com/questions/7597825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I enable screen compatibility mode in android >11 I have an app that is quite old and still has to support Android 1.5 (API version 3) devices. For some reason the screen compatibility mode has stopped running and I can't figure out why. It did work fine on honeycomb devices. The result I am getting is that that the app is zoomed (i.e. all elements are oversized) instead of being stretched (all my activity use relative layouts so they all stretch fine - and it was working!). In My Manifest I have: <uses-sdk android:minSdkVersion="3"/> and <supports-screens android:largeScreens="true" android:anyDensity="true" android:smallScreens="true" android:resizeable="true" /> I have tried adding android:xlargeScreens="true" but to not avail. The thing I cant figure out is why the compatibility mode button has disappeared for this app. Is there something in the manifest that can do that? I have also tried : <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="11"/> <supports-screens android:largeScreens="true" android:anyDensity="true" android:smallScreens="true" android:resizeable="true" android:xlargeScreens="true" /> A: Your application target is API version 11, which means that the screen compatibility chooser won't show up. Try with a lower target version, i.e. version 10 (Android 2.3).
{ "language": "en", "url": "https://stackoverflow.com/questions/7597828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MKAnnotationView do not anything - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { NSLog(@"I'm Working"); static NSString *identifier = @"MyLocation"; if ([annotation isKindOfClass:[userPins class]]) { userPins *location = (userPins *) annotation; MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; if (annotationView == nil) { annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; } else { annotationView.annotation = annotation; } annotationView.enabled = YES; annotationView.canShowCallout = YES; if ([location.name compare:@"LARCENY"] == NSOrderedSame) { annotationView.pinColor = MKPinAnnotationColorGreen; } return annotationView; } return nil; } This code not working. I'm adding pins from JSON. I see red pins but I can't see nslog(I'm working). Any ideas? A: You need to set the mapView's delegate in viewDidLoad or in the nib or wherever you are creating it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make one Rails 3 route work with 2 controllers depending on database data? I am developing a Rails 3 app on Heroku, and here is the situation: There are two models: User and App. Both have "slugs" and can be accessed via the same url: /slug Example: /myuser => 'users#show' /myapp => 'apps#show' What is the best practice to handle this? What clean solution should I implement? The same logic you can see on AngelList. For example, my personal profile is http://angel.co/martynasjocius, and my app can be found at http://angel.co/metricious. Thank you! A: I would think about introducing a third model, ill call it Lookup for the example, but you will probably want to find a better name. I will also assume your User and App models also define a name field. class Lookup < ActiveRecord::Base belongs_to :owner, :polymorphic => true validates_uniqueness_of :name end class User < Active::Record::Base has_a :lookup, :as => :owner, :validate => true before_create :create_lookup_record def create_lookup_record build_lookup(:name => name) end end class App < Active::Record::Base has_a :lookup, :as => :owner, :validate => true before_create :create_lookup_record def create_lookup_record build_lookup(:name => name) end end LookupsController < ApplicationController def show @lookup = Lookup.find_by_name(params[:id]) render :action => "#{@lookup.owner.class.name.pluralize}/show" end end # routes.rb resources :lookups I hope this idea helps, sorry if its no use :) A: Try this (substituting action for your actions, like show, edit, etc): class SlugsController < ApplicationController def action @object = Slug.find_by_name(params[:slug]).object # or something self.send :"#{@object.class.to_s.downcase}_action" end protected def app_action # whatever end def user_action # something end end Separate stuff out into modules as you see fit. You can have objects of each class get their own actions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: TrueZip creates virtual directory instead of archive I'm having an issue with the following code: TFile src = new TFile(this.getMellomStasjon()); TFile dst = new TFile(this.getZipFolder()+""+zipFile+".zip"); if(dst.isDirectory()) dst = new TFile(dst, src.getName()); TFile.cp_rp(src, dst, null); TFile file = newNonArchiveFile(dst); if(dst.isArchive()) TFile.umount(dst); My goal is to put a directory containing files into a ZIP-archive using TrueZip. The problem is that the code works locally but not on the production computer. Locally I get a single ZIP-file, but in production I get a folder containing the files I'm trying to put in the archive (virtual directory). I have to use TrueZip because I'm archiving content over 4GB. Is there any way to force TrueZip to create an archive instead of a (virtual) directory? A: It probably didn't work because the JAR artifact of the module TrueZIP Driver ZIP was not present on the run time class path. To make sure it is, you could make the ZipDriver a compile time dependency by setting a custom TArchiveDetector. Here is an example: http://truezip.java.net/usecases/aff.html The code you show here is problematic. You should probably fix it to: // Call this once at application startup to make the ZipDriver a compile time // dependency. TFile.setDefaultArchiveDetector( new TArchiveDetector( "zip", new ZipDriver(IOPoolLocator.SINGLETON))); // Here's the work. TFile src = new TFile(this.getMellomStasjon()); TFile dst = new TFile(this.getZipFolder(), zipFile + ".zip"); TFile.cp_rp(src, dst, TArchiveDetector.NULL); TFile.umount(dst); A: Found an alternative library by Apache, Commons Compression. Using it instead of TrueZip. Seems to support >4gb files as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7597836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }