text
stringlengths
8
267k
meta
dict
Q: Unknown error (0xfffffffe) while impersonating in C# C# Impersonate Error Hello, wanted to create an application that would give me privileges to install applications with an user that has such accesses. It's important that the user with elevated privileges would be log onto from inside the application and thats what i've been trying to do but it seems it doesn't work. So what i did was used this library: http://impersonation.codeplex.com/ So i could impersonate admin user from within the application. Everything works fine until i try to actually run the application with elevated user access, if i don't log in with admin user, then my application simply gives me exception where it says that access is denied, when however i log in with user that has these privileges, it gives me unknown error exception, so im wondering why is that. However, when i try to run file that my current user has access to, it runs just fine. Now there probably isn't any workaround here unless i run this application as service, but i just want to make sure. Application GUI (source: upload.ee) Error Snapshot Full source: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Diagnostics; using Iuf.Network.Authentication; namespace AccessPool { public partial class Form1 : Form { Impersonation UserAccess; Process FileProcess; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnButton_Click(object sender, EventArgs e) { UserAccess = new Impersonation(txtUsername.Text, txtPassword.Text, "ametikool.local"); try { UserAccess.ImpersonateUser(); } catch (Exception ImpersonateException) { MessageBox.Show(ImpersonateException.ToString()); } finally { MessageBox.Show("Access granted!"); btnOpenFile.Enabled = true; } } private void btnOpenFile_Click(object sender, EventArgs e) { OpenFileDialog FileDialogObject = null; try { FileDialogObject = new OpenFileDialog(); FileDialogObject.ShowDialog(); } catch (Exception FileDialogException) { MessageBox.Show(FileDialogException.ToString()); return; } finally { txtFilePath.Text = FileDialogObject.FileName; } } private void btnRun_Click(object sender, EventArgs e) { try { FileProcess = new Process(); FileProcess.StartInfo.FileName = txtFilePath.Text; FileProcess.Start(); } catch (Exception FileProcessException) { MessageBox.Show(FileProcessException.ToString()); } } } } Any help is appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to access a deployed HelloWorld application in JBoss AS7 I am trying out JBoss AS 7 with a simple HelloWorld application. * *The HelloWorld application folder has a simple hello.jsp file. *The deploy copies the HelloWorld.war to the jboss7.0.1\standalone\deployments folder. *After this I start the jboss.cmd from the HelloWorld folder to start the application *If I access the URL http://localhost:8080/HelloWorld/hello.jsp, I get the Internet Explorer cannot display the webpage error I am able to access the Admin console at http://localhost:9990/console normally, but I can't see why I am not able to access the above URL. Here is the JBoss stdout: =============================================================================== 16:17:23,921 INFO [org.jboss.modules] (main) JBoss Modules version 1.0.1.GA 16:17:24,218 INFO [org.jboss.as.process.Host Controller.status] (main) Starting process 'Host Controller' [Host Controller] 16:17:24,671 INFO [org.jboss.modules] (main) JBoss Modules version 1.0.1.GA [Host Controller] 16:17:25,031 INFO [org.jboss.msc] (main) JBoss MSC version 1.0.0.GA [Host Controller] 16:17:25,421 INFO [org.jboss.remoting] (MSC service thread 1-7) JBoss Remoting version 3.2. 0.Beta2 [Host Controller] 16:17:25,437 INFO [org.xnio] (MSC service thread 1-7) XNIO Version 3.0.0.Beta3 [Host Controller] 16:17:25,453 INFO [org.xnio.nio] (MSC service thread 1-7) XNIO NIO Implementation Version 3 .0.0.Beta3 [Host Controller] 16:17:26,593 WARN [org.jboss.as] (Controller Boot Thread) No security realm defined for nat ive management service, all access will be unrestricted. [Host Controller] 16:17:26,593 INFO [org.jboss.as] (Controller Boot Thread) creating http management service using network interface (management) port (9990) [Host Controller] 16:17:26,593 WARN [org.jboss.as] (Controller Boot Thread) No security realm defined for htt p management service, all access will be unrestricted. [Host Controller] 16:17:26,687 INFO [org.jboss.as.remoting] (MSC service thread 1-1) Listening on /127.0.0.1: 9999 [Host Controller] 16:17:26,703 INFO [org.jboss.as.host.controller] (Controller Boot Thread) Starting server s erver-one 16:17:26,718 INFO [org.jboss.as.process.Server:server-one.status] (ProcessController-threads - 3) Starting pr ocess 'Server:server-one' [Host Controller] 16:17:26,796 INFO [org.jboss.as.host.controller] (Controller Boot Thread) Starting server s erver-two [Server:server-one] 16:17:27,093 INFO [org.jboss.modules] (main) JBoss Modules version 1.0.1.GA 16:17:27,468 INFO [org.jboss.as.process.Server:server-two.status] (ProcessController-threads - 3) Starting pr ocess 'Server:server-two' [Server:server-one] 16:17:27,484 INFO [org.jboss.msc] (main) JBoss MSC version 1.0.0.GA [Server:server-one] 16:17:27,562 INFO [org.jboss.as] (MSC service thread 1-3) JBoss AS 7.0.1.Final "Zap" star ting [Server:server-two] 16:17:27,828 INFO [org.jboss.modules] (main) JBoss Modules version 1.0.1.GA [Server:server-two] 16:17:28,218 INFO [org.jboss.msc] (main) JBoss MSC version 1.0.0.GA [Server:server-two] 16:17:28,296 INFO [org.jboss.as] (MSC service thread 1-4) JBoss AS 7.0.1.Final "Zap" star ting [Server:server-one] 16:17:28,328 INFO [org.apache.catalina.core.AprLifecycleListener] (MSC service thread 1-8 ) The Apache Tomcat Native library which allows optimal performance in production environments was not found o n the java.library.path: C:\Program Files\Java\jdk1.6.0_26\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\ WINDOWS;C:\Program Files\Java\jdk1.6.0_26\bin;C:\Program Files\Java\jdk1.6.0_26\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools;\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Python27;. [Server:server-two] 16:17:29,109 INFO [org.apache.catalina.core.AprLifecycleListener] (MSC service thread 1-2 ) The Apache Tomcat Native library which allows optimal performance in production environments was not found o n the java.library.path: C:\Program Files\Java\jdk1.6.0_26\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\ WINDOWS;C:\Program Files\Java\jdk1.6.0_26\bin;C:\Program Files\Java\jdk1.6.0_26\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools;\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Python27;. [Server:server-two] 16:17:29,156 INFO [org.apache.coyote.http11.Http11Protocol] (MSC service thread 1-8) Star ting Coyote HTTP/1.1 on http--127.0.0.1-8230 When I check the console, I see that none of the servers are started; I am not sure if this is the problem. A: Looking at your boot logs and deployment intentions, there is an important distinction to make regarding the automatic deployments, and the different methodologies between the standalone and domain instances. The deployment folder that you are trying to deploy from is based under the following path: AS_HOME/standalone/deployments As you will notice, there is no such directory under the AS_HOME/domain/ path. This is because only the standalone instance is able to use hot deployments, with AS7 shipping with the automatic deployment functionality enabled by default for the deployment scanner that manages this directory. The scanner will attempt to deploy any application copied to this folder, using marker files to indicate status of the deployment. In your example, the HelloWorld will deploy if you spin up a standalone instance of the application server with the following script. Windows: EAP_HOME/bin/standalone.bat Linux: EAP_HOME/bin/standalone.sh Keep in mind that the server first has to be active (which sounds silly to mention, but is easily overlooked when testing AS7 out), and that the deployment folder will confirm a deployment with a <filename>.<filetype>.deployed marker file. Likewise a failed deployment will result in a <filename>.<filetype>.failed marker file. You can also deploy the example using the Management CLI and the Management Console (as well as via an IDE such as JBoss Developer Studio or even via Maven). My pick is usually the Console, for sake of ease of use and the visual feedback. This video by a JBoss developer shows all of the available methods: http://www.youtube.com/watch?v=OuFaYYQVJP0 For domain instances, it is advised that you use either the Management CLI or the Management Console. There's more information on the JBoss documentation page for application deployment. https://docs.jboss.org/author/display/AS7/Admin+Guide#AdminGuide-Applicationdeployment A: This was my previous start-server script that was calling the domain.bat. @echo off set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_26 set JBossHome=C:\apps\jboss702 set Path=%JAVA_HOME%\bin;%Path% cd %JBossHome%\bin domain.bat After some research, I understood that the script needs to call the standalone.bat. @echo off set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_26 set JBossHome=C:\apps\jboss702 set Path=%JAVA_HOME%\bin;%Path% cd %JBossHome%\bin standalone.bat After this change, the war file was deployed automatically upon start. A: You can't just copy an archive into the deployments directory to deploy it. You should use the console to deploy the archive. It will work much better for you. When you bring the console up at the top click on the Server Groups. On the Server Groups page click on Manage Deployments and you'll see an Add Content button. From there just follow the wizard and you should be good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPad + UIWebView + presentModalViewController I have a very basic view controller class, created via interface builder. it only has one view, which is a UIWebView (see here: http://i55.tinypic.com/xdax01.png). Somewhere in my app i want to open this view controller as modal dialog via presentModalViewController. This is my code to achieve this: self.viewController.modalPresentationStyle= UIModalPresentationFormSheet; WebController* dvc= [[WebController alloc] initWithNibName:@"WebController" bundle:nil]; [self.viewController presentModalViewController:dvc animated:YES]; The modal dialog is shown, but unfortunately it is shown full screen, instead of the smaller dimensions of UIModalPresentationFormSheet. When i replace the above code with this one: self.viewController.modalPresentationStyle= UIModalPresentationFormSheet; MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init]; [self.viewController presentModalViewController:mailViewController animated:YES]; The app will correctly show a modal dialog with form sheet size (not fullscreen). What do i have to do in order to present my view controller class in the smaller form sheet size instead of fullscreen? A: modalPresentationStyle applies to the presented view controller and not the hosting view controller. So in your case you must do this: dvc.modalPresentationStyle=UIModalPresentationFormSheet;
{ "language": "en", "url": "https://stackoverflow.com/questions/7528015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: fast table view scroll and back button hit When I scroll my table view fast (with a long and quick gesture) so it will scroll for a few seconds more on screen displaying my cells (let's say 3-4 seconds) - and so very quickly I hit the back button to go back to the previous screen: it works... BUT then the scrolling would have come to a stop (on the screen that I cannot see anymore - so 3-4 seconds later): the app crashes! and that each time I do that "fancy" crash test. I used my own table view cells - and I am a bit out of ideas of where to start to fond that bug. I can only think that the previous view tries to "release" something that obviously is not displayed anymore. Has any of you experienced this? or have you tried on your own apps that "test" to ensure it will not crash like mine? any pointer of help is of course highly appreciated! Thanks Cheers, geebee EDIT1: thanks to your answers - I finally saw that this behavior happens if you put my removeallobjects like I was doing in the viewwilldisappear instead of viewDidDisappear method... all good now A: In back button action check for this condition. E.g -(void)backButtonAction:(id)sender { //If table is scrolling if([mTableView isDecelerating]){ //Don't push back or condition you want to perform } else { //your condition. } } As we know tableview is hierarchy of UIScrollview we can use isDecelerating to check whether the table is scrolling when button is pressed. A: When the view stops, it calls some functions of its scrollView delegate, which is your ViewController I guess. When the user hits back, the navigationController release the ViewController it was showing. So if YOU didn't retain it somewhere, the ViewController will be deallocated and the view will send a message to an object that doesn't exists anymore. In order to see if I'm right really quick, you can add the NSZombieEnable = YES in your project. After that you will get more precise informations about your crash. My guess is that you will see something like : "XXXX message send to a deallocated instance [UIViewController XXXX]" A: The cause of this would appear to be that your UITableView is living longer than its datasource or delegate - are you sure its not leaking? In the dealloc method for your datasource / delegate you should set tableView.delegate = nil; tableView.dataSource = nil;
{ "language": "en", "url": "https://stackoverflow.com/questions/7528018", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recipe linkandpostlink failed with exit code 1 error When I try to run a qt application on a Symbian device (N8 for example), I receive the following: warning: Missing dependency detected: C:/QtSDK/Symbian/SDKs/Symbian3Qt473/epoc32/release/armv5/lib/kqoauthd0.dso error: Recipe linkandpostlink failed with exit code 1. Any one hear about that type of error? A: Solved !!! The problem was that I am including a .dll library, this works great for the simulator but not for the device, so the idea was to include all .h and .cpp files if the target is a symbian device, and the .dll library if the target is the simulator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to call Creator Method's If we have a Class public class A { public void resetValues() { //DoSomething } B b = new B(); } public class B { public B() { } void doSomething() { //Is there a way here to call A(the Creator) method resetValues(); //Like Creator.resetValues(); } } So is there a way to call the Creator methods like in this Example Class A method's . This is is very needful when i use a Form to show Another Form : from FormA FormB frmB = new FormB(); frmB.Show(); this.hide(); Than i should onFormClose Event of FormB to Show again the FormA EDIT First i thought parsing A by Ref as Object ,but Storing a Reference as a Field later i founded out that's impossible ! First i thought maybe using reflection we can Identify and Call Creator method's but i think i mismatched some of OOP Design Pattern's A: The only way is to pass in the "creator" when calling the constructor: B b = new B(this); Of course, that means that B needs to have a constructor with the appropriate parameter type, which should match whatever it needs to do with its creator. EDIT: As noted in comments, it doesn't really need to be done at construction - it could be a property: B b = new B(); b.Creator = this; They amount to basically the same thing though. I would suggest this is usually a bad idea, to be honest. It's introducing a reasonably tight coupling between the two classes. It might be better for B to publish an event which the creator can subscribe to, in order to handle appropriate state changes etc on B. A: You can use simply Action instead Func<bool>, returning bool allows passing back a state which indicating whether operation was executed successfully. class B { private Func<bool> executeExternal; public B(Func<bool> executeExternal) { this.executeExternal= executeExternal; // here is resetValues() will be executed in case of B class bool isDoneSuccessfully = this.executeExternal(); } } public class A { public void resetValues() { //DoSomething } // basically we injecting a delegate B b = new B(() => { this.resetValues(); return true; } ); } A: Following on from @Jon Skeet's answer, it would be preferable for class B to emit an event when something happens and for class A to consume that event. In this way, class B has no dependency on class A. You could reuse class B with classes other than class A without modifying the internals of class B. From a maintenance POV, this is far more preferable. You could set it up as follows: public class A { B b = new B(); public A() { b.SomethingHappened += SomethingHappenedHandler; } public void resetValues() { //DoSomething } public void SomethingHappenedHandler(object sender, EventArgs args) { resetValues(); } } and public class B { public event EventHandler SomethingHappened; public B() { } void doSomething() { var ev = SomethingHappened; if(ev != null) { ev(this, EventArgs.Empty); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace SWF Resources without having to decompile? I want to replace an image inside of a SWF File without the need to decompile it. A: I think this is not possible, you need to recompile the swf file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Google Radar chart by Post Method I have asp.net page. In which i am loading multiple times google radar chart by post method in different frame. So for multiple charts my page having multiple frames. at last i am getting radar chart but issue is that i am having data of last radar chart in all charts. As shown below i am loading 2 radar chart in 2 div by frames from 2 different pages which posts data to google and creating chart but i am getting same result in both charts. divRadarChart1.InnerHtml = "<iframe class='RadarSize' src='RadarChart.aspx' frameborder='0' width='680px' height='520px'></iframe>"; divRadarChart2.InnerHtml = "<iframe class='RadarSize' src='RadarChart1.aspx' frameborder='0' width='680px' height='520px'></iframe>"; Please reply me as soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Large string split into lines with maximum length in java String input = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011."; //text copied from http://www.nationalgeographic.com/community/terms/ I want to split this large string into lines and the lines should not content more than MAX_LINE_LENGTH characters in each line. What I tried so far int MAX_LINE_LENGTH = 20; System.out.print(Arrays.toString(input.split("(?<=\\G.{MAX_LINE_LENGTH})"))); //maximum length of line 20 characters Output : [THESE TERMS AND COND, ITIONS OF SERVICE (t, he Terms) ARE A LEGA, L AND B ... It causes breaking of words. I don't want this. Instead of I want to get output like this: [THESE TERMS AND , CONDITIONS OF , SERVICE (the Terms) , ARE A LEGAL AND B ... One more condition added : If a word length is greater than MAX_LINE_LENGTH then the word should get split. And solution should be without helping of external jars. A: Thanks Barend Garvelink for your answer. I have modified the above code to fix the Bug: "if a word in the input is longer than maxCharInLine" public String[] splitIntoLine(String input, int maxCharInLine){ StringTokenizer tok = new StringTokenizer(input, " "); StringBuilder output = new StringBuilder(input.length()); int lineLen = 0; while (tok.hasMoreTokens()) { String word = tok.nextToken(); while(word.length() > maxCharInLine){ output.append(word.substring(0, maxCharInLine-lineLen) + "\n"); word = word.substring(maxCharInLine-lineLen); lineLen = 0; } if (lineLen + word.length() > maxCharInLine) { output.append("\n"); lineLen = 0; } output.append(word + " "); lineLen += word.length() + 1; } // output.split(); // return output.toString(); return output.toString().split("\n"); } A: Starting from @Barend 's suggestion, following is my final version with minor modifications : private static final char NEWLINE = '\n'; private static final String SPACE_SEPARATOR = " "; //if text has \n, \r or \t symbols it's better to split by \s+ private static final String SPLIT_REGEXP= "\\s+"; public static String breakLines(String input, int maxLineLength) { String[] tokens = input.split(SPLIT_REGEXP); StringBuilder output = new StringBuilder(input.length()); int lineLen = 0; for (int i = 0; i < tokens.length; i++) { String word = tokens[i]; if (lineLen + (SPACE_SEPARATOR + word).length() > maxLineLength) { if (i > 0) { output.append(NEWLINE); } lineLen = 0; } if (i < tokens.length - 1 && (lineLen + (word + SPACE_SEPARATOR).length() + tokens[i + 1].length() <= maxLineLength)) { word += SPACE_SEPARATOR; } output.append(word); lineLen += word.length(); } return output.toString(); } System.out.println(breakLines("THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING " + "AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, " + "www.nationalgeographic.com, which includes but is not limited to products, " + "software and services offered by way of the website such as the Video Player.", 20)); Outputs : THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player. A: Just iterate through the string word by word and break whenever a word passes the limit. public String addLinebreaks(String input, int maxLineLength) { StringTokenizer tok = new StringTokenizer(input, " "); StringBuilder output = new StringBuilder(input.length()); int lineLen = 0; while (tok.hasMoreTokens()) { String word = tok.nextToken(); if (lineLen + word.length() > maxLineLength) { output.append("\n"); lineLen = 0; } output.append(word); lineLen += word.length(); } return output.toString(); } I just typed that in freehand, you may have to push and prod a bit to make it compile. Bug: if a word in the input is longer than maxLineLength it will be appended to the current line instead of on a too-long line of its own. I assume your line length is something like 80 or 120 characters, in which case this is unlikely to be a problem. A: Since Java 8 you can also use Streams to tackle such problems. Following you can find a full example that utilizes Reduction using the .collect() method I think this one should be shorter than other non-3rd-party solutions. private static String multiLine(String longString, String splitter, int maxLength) { return Arrays.stream(longString.split(splitter)) .collect( ArrayList<String>::new, (l, s) -> { Function<ArrayList<String>, Integer> id = list -> list.size() - 1; if(l.size() == 0 || (l.get(id.apply(l)).length() != 0 && l.get(id.apply(l)).length() + s.length() >= maxLength)) l.add(""); l.set(id.apply(l), l.get(id.apply(l)) + (l.get(id.apply(l)).length() == 0 ? "" : splitter) + s); }, (l1, l2) -> l1.addAll(l2)) .stream().reduce((s1, s2) -> s1 + "\n" + s2).get(); } public static void main(String[] args) { String longString = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011."; String SPLITTER = " "; int MAX_LENGTH = 20; System.out.println(multiLine(longString, SPLITTER, MAX_LENGTH)); } A: Best : use Apache Commons Lang : org.apache.commons.lang.WordUtils /** * <p>Wraps a single line of text, identifying words by <code>' '</code>.</p> * * <p>New lines will be separated by the system property line separator. * Very long words, such as URLs will <i>not</i> be wrapped.</p> * * <p>Leading spaces on a new line are stripped. * Trailing spaces are not stripped.</p> * * <pre> * WordUtils.wrap(null, *) = null * WordUtils.wrap("", *) = "" * </pre> * * @param str the String to be word wrapped, may be null * @param wrapLength the column to wrap the words at, less than 1 is treated as 1 * @return a line with newlines inserted, <code>null</code> if null input */ public static String wrap(String str, int wrapLength) { return wrap(str, wrapLength, null, false); } A: You can use WordUtils.wrap method of Apache Commans Lang import java.util.*; import org.apache.commons.lang3.text.WordUtils; public class test3 { public static void main(String[] args) { String S = "THESE TERMS AND CONDITIONS OF SERVICE (the Terms) ARE A LEGAL AND BINDING AGREEMENT BETWEEN YOU AND NATIONAL GEOGRAPHIC governing your use of this site, www.nationalgeographic.com, which includes but is not limited to products, software and services offered by way of the website such as the Video Player, Uploader, and other applications that link to these Terms (the Site). Please review the Terms fully before you continue to use the Site. By using the Site, you agree to be bound by the Terms. You shall also be subject to any additional terms posted with respect to individual sections of the Site. Please review our Privacy Policy, which also governs your use of the Site, to understand our practices. If you do not agree, please discontinue using the Site. National Geographic reserves the right to change the Terms at any time without prior notice. Your continued access or use of the Site after such changes indicates your acceptance of the Terms as modified. It is your responsibility to review the Terms regularly. The Terms were last updated on 18 July 2011."; String F = WordUtils.wrap(S, 20); String[] F1 = F.split(System.lineSeparator()); System.out.println(Arrays.toString(F1)); }} Output [THESE TERMS AND, CONDITIONS OF, SERVICE (the Terms), ARE A LEGAL AND, BINDING AGREEMENT, BETWEEN YOU AND, NATIONAL GEOGRAPHIC, governing your use, of this site,, www.nationalgeographic.com,, which includes but, is not limited to, products, software, and services offered, by way of the, website such as the, Video Player,, Uploader, and other, applications that, link to these Terms, (the Site). Please, review the Terms, fully before you, continue to use the, Site. By using the, Site, you agree to, be bound by the, Terms. You shall, also be subject to, any additional terms, posted with respect, to individual, sections of the, Site. Please review, our Privacy Policy,, which also governs, your use of the, Site, to understand, our practices. If, you do not agree,, please discontinue, using the Site., National Geographic, reserves the right, to change the Terms, at any time without, prior notice. Your, continued access or, use of the Site, after such changes, indicates your, acceptance of the, Terms as modified., It is your, responsibility to, review the Terms, regularly. The Terms, were last updated on, 18 July 2011.] A: I have recently written a few methods to do this that, if no whitespace characters are present in one of the lines, opts for splitting on other non-alphanumeric characters prior to resorting to a mid-word split. Here is how it turned out for me: (Uses the lastIndexOfRegex() methods I posted here.) /** * Indicates that a String search operation yielded no results. */ public static final int NOT_FOUND = -1; /** * Version of lastIndexOf that uses regular expressions for searching. * By Tomer Godinger. * * @param str String in which to search for the pattern. * @param toFind Pattern to locate. * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise. */ public static int lastIndexOfRegex(String str, String toFind) { Pattern pattern = Pattern.compile(toFind); Matcher matcher = pattern.matcher(str); // Default to the NOT_FOUND constant int lastIndex = NOT_FOUND; // Search for the given pattern while (matcher.find()) { lastIndex = matcher.start(); } return lastIndex; } /** * Finds the last index of the given regular expression pattern in the given string, * starting from the given index (and conceptually going backwards). * By Tomer Godinger. * * @param str String in which to search for the pattern. * @param toFind Pattern to locate. * @param fromIndex Maximum allowed index. * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise. */ public static int lastIndexOfRegex(String str, String toFind, int fromIndex) { // Limit the search by searching on a suitable substring return lastIndexOfRegex(str.substring(0, fromIndex), toFind); } /** * Breaks the given string into lines as best possible, each of which no longer than * <code>maxLength</code> characters. * By Tomer Godinger. * * @param str The string to break into lines. * @param maxLength Maximum length of each line. * @param newLineString The string to use for line breaking. * @return The resulting multi-line string. */ public static String breakStringToLines(String str, int maxLength, String newLineString) { StringBuilder result = new StringBuilder(); while (str.length() > maxLength) { // Attempt to break on whitespace first, int breakingIndex = lastIndexOfRegex(str, "\\s", maxLength); // Then on other non-alphanumeric characters, if (breakingIndex == NOT_FOUND) breakingIndex = lastIndexOfRegex(str, "[^a-zA-Z0-9]", maxLength); // And if all else fails, break in the middle of the word if (breakingIndex == NOT_FOUND) breakingIndex = maxLength; // Append each prepared line to the builder result.append(str.substring(0, breakingIndex + 1)); result.append(newLineString); // And start the next line str = str.substring(breakingIndex + 1); } // Check if there are any residual characters left if (str.length() > 0) { result.append(str); } // Return the resulting string return result.toString(); } A: My version(The previous were not working) public static List<String> breakSentenceSmart(String text, int maxWidth) { StringTokenizer stringTokenizer = new StringTokenizer(text, " "); List<String> lines = new ArrayList<String>(); StringBuilder currLine = new StringBuilder(); while (stringTokenizer.hasMoreTokens()) { String word = stringTokenizer.nextToken(); boolean wordPut=false; while (!wordPut) { if(currLine.length()+word.length()==maxWidth) { //exactly fits -> dont add the space currLine.append(word); wordPut=true; } else if(currLine.length()+word.length()<=maxWidth) { //whole word can be put if(stringTokenizer.hasMoreTokens()) { currLine.append(word + " "); }else{ currLine.append(word); } wordPut=true; }else{ if(word.length()>maxWidth) { int lineLengthLeft = maxWidth - currLine.length(); String firstWordPart = word.substring(0, lineLengthLeft); currLine.append(firstWordPart); //lines.add(currLine.toString()); word = word.substring(lineLengthLeft); //currLine = new StringBuilder(); } lines.add(currLine.toString()); currLine = new StringBuilder(); } } // } if(currLine.length()>0) { //add whats left lines.add(currLine.toString()); } return lines; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Anyway in TFS to check-in modified files which are not checked-out Anyway in TFS to check-in modified files which are not checked-out. I made modifications in some fo the files which are I didnt check-out. In Sub version we can check-in only modified files is there any similar way here as well.. I am new to TFS A: Ultimately, you do need to check out files before they can be checked in. There's a couple of ways to do this - if you know exactly which files you've modified, you can simply check them out with the UI or with the command line client. Of course, it's much easier to just let TFS determine which files you've modified and check them out for you. You can use the Team Foundation Server Power Tools to scan your local disk for changes that were made using the command: tfpt online This will locate files that were modified and not checked out as well as files that were added to your disk that don't have a corresponding add pended and files that were removed that don't have a corresponding delete pended. You can then choose to pend any or all of those changes to the server and then checkin. A: Make a copy of the modified files to another directory, check the files out that you have modified, then copy over the files with the new/modified ones and then check them back in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Live search optimisation in Javascript I have some code in Javascript (not jQuery, unfortunately) at the moment that performs a live search on a database, depending on what the user enters. The problem is, if you type quickly, it'll still be performing the search from the last keystroke and this can add up to a delay of anything up to ten seconds. I know I should cache this information, and it's definitely something I'd love to do soon (along with implementing jQuery) but for now I was wondering if there was any way at all to speed this up? I've already limited the number of rows the search returns to 20, and have made sure the search doesn't run unless there are 3 or more characters. Thanks A: Make the ajax call trigger 1 or 2 seconds after the user stopped typing. If you need code for this let me know in the comments. A: You can check if there's already a request running. If so, abort it. (currentRequest.abort())
{ "language": "en", "url": "https://stackoverflow.com/questions/7528050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Listing MySQL tables and fields together I know you can print all the tables in MySQL database using show tables; and all the fields in a table using describe table; but is there a way of putting this together? Thanks! A: SELECT table_name, column_name, COLUMN_TYPE FROM information_schema.columns WHERE TABLE_SCHEMA = 'my_db' ORDER BY table_name, column_name See: http://dev.mysql.com/doc/refman/5.0/en/columns-table.html and: http://dev.mysql.com/doc/refman/5.0/en/information-schema.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7528058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Signing In fails before checkout In virtuemart I'm using Virtumart on Joomla. Here is my problem : After adding some products to the cart, when I choose to checkout, I have two solutions (as any usual E-commerce website) : * *Signing up *Signing in I'm having some troubles with the second one. When I fill all the fields and validate the form. it redirects me to the same page but loaded with a different template instead of the checkout page. BUT when I deactivate the Javascript, it works... here's a link to a product for testing. The only Javascript that seems to be pointing at my form is the function submitregistration Feel free to check if other functions do.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with xml parsing in phonegap application I want to parse xml webservice in my phonegap application but i don't have any idea how is it possiblem.I tried it with my local xml file which is stored in my remote server and it is working fine but when i am calling server side xml file then i am not getting any result.Pls anybody have idea then please solve my issue. Pls any one have working simple code then pls send it to me. I tried to find out my solution from google but didn't get any answer .Please solve my issue.My server file is http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml. A: please try following code in your index.html file, I have tested the url (http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml) in iPhone/Android Simulator and its work like charm. <html> <head> <script src="js/jquery-1.4.2.js" type="text/javascript" charset="utf-8"></script> <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script> <script> function bodyload(){ alert("We are calling jquery's ajax function and on success callback xml parsing are done"); $.ajax({ url:'http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml', dataType:'application/xml', timeout:10000, type:'POST', success:function(data) { $("#bookInFo").html(""); $("#bookInFo").append("<hr>"); $(data).find("Book").each(function () { $("#bookInFo").append("<br> Name: " + $(this).find("name").text()); $("#bookInFo").append("<br> Address: " + $(this).find("address").text()); $("#bookInFo").append("<br> Country: " + $(this).find("country").text()); $("#bookInFo").append("<br><hr>"); }); }, error:function(XMLHttpRequest,textStatus, errorThrown) { alert("Error status :"+textStatus); alert("Error type :"+errorThrown); alert("Error message :"+XMLHttpRequest.responseXML); $( "#bookInFo" ).append( XMLHttpRequest.responseXML); } }); } </script> </head> <body onload="bodyload()"> <button onclick="bodyload()">Ajax call</button> <p id="bookInFo"></p> </body> </html> Output- A: Use this: <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" /> <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script> <script type="text/javascript"> $(function() { $("#requestXML").click(function() { $.ajax({ type: "POST", url: "http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml", data: "{}", cache: false, dataType: "xml", success: onSuccess }); }); $("#resultLog").ajaxError(function(event, request, settings, exception) { $("#resultLog").html("Error Calling: " + settings.url + "<br />HTTP Code: " + request.status); }); function onSuccess(data) { $("#resultLog").append(""+data); $(data).find("Book").each(function () { $("#resultLog").append("<br> Name: " + $(this).attr("name")); $("#resultLog").append("<br> Address: " + $(this).attr("address")); $("#resultLog").append("<br> Country: " + $(this).attr("country")); $("#resultLog").append("<br><hr>"); }); } }); </script> Button to call the above method: <input id="requestXML" type="button" value="Request XML" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7528065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Simple javascript regex help needed I have an regex expression: \[quote\](.*?)\[\/quote\] and it matches correctly between [quote]example[/quote] but it does not find a match for: [quote] example [/quote] how can I change the regex so it finds a match in the latter case too? *And keeps the format (multiple lines) Thanks. A: Add [\r\n]* to the regular expressiuon \[quote\](.*?)\[\r\n]*[\/quote\] A: The problem is that in JavaScript the . does not match a new line (and this cannot be changed unlike in other languages where you might use the s modifier). So the following should work: \[quote\]([\s\S]*?)\[\/quote\] \s will match every whitespace character (including new lines) and \S will match every non-whitespace character - together [\s\S] matches every character including new lines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .NET 4.0 in C++ - How call AppendText for RichTextBox from a static member function My mind somehow is stuck in a "loop of errors". I don't want to waste time any more with endless trial and error, so I better ask here: I have a Windows-Form (.NET, C++) like following. The simplified version here only has a RichTextBox, a static and a non-static member function. Appending Text to the RichTextBox from the non-static function "nonstaticFunc()" works as expected. But how can I do this from the static member function "staticFunc()"? I tried several approaches proposed in this forum on how to call non-static functions from static functions, but somehow I couldn't figure out how to do this. public ref class Form1 : public System::Windows::Forms::Form { public: Form1() { InitializeComponent(); } protected: ~Form1() { if (components) { delete components; } } protected: private: System::ComponentModel::Container ^components; private: System::Windows::Forms::RichTextBox^ myTextBox; System::VoidInitializeComponent( System::Void ) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid)); this->myTextBox = (gcnew System::Windows::Forms::RichTextBox()); } public: System::Void nonstaticFunc( System::Void ) { this->myTextBox->AppendText( L"Append this...\n" ); } public: static System::Void staticFunc( System::Void ) { // How do I AppendText here?? // Not working: this->myTextBox->AppendText( L"Append this...\n" ); } } Thanks for every little bit of help! Appreciated a lot! A: You need to work out which text box you're interested in. What if there are two visible forms? You don't have enough context. Now you could keep a static member to keep track of "the one true form" - or you could take the textbox or form as a parameter... but fundamentally you need to have that context somehow. Why do you want to do this from staticFunc anyway? Why can the caller not call the method on the appropriate form? Once you understand the problem - why it won't work - you should be able to think about the most appropriate change. We can't really tell you that, as we don't have enough information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add google maps object from GWT code? I would like to use google maps in my GWT application. The thing is that the gwt-maps API only supports Google Maps API version 2, and the regular maps api is version 3. So basically what I want to do is to use the standart js maps library from my GWT code, but this doesn't work: public void onModuleLoad() { buildMap(); } private final native void buildMap()/*-{ <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script> var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); }-*/; I suspect that the problem is that onModuleLoad is not equivalent to body.onload. What do you think? A: You should check out gwt-google-maps-v3, the open source wrapper for version 3 of the Maps API. The project is technically deprecated because it's being merged with gwt-google-apis, but it'll at least get you on the right track. A: Ok, I found a solution. The first thing I did was to create a UIBinder to hold the div of the map: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui"> <div id="map_canvas" style="width:100%; height:100%"></div> </ui:UiBinder> And here is the rest of the code: public void onModuleLoad() { mapCanvas canvas = new mapCanvas(); Document.get().getBody().appendChild(canvas.getElement()); buildMap(); } private final native void buildMap()/*-{ var latlng = new $wnd.google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: $wnd.google.maps.MapTypeId.ROADMAP }; var map = new $wnd.google.maps.Map($doc.getElementById("map_canvas"), myOptions); }-*/; A: I have a whole app to do this. Check out the project at https://github.com/dartmanx/mapmaker/tree/0.5.2 You may want to pay special attention to my utility class for Google Maps: https://github.com/dartmanx/mapmaker/blob/0.5.2/src/main/java/org/jason/mapmaker/client/util/GoogleMapUtil.java Hope it helps, I went through alot of pain with that JSNI. Jason
{ "language": "en", "url": "https://stackoverflow.com/questions/7528083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP PDO::prepare() - SQL Error with placeholders My problem is that I can't get placeholders to work in my SQL statements. Specifically, in the below code, when I replace the placeholder ':tripsid' with a value like 'abcdefg' the TABLE isn't being created as intended. SQL Error is: PDO::errorInfo(): Array ( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near *''sdfghjk' ( id INT NOT NULL, stop_start SMALLINT NOT NULL, stop_end SMA'* at line 1 ) And the code: // My method to create a table with PDO and placeholders public function routes_table() { $this->connect(); $STH = $this->DBH->prepare('CREATE TABLE IF NOT EXISTS :tripsid ( id INT NOT NULL, stop_start SMALLINT NOT NULL, stop_end SMALLINT NOT NULL, distance SMALLINT NOT NULL, duration TINYINT NOT NULL, medium TINYTEXT NOT NULL, CONSTRAINT pk_routes PRIMARY KEY ( id ) )'); $tripsid = "sdfghjk"; $STH->bindParam(':tripsid', $tripsid, PDO::PARAM_STR, 7); $STH->execute(); // SQL Errors if (!$STH->execute($input)) { echo "\nPDO::errorInfo():\n"; print_r($STH->errorInfo()); } $this->disconnect(); } I have tried everything I could think of. Does anyone see the mistake? A: I see this question is over a year old, but I've just stumbled across it and would like to highlight something: this has nothing to do with the quotation marks. When an error occurs and you are given the snippet of SQL relating to the syntax in question, it is automatically enclosed around a pair of single quotation marks. This can often make it look as though there's a different issue, namely that of a mixture of double and single quotes. In this example - PDO::errorInfo(): Array ( [0] => 42000 1 => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sdfghjk' ( id INT NOT NULL, stop_start SMALLINT NOT NULL, stop_end SMA' at line 1 ) It's referring to: 'sdfghjk' ( id INT NOT NULL, stop_start SMALLINT NOT NULL, stop_end SMA The outermost quotation marks are just specific to the error output; like me - I fear you noticed this and thought your error was about incorrect quotation marks. This is a red herring! Remove the outermost single quotes to actually see the SQL which was incorrect. As for your real problem: You CANNOT specify the table name (or a column name) as a parameter; this is common to prepared statements on most platforms and APIs. This goes for any query - select/insert/update etc etc - none of them can accept the tablename as a parameter. For more information - see this question here. So with this in mind, I would use sprintf() to achieve something like this... $STH = $this->DBH->prepare( sprintf('CREATE TABLE IF NOT EXISTS %s ( id INT NOT NULL, stop_start SMALLINT NOT NULL, stop_end SMALLINT NOT NULL, distance SMALLINT NOT NULL, duration TINYINT NOT NULL, medium TINYTEXT NOT NULL, CONSTRAINT pk_routes PRIMARY KEY ( id ) )', $tripsid) ); $STH->execute(); Yes, it rather takes the beauty out of PDO when you still have to manipulate strings - unfortunately, this is the case for using table names as parameters! Also, remember this means 'old stylee' SQL Injection risks could still apply as you are manipulating the query directly. I don't expect this will help the OP a year later, but I hope it'll help someone else now! :) A: ok now I know that the quotation marks bound to the parameter automatically by PDO::bindParam() is causing the problem. Does anybody have an idea how to remove the quotation marks from the table name so my code will be... $STH = $this->DBH->prepare('CREATE TABLE IF NOT EXISTS tablename ( id INT NOT NULL,... instead of $STH = $this->DBH->prepare('CREATE TABLE IF NOT EXISTS 'tablename' ( id INT NOT NULL,
{ "language": "en", "url": "https://stackoverflow.com/questions/7528084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create setup for asp.net 2.0 application I have an asp.net 2.0 application that i want to deploy to a server. I want to make a setup that will install this application on the server. Also I must be able to configure parameters such as connection strings on the setup and these changes should reflect on the web.config. I am using .NET Framework 2.0 and VS 2005. P.S: I understand that searching "asp net application deployment" on google will give me tons of results, but as i have some special requirements and am doing this for the first time, someone with more experience may be able to push me in the right direction. Regards, A: You can easily deploy your project using publish wizard (Visual Studio). Take a look at following articles : * *Using Web Deployment Projects with Visual Studio 2005 *VS 2005 Web Deployment Projects - by scott gu
{ "language": "en", "url": "https://stackoverflow.com/questions/7528087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Xuggler for MXF to FLV I am trying to transcode an mxf file to flv type using Xuggler. But I am getting this exception - 2011-09-23 11:48:06,328 [main] WARN com.xuggle.xuggler - Got error: picture is not of the same PixelType as this Coder expected (../../../../../../../csrc/com/xuggle/xuggler/StreamCoder.cpp:1204) My code is very simple and it looks like this - public static void main(String[] args) { // create a media reader IMediaReader mediaReader = ToolFactory.makeReader(inputFilename); // create a media writer IMediaWriter mediaWriter = ToolFactory.makeWriter(outputFilename, mediaReader); // add a writer to the reader, to create the output file mediaReader.addListener(mediaWriter); // create a media viewer with stats enabled // IMediaViewer mediaViewer = ToolFactory.makeViewer(true); // add a viewer to the reader, to see the decoded media // mediaReader.addListener(mediaViewer); // read and decode packets from the source file and // and dispatch decoded audio and video to the writer while (mediaReader.readPacket() == null) ; } It works for files like MP4 and MOV types. Any pointers please. Since no one replied and I could not find any solution, I decided to do using command arguments from Java. I tried this and I am getting errors - public class FfmpegCommandTest { public static void main(String args[]) { String commandStr[] = { "ffmpeg -f dv -i \"C:\temp\0001NY.MXF\" -ar 44100 -v codec libx264 -maxrate 2000k -bufsize 2000k -vf scale=\"iw/2:ih/2\" -strict experimental -vstats_file \"C:\nasir\progress.txt\" \"C:\temp\0001NYoutput-short1.mov\"" }; // print the command to execute for (String x : commandStr) { System.out.print(x + " "); } // execute ffmpeg with the command generated by the previous segment try { ProcessBuilder proc = new ProcessBuilder(commandStr); proc.directory(new File("C:\temp")); //proc.command(commandStr); proc.start(); } catch (IOException ex) { ex.getMessage(); ex.printStackTrace(); } } } the error is The system cannot find the file specified at java.lang.ProcessBuilder.start(Unknown Source) at com.xuggle.xuggler.demos.FfmpegCommandTest.main(FfmpegCommandTest.java:21) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.<init>(Unknown Source) at java.lang.ProcessImpl.start(Unknown Source) A: for the command stuff: use \"C:\\temp\\0001NY.MXF\" instead of \"C:\temp\0001NY.MXF\". See double back-slash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I work out how powerful a given machine is? I'm confronted with a bewildering array of linux boxen. How do I find out how many processors they have, how many cores, how much RAM they have, how fast their disks are, how heavily loaded they are by competing people etc, etc? A: * *If you want a static list, check for each characteristic with its own command and let your shell do the automation. That is, use /proc/cpuinfo for the CPU, /proc/meminfo for the memory, and /proc/loadavg for the computational load. *If you want to identify bottlenecks, have a look at atop. A: You can run the command sysinfo This returns a few things including * *Number of Processes *Memory Size Full List here There are also files such as /proc/cpuinfo, and /proc/meminfo that hold CPU and memory info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ncurses trapping extended keys (Control-left, Shift-Function etc) I am trying to trap Control-Left, Shift-F10 etc in my ruby programs. Normally, using just getch I get a list of ints such as 27,91,50,50,126 which works. However I fear these may be system or terminal dependent. After googling I found about use_extended_names, tigetstr etc. I found a C program using these which discovers the keycodes at run time (by Thomas Dickey). I run it and it seems to discover extended keys, but then the getch in the same program still gives me the usual list of ints such as [27,91,53,68] for C-left which I am getting anyway. I expect to get one return value, the one it mentions. What am i missing ? Here is the output when I press Control-left: keypress=27 keypress=91 keypress=53 keypress=68 key=kLFT5, code=540 key=kEND5, code=525 key=kHOM5, code=530 key=kHOM3, code=528 key=kUP5, code=561 key=kDN5, code=520 Should I not get just 540 ? Here is keytest.c : https://gist.github.com/1237091 Strangely, all the codes show 0 when running under TERM=screen. The above is TERM=xterm. (I am on OSX using Terminal) A: ncurses by itself does not know about the control-, shift-, meta- and alt-modifiers because it only knows about characters. Modifiers are something that particular terminals know about. Some terminals can encode keyboard modifiers in the characters which they send to the host. xterm, for instance can do this. terminfo (and termcap) have predefined lists of special keys (such as cursor-keys, function-keys), including a small number of modified special keys (such as shifted right arrow). The predefined keys have well-defined names in the terminal description as well as KEY_xxx names in the curses.h header. ncurses provides two ways to extend these lists of special keys * *the -x option of tic with the corresponding use_extended_names function (which defines a name for a given input string). *the define_key function (which assigns a code to be returned by getch for a given input string). The ncurses terminal database provides the most useful definitions for modified special keys, focusing on the cursor-keys and editing-keypad. There are a few issues with this: * *the terminal database does not provide all definitions because portable terminfo definitions are limited to 4096 bytes. If there were no limit on size, then conceivably one could generate complete tables for each of the (literally) thousands of combinations of xterm's keyboard-related resource-settings. *some terminals which set TERM to xterm do not send the same strings as xterm. (In fact, most differ, though a few are subsets rather than simply differing). *for the example given, the string in terminfo would be \E[5D, which does not appear to be one of xterm's. (OP indicated that this is OSX Terminal, from a few years ago -- each release of OSX includes changes to Terminal, but no release of OSX Terminal yet matches xterm exactly). The reason why it does not appear to be xterm's is that the modifier (5) appears in the first position rather than in the second. xterm deprecated that in 2002 (patch #167). *function-keys are mentioned in the question without specifics. The convention used in ncurses is to assign the (almost standard) 12 PC-keyboard function keys with the 4 most useful combinations of shift- and control-modifiers to obtain 48 function keys. There are 60 predefined function keys in terminfo; when there are additional well-known strings for those, the remaining dozen are filled in up to the limit. So much for making predefined tables using terminfo (with the problems of size and terminals which pretend to be something different). The define_key function has no limit on size, and has long been available to applications which have specialized needs. For instance, one could use it to build a table by merging the most common variants of the most common terminals. A: Curses was designed at a time before people were really doing modifiers in terminals. Its key handling model is effectively a flat enumeration of values, and doesn't easily handle arbitrary key + modifier combinations. To solve this better, I wrote libtermkey, you may be more luck using this instead. http://www.leonerd.org.uk/code/libtermkey/ It's a C library, though it has both Perl and Python bindings. I'd imagine someone ought to be able to build some Ruby bindings quite easily for it as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Move record to different table MySQL I see this question have been asked in many different ways, but I don't understand them quite well. I want to move my records that have expired (their date is behind/smaller than now() - each one has a field with their date in, this is in seconds from 1970) to a different identical table. This is to make the event-cue smaller in the main table. Is there any single query I can use to move a record to a different table? I can do the checking of the time/when expires myself. A: You cant do this in one query, you have to perform two: query 1: INSERT INTO newtable SELECT * FROM oldtable WHERE date<now(); query 2: DELETE FROM oldtable WHERE date <= SELECT MAX(date) FROM newtable A: insert into backupTable (select field1, field2 from mainTable where myDate < UNIX_TIMESTAMP(NOW())) delete from mainTable where myDate < UNIX_TIMESTAMP(NOW())
{ "language": "en", "url": "https://stackoverflow.com/questions/7528099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: put image in center of div where image is in absolute position <div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute in this code i want to put image in center of div but it not come in center align due to absolute position of image, so, please help me to put this image in center of div. Please help me A: First, Set the div to position:relative. Second, add this code: $(document).ready(function(){ var div_height = $(".img-box").height(); var div_width = $(".img-box").width(); $("img").each(function(){ $(this).css({ "top": (div_height-$(this).height())/2+"px", "left": (div_width-$(this).width())/2+"px" }); }); }); To center an element relative to the parent, the width of the child element has to be subtracted from the width of the parent. After dividing this result by 2, you know the desired offset of the child (relative to the parent). A: if you know img width and height, you could set top and left 50% margin: -imgHeight/2 0 0 -imgWidth/2 A: You can do it in css: .img-box img { position:relative; margin: auto; display:block; } If you've already got position:absolute applying to your img nodes it might mean you have other strange CSS that mucks this up. Although if your intention is to have the images appear on top of each other this isn't the solution, but your question isn't clear on that. A: in css: image{ position: relative; left: 50%; } If the images don't line up on top of each other, I would just put them inside a smaller div with the width set to the same as the width of the image, so the second image is forced to display underneath rather than next to. And then set that second div to display in the center of the parent one using the 'left:50%' Might not be best way to do it, but it's probably how I'd do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TFS build adding an unwanted code block to xap file Microsoft.Practices.ServiceLocator Here is a list of my references in my silverlight project. Microsoft.Practices.Unity.Silverlight<br/> mscorelib<br/> Prospector.ProviderMatching.LinkedDataObjects<br/> Prospector.ProviderMatching.SLDataObjects<br/> System<br/> System.ComponentModel.DataAnnotations<br/> System.Core<br/> System.Net<br/> System.ServiceModel<br/> System.Windows<br/> System.Windows.Browser<br/> System.Windows.Controls<br/> System.Windows.Controls.Data.Input<br/> System.Windows.Controls.Toolkit<br/> System.Windows.Data<br/> System.Xml<br/> When I build the project localy the contence of my xap file looks like the following. AppManifest.xaml Microsoft.Practices.Unity.Silverlight.dll Prospector.ProviderMatching.DataObjects.SL.dll Prospector.ProviderMatching.Silverlight.dll Prospector.ProviderMatching.SLDataObjects.dll ServiceReferences.ClientConfig System.ComponentModel.DataAnnotations.dll System.Windows.Controls.Data.dll System.Windows.Controls.Data.Input.dll System.Windows.Controls.dll System.Windows.Controls.Toolkit.dll System.Windows.Controls.Toolkit.Internals.dll System.Windows.Data.dll When this is checked in and the build server kicks off it creates a xap file with the following contence. AppManifest.xaml Microsoft.Practices.ServiceLocation.dll Microsoft.Practices.Unity.Silverlight.dll Prospector.ProviderMatching.DataObjects.SL.dll Prospector.ProviderMatching.Silverlight.dll Prospector.ProviderMatching.SLDataObjects.dll ServiceReferences.ClientConfig System.ComponentModel.DataAnnotations.dll System.Windows.Controls.Data.dll System.Windows.Controls.Data.Input.dll System.Windows.Controls.dll System.Windows.Controls.Toolkit.dll System.Windows.Controls.Toolkit.Internals.dll System.Windows.Data.dll As you can see I have gained a code block in the xap file that the application does not use. However not only is this a waste of bandwidth, it actually prevents the silverlight app from doing anything, it is downloaded but does not run. If I remove the offending Microsoft.Practices.ServiceLocator.dll from the xap file and the manifest.xml the silvlight app then functions as intended. Has anyone got any ideas why the build server is including this library and how to prevent it from doing so...? A: I think Microsoft.Practices.ServiceLocation.dll keeps getting added as you have a reference to Microsoft.Practices.Unity.Silverlight.dll I have a feeling that they are dependent on each other. Do you need to use Unity? As to why your app fails when Microsoft.Practices.ServiceLocation.dll is included in the XAP; I have a suspicion that you may be using the wrong version of the Microsoft.Practices.Servicelocation.dll (WPF version?) A: Myles really got to the crucks of the matter and I just add this for more detail of my particular problem. The problem was that the .net version of ServiceLocator was being built into the xap on the build server. I think the reason it was not being built in locally was because it was being resolved by the GAC. I took copies of the Microsoft.Practices.Unity.silverlight.dll and Microsoft.Practices.ServiceLocator.dll and added them to a shared binary folder which is checked into source control to which the build server can reference. I then uninstalled Unity for Silverlight 2.0 from my installed programs (I assume this de-Gaced it). I added references to the above dlls that were now in my binary folder and built my solution locally. Hay presto I now have Microsoft.Practices.ServiceLocator.dll included in my xap file. Once all this was checked into TFS the build now picked up the right version of Microsoft.Practices.ServiceLocator.dll from the shared binarys folder and included it in the xap. Job done. I think the cause of this problem lies in the Global Assembly Cache. Hope this helps someone equally frustrated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Migrating Oracle Database with expdp and impdp Does the target database need to be prepared with tablespace and/or user (schema) in order to successfully migrate a schema from one database (11g R1) to another (11g R2)? Currently I only can make tests with the 11g R1 database. My test was to export a schema and import it into a new schema within the same database. expdp system/systempass schemas=oldschema After that I tried to import it with: impdp system/systempass expdat.dmp remap_schema=oldschema:newschema But this leads to the error: UDI-00014: invalid value for parameter, 'attach' * *Does this error tell me that newschema is not defined? *Do I have to create a new user? *Do I have to create a tablespace for such a new user? The questions also relate to a new installed 11g R2 database on a new PC. Any suggestions migrating a database to a fresh installed database are welcome! A: "Does the target database need to be prepared with tablespace and/or user (schema) in order to successfully migrate a schema from one database (11g R1) to another (11g R2)?" Tablespaces - yes. Users - no. UDI-00014: invalid value for parameter, 'attach' I think the order of parameters is incorrect when calling impdp. Should be of the form: impdp username/password DUMPFILE=<filename> [and then whatever other parameters you need for your import] Since you're doing a "migration" I assume it's a full imp/exp, in which case you probably want: impdp username/password DUMPFILE=<filename> FULL=Y With regard to your current test within the same db, I suggest you check-out: http://psoug.org/reference/datapump.html for a couple of examples A: I asume that a lot of people came here for: 'UDI-00014: invalid value for parameter' error like me. For those my situation was the following. I had a different scenario and for me it was complaining on 'remap_schema' parameter. It appeared that I need to add double quotes to values like the following: Before (failed) impdp user/password directory=dump_dir dumpfile=myfile.dmp remap_schema=my_schema:my_schema remap_tablespace=my_schema:my_schema logfile=mylog.log After (worked) impdp user/password directory=dump_dir dumpfile=myfile.dmp remap_schema="my_schema":"my_schema" remap_tablespace="my_schema":"my_schema" logfile=mylog.log A: If you are not using the ATTACH parameter during the import then open a new command line window and run the import and it should now work. For me the environment variables are the same, but some how this is now working. A: I had the same error when using the transform parameter(UDI-00014: invalid value for parameter, 'transform'), I moved the logfile bit to be the last part of the command. In other words, check the order. Before:(failed) impdp MY_CLONE/password schemas=ORIGINAL directory= db_import_dmp dumpfile=ORIGINAL.dmp logfile= CLONE.log remap_schema=ORIGINAL:MY_CLONE transform=oid:n; After:(worked) impdp MY_CLONE/password schemas=ORIGINAL directory= db_import_dmp dumpfile=ORIGINAL.dmp remap_schema=ORIGINAL:MY_CLONE transform=oid:n logfile= CLONE.log;
{ "language": "en", "url": "https://stackoverflow.com/questions/7528106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to disable android application automatic restart after a crash (Android 2.2) Is there a way to disable android application automatic restart after a crash (Android 2.2)? Application crashes and after it android restarts application. It seems that android tries to restore activity back stack and it causes issues because all data which was received from the server on login is gone. UPDATE: my application starts with login screen on which it loads some data from server and in case of restart after crash no login is done I see that there is simmilar question but without solution A: * *It has a simple solution after crashing if your activity is restarting then check at start point that this activity has all required data of login or not if it has not all the data then redirect it to login activity.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: windows phone 7, adding buttons to panel Following piece works very well in silverlight, <Grid x:Name="ContentPanelInner" Grid.Row="1" Margin="12,0,12,0"> <StackPanel x:Name="stackPanelInner"> <Grid VerticalAlignment="Top"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Grid.Column="0" Content="Ok" Width="100"/> <Button Grid.Column="1" Content="No" Width="100"/> </Grid> </StackPanel> </Grid> It just adds two buttons in the same row. When I try to do same from C#, it couldn't work. Here is my c# code: Grid g1 = new Grid(); //StackPanel innerSP = new StackPanel(); ColumnDefinition cd1 = new ColumnDefinition(); ColumnDefinition cd2 = new ColumnDefinition(); g1.ColumnDefinitions.Add(cd1); g1.ColumnDefinitions.Add(cd2); panel1.Children.Add(g1); Grid.SetColumn(buttonOk,0); Grid.SetColumn(buttonNo, 1); panel1.Children.Add(buttonOk); panel1.Children.Add(buttonNo); border.Child = panel1; // Set the Child property of Popup to the border // which contains a stackpanel, textblock and button. p.Child = border; Can someone tell me what has been wrong? A: Change this: Grid.SetColumn(buttonOk,0); Grid.SetColumn(buttonNo, 1); to this: buttonOk.SetValue(Grid.ColumnProperty, 0); buttonNo.SetValue(Grid.ColumnProperty, 1); If the buttons are supposed to be in the Grid columns (which would seem to make sense), then you should also change this: panel1.Children.Add(buttonOk); panel1.Children.Add(buttonNo); to this: g1.Children.Add(buttonOk); g1.Children.Add(buttonNo);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Optimal data structure for a special dictionary Which data structure is best in terms of computational complexity to implement a dictionary of (key,val) items, which must support only following commands: * *Insert(key) - appends an item (key,val) with val=1 *Increment(key) - increments val of existed (key,val) *Find(key) - returns a val of (key,val) *Select(part_of_key) - returns a list of all items (key,val) if strstr(key,part_of_key)!=NULL in the form of a new dictionary of the same type (without allocating new memory if possible); for example if dictionary is {(red,3), (blue,4), (green,1)}, then Select(re)={(red,3), (green,1)} *Max(i) - returns an item which has the i-th maximal value among all items; for example if dictionary is {(red,3), (blue,4), (green,1)}, then Max(1)=blue, Max(2)=red, Max(3)=green The keys are strings and the values are positive integers. The number of items in the dictionary is expected to be very large. I think it must be a synthesis of two different data structures. But should it be a hash table + a binary tree or a trie + sorted array or something else? A: A combination of balanced tree (such as red-black tree) and suffix tree (or suffix array). * *Balanced tree: operation 1, 2 (implemented as remove + insert), 3 and 5. *Suffix tree: operation 4. NOTE: Hash table will not be able to support operation 5 efficiently. I think you'll have a hard time implementing the suffix tree. You could possibly use Mark Nelson's C++ implementation of Ukkonen's algorithm, but it has memory leaks and is essentially a singleton, so you'll need to clean it up before being ready for production use. Even after you fix it, you'll need to adjust it so it works with your "other" data structure (which is balanced tree in my proposal) instead of one big plain string. If you do operation 1 more frequently than operation 4 and/or you can live with linear operation 4, I recommend you skip the whole complication with the suffix tree and just traverse your data structure linearly. A: For first three operation, hash table might be good idea. For 4th operation (select part of key), you may have to write hash function differently. Yes, hash function which was used to find/calculate hash value from given key. As you want to support partial match and your key is string, you may want to use Suffix-tree or trie. For 5th operation (ith max element), you may want to maintain heap or sorted Linked-list (or skip-list) which interacts with hash-table. You will also have to see various use-cases and find which operation should be optimized. For exa: If you have lots of query on part_of_key operation, you should use Suffix-tree/LC-trie kind of structure and that will give good results. However, your Find operation may not be fast as it will take O(logN) instead of constant look-up. To summarize, you need to integrate hash-table, heap and suffix tree to achieve all operations. A: While the exact answer depends on the frequency of your operations, your list of options should include a suffix array A: I think a trie with several shortcuts would be best. 1-3 are already supported by a trie as fast as possible (length of the key). For 4 I would add an additional table of 256 elements to all trie nodes that can be entered from that character. This way I can do fast lookup of parts of the string, without ever explicitely constructing or storing the suffixes as in a suffix tree. For 5 I would add a linked list on the leaves, that get's updated sorted when data is inserted. You would maybe need another reference to the head of the list and backlinks in the trie to find the right value and get the key. The memory complexity does not change from the trie with these additions, since it is bounded by the number of trie nodes. However the time that insertions take might change because of the inefficient sort of the linked list. The final structure should probably be called a hash-leaf-trie. But I would not want to be implementing such a beast. A: I think an efficient data base will be a modified trie, with bi-directional links [can go from leaves to the root and reconstruct the word], and each terminating node will have additional 'value' field. You will also need a multimap [i.e. a map, in which each value is a set of addresses]. The keys will be arranged in a tree like, and the set of values will be hash based. [in jave, it should be something like TreeMap<Integer,HashSet<Node>>] Pseudo-code: [well, very pseudo... it just shows the general ideas for each op]. Insert(key): 1. Insert a word into the trie 2. add the value `1` to the terminating node. 3. add the terminating field to the multimap [i.e. map.add(1,terminating_node_address)] Increment(key): 1. read the word in the trie, and store the value from the terminating node as temp. 2. delete the entree (temp,terminating_node_address) from the multimap. 3. insert the entree (temp+1,terminating_node_address) to the multimap. 4. increase the value of the terminating node's address by 1. Find(key): 1. find the terminating node for the key in the trie, return its value. Select(part_of_key): 1. go to the last node you can reach with part_of_key. 2. from this node: do BFS and retrieve all possible words [store them in an empty set you will later return]. Max(i): 1. find the i'th biggest element key in the multimap. 2. choose an arbitrary address, and return get the relevant terminating word node. 3. build the string by following the uplinks to the root, and return it. complexities: let n be the number of strings, k be the maximum value, and S a string's length. Insert: O(S) [trie insertion is O(S)]. The smallest element (1) in the map can be cached, and thus can be access at O(1). Increment: O(S+logk): find the string in a trie is O(S), finding the relevant key is O(logk), deleting element from a hash-set is O(1), finding the next element in the tree is also O(logk) [can be O(1) actually, for a skip-list based map], and inserting a value is O(1). Note that by linking the node to the relevant key in the map, complexity can even be improved to O(S), since no search is actually required. Find: O(S): just find in the trie and return the value. Select: O(S*n): at worst case you need to retrieve all elements, which enforces you to iterate the whole trie in order to find all words. Max: O(logk+S): find a key in a sorted map, reconstruct the word. EDIT: Note that in here, I assumed for find(i) you want the i'th distinct biggest element. If it is not the case, you will need to modify the set a bit, and use a multimap that allows duplicate keys [instead a set as a value]. This will make all the tree based ops O(logn) instead O(logk), still efficient in my opinion...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: CSS for Mobie site - search box and button combined 100% width? Im trying to optimise my site for mobile. Im going with a 1 column liquid layout. The issue im having is that I cant get my search box and submit button to be 100% wide. This is that I want: I cant set a fixed width for the search box (an input). It also seems to ignore width: 100% and absolute positioning. Is there anyway of achieving this? I thought maybe if I made the input an inline element it would flow to 100%, but it doesn't seem to. Thanks UPDATE - What about this: http://jsfiddle.net/jdln/3ms5f/ Ive made the search box 100% wide, but put it in a container div which has 5em of padding on the right. As the container div is 100% wide its knocks the button to the new row, but ive 'lifted' the button with absolute positioning. It seems to work well when I resize the window. I thought the layout would be more robust if I used em for the widths instead of px, which means Ive had to normalize the text sizes. Are there any issues with my solution? Thanks A: http://jsfiddle.net/jdln/3ms5f/ Ive made the search box 100% wide, but put it in a container div which has 5em of padding on the right. As the container div is 100% wide its knocks the button to the new row, but ive 'lifted' the button with absolute positioning. It seems to work well when I resize the window. I thought the layout would be more robust if I used em for the widths instead of px, which means Ive had to normalize the text sizes. A: See here: http://jsfiddle.net/chricholson/wCvVB/9/ Notice I have had to turn off the borders from both inputs as these would add up to a number greater than 100% (ie. 80% width plus 2px (the border each side)). You could make the inputs 79% and 19% respectively and then try putting a 1px border. I have put all inside a div with a width, but this could just as easily be the body tag which is by default 100% wide. A: You need to contain the input fields properly and the width needs to be relative to their container. Try something like this: CSS .searchbar { width:100%; } .searchfield, .searchbtn { float:left; } .searchfield { width:70%; margin-right:5%; } .searchfield input { width:100%; } .searchbtn { width:25%; } HTML <div class="searchbar"> <div class="searchfield"> <input type="text" name="Search" value="Search" /> </div> <div class="searchbtn"> <input type="submit" value="Search" /> </div> </div> DEMO: http://jsfiddle.net/andresilich/pHwYG/
{ "language": "en", "url": "https://stackoverflow.com/questions/7528116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL to UML diagram or graphic tool I have a database and want to output a UML Diagram. Is there software that does this? Ideally it will be UML, but a graphics representation of the database could work. A: Boxes and arrows are all you need, but I'd recommend that you try E/R tools. They are similar to UML, but intended for relational databases. A good one can import and export SQL, which you won't get from a UML tool. If you use MySQL, the MySQL Workbench does a very nice job, indeed. A: You can use Erwin Data Modeler, Embarcadero's ER Studio, or Microsoft's Visio. For a longer list visit this site http://www.databaseanswers.org/modelling_tools.htm. A: Enterprise Architect from Sparx Systems is a commercial UML modelling tool, with data(base) modelling facilities which include forward (to SQL) and reverse (from ODBC) schema engineering. It supports most of the biggest databases, including Oracle, Sybase, MySQL, Access, SQL Server and PostgreSQL. A: I would recommend to use the Dali plugin of Eclipse. You just need a jdbc conncetor and can create java code from your database. From java code you then just reverse engineer the code into UML model in order to get class diagrams. A: The IntelliJ IDEA built-in Database tool window does perfect job and supports a load of DBMS types. Generate a diagram for a database object In the Database tool window (View | Tool Windows | Database), right-click a database object and select Diagrams | Show Visualization. The resulting ERD can then be exported in multiple formats: A: actually i found a software that do what you want it is called draw.io its main use is to create diagrams but if you went to arrange section then insert and chose advanced you will find SQL where you can put your SQL code and it will make it as diagram
{ "language": "en", "url": "https://stackoverflow.com/questions/7528118", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Image managing library I have a little projet that will do basicly 3 steps * *Upload image from your computer *place it under another photo, only the face missing *Scale it, rotate it, move it in place *save the muckup and send it by email It's a electonis version of the plywood board you put your face in the hole to have your friend take a photo of you. If you know http://www.elfyourself.com/ it's something like that, without the dancing ! QUESTION : I know PHP, jQuery, Javascript and NO FLASH.Do you know a library already done that manage upload-scale-rotate and how do you do that, without reinventing the wheel Or it'a a thing for flash, wich library will you used ? Thanks in advance A: From my comment: This can be done a day or two days using PHP (gd or imagick) and jQuery. The user can manipulate the image client side using jQuery and then send the info to the server which will then generate a whole image out of the two. I did something similar for a facebook app a while ago. Found it: http://apps.facebook.com/gongum_til_gods/?ref=ts You could use the same method except you put the movable image under the main image and then overlay an invisible div on top to move the underlaying image. I'm sure you'll figure it out :p The source code is a bit messy but I had a tight deadline: <?php require_once 'facebook-php-sdk/src/facebook.php'; $facebook = new Facebook(array( 'appId' => 'xxx', 'secret' => 'xxx', 'cookie' => true, )); $session = $facebook->getSession(); $me = null; if ($session) { try { $uid = $facebook->getUser(); $me = $facebook->api('/me'); } catch (FacebookApiException $e) { error_log($e); } } if(!$me) { $url = "https://graph.facebook.com/oauth/authorize?" ."client_id=xxx&" ."redirect_uri=http://apps.facebook.com/gongum_til_gods/&" ."scope=user_photos,publish_stream"; ?> <!doctype html> <html xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>Göngum til góðs</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <script language=javascript>window.open('<?php echo $url ?>', '_parent', '')</script> </head> <body> Hleð.... </body> </html> <?php exit; } else { $path = 'photos/'.$uid.'.jpeg'; $photo_url = 'https://graph.facebook.com/'.$uid.'/picture/?type=large'; $photo_url_small = 'https://graph.facebook.com/'.$uid.'/picture/'; $watermark = imagecreatefrompng('spor.png'); $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); $image = imagecreatefromjpeg($photo_url); $image_width = imagesx($image); $image_height = imagesy($image); $canvas = imagecreatetruecolor($image_width, $image_height); imagecopy($canvas, $image, 0, 0, 0, 0, $image_width, $image_height); # ratio is less than 1 if the image is smaller than 200px; if($image_height < $watermark_height) { $ratio = $image_height / 200; } else { $ratio = 1; } #downscale the image only if the height of the profile picture is less than 200px; $new_width = $watermark_width * $ratio; $new_height = $watermark_height * $ratio; #lower right corner: $dest_y = $image_height - $new_height; $dest_x = $image_width - $new_width; $commit = isset($_REQUEST['commit']); if($commit) { $x = $_REQUEST['x']; $y = $_REQUEST['y']; $r = $_REQUEST['ratio']; #downscale to request ratio. $new_width = $watermark_width * $r; $new_height = $watermark_height * $r; imagecopyresampled($canvas, $watermark, $x, $y, 0, 0, $new_width, $new_height, $watermark_width, $watermark_height); imagejpeg($canvas, $path, 100); imagedestroy($canvas); imagedestroy($image); imagedestroy($watermark); $facebook->setFileUploadSupport(true); $args = array('message' => 'Göngum til góðs'); $args['image'] = '@' . realpath($path); $data = $facebook->api('/me/photos', 'post', $args); } elseif(isset($_REQUEST['set_status'])) { $data = $facebook->api('/me/feed', 'post', array( 'message' => $_REQUEST['set_status'], 'picture' => 'http://static.jl.is/gtg/img/logo1.png', 'link' => 'http://apps.facebook.com/gongum_til_gods/', 'name' => 'GÖNGUM TIL GÓÐS', 'caption' => 'Smelltu hér til að vera með', 'description' => "Vertu einn af 3000 sjálfboðaliðum og settu fótspor á myndina þína. Landssöfnun Rauða krossins, Göngum til góðs, fer fram laugardaginn 2. október. Þá verður þörf fyrir 3000 sjálfboðaliða og eru því allir sem vettlingi geta valdið hvattir til þátttöku. Söfnunarfénu verður varið til verkefna Rauða kross Íslands í Afríku. Sérstaklega er um barna- og ungmennaverkefni í Malaví og Síerra Leóne að ræða. Í Malaví þar sem verkefnin fara æ vaxandi, aðstoðar Rauði krossinn börn sem eiga um sárt að binda vegna alnæmis og í Síerra Leóne er unnið að stuðningi við stríðshrjáð börn og barnahermenn." )); print_r($data); exit; } $photo_url = $photo_url.'&no-cache='.mt_rand(1,9999); } ?> <!doctype html> <html xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title>Göngum til góðs</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <link type="text/css" rel="stylesheet" href="style.css" /> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <script src="script.js"></script> <script type="text/javascript"> var overlay_height = <?php echo $new_height ?>; var overlay_width = <?php echo $new_width ?>; var overlay_pos_x = <?php echo $dest_x ?>; var overlay_pos_y = <?php echo $dest_y ?>; var image_height = <?php echo $image_height ?>; var image_width = <?php echo $image_width ?>; $(document).ready(function() { $('#img-container .overlay').each(function() { $(this).height(overlay_height); $(this).width(overlay_width); $(this).css({top: overlay_pos_y, left: overlay_pos_x}); $(this).draggable({ containment: 'parent', stop: function(event, ui) { var pos = $(this).position(); overlay_pos_x = pos.left; $('#x-axis').val(pos.left); overlay_pos_y = pos.top; $('#y-axis').val(pos.top); } }) }); $('#slider').slider({ min: 0.65, max: <?php echo $ratio; ?>, step: 0.001, value: <?php echo $ratio; ?>, slide: function(event, ui) { var height = ui.value * <?php echo $watermark_height ?>; var width = ui.value * <?php echo $watermark_width ?>; if(height + overlay_pos_y > image_height) { $('#img-container .overlay').css({top: image_height - height}); } if(width + overlay_pos_x > image_width) { $('#img-container .overlay').css({left: image_width - width}); } $('#img-container .overlay').height(height); $('#img-container .overlay').width(width); $('#ratio').val(ui.value); } }); $('#status-update input').autoGrowInput({ comfortZone: 10, minWidth: 67, maxWidth: 200 }).keyup(); $('#status-update input').focus(function() { if($(this).val() == 'mína götu') { $(this).val('').keyup(); } }); $('#status-update input').blur(function() { if($(this).val() == '') { $(this).val('mína götu').keyup(); } }); $('#status-update button').click(function() { // get the parent li var $p = $(this).parent(); // replace input with input value var input_string = $p.find('input').val(); $p.find('input').after(input_string); $p.find('input').remove(); $p.find('tester').remove(); // remove all buttons $('#status-update button').remove(); // get clean text before appending ajax-loader var text = $p.html(); // show ajax loader gif $p.append('<img class="ajax-loader" src="img/ajax-loader.gif" />'); // send ajax request to self $.ajax({ type: "POST", data: "set_status= " + text, success: function(msg) { //remove ajax-loader on success $('.ajax-loader').remove(); //show that the ajax call was successful $p.append('<img class="ajax-loader" src="img/loaded.png" />'); //show a facebook link: $('#fb-back').show(); //alert(msg); }/*, error: function() { alert('Ajax request error!'); }*/ }); }); }); </script> <style type="text/css"> #status-update li { background-image:url('<?php echo $photo_url_small ?>'); } </style> </head> <body> <div id="fb-root"></div> <script> (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root').appendChild(e); }()); window.fbAsyncInit = function() { FB.init({ appId : '<?php echo $facebook->getAppId(); ?>', session : <?php echo json_encode($session); ?>, // don't refetch the session when PHP already has it status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true // parse XFBML }); // whenever the user logs in, we refresh the page FB.Event.subscribe('auth.login', function() { window.location.reload(); }); }; </script> <?php if($me) { if($commit or isset($_GET['test_commit'])) { ?> <div style="position:relative;height:230px;"> <div style="position:relative;z-index:1;"> <h1>Núna ertu búin/-n að setja &bdquo;Göngum til góðs&rdquo;<br/> fótspor inná mynd í myndasafni</h1> <ol> <li>Farðu inn í myndasafn</li> <li>Veldu myndina</li> <li>Gerðu hana að forsíðumynd</li> </ol> </div> <img style="float:none;position:absolute;right:-10px;top:-20px;z-index:0;" src="img/instructions.png" /> <img style="float:none;position:absolute;right:265px;top:143px;z-index:1;" src="img/rarr-tp.png" /> <div style="position:absolute;bottom:0;left:0;z-index:2;" class="line"></div> </div> <div style="position:relative;z-index:2;width:380px;float:left;"> <p style="margin-left:10px;">Hér fyrir neðan eru nokkrar tillögur að<br/>&nbsp;&nbsp;skilaboðum sem hægt er að setja inn.</p> <ul id="status-update"> <li>Ég tek <input type="text" name="street" value="mína götu" /> laugardaginn 2. október!<button></button></li> <li>Ég geng til góðs á laugardaginn, en þú?<button></button></li> <li>Ég ætla að ganga til góðs laugardaginn 2. október!<button></button></li> </ul> <img src="img/logo2.png" style="margin-top:60px;"/> </div> <div style="float:left;width:340px;margin: 50px 0 0 40px;"> <h1><a target="_NEW" href="http://rki.is/flex/gtg/" style="color:inherit;text-decoration:none;">Skráðu þig hér til að taka<br/>þátt í göngunni</a></h1> <p>Kærar þakkir fyrir að taka þátt í þessu með okkur hérna á Facebook. Sjáumst í göngunni, laugardaginn 2. október.<br/>Hvert skref skiptir máli.</p> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <br/> <center><a id="fb-back" target="_parent" href="http://www.facebook.com">Fara aftur á facebook</a>&nbsp;&nbsp;&nbsp;&nbsp;</center> </div> <?php } else { ?> <h1>Hvernig á að setja fótspor &bdquo;Göngum til góðs&rdquo; inn á Facebook mynd</h1> <ol> <li>Forritið velur forsíðumyndina sem þú ert að nota núna</li> <li>Hægt er að færa fótspor með því að draga það til og/eða breyta stærð þess með því að færa stikuna</li> <li>Þegar þú ert ánægð/-ur með myndina ýtir þú á &bdquo;Búa til mynd&rdquo;</li> <li>Nýja myndin birtist í nýju myndasafni og þar getur þú gert hana að forsíðumynd</li> </ol> <div id="lwrapper"> <div id="images"> <div class="bg left source"> <img src="<?php echo $photo_url ?>" /> </div> <div class="bg float"> <div id="img-container" style="height:<?php echo $image_height ?>px"> <img class="photo" src="<?php echo $photo_url ?>" /> <img class="overlay" src="spor.png" /> </div> </div> <div class="clr"></div> </div> <div id="extra"> <img id="logo" class="left" src="img/logo.png" /> <div class="left pa"> <div id="slider"></div> <img id="darr" src="img/darr.png" style="margin: 18px 0 18px 86px;" /> <div class="clr"></div> <div id="buttons" style="text-align:center;"> <form method="POST"> <input type="hidden" id="ratio" name="ratio" value="<?php echo $ratio ?>"/> <input type="hidden" id="x-axis" name="x" value="<?php echo $dest_x ?>"/> <input type="hidden" id="y-axis" name="y" value="<?php echo $dest_y ?>"/> <input type="submit" name="commit" value="Búa til mynd" /> </form> </div> </div> <div class="clr"></div> </div> </div> <?php } } ?> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7528120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPA 1.0: How to write an efficient transformer from an entity to a transfer object? I want to write an efficient transformer, that will transform a JPA (1.0) entity to my transfer object and that: * *will be called in a transactional context, *will cause no extra DB interaction, that is will transform only what's already loaded. I cannot use the construct if (entity.getSomething() != null) as "something" will get loaded. The only thing I can think of is having the transformer spawn a new transaction, reload the entity in the new transaction's context and commit it — and then working on a detached entity. It does involve a reload, though. Any cleverer ideas? A: You may use XStream to transform your Entity[Implicitly Serializable] to XML & to de-serialize back to object. It may not be the effcient one, but fast & easy to implement. I am successfully using the same process for a project. A: ORM proxy stuff can be helped with using Gilead. http://noon.gilead.free.fr/gilead/ A: JPA provides a PersistenceUnitUtil class with an isLoaded() API that can be used to determine if a relationships is loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get a user input in google maps using custom controls? I have custom controls on my map with this tutorial http://code.google.com/apis/maps/documentation/javascript/controls.html#CustomDrawing how can I create input boxes with something similar to this, so I could pass user input values e.g. numbers to my javascript for further use? A: It isn't that different to add inputs, buttons or labels instead of divs. I put together an example on jsfiddle. A: If you want to create custom controls that happen to be input buttons, it works in a manner very similar to the way in the link you've posted. Instead of a div, you'll need to make an input. The code would look something like this: //create your control HTML var controlDiv = document.createElement('DIV'); var controlInput = document.createElement('INPUT'); controlInput.name = "inputName"; controlInput.type = "text"; controlDiv.appendChild(controlInput); //create your control javascript (e.g. any handlers that you need) var myControl = MyControl(controlDiv) //add the control to your map map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv); As you've already mentioned, the tutorial should cover most of the issues you're encountering, you just need to ensure that you create an input element and get values from that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Chronometer format change to 0:0 to 00:00? i want chronometer star like this, if it is at 0:5 (M:S) i want like this 00:05 this is the code i am using : stopWatch = (Chronometer) findViewById(R.id.chrono); stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){ @Override public void onChronometerTick(Chronometer arg0) { countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000; String asText = (countUp / 60) + ":" + (countUp % 60); time_view.setText("Time : " +asText); } }); stopWatch.start(); where i have to change for that modification.. A: You could use NumberFormatter NumberFormat formatter = new DecimalFormat("00"); stopWatch = (Chronometer) findViewById(R.id.chrono); stopWatch.setOnChronometerTickListener(new OnChronometerTickListener(){ @Override public void onChronometerTick(Chronometer arg0) { countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000; String asText = formatter.format(countUp / 60) + ":" + formatter.format(countUp % 60); time_view.setText("Time : " +asText); } }); stopWatch.start(); Some more number format examples A: Here is an easy and smart solution for time format 00:00:00 in chronometer in android Chronometer timeElapsed = (Chronometer) findViewById(R.id.chronomete); timeElapsed.setOnChronometerTickListener(new OnChronometerTickListener(){ @Override public void onChronometerTick(Chronometer cArg) { long time = SystemClock.elapsedRealtime() - cArg.getBase(); int h = (int)(t/3600000); int m = (int)(t - h*3600000)/60000; int s= (int)(t - h*3600000- m*60000)/1000 ; String hh = h < 10 ? "0"+h: h+""; String mm = m < 10 ? "0"+m: m+""; String ss = s < 10 ? "0"+s: s+""; cArg.setText(hh+":"+mm+":"+ss); } }); timeElapsed.setBase(SystemClock.elapsedRealtime()); timeElapsed.start();
{ "language": "en", "url": "https://stackoverflow.com/questions/7528127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: $facebook->getUser() always return zero Hi I m integrating facebook connect functionality in my website. So I used facebook new graph api. I used following code.. ............. ............. $facebook = new Facebook(array( 'appId' => $fbconfig['appid'], 'secret' => $fbconfig['secret'], )); $uid = $facebook->getUser(); var_dump($uid); if($uid) { //do someting } else ...... but problem is that $uid always comes zero. Why this is happening. Please help.. A: Try This $user = null; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, )); $user = $facebook->getUser(); if ($user) { echo "user"; } else { echo("<script language=\"javascript\">"); echo("top.location.href = \"http://apps.facebook.com/myapp\";"); echo("</script>"); exit; } A: this is code by which you can login with fb account.. <?php $cookie = get_facebook_cookie(FACEBOOK_APP_ID, FACEBOOK_SECRET); if(isset($cookie)) { $first_name = json_decode(@file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->first_name; $last_name = json_decode(@file_get_contents('https://graph.facebook.com/me?access_token=' .$cookie['access_token']))->last_name; } ?> <script src="http://connect.facebook.net/en_US/all.js"></script> <script> FB.init({appId: <?php echo FACEBOOK_APP_ID;?>, status: true, cookie: true, xfbml: true}); FB.Event.subscribe('auth.logout', function(response) {}); FB.Event.subscribe('auth.sessionChange', function(response) { if (response.session) { FB.api('/me', function(response) { if(response.id!='undefined') { window.location='Fbaccess.php?first_name='+response.first_name+'&last_name='+response.last_name+'&email='+response.email; } else { window.location='login.php'; } }); } else { // The user has logged out, and the cookie has been cleared } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7528128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: splitting a huge sql file to multiple sql files I have a huge SQL file that I want to restore to mysql server 5.5 .... while I'm restoring the the file at the middle of restoring process stopped, then i got an idea to split that file to several files using java ... is anybody got the the idea how to split the SQL file into several files ..... the following code is for the java class that i create to split the SQL file... this class can create for each line in the sql huge file a file"which is not usable", i would like to split the SQL file so i can have files which is able to be restored in the mysql-server import java.io.*; import java.io.FileWriter; class DataBase { public static void main(String args[]){ try{ FileInputStream fstream = new FileInputStream("D:/dewiki-20110831-site_stats.sql"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; File f; int i=1; while ((strLine = br.readLine()) != null){ f=new File("D:/myfile"+i+".sql"); if(!f.exists()){ f.createNewFile(); PrintWriter out = new PrintWriter(new FileWriter(f)); out.write(strLine); out.close(); } System.out.println (strLine); i++; } in.close(); }catch (Exception e){ System.err.println("Error: " + e.getMessage()); } } } A: Just wondering why the process interrupts halfway through? How are you importing the database? Just asking because from what I've experienced it's easy to do through the MySQL console or similar using the SOURCE command. At least up to 50-60mb. A: Try using mysqldbimport instead. A: actually there is no need to split the file into several files and store them to the database ... i found a way where you can restore the database to mysql which is using mysql commands here is the command that i used: mysql - u user_name -p your_password database_name < file_name.sql it works for me ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Copy XValues from one TChartSeries to another Does anyone know how to copy the XValues from one TChartSeries to another in Delphi7 (and TeeChart 4.04)? TChartSeries.ReplaceList(CopySeries.XValues, OriginalSeries.XValues) does not work, since it seem to replace the reference, so when OriginalSeries is changed, so is CopySeries. The length of CopySeries is equal or greater than OriginalSeries. I want to preserve the CopySeries.YValues. My workaround has been to create a temporary list Dummy := TChartSeries.Create(nil); Dummy.AssignValues(OriginalSeries); CopySeries.ReplaceList(CopySeries.XValues, Dummy.XValues); Dummy.YValues.Destroy; but I get a memory leakage since I cannot Destroy the Dummy since that also removes the Dummy.XValues referenced by CopySeries.XValues. Any help is greatly appreciated. A: I can think of two options: * *Assigning ValueList arrays directly to the series as in the Real-time Charting article, for example: uses Series; procedure TForm1.FormCreate(Sender: TObject); begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues; Chart1.AddSeries(TLineSeries.Create(Self)); { set our X array } Chart1[1].XValues.Value:=Chart1[0].XValues.Value; { <-- the array } Chart1[1].XValues.Count:=Chart1[0].Count; { <-- number of points } Chart1[1].XValues.Modified:=True; { <-- recalculate min and max } { set our Y array } Chart1[1].YValues.Value:=Chart1[0].YValues.Value; Chart1[1].YValues.Count:=Chart1[0].Count; Chart1[1].YValues.Modified:=True; { Show data } Chart1.Series[1].Repaint; end; *Clone series: uses Series; procedure TForm1.FormCreate(Sender: TObject); begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues; Chart1.AddSeries(CloneChartSeries(Chart1[0])); end; *If you are using TeeChart 4.04 you'll probably have to address series like Chart1.Series[0] instead of Chart1[0] as in the Repaint call in the first example. Alternatively you could try something like this: uses Series, Math; procedure TForm1.FormCreate(Sender: TObject); var i, MinNumValues, MaxNumValues: Integer; begin Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues(15); Chart1.AddSeries(TLineSeries.Create(Self)).FillSampleValues(25); MinNumValues:=Min(Chart1.Series[0].Count, Chart1.Series[1].Count); MaxNumValues:=Max(Chart1.Series[0].Count, Chart1.Series[1].Count); for i:=0 to MinNumValues -1 do Chart1.Series[1].XValue[i]:=Chart1.Series[0].XValue[i]; for i:=MinNumValues to MaxNumValues-1 do Chart1.Series[1].ValueColor[i] := clNone; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/7528132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: show statusbar in camera imagePicker I am woking on imagePicker where i need to show camera with some overlay view.But it's hiding status bar please tell me how i can show it here is a code imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.delegate = self; imagePickerController.sourceType = sourceType; imagePickerController.showsCameraControls = NO; imagePickerController.cameraViewTransform = CGAffineTransformScale(imagePickerController.cameraViewTransform, 0.5f, 0.5f); imagePickerController.cameraOverlayView = self.tabBarController.view; self.navigationController.navigationBarHidden = YES; imagePickerController.navigationBar.barStyle = UIBarStyleBlack; [self presentModalViewController:imagePickerController animated:YES]; A: try this [[UIApplication sharedApplication] setStatusBarHidden:NO animated:NO]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7528136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google toolbar in C# web browser? I am working on web Browser in C# and I want to ask if is possible to integrate google toolbar somehow? I am looking for some easy solution to block pop up windows and google toolbar includes this protection. Any ideas would be appreciated Thanks for answers. choze88, Czech Republic. A: It should be possible if you write a host for Browser Helper Objects, the interface used for the Google Toolbar.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jquery select that effects the amount of images I have a table with multiple rows, each row has: * *layout (select) *images * 10 The amount of images depends on the layout selected. I want to write some jquery code that hides/shows the amount of images depending on the layout selected/changed. At the moment I have this which doesn't work correctly and only shows 1 image each time. $('select.layouts').bind("change keyup",function(){ var val = $(this).val(); switch(val){ case 1: showImgs = 1; break; case 2: showImgs = 2; break; case 3: showImgs = 3; break; case 4: showImgs = 4; break; default: showImgs = 1; } $(this).parents("tr").find(".images .image:lt("+showImgs+")").show(); }) Also would it be best practice to instead of adding how many images per layout into the JS code, I have a data attribute to the select option? HTML Table <table class="list" id="images"> <thead> <tr> <td>Layout:</td> <td>Image:</td> </tr> </thead> <tbody id="image-row0"> <tr> <td> <select class="layouts" name="banner_image[0][layout]"> <option value="1">Layout 1</option> <option selected="selected" value="2">Layout 2</option> <option value="3">Layout 3</option> <option value="4">Layout 4</option> <option value="5">Layout 5</option> <option value="6">Layout 6</option> <option value="7">Layout 7</option> <option value="8">Layout 8</option> <option value="9">Layout 9</option> <option value="10">Layout 10</option> </select> </td> <td class="left images"> <div style="display: none" class="image"> <label for="thumb0">Image 1</label><br> <input type="hidden" id="image0" value="data/slides/dd1.png" name="banner_image[0][image]"> <br> </div> <div style="display: none" class="image"> <label for="thumb20">Image 2</label><br> <input type="hidden" id="image20" value="data/slides/dd1.png" name="banner_image[0][image2]"> <br> </div> <div style="display: none" class="image"> <label for="thumb30">Image 3</label><br> <input type="hidden" id="image30" value="data/slides/dd1.png" name="banner_image[0][image3]"> <br> </div> <div style="display: none" class="image"> <label for="thumb40">Image 4</label><br> <input type="hidden" id="image40" value="data/slides/dd1.png" name="banner_image[0][image4]"> <br> </div> <div style="display: none" class="image"> <label for="thumb50">Image 5</label><br> <input type="hidden" id="image50" value="data/slides/dd1.png" name="banner_image[0][image5]"> <br> </div> <div style="display: none" class="image"> <label for="thumb60">Image 5</label><br> <input type="hidden" id="image60" value="data/slides/dd1.png" name="banner_image[0][image6]"> <br> </div> </td> </tr> </tbody> <tbody id="image-row1"> <tr class="odd"> <td> <select class="layouts" name="banner_image[1][layout]"> <option selected="selected" value="1">Layout 1</option> <option value="2">Layout 2</option> <option value="3">Layout 3</option> <option value="4">Layout 4</option> <option value="5">Layout 5</option> <option value="6">Layout 6</option> <option value="7">Layout 7</option> <option value="8">Layout 8</option> <option value="9">Layout 9</option> <option value="10">Layout 10</option> </select> </td> <td class="left images"> <div style="display: none" class="image"> <label for="thumb0">Image 1</label><br> <input type="hidden" id="image0" value="data/slides/dd1.png" name="banner_image[0][image]"> <br> </div> <div style="display: none" class="image"> <label for="thumb20">Image 2</label><br> <input type="hidden" id="image20" value="data/slides/dd1.png" name="banner_image[0][image2]"> <br> </div> <div style="display: none" class="image"> <label for="thumb30">Image 3</label><br> <input type="hidden" id="image30" value="data/slides/dd1.png" name="banner_image[0][image3]"> <br> </div> <div style="display: none" class="image"> <label for="thumb40">Image 4</label><br> <input type="hidden" id="image40" value="data/slides/dd1.png" name="banner_image[0][image4]"> <br> </div> <div style="display: none" class="image"> <label for="thumb50">Image 5</label><br> <input type="hidden" id="image50" value="data/slides/dd1.png" name="banner_image[0][image5]"> <br> </div> <div style="display: none" class="image"> <label for="thumb60">Image 5</label><br> <input type="hidden" id="image60" value="data/slides/dd1.png" name="banner_image[0][image6]"> <br> </div> </td> </tr> </tbody> </table> EDIT: @Kalle H. Väravas code var layouts_data = { 0: { name: 'None', images: 0 }, 1: { name: 'Layout 1', images: 1 }, 2: { name: 'Layout 2', images: 4 }, 3: { name: 'Layout 3', images : 6 }, 4: { name: 'Layout 4', images: 4 }, 5: { name: 'Layout 5', images: 5 } }; SetLayout = function (row, layoutid) { var current_layout = layouts_data[layoutid]; $(row).find('.image').hide().each(function (i, elm) { if ((i + 1) <= current_layout['images']) { $(elm).show(); } }); }; $(document).ready(function () { $('#images tbody tr').each(function(i, elm) { SetLayout($(this), $(this).find('select.layouts option:selected').val()); }); }); // Lets catch the event $('select.layouts').bind("change keyup", function () { SetLayout($(this).parents("tr"), $(this).val()); }); A: Replace your switch statement with: var showImgs = 1; if (val < 5) showImgs = val; I'd probably run val through parseInt(val, 10) for good measure too. A: I'm not sure if this will solve your problem, but at the moment your switch statement always drops into the 'default' case as it's trying to match an integer and the value in the val variable is a string. Doing a parseInt should fix it- switch(parseInt(val)){ A: Revision 1 As reading your comments and understand the issue better. I have composed a nice little layout-array. This way you can store more data and basically just pick the layout with the select. http://jsfiddle.net/hobobne/FxU6V/1/ General idea stays the same, but little bit more complex. Original I might have understood you wrong, but this is what I got to offer: <style> .imgs {margin: 5px; width: 100px; height: 100px; float: left; display: none;} </style> Show how many images: <select name="show-images"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> <div class="imgs" style="background: yellow;"></div> <div class="imgs" style="background: blue;"></div> <div class="imgs" style="background: green;"></div> <div class="imgs" style="background: brown;"></div> <div class="imgs" style="background: pink;"></div> <script> $('select[name="show-images"]').bind("change keyup", function () { var images_amount = $('select[name="show-images"] option:selected').text(); $('.imgs').hide().each(function (i, elm) { if ((i + 1) <= images_amount) { $(elm).show(); } }); }); </script> [ View output ] For this example, I used colorful containers instead of the images, but technically it doesn't matter. And as you can see, the fiddle contains comments, so you can understand each step :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binary Writer returns byte array of null I'm working with the MRIM (Mail.Ru Agent) protocol. MRIM is a binary protocol, so in order to make the data binary, I'm using the BinaryWriter class. Here's the code: private byte[] CreateMrimPacket(ulong message) { byte[] binaryData; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(CS_MAGIC); //CS_MAGIC is a constant that doesn't equal 0 bw.Write(PROTO_VERSION); //Same thing bw.Write((ulong)SeqCounter); bw.Write(message); bw.Write((ulong)0); bw.Write((ulong)0); bw.Write((ulong)0); bw.Write((ulong)0); bw.Write((ulong)0); bw.Write((ulong)0); bw.Write((ulong)0); binaryData = new byte[ms.Length]; ms.Read(binaryData, 0, binaryData.Length); } } return binaryData; } This function returns byte array but all the values are 0. Please, help me to solve this problem. Thanks in advance A: You're writing to the stream, leaving it at the end of the data you've written, and then reading from it. There's no data at the current position! You could use ms.Position = 0; before reading... but fortunately, it's easier than you're making it anyway... just use: return ms.ToArray(); MemoryStream.ToArray returns all the data in the stream, regardless of the current position (and also regardless of whether the stream is closed or not).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WCF web service removing svc extension adds .svc to all extensions I've applied an URL Rewrite rule in IIS 7 as follows: Pattern: ^([0-9a-zA-Z-]+)/([0-9a-zA-Z-./()]+) RewriteUrl: {R:1}.svc/{R:2} This works perfect when I call my service like so: http://mysite/site/myservice/input/params The issue I am faced with is that all other links to HTML files within my project seem to have been appended with .svc, for example this code does not work: < link rel="stylesheet" type="text/css" href="StyleSheet/StyleSheet.css" /> When I try to navigate to the URL in a web browser I receive an error message as follows: the resource cannot be found: Requested URL: /site/stylesheet*.svc*/stylesheet.css IIS seems to correctly remove svc when it is present, but adds it in cases where it is not present. Any ideas?? A: What you're describing is in fact the correct behavior given how the rewrite rule is defined. Remember, the rule basically says, for any incoming URL that matches the pattern ^([0-9a-zA-Z-]+)/([0-9a-zA-Z-./()]+), rewrite it so that .svc is appended to the 1st group. Obviously, that's not what you want. Hence, you need to insure that the rewrite is only applied to some URLs, i.e. your service calls. I'd suggest to place all your .svc files in a dedicated subfolder, e.g. "services", and change the rule like so: ^services/([0-9a-zA-Z-]+)/([0-9a-zA-Z-./()]+) That way, only service URLs will be rewritten, and all others won't be touched as they don't match the pattern any longer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# Block threads of unmanaged code Suppose we have an unmanaged process which loads a managed DLL. Within the DLL there is the need to block some or all threads of the unmanaged application to synchronize concurrent access to some memory. How can one block those unmanaged threads? I only have the binary of the unmanaged application, so no recompile is possible. A: I call to your attention the "Remarks" section of the docs for the SuspendThread API function: This function is primarily designed for use by debuggers. It is not intended to be used for thread synchronization. (emphasis mine) That should suggest to you that what you're trying is a bad idea. So should the fact that the managed API for suspending threads (Thread.Suspend) turned out to be so problematic that Microsoft actually removed it from the .NET Framework. The fact is, you cannot safely suspend a thread in the same process as you, without some cooperation from that thread. As one example, you could end up suspending another thread while it's in the middle of allocating memory, and has a lock on the heap's control structure. Bam: your thread will deadlock if you try to do anything that allocates memory, which includes JIT-compiling your .NET code. (And the heap lock is just one possible deadlock out of many. And there are race conditions. Just don't do it.) As Hans said in the comments above, you cannot implement thread-safe code by suspending threads. You must cooperate with the other thread, by sharing a synchronization object (mutex, slim reader/writer lock, monitor, etc.) and having both sides appropriately signal that synchronization object to say "I'm starting to access this shared resource" and "I'm done". If one side won't cooperate, then you cannot have thread safety. If you really must suspend your unmanaged app to update memory locations, and you really can't get that app's cooperation, the safest way would probably be to forget about writing an in-process DLL, and instead look to the debugger API. Here's an article that demos how to use some of the debugger API from .NET. Make your app a separate process that attaches to your unmanaged app as a debugger (either by attaching after the app is launched, or by starting the app under debug control), and can then control it from outside just as if you were running the unmanaged app under the Visual Studio debugger -- suspend, modify memory, resume. Now that you're in a separate process, you aren't sharing the heap lock (or most of the other deadlock problems) with the app you're trying to suspend -- so the reasons to avoid SuspendThread largely go away. Since you are writing a debugger (of sorts), now calling SuspendThread is appropriate. But you'll still have to deal with the race conditions yourself. Think carefully about what happens if another thread is halfway through writing to your block of memory. (When you resume that thread, it'll write the other half, corrupting the data you just put there.) And what if another thread is halfway through reading your block of memory -- if it's read the first few bytes, made a decision based on them, and is about to read the next few bytes? If it just read that memory, has a copy of it in its registers, and is about to write it back with changes? Tread carefully.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: header guard conundrum - already defined in .obj problem I have a class (A) which has to include two files, class X and class Y. unfortunately class Y also needs to include class X in it's header file because the constructor takes a pointer to a class X type as an argument. The potential problem is that there would be a linker error? as class A now has two copies of class X in it, one that it needs to use, and one from class Y. This is the situation where header guards are of no use. My question is - is this purely a structural problem or is there a way around this? I really would prefer to not include anything in class Y's header file, in case I want to include THAT in anything else, but is it necessary because of the function prototype? A: If you have the following: X.h #ifndef X_H__ #define X_H__ class X { public: int foo() { return 1; } }; #endif Y.h #ifndef Y_H__ #define Y_H__ #include "X.h" class Y { public: Y(X *pX) { myval = pX->foo(); } int myval; }; #endif something.cpp #include "X.h" ... something_else.cpp #include "Y.h" ... Then there should be no problem. However, if X.h instead looks like this: #ifndef X_H__ #define X_H__ class X { public: int foo(); }; int X::foo() { return 1; } #endif then you will indeed get a linker error when you try to link something.cpp and something_else.cpp. X::foo will have been defined non-inline into two separate translation units. A: You can use a declaration in the Y header. class X; Since you only use a pointer to X the compiler doesn't need to know it's definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: find & replace commas with newline on Google Spreadsheet I've been trying to figure out how to replace commas with line-breaks. I've tried using (/r/n/), char(10), the Unicode representation (can't remember now), but it rather predictably replaces the comma with whatever I type in the other box, not converting it to a line-break A: IF you are trying to use the Ctrl+F to find and replace well you can't. at least I dont know how. but if you have a cell say A1 that contains the following : "stack,overflow" then if you type this in A2 it should work: =SUBSTITUTE(A1, ",", char(10)) https://support.google.com/docs/bin/static.py?hl=en&topic=25273&page=table.cs you can then copy the content of A2 and in A3 right click -> Paste Special... -> Values Only. Hope this helps UPDATE 2016-AUG Google Spreadsheet now support searching for newline using \n here is how: Edit -> Find and Replace A: If I properly understood you want to obtain something like that: The trick I discovered is this one: * *you insert an expression as =SUBSTITUTE(A3,",","") *then edit the formula you've just types, you placed the cursor in between the latest two double quotes: =SUBSTITUTE(A3,",","<PLACE CURSOR HERE>") *and finally you press CTRL+ENTER. This is the way to insert a "new line" character. A: This response doesn't specifically answer the original question, but it is a similar use-case that I found which may help someone else. If you are searching for a newline character with other text and you want your replace to keep the newline character, here's one way you can do it. My example searches for newline plus space and then replaces it with just a new line. Find: (\n)\s Replace: $1 It would be nice if google allowed regex in the replace field, but this might help someone if the newline character is part of the search parameters and needs to be included in the replace portion. NOTE: Per Google's documentation, replace groups only work with Sheets. (as of July 13, 2017) A: Using the substitute formula gmansour mentioned above works in the new google sheets. However, doing a Find and Replace (CTRL H) does not. I tried using char(10) as a replace and only shows "char(10)". A: example using formula to parse =SPLIT(A14,CHAR(10)) A: To change all ">"(greater than) to ">\n"(greater than followed by a newline), I took this 3 step circuitous approach. * *Copy the text onto LibreOffice "Text document" *Edit => Find & Replace // shortcut: Ctrl + H *Fill out 3 fields(boxes 1~3 in the below figure) there and click "Replace All" button. A: Use the "replace using regular expressions" option. Then the target is \n and the replacement is , (i.e., comma followed by space).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Multiple consumers and querying a C# BlockingCollection I am using a .NET 4.0 BlockingCollection to handle a queue of items that each need to be processed by an operation that can take up to a second to process each item. This queue of items can be added to by different threads. I have a couple of questions regarding this a) allowing multiple consumers to work on this BlockingCollection? I noticed GetConsumingEnumerable(), which seems to be applicable for single consumer scenarios. The reason for having multiple consumers is that the processing, via a named pipe instance, can process up to three of these items at a time, so I thought I could have three consumers. b) Is there a way of checking to see if an item is on this queue, and if so, getting the caller that checks to see if there is an item to block until the item has been processed? EDIT: Based on Jon Skeet's answer here's some sample code to illustrate multiple consumers acting on a BlockingCollection populated by a single producer, with consumers using GetConsumingEnumerable(): static BlockingCollection<string> coll = new BlockingCollection<string>(); static void Consume() { foreach (var i in coll.GetConsumingEnumerable()) { Console.WriteLine(String.Format("Thread {0} Consuming: {1}", Thread.CurrentThread.ManagedThreadId, i)); Thread.Sleep(1000); } } static void Main(string[] args) { int item = 0; Task.Factory.StartNew(() => { while (true) { coll.Add(string.Format("Item {0}", item++)); Thread.Sleep(500); } }); for (int i = 0; i < 2; i++) { Task.Factory.StartNew(() => Consume()); } while (true) ; } The items are processed in an interleaved manner between the two consumers operating on the two different threads, e.g. Thread 4 Consuming: Item 0 Thread 5 Consuming: Item 1 Thread 4 Consuming: Item 2 Thread 5 Consuming: Item 3 Thread 4 Consuming: Item 4 A: GetConsumingEnumerable is in fact safe to call from multiple consumers simultaneously; the enumerable only completes when the collection is marked as complete. Each item is only consumed once. GetConsumingEnumerable is essentially equivalent to: while (!IsCompleted) { if (TryTake(out var item, Timeout.Infinite)) yield return item; } plus a bit of cancellation/cleanup logic. A: Multiple consumers can just call Take or TryTake concurrently - each item will only be consumed by a single consumer. However, I believe GetConsumingEnumerable will also do what you want. I believe if each caller calls that, each will get a separate consuming enumerable, which again will make sure that each item is only consumed once. I'm not sure offhand what happens when the queue becomes empty - I don't know whether MoveNext() then blocks, or returns false. I didn't really follow your second question though...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Facebook API key hash - debug and release I've integrated Facebook to my App, created a valid hash key and saved the key on facebook. I used a different key for debug and release. When I released, I had to regenerate the key hash from the release keystore. Now I cannot log in to facebook using the debug key. Anyone know how I could still use the debug version as well as the release version? A: Just doing this myself, and discovered that this was already answered here: Android Facebook single sign-on - multiple key hashes possible?. All you need to do is add (paste) both key hashes into the FB configuration for your app, and you should be all set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Java EE getting information about what environment the application is currently running You can run a Java EE application in a test environment, a development environment or a production one. How can I use Java code or XML to get hold of that information? if ( ApplicationContext.inDevelopment() { // do this } Obviously the above is not correct. But you get the point. How can I do this? A: there are many ways to achieve it. * *check ip address of the sever to decide which platform it is running on. *add -D property into your server start script, in your program get the system property. *for different platforms using different properties files. each properties file contains a "platform" property *or if you are using maven to build your application, you can create profiles, to set property/attribute at building time. ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7528183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Communications between a C# PC program and an android tablet app So the goal is that the tablet can read and write a value of the PC program. So far I have managed to solve this. I have : an android app which uses ksoap2. a web server, ASP.NET in C# and the main program in C# Example : tablet calls a web method of the web server -> setA(42) web server change its static value of a to 42 main program calls a web method of the web server -> getA() and so it can save the 42 in his own a attribute. So it does the job but it s quiet heavy. I am just exchanging integers or strings. I've heard of socket programming but it appears to be less easy to use especially with firewalls, corporate networks... any ideas :) ? A: Obviously you get a lot of overhead with a web service but much less coding.. Setting up you own socket connection is not really a big deal as both Java(android) and .Net have nice simple support for this. http://developer.android.com/reference/java/net/Socket.html http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx A: I would not go for sockets. As you say, firewalls and routes can be a problem. HTTP is usually open. It's also easier to scale services that use HTTP since everything needed already exists (such as load balancers). You could even direct different versions of your protocol to different servers by using a HTTP proxy. For that simple requests, simply put everything in the URI: http://yourservice.com/v1/productname/seta/?value=42 Use JSON for a bit more complex requests: http://yourservice.com/v1/seta { "a": 42, "b": "Something" } * *JSON in android: http://developer.android.com/reference/org/json/JSONObject.html *JSON in C#: asp.net mvc has built in support.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create database error MYSQL I have the following error when trying to import .sql file into MYSQL from the command prompt. C:\Program Files\MySQL\MySQL Workbench 5.2 CE\utilities>mysqldbimport --server= root:password@localhost <filepath> # Source on localhost: ... connected. # Importing definitions from <filepath> ERROR: Invalid statement: CREATE DATABASE `None`; I have had a look at the command line parameters when using mysqldbimport.exe and found a skip command which gets past this error by adding --skip CREATE_DB, which imports however there is no data available as the process has been skipped. How can I get around this error? A: Can you manually create the database (either through console or other application), then skip the creation like you did there? Edit; Logging into MySQL console, mysql> create database `testdb`; Query OK, 1 row affected (0.05 sec) mysql> use testdb; Database changed mysql> You may have to edit the .sql file if possible, changing the Create database statement to "use testdb;", but it's hard to tell without knowing the full file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Help converting NotifyOnChange Properties to Dependency Properties What is the best way of converting the fictional code below to dependency properties? Where the Date Property will be in another control? [DependsOn("Date")] public int Year { get { return Date.Year; } set { Date.Year = value; } } [NotifyOnChange] public DateTime Date { get; set; } A: Dependency properties can be dependent on one another via Binding, Style, Trigger, Template etc. In certain cases they inherit values like DataContext. In other cases they copy the values of the owner like Border's background color. In your case do you want to create two dependency properties which by default depend on each other at declaration level itself i.e. in code behind? If so, your Date can be one Dep.Prop say DateProperty. and Year can be other say YearProperty. In DateProperty and YearProperty's PropertyChangedCallBack metadata, change each other taking care that they do not fall in deadlock.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the property -webkit-column-gap, -webkit-column-width in webview? How to set css3 property value "-webkit-column-gap, -webkit-column-width " the before loading mywebpage in webview? How to scroll webview content(horizontal Scrolling) by using css3 multicolumn layout without changing the source HTML?
{ "language": "en", "url": "https://stackoverflow.com/questions/7528196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to calculate the size of an Erlang process in memory? I have a 'worker' process which I am going to assign to a job. Before I spawn hundreds of processes of this type I would like to know the memory consumption figures for it. I know that I should sum all the elements which are stored in the process' loop data (all tuples, atoms, lists, etc) and the actual process memory footprint. As I understand, before doing that I have to know the actual size of a {tuple|atom|list|process} itself. Given a certain data structure which is stored in the process' memory how can I calculate the overall size of the process in memory? A: erlang:process_info/2 will give you the amount of memory, in bytes, that a process occupies. For example: 1> erlang:process_info(whereis(code_server), memory). {memory,284208} Note that binaries are not included since they are not located in the process heap. Those you have to count the size of manually. A: Did you read the Erlang Efficiency Guide on Memory?
{ "language": "en", "url": "https://stackoverflow.com/questions/7528199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PHP array : renumber elements when new element added I have a PHP array with elements: $myarray = array ( "tom", "dick", "Harry" ); . I need to keep the array fixed in size of just 3 elements . I need to add a new element "jerry" such that the array now looks like $myarray = array ( "jerry", "tom", "dick"); so in a way I am moving the elements along and the 4th one drops out, with the newest element going at the beginning. I could write all of this by hand, renumbering the elements etc etc. I just wondered if there was a quicker way to do this though. Many thanks! J A: One way to do this is to utilize array_pop and array_unshift: # Pop the last element off the array array_pop($myarray); # Insert the new value array_unshift($myarray, "jerry"); Or, you can use array_merge and array_slice: $myarray = array_merge(array("jerry"), array_slice($myarray, 0, 2)); Both of these methods reset the keys, so they will be renumbered from 0 to 2. A: You might want to have a look at SplQueue. On every addition of a new element, check whether the number of elements is higher than x and dequeue if necessary. A: $myarray = array ( "tom", "dick", "Harry" ); array_pop( $myarray ); //remove the last element array_unshift( $myarray, "jerry" ); //prepend the new element
{ "language": "en", "url": "https://stackoverflow.com/questions/7528200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Something like thread in php I'm trying to program yahoo messenger robot,now my robot can get messages and answer to them. Yahoo only can send 100 pm at each time I get notification. now I wanna answer the each pm. I use while(true){ } to it and answer first pm,then second ,then 3rd and ... . It's so slow ,because I can make only one connection to yahoo by this(I use curlib). how can I send some messages at same time?I think I need something like thread but in php. A: you can use pcntl_fork(). http://www.php.net/manual/en/function.pcntl-fork.php You need pcntl extension and it only works on Unix If you use curl function you might take a look at curl_multi_init(). http://www.php.net/manual/en/function.curl-multi-init.php A: I've wrote a simple function below, which launches URL, and doesn't wait for a result, so like this you can launch many URLs on your own site, it will make your loop fast, and also no need to install any extensions to your server. function call_url_async($url, $params, $type='POST', $timeout_in_seconds = 1) { //call the URL and don't wait for the result - useful to do time-consuming tasks in background foreach ($params as $key => &$val) { if (is_array($val)) $val = implode(',', $val); $post_params[] = $key.'='.urlencode($val); } $post_string = implode('&', $post_params); $parts=parse_url($url); $fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, $timeout_in_seconds); //if ($fp == FALSE) // echo "Couldn't open a socket to ".$url." (".$errstr.")<br><br>"; // Data goes in the path for a GET request if ('GET' == $type) $parts['path'] .= '?'.$post_string; $out = "$type ".$parts['path']." HTTP/1.1\r\n"; $out.= "Host: ".$parts['host']."\r\n"; $out.= "Content-Type: application/x-www-form-urlencoded\r\n"; $out.= "Content-Length: ".strlen($post_string)."\r\n"; $out.= "Connection: Close\r\n\r\n"; // Data goes in the request body for a POST request if ('POST' == $type && isset($post_string)) $out.= $post_string; fwrite($fp, $out); fclose($fp); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails form submitted multiple times but don't know why I have a form as follows: <%= form_for(:session, :url => sessions_path, :remote => true, :html => {:id => 'login_form'}) do |f| %> <div class="formRow"> <%= f.label :email %><br> <%= f.text_field :email, :value => (@email if @email) %> </div> <div class="formRow"> <%= f.label :password %><br> <%= f.password_field :password %> </div> <div class="formRow small"> <%= link_to "I forgot my password",'#' %> </div> <div class="formRow"> <%= f.submit signin_button_text, :class => "button-big left" %> </div> <% end %> It goes to this controller: def create @email = params[:session][:email] user = User.authenticate(params[:session][:email],params[:session][:password]) respond_to do |format| if user.nil? @title = "Sign in" flash.now[:error] = "Invalid email/password combination" format.js {render :action => :new } else sign_in user format.js {render :action => :create } end end end Here is the new.js file: $('#login_form').replaceWith("<%=escape_javascript(render 'login_form')%>"); if($('.flash-block').length ==0) { $('#login_form').before("<div class='flash-block error'><span><%=escape_javascript(flash[:error])%></span></div>"); } For some reason if the form is submitted with errors it loops four times. I don't understand why. Is there something in the code that causes this to loop? A: I am assuming that you are using jquery. This is usually happened when there is an incomplete call or there is some sort of error and you haven't refresh the page. Try something like this: <script type="text/javascript"> $('#login_form').submit(function() { $(this).unbind('submit').submit(); }); </script> A: I was using Fancybox and was not opening it in an iframe. So I wound up loading the jquery libraries twice and thus when I submitted the form I had multiple submissions. Once I opened Fancybox in an iframe it submitted only once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Jar File As Stream Class Loader How can I load classes from a jar file stored as a blob in a database as the URL Class loader only accept a URL or file path? A: Implement your own subclass from java.lang.ClassLoader that does the loading from the database. Maybe this post helps to get started: http://www.javablogging.com/java-classloader-2-write-your-own-classloader/ A: Writing your own ClassLoader can be quite confusing, especially for a beginner. I recently needed to load some jars dynamically and found this answer very helpful. It explains how to use ResourceFinder, a class from Apache xbean or something. It's a single file that you can easily drop into your project. Most advantageously for your situation, although ResourceFinder loads by URL, the readContents function (used to actually load up the jar file) looks like this: private String readContents(URL resource) throws IOException { InputStream in = resource.openStream(); BufferedInputStream reader = null; StringBuilder sb = new StringBuilder(); try { reader = new BufferedInputStream(in); int b = reader.read(); while (b != -1) { sb.append((char) b); b = reader.read(); } return sb.toString().trim(); } finally { try { in.close(); reader.close(); } catch (Exception e) { } } } which could easily be modified to work on any Stream/blob you have. Some minor changes to the class could, I'm sure, make it do exactly what you want, or at the very least point you in the right direction. Writing ClassLoaders from scratch is no fun. EDIT: Y'know, I've just taken another look, and I'm not so sure that you could get away with only minor changes to ResourceFinder. Still, look it over, see what you can get from it. A: If you look at the code for JarClassLoader in the Java tutorial that will get you started. There are also other resources available if you Google for Jar Class Loader. You will need to modify the code to pass in the ByteStream that you have obtained from the BLOB in the DB. A: implementing your own classloader is the obvious answer. depending on how you need to use the classes that could be problematic. another, lesser known option, would be to implement your own url handler. you could come up with a custom url scheme like "db://<dbname>/<tablename>/<jarfile>" or something. you would implement a custom URLStreamHandler, details here. A: one way to laod jar file .. it may helpful to you. public class JarLoad { public static void main(String[] args) throws ZipException, IOException { File jarfile = new File("C\\scan.jar"); if(! jarfile.isDirectory()){ ZipFile jar = new ZipFile(jarfile); Enumeration enumeration = jar.entries(); while(enumeration.hasMoreElements()){ ZipEntry zipEntry = (ZipEntry)enumeration.nextElement(); System.out.println(zipEntry.getName()); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CSS - How to prevent ul/ol li's second row of text from going further left than the first line? I have a few lists on my webpages that look like this: > lorem ipsum And I want them to look like this: > lorem ipsum If you could even help me how to properly phrase the question I am after I would much appreciate it. A: list-style-position is the CSS attribute you want, in particular setting it to "outside" - http://www.w3.org/TR/CSS2/generate.html#list-style The w3 descriptions are confusing for the outside but the key is that inside places the marker as the first inline item in the content. http://jsfiddle.net/chrisvenus/uQNPk/2/ has an example showing the results for inside and outside. I believe that "outside" is usually the default which leads me to believe that you may have something in your stylesheet overriding this explicitly or possibly you are using some kind of reset stylesheet that has different defaults than you want. Simply put the following should sort you out assuming no overriding from other stylesheet elements: ul, ol { list-style-position: outside; } You may also need to fiddle with the left margin to make sure your bullets don't hit something you don't want them to... A: make it block, set padding, > insert with :before pseudo element :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7528218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I create a new FBML/FBJS app? I have a 3 year old app that was written in FBML/FBJS. I'm working on making it multiuser, so I'm creating a new app for this project. I want to use my existing codebase which uses FBML/FBJS, but I can't figure out how to enable these features from my Facebook app control panel. There no longer appears to be a "Facebook Integration" tab. Please help me figure out how to enable FBML/FBJS for my new app. Thanks! A: How do I create a new FBML/FBJS app? You CAN'T, back on March 11, 2011 no new FBML/FBJS applications are allowed, please check the Facebook Roadmap and this blog post. A: Since FBML/FBJS have been abandoned you can use the Facebook JS SDK to create your app. It is easy to implement. http://developers.facebook.com/docs/reference/javascript/ Here is a working example: http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
{ "language": "en", "url": "https://stackoverflow.com/questions/7528222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Python API for drawing diagrams (that use lines to connect corresponding values between two lists) Given two lists, which contain same elements of string but in different orders, is there any API that can draw diagrams like The diagram consists of two stacks of string. Between these two stacks, lines are used to link same elements between these two stacks. Its outlook is similar as the visualization of sonar (an Eclipse code diff. tool), but the semantics of lines are different. Does this kind of diagram have some formal name? A: The general graph description format DOT seems the most appropriate to me: it is easy to describe a huge variety of graphs, with this (text) format, and you can plot them with one of the many tools available (Graphviz comes to mind, for example). You also have the specialized python-graph module at your disposal (which can work with the DOT format too). A: With python you have many options, see here for more. I would recommend matplotlib, take a look at this example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to stop form submit during ajax call I can only modify the code in the ajax call. The ajax call occurs when I click the submit in form named $('#form1'). $('#form1').submit(function () { $.ajax({ url: 'some.php', type: 'POST', data: somedata, success: function (msg) { if (!msg) { // I wanna to stop '#form1' submit here,how to do that? I can only modify the code in the ajax call. } } }); }); A: You can also use preventDefault() http://api.jquery.com/event.preventDefault/ A: return false or event.preventDefault should help you: $('#form1').submit(function(){ $.ajax({ url:'some.php', type:'POST', data:somedata, success:function(msg){ if(!msg){ //i wanna to stop form1 submit here,how to do that? you can only modify the code in the ajax call } } }); return false; }); or: $('#form1').submit(function(e){ e.preventDefault(); $.ajax({ url:'some.php', type:'POST', data:somedata, success:function(msg){ if(!msg){ //i wanna to stop form1 submit here,how to do that? you can only modify the code in the ajax call } } }); }); A: Put a return false; This should stop the function to continue A: You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late). But yes, put return false at the end of your function. function SubmitHandler(){ // Your AJAX call here // blah blah blah return false; // Stop form submit } If it's really important that it is in the success handler, then you could execute the call synchronously. A: You need to prevent form submitting onclick="ajaxcall(); return false;" And do it in your code: $.ajax({ url:'some.php', type:'POST', data:somedata, success:function(msg){if(msg) $('#form1').submit();} }) A: You can change button type from "submit" to "button" then submit form using jquery form.submit(); function according to your conditions. Consider the following example code below: <script> $(document).ready(function() { $("#button-id").click(function() //on click at button { var sel=$("#input").val(); $.post("ajax-war.php",{jid:sel,rand:Math.random() } ,function(data) { if(data=='valid') //if correct login detail { $('#war_form').submit(); //Submit form } else { alert('not valid'); //will not submit form } }); }); }); </script> A: Assuming the form's ID is #form1, you could bind a submit handler and return false from it: $.ajax({ url:'some.php', type:'POST', data:somedata, success:function(msg){ if(!msg){ $('#form1').submit(function(){ return false; // prevents form submit }); } } })
{ "language": "en", "url": "https://stackoverflow.com/questions/7528234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Redirect “/” to “/web” using IIS7 I'm hosting a site where I would like for various reasons to have http://mydomain.com automatically redirect to http://mydomain.com/web while at the same time still allowing http://mydomain.com/foo.html to be served. Using HTTP Redirect from IIS 7 I seem to be creating an endless redirect loop. Would you have any hints for me? A: Give URL Rewrite Module a try. Following code should work for you : <rewrite> <rules> <rule name="Redirect example.com to example.comn/web" patternSyntax="ECMAScript" stopProcessing="true"> <match url="^$" /> <action type="Redirect" url="/web" /> </rule> </rules> </rewrite> How you can get start with Rewrite Module is briefly documented on below post : http://www.tugberkugurlu.com/archive/remove-trailing-slash-from-the-urls-of-your-asp-net-web-site-with-iis-7-url-rewrite-module
{ "language": "en", "url": "https://stackoverflow.com/questions/7528236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: problem in hiding tabbarController in iphone sdk? I'm displaying a list employess when clicking on tabBarButton. I want to hide the tabBar when I click on the cell to dispaly details of the employ and I want to show tabBar when I come back to the list . please anyone help me. thanks in advance laxmi A: [ViewControllerToBePushed setHidesBottomBarWhenPushed:YES];
{ "language": "en", "url": "https://stackoverflow.com/questions/7528239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle multiple statments do not run correctly I have a file with 3 "create type" statements. I do not understand why, when I run the script it creates only the first type. When I open created type I see all three create statements inside. What am I missing here? CODE: create type SplitPathTableType as table of varchar2(450); create TYPE TSMNodesRecord AS OBJECT ( NodeID number(20), IsDataNode number(1), Path nvarchar2 (450), ParentID number(20), TimeStep number(20) ); create type TSMNODESTABLE as table of TSMNODESRECORD; A: You need / after each statement... create type SplitPathTableType as table of varchar2(450); / create TYPE TSMNodesRecord AS OBJECT ( NodeID number(20), IsDataNode number(1), Path nvarchar2 (450), vParentID number(20), TimeStep number(20) ); / create type TSMNODESTABLE as table of TSMNODESRECORD; /
{ "language": "en", "url": "https://stackoverflow.com/questions/7528241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Simple Validation for a Single Text Box in ASP.NET MVC I have added a text box to a simple form in ASP.NET MVC and I want a client-side 'required' validation for this. I know I can do this using a strongly typed model view but I would like to do it manually in this case. Is there a simple way to perform this? I tried setting the Model/property name of the Html.ValidationMessage helper to the input name but this didnt work: @Html.TextBox("emailStr" ) @Html.ValidationMessage("emailStr","* Required") A: Assuming you use default jQuery validation plugin, you can use Rules.Add method on client side for this $("#emailStr").rules("add", { required: true, messages: { required: "* Required", } }); Also, do not forget to include jquery.validate.min.js A: Not sure why you would want to do it manually - but I don't think you can use @Html.ValidationMessage unless you use a TextBoxFor. You can't use the TextBoxFor unless you have a model to work with inside the view. You could write some javascript/jquery to find the textbox and make sure it's not empty, and if it is, unhide an element with the validation message in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sorting algorithm in OpenOffice calc I'm having a really long day, the culmination of which is a dumb moment trying to sort a list of strings. Calc sorts them like this: 0DCv6UlY6T0 0ITZEBZrwMk 1062VEX2EfI 2jk7hilGMs0 2lZVu3haI6A 3f8s3KbFQ0Q 3hB09daYLmk 43Erj3qFxxo 6lj33w3YoOw 7jiNQnkfx0k 7TSMj6g3UoE 7Wba8IUk6v8 9hbG9dS7zl0 ALThJiGFBSc by_VzOiPhZM Ce250P1xep0 Cgx6DV6RJg8 d5dDgLRd1-o DnyzZwaYDXE dO5KLh2er4E This isn't quite what I expected. Look at the last 3 values. Shouldn't the entry starting with a capital D come before the ones starting with lowercase d (or the other way around)? Why does it come between the lowercase d entries? Funnily, command line sort in Linux does things the same way. Can somebody explain the logic behind such sorting? I need to replicate it (or reproduce it in Python, if it's already implemented somewhere). A: It's because of locale. See the difference between: sort inputfile and with (what you probably want): LANG="C" sort inputfile output of second command: 0DCv6UlY6T0 0ITZEBZrwMk 1062VEX2EfI 2jk7hilGMs0 2lZVu3haI6A 3f8s3KbFQ0Q 3hB09daYLmk 43Erj3qFxxo 6lj33w3YoOw 7TSMj6g3UoE 7Wba8IUk6v8 7jiNQnkfx0k 9hbG9dS7zl0 ALThJiGFBSc Ce250P1xep0 Cgx6DV6RJg8 DnyzZwaYDXE by_VzOiPhZM d5dDgLRd1-o dO5KLh2er4E A: Whether capitals are lexicographically distinct from lower-case letters depends on the locale (specifically LC_COLLATE), which explains the command line sort program (and ls and ...), and presumably also Openoffice. E.g. $ cat test Abc aabc $ sort test aabc Abc $ LC_COLLATE=C sort test Abc aabc A: For replication: data = [ "abc", "aBB", "abD", "Aac", "AAb", "ABc", "ABa" ] print sorted(data, key = lambda item: item.upper()) The trick is to provide the key argument. This function is applied to the list items, and the result is used for comparisions during the sort.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Load html data with AJAX in Sencha touch when panel is shown I have a TabPanel with a Tabbar and four panels inside. I want to load the HTML content for the fourth panel with an AJAX call when the panel becomes visible. The AJAX function fetches the data from the server and places it inside the panel, which uses the panel update function. The problem is how to call this function when the panel becomes visible. A simplified version is: Pages.Contact = new Ext.Panel({ title: 'Contact', html: 'test data', iconCls: 'user', cls: 'cHome', activate: function () { Pages.Contact.update("my ajax data"); } }); When I go to my panel the body content is not affected. Does anyone know what goes wrong here? I've already tried to replace activate with render and show. A: To add event's listeners you need to do listeners: { activate: function(){ console.log('activate fired'); } }, But that's not the event you want to listen. It's better to listen for beforecardswitch on the TapPanel object, example: listeners: { beforecardswitch:function(newCard, oldCard, index, anim){ if(index == 3){ //loadJson and update card. // you may want to use this also newCard.setLoading(true); //and after the json request has finished set it to false. } } }, A: The solution was to use: beforecardswitch:function(object, newCard, oldCard, index, anim) { As shown by Ilya139 by with the object parameter as first parameter. Then the index variable returns the correct cardnumber.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to validate very large XML files? How can I validate a large XML file (>100mb)? I try to open it with IE, FX & GC and it either crashes or doesn't do anything. A: You can try using a command-line validator, for example xmlstarlet: $ xmlstarlet validate bigfile.xml A: The only tool I know that combines a large file viewer and an XML validator for huge files is XML ValidatorBuddy . The file viewer doesn't load the complete file at once but it is possible to scroll and there is also XML syntax-coloring applied. The validation uses the SAX parser from Xerces and your document with >100mb shouldn't be a problem. A: Oxygen XML has a HUGE FILE support that does validation http://www.oxygenxml.com/#14.1Huge_XML_Files_Support A: You can also use the XML Tools Plugin in Nodepad++, it has a function "Check XML Syntax now". It's simple to download and if you don't use Notepad++ already, it's a good reason to start! A: xmllint --stream Worked on a 1.2Gb file with memory limited to 500Mb: ulimit -Sv 500000 xmllint --stream a.xml Without --stream, Linux kills the process, and without ulimit, my computer jams. I was not able however to get output from --xpath when using --stream: How to do command line XPath queries in huge XML files? Tested in Ubuntu 14.04, xmllint version 20901. A: The following command worked for me xmllint --huge A: In Java, and I'm sure in other languages, there are solutions for reading in an entire XML file and processing it as a complete DOM, and solutions that process the XML as a stream in an event-driven way. You would want the second kind of solution, which never loads the entire file in memory. See SAX for a Java solution to the problem. A: You could try the EditiX XML editor. If you load your document into EditiX and there are problems with the XML, eg. mismatched opening and closing tags, the editor will still load the file and in the bottom right corner of the screen you'll see a number displayed in red eg. a red "5" means there are five errors in the document. I've not tried a 100mb document but I've done over 15mb and it seemed quite happy. There's a free version. A: in addition to dj_segfault's comment on phihag's answer, xmlstarlet is fortunately NOT dead. They've just released Version 1.3 If you want a decent commandlinetool that can manipulate xml, xmlstarlet is perfect (and pretty fast). A: Windows Version of XML Starlet: > xml val <xmlfile.xml> A: Liquid Studio Community Edition contains a Large File Editor which can also be used to validate XML files. Its not really got an upper limit on the size of the files you can open Terra-byte files open instantly on low spec machines, and its free. A: On Windows you can write a simple application based on .net platform. The System.Xml.XmlReader class is capable of validating huge files. An example is in this answer: Validating an XML against referenced XSD in C#
{ "language": "en", "url": "https://stackoverflow.com/questions/7528249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Facebook Batch Post Requests using PHP I'm trying to make a batch request using PHP that make a post in the user wall without any luck. I have succeed to make bath request of a type "GET" but not of a type "POST". My code: $batched_request = '[{"method":"POST","relative_url":"me/feed","body": "message=hi"},' . '{"method":"GET","relative_url":"me/feed?limit=1"}]'; $post_url = "https://graph.facebook.com/" . "?batch=" . $batched_request . "&access_token=" . $access_token . "&method=post"; echo $post_url; $post = file_get_contents($post_url); echo '<p>Response: <pre>' . $post . '</pre></p>'; $decoded_response = json_decode($post, true); print_r($decoded_response); If I change $batched_request to be only: $batched_request = '[{"method":"GET","relative_url":"me/feed?limit=1"}]'; The batch request will suceeded and will show me the first post of the user wall.. but what is my problem with my POST request? A: I wrapped the $batched_request within urlencode() and it worked like a charm: $batched_request = '[{"method":"POST","relative_url":"me/feed","body": "message=hi"},' . '{"method":"GET","relative_url":"me/feed?limit=1"}]'; $post_url = "https://graph.facebook.com/" . "?batch=" . urlencode($batched_request) . "&access_token=" . $access_token . "&method=post"; echo $post_url; $post = file_get_contents($post_url); echo '<p>Response: <pre>' . $post . '</pre></p>'; $decoded_response = json_decode($post, true); print_r($decoded_response); Also make sure you have granted the publish_stream permission. A: This class will simplify making batch requests to Facebook.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tomcat 7 and shared.loader problem I am using a custom directory for properties files located at ${catalina.home}/conf/properties and in order to add it to the classpath i edited ctalina.properties and added shared.loader=${catalina.home}/conf/properties But contents of this directory are not accessible when I try to read them from a listener via: MyListener.class.getResourceAsStream("/sample.props") I most probably have misunderstood something here. Any help would be greatly appreciated. A: Use Thread.currentThread().getContextClassLoader() .getResourceAsStream("/sample.props"); A: Worked for me with : Thread.currentThread().getContextClassLoader() .getResourceAsStream("sample.props");
{ "language": "en", "url": "https://stackoverflow.com/questions/7528251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jade templating syntax support for eclipse? I have just starting using the nodejs templating engine jade. Unfortunately my IDE eclipse doesn't seem to have support for this syntax and is not highlighting correctly. Is it possible to add support for .jade files to eclipse? A: As current lead of Nodeclipse effort www.nodeclipse.org I announce that Nodeclipse v0.12 has added Minimalist Jade Editor, see http://www.nodeclipse.org/history. Added just before release as I got sick of .jade to be opened outside of Eclipse. * *#134 - Minimalist Jade Editor idea is to define HTML tags and JavaScript keywords as words for highlight in Word.java and then use it together with EditBox Nodeclipse scope is growing, now it has Gradle for Android and JavaScript in general that I want to work on for next iteration. Also looking for developers and company willing to support the project. Raise an issue on GitHub/Nodeclipse to continue. A: check if this helps Jade-syntax-highlight A: Follow the pattern used for adding HAML support to an Eclipse install, and find a lexer and colorizer for Jade.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: export gridview to excel without the gridview formatting VB I am able to export a gridview to excel, my problem is that I cannot figure out how to remove the formatting from coming over from the girdview. Here is the code I am using to export the gridview: Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Response.Clear() Response.Charset = "" 'Response.ContentType = "application/vnd.ms-excel" Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" Dim stringWrite = New System.IO.StringWriter() Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite) GridView1.GridLines = GridLines.None GridView1.HeaderStyle.Font.Bold = True GridView1.DataSourceID = SqlDataSource1.ID GridView1.DataBind() GridView1.RenderControl(htmlWrite) Response.Write(stringWrite.ToString) Response.End() End Sub A: What I suggest that you should iterate datasource , append the content of each row into StringBuilder object and write that string to the response buffer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BitmapData.draw with different shape is it possible to change the Rectangle I use as fifth parameter of draw BitmapData class? bitmapData.draw(image,null,null,null,rect,false); I'm trying to draw and save a different shape (with the shape of a particular MovieClip). A: If you look at the definition for the BitmapData's copyPixels method (adobe documentation), you'll see: "If you include the alphaBitmap and alphaPoint parameters, you can use a secondary image as an alpha source for the source image. If the source image has alpha data, both sets of alpha data are used to composite pixels from the source image to the destination image. The alphaPoint parameter is the point in the alpha image that corresponds to the upper-left corner of the source rectangle. Any pixels outside the intersection of the source image and alpha image are not copied to the destination image." You can probably get this to do what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xcode 4 organizer repository view changes says "No Version Editor" My prior problem was this. Now, when i see change logs and click view changes, the pop-up comes but right pane just tells "No version editor". My search couldn't yield any solutions suitable to this. Any suggestions or solutions to this problem? Please. A: My problem was gone after i installed the public version of Xcode 4.2 with iOS 5. Mine is Mac OS Leopard.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Zoom ignoring pictures I would like to take the contents of an HTML page, an make every element 50% larger. I have tried using CSS3 zoom: 150% but this also attempts to zoom pictures. Because the resolution of the images were originally crafted for a normal view, they look blurry with the zoom. Is it possible to make all HTML bigger, except for the images? A: When you apply a scale transformation to an element, the magnification is applied to the element itself and to all of their children. This is a behavior common to most browsers, with the exception of IE (I believe). So, to do what you want, you need to scale only the following elements: * *elements that are not img and do not contain any img descendants By using jQuery $("button").click(function () { $("*").each(function (index, value) { var $this = $(value); // if this is not an image if (!$this.is("img") && // and if it does not contain child images $this.find("img").length == 0) { // then scale it up $this.css({ '-webkit-transform': 'scale(1.5)', '-moz-transform': 'scale(1.5)', '-o-transform': 'scale(1.5)', '-ms-transform': 'scale(1.5)', 'transform': 'scale(1.5)' }); } }); }); You can see it live here you can also use $this.css('zoom', '1.5'); instead of $this.css({ '-webkit-transform': 'scale(1.5)', '-moz-transform': 'scale(1.5)', '-o-transform': 'scale(1.5)', '-ms-transform': 'scale(1.5)', 'transform': 'scale(1.5)' }); A: try transform: scale(1.5); This should help A: A crude way of doing it would be to have: body { zoom: 150%; } img { zoom: 67% } That will not rescale background images or other non-img elements, so it's not ideal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Posting attachment without open dialog using Facebook Android SDK? I am working on Facebook Integration in my Android app. I am able to send attachment by using "stream.publish" with opening dialog. Is there a way to post without opening dialog? I am using following method. Please give me any idea. postParams.put("seriesname", "Commented during the TV show"+" '"+series+"'"); postParams.put("description", text); parameters.putString("attachment", "{\"name\":\""+postParams.get("seriesname")+"\"," +"\"href\":\""+"http://www.google.com\","+"\"description\":\""+postParams.get("description")+"\"}"); mFacebook.dialog(FacebookComments.this, "stream.publish", parameters, new SampleDialogListener()); Log.d("FACEBOOK RESPONSE", response); if (response == null || response.equals("") || response.equals("false")) { Log.v("Error", "Blank response"); } } } catch (Exception e) { Log.e("Facebook", "Error: " + e.getMessage()); } } A: Check this code for Posting in Facebook wall without Dialog : public boolean postOnWall(String msg) { Log.d("Tests", "Testing graph API wall post"); try { String response; Bundle parameters = new Bundle(); parameters.putString("message", msg); parameters.putString("description", "test test test"); parameters.putString("tags",person_id); response = ZValues.authenticatedFacebook.request("me/feed", parameters,"POST"); Log.d("Tests", "got response: " + response); if (response == null || response.equals("") || response.equals("false")) { Log.v("Error", "Blank response"); return false; } } catch(Exception e) { e.printStackTrace(); } return true; } Check this for sending links in Post
{ "language": "en", "url": "https://stackoverflow.com/questions/7528258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CallBack won't work, please help Somehow my callback doesn't work... from a sending activity: Intent intent=new Intent(); intent.setAction("Constructor.rob.call"); sendBroadcast(intent); receiving activity: public class popup extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.popupcanvas); IntentFilter filter = new IntentFilter("Constructor.rob.com.call"); this.registerReceiver(new Receiver(), filter); } private class Receiver extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { finish(); } } } and from the manifest: ... <intent-filter> <action android:name="Constructor.rob.com.call" /> </intent-filter> </application> </manifest> Any ideas what might be wrong? Thanks! A: You are sending "Constructor.rob.call" but catching "Constructor.rob.com.call"
{ "language": "en", "url": "https://stackoverflow.com/questions/7528260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PC Lint while(TRUE) vs for(;;) I'm using PC Lint for the first time. I was "linting" my code, when PC Lint warns me about my while(TRUE). This is what it says: 716: while(1) ... -- A construct of the form while(1) ... was found. Whereas this represents a constant in a context expecting a Boolean, it may reflect a programming policy whereby infinite loops are prefixed with this construct. Hence it is given a separate number and has been placed in the informational category. The more conventional form of infinite loop prefix is for(;;). I didn't understand this statement. Can anyone help me to understand it? A: The text says that although while(TRUE) (which gets preprocessed into while(1)) is a perfectly valid infinite loop, the more conventional form of writing an infinite loop is for(;;) { ... } because it doesn't use any values at all and therefore is less error-prone. A: It says that the more conventional infinite loop is for(;;), which I'd say is an arguable assertion, and that it's categorized this construct as an "informational category" finding - I suspect that if you used the for(;;) instead it would go away. I've always written these as while(1) and never for(;;) myself. If it does what you expect, I'd ignore the findings of PC LINT on this one or switch it if you're worried about someone redefining TRUE because if someone redefined TRUE your loop wouldn't run at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: encode and decode base64 string to decimal string coddec I have a base64 string like this = "pCZXOVjpnlePyDk6znZrSw==" i need a encoder/decoder to convert it to decimal string like this = "84587163248712923874" Is there any codec that do it? A: You probably need a two stage process: * *Convert the Base64 string to a byte array. *Convert the byte array to a number. 16 bytes is too big for a Java long so I assume that you will need a BigInteger. There is a BigInteger constructor that takes a byte array as parameter, though you will need to be careful with the sign bit. The toString() method for the BigInteger will give you the string you want. A: Base64 encode/decode is part of the default libraries now (finally). Look at the class javax.xml.bind.DatatypeConverter. In there you will find two methods printBase64Binary and parseBase64Binary (along with a few other conversion routines).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Twitter search: OR with Tags - but how? I cannot search the twitter API for tweets which contain one of multiple tags. Like: q="#tag1 OR #tag2 OR #tag3" If I leave away the hashes and only search for words, the OR-ing works. For tags they don't. When I only use spaces, the search terms will be AND-ed, what shrinks the result... I use the twitter4j library with: Twitter rest = new TwitterFactory().getInstance(); Query query = new Query(); query.setQuery("#win | #fail"); QueryResult result = rest.search(query); Isn't it possible, or didn't i use it correctly? A: Might just be easier to use twitter's REST API. You'll want to use the search query. Here's an example search url searching for #LA, #NYC or #Boston. Note the spaces and #s are all URL encoded. Just pop a URL like that into a getJSON call like below and you can easily extract your values from the returned JSON object as in the example. var requestedData = "http://search.twitter.com/search.json?q=%23LA%20OR%20%23NYC%20OR%20%23Boston%22&callback=?" $.getJSON(requestedData,function(ob) { var firstTweet = ob.results[0].text; var firstTweeter = ob.results[0].from_user; } From there it's just a matter of looping through your results and pulling the appropriate fields which are all outlined in the JSON file if you simply visit that example search link in your browser! I don't know this TwitterFactory API but its possible they haven't updated to Twitter's new API or they're just not URL encoding appropriately. Good luck! A: Try to use OR operator instead of "|": query.setQuery("#win OR #fail"); See available Twitter search API operators here: Using the Twitter Search API
{ "language": "en", "url": "https://stackoverflow.com/questions/7528268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to get the relative path to include javascript functions file I have following directory structure dir1 dir2 dir3 dir4 file1 dir5 file2 I want to access file1 that is in directory4 in file2 that is in directory5. I have tried using absolute as well as relative paths. Could anyone help me how to access this file ? A: if I understand the question well, you have this directory-structure: | dir1 | dir2 | dir3 | dir4 | >> file1 | dir5 | >> file2 In that case, you can use ../dir4/file1
{ "language": "en", "url": "https://stackoverflow.com/questions/7528274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get the web sites running in the current application pool by WMI? I am trying to find out which web sites are running an application pool. MicrosoftIISv2/WebServerSetting only offers AppPoolId property and all of the valuse are DefaultAppPool . I can see all of these application pools are running different web sites on IIS. How can I get the web sites running on an application pool by WMI? A: I found out it can be done with EnumAppsInPool method. Here's the code: public static IEnumerable<string> GetWebSitesRunningOnApplicationPool(ManagementScope scope, string applicationPoolName) { //get application names from application pool string path = string.Format("IIsApplicationPool.Name='W3SVC/APPPOOLS/{0}'", applicationPoolName); ManagementPath managementPath = new ManagementPath(path); ManagementObject classInstance = new ManagementObject(scope, managementPath, null); ManagementBaseObject outParams = classInstance.InvokeMethod("EnumAppsInPool", null, null); //get web server names from application names IEnumerable<string> nameList = (outParams.Properties["Applications"].Value as string[]) //no null reference exception even there is no application running .Where(item => !String.IsNullOrEmpty(item)) //but you get empty strings so they are filtered .ToList() //you get something like /LM/W3SVC/1/ROOT .Select(item => item.Slice(item.NthIndexOf("/", 2) + 1, item.NthIndexOf("/", 4))); //your WebServer.Name is between 2nd and 4th slahes //get server comments from names List<string> serverCommentList = new List<string>(); foreach (string name in nameList) { ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, new ObjectQuery(string.Format("SELECT ServerComment FROM IIsWebServerSetting WHERE Name = '{0}'", name))); serverCommentList.AddRange(from ManagementObject queryObj in searcher.Get() select queryObj["ServerComment"].ToString()); } return serverCommentList; } And the string extensions taken from here and here public static int NthIndexOf(this string target, string value, int n) { int result = -1; Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}"); if (m.Success) { result = m.Groups[2].Captures[n - 1].Index; } return result; } public static string Slice(this string source, int start, int end) { if (end < 0) { end = source.Length + end; } int len = end - start; return source.Substring(start, len); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When I read does'nt implement all the specification what does it mean? When I read that glassfish supports all of the Java EE API specifications and tomcat does not, does that mean I cannot perform some functionality on tomcat that I can using glassfish? A: http://www.datadisk.co.uk/html_docs/java_app/tomcat6/tomcat6_apache.htm Tomcat 6 supports the Servlet and JSP APIs, whereas Java EE consists of those plus other APIs. You'll need to check which EE APIs your code actually uses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to inject the @Context when consuming FIQL queries in Apache CXF - JAX-RS? I am trying to implement a FIQL search queries and I am following the guide at http://cxf.apache.org/docs/jax-rs-advanced-features.html#JAX-RSAdvancedFeatures-FIQLsearchqueries. The issue is that the SearchContext is always null and I am getting a NullPointerException at runtime. My sample code is : @Context private SearchContext searchContext; @GET @Path("/actor/") @Override public List<Actor> getActorBy() { SearchCondition<District> sc = searchContext.getCondition(Actor.class); } I am getting the NullPointerException when executing the method getCondition on searchContext. The others rest calls are working. Is there a way to inject or configure the SearchContext so I can be able to execute a fiql search query ? A: There seems to be some problem injecting @Context(s)... I was able to get this working by public List<Actor> getActorBy(@Context SearchContext searchContext) { ... A: You need to add a SearchContextProvider to your jaxrs:server example: <jaxrs:server id="myWebServices" address="/ws"> [...] <jaxrs:providers> [...] <bean class="org.apache.cxf.jaxrs.ext.search.SearchContextProvider"/> </jaxrs:providers> </jaxrs:server>
{ "language": "en", "url": "https://stackoverflow.com/questions/7528283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy duplicate rows of one datatable to another datatable using LinQ Is there any way to copy the duplicate(based on one or more columns) rows in a source datatable to the destination datatable with or without LINQ in C#? A: Write what code you have so far makes it far easier to glean intent. If you use LINQ, you want to use the group operator, or use LINQ extensions and the GroupBy() method, although it would give you the key list. Like: from row in yourDataTable.AsEnumerable() group row by new { c1 = yourDataTabe["col1"], c2 = yourDataTable["col2"], //etc, your keyed columns } into groupedRow where groupedRow.Count() > 1 select new { //output whatever anonymous type information you want } Without LINQ just use a HashSet<T> as memory, and do a simple check, if it's in the HashSet, then you've seen it before, and then just add to your secondary table, if not, then add it to the HashSet because it's the first time you've seen this element. A: I've asked same myself yesterday. Maybe you find following helpful even if it's VB.NET: Dim dups = From row In source Group By grp = New With {Key .Value1 = CInt(row("Value1")), Key .Value2 = CInt(row("Value2"))} Into Group Where Group.Count > 1 Let Text = Group.First.Item("Text") Select Group.First If dups.Any Then Dim dest = dups.CopyToDataTable End If The Let-keyword is important to add the other columns to your query in order to get a new DataTable with the duplicate rows. A: Hie You have to do something like this for finding duplicate records using LINQ int[] listOfItems = new[] { 4, 2, 3, 1, 6, 4, 3 }; var duplicates = listOfItems .GroupBy(i => i) .Where(g => g.Count() > 1) .Select(g => g.Key); foreach (var d in duplicates) Console.WriteLine(d);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How does date_add and interval works in MySQL? I try to select those rows from the table in which datatime is withing 1 minute from now. I try to do it in the following way: SELECT datetime FROM my_table WHERE datetime > date_add( curdate( ) , INTERVAL -1 MINUTE ) This is what I get: 2011-09-23 02:39:53 2011-09-23 08:10:07 Something is clearly wrong with that. Does anybody know why? ADDED It looks really strange. If I use interval -1 hour I got results which are 4 or 7 hours old (I should not get them) but I do filter results which are older than 14 hours. How is it possible? A: From one minute in the past to one minute in the future: SELECT * FROM my_table WHERE datetime BETWEEN DATE_ADD(NOW(), INTERVAL -1 MINUTE) AND DATE_ADD(NOW(), INTERVAL 1 MINUTE) From now to one minute in the future: SELECT * FROM my_table WHERE datetime BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 1 MINUTE) From one minute in the past to now: SELECT * FROM my_table WHERE datetime BETWEEN DATE_ADD(NOW(), INTERVAL -1 MINUTE) AND NOW()
{ "language": "en", "url": "https://stackoverflow.com/questions/7528287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cann't receive REMOTE host log messages with Chainsaw (localhost messages just OK) I did a logger with programmatically configured SocketAppender for Chainsaw. I successfully receive messages in the SimpleReceiver of Chainsaw from code running on localhost, but from remote host i'm just getting like 63 Fri Sep 23 14:44:08 MSD 2011 INFO org.apache.log4j.chainsaw.messages.MessageCenter Connection received from my.host.com:50299 Chainsaw-WorkerThread log chainsaw 68 Fri Sep 23 15:12:22 MSD 2011 INFO org.apache.log4j.chainsaw.messages.MessageCenter Connection lost! :: null Chainsaw-WorkerThread log chainsaw 69 Fri Sep 23 15:12:22 MSD 2011 DEBUG org.apache.log4j.net.SocketReceiver accepted socket Chainsaw-WorkerThread log chainsaw 70 Fri Sep 23 15:12:22 MSD 2011 DEBUG org.apache.log4j.net.SocketReceiver socket not null - creating and starting socketnode Chainsaw-WorkerThread log chainsaw 71 Fri Sep 23 15:12:22 MSD 2011 DEBUG org.apache.log4j.net.SocketReceiver w*aiting to accept socket* Chainsaw-WorkerThread log chainsaw but no tab with log messages from remote host. What's wrong? No firewall is running. Tested with v2 and v2.1-trunk-today. A: Solved yesterday. Log level in big app's plugin wasn't set correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to add a check box on Ultrawebgrid? I have requirement like i want to add a checkbox on my Ultraweb grid. how can achive this? I want to add this in the run time i.e row initialization time. can one help me? A: Since the UltraWebGrid is an Infragistics-control, I suggest you look at their forums - they're quite good at providing thorough answers. A quick googling led me to this page (link) on their forums, where they also discuss under which scenarios it is useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Sign Android APK Possible Duplicate: How to sign an android apk file I am developing one application which is based on GPS. It displays the map correctly on my device, but when I install it on another device the map is not displayed. How do I sign my app? Thank you. A: You should refer this doc. For map key process refer this doc. A: You need two separate MapView keys: one for debug and one for release. See the Google API document on this topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php contact form with reply message I created a contact form that uses my php script to email the form parameters: //File email.php <?php include('variables.php'); $to = "info@timeshare.org.uk"; $subject = "Quote From Website"; $name = $_POST["name"]; $email = $_POST["email"]; $number = $_POST["number"]; $resort = $_POST["resort"]; $headers = "From: ".$to."\r\n"; $message = "Name: ".$name."\r\n". "Email: ".$email."\r\n". "Number: ".$number."\r\n". "Resort Name:".$resort."\r\n"; if (mail($to,$subject,$message,$headers)){ $replyHeader = "Thank You!"; $replyMessage = "Thank you for using our quick contact form. We will get back to you as soon as possible."; }else{ $replyHeader = "Oops!"; $replyMessage = "An Error Occured whilst trying to send the form. Please try again later"; } header( 'Location: http://localhost/TimeShare/formReturn.php' ) ; ?> on submit the form action points to this code. Now if the mail function is successfull, i want the form to redirect to formReturn.php, however i want the content in a particular div to show the $replyHeader and $replyMessage. So once the form is posted, it redirects to a page that either displays a successfull message or an error message. Now on my formReturn.php page ive tried including the variables Like so: //File: formReturn.php <body> //Header code... //sidebar code... <div> <?php include('php/email.php'); ?> <h1> <?php echo $replyHeader; ?> </h1> <p> <?php echo $replyMessage ?> </p> </div> //Footer code... </body> Problem with this code is, because im including the email.php file, i end up with a redirection loop. Which is bad! So how would i get the variables $replyHeader and $replyMessage onto the page in that specific location depending on the success or failure of the mail() function A: You can also add a GET-variable to your second page: if($mail_is_succesfull) header('Location: http://localhost/TimeShare/formReturn.php?success=true'); else header('Location: http://localhost/TimeShare/formReturn.php?success=false') ; Then you can add the message in your other page. A: you could pass it as a get variable <?php include('variables.php'); $to = "info@timeshare.org.uk"; $subject = "Quote From Website"; $name = $_POST["name"]; $email = $_POST["email"]; $number = $_POST["number"]; $resort = $_POST["resort"]; $headers = "From: ".$to."\r\n"; $message = "Name: " . $name . "\r\n". "Email: " . $email . "\r\n". "Number: " . $number . "\r\n". "Resort Name:". $resort . "\r\n"; if (mail($to,$subject,$message,$headers)){ $replyHeader = "Thank You!"; $replyMessage = "Thank you for using our quick contact form. We will get back to you as soon as possible."; header( "Location: http://localhost/TimeShare/formReturn.php?header={$replyHeader}&message={$replyMessage}" ) ; }else{ $replyHeader = "Oops!"; $replyMessage = "An Error Occured whilst trying to send the form. Please try again later"; header( "Location: http://localhost/TimeShare/formReturn.php?header={$replyHeader}&message={$replyMessage}" ) ; } ?> //File: formReturn.php <body> <div> <h1> <?php echo $_GET['header'] ?> </h1> <p> <?php echo $_GET['message'] ?> </p> </div> </body> A: just update your email thing to send email and redirect ONLY IF if (isset($_POST["email"])){ } otherwise you know that form is not submitted and that you don't want to bother about sending email. and as others suggested, you have to append some get param to the url, like Snicksie (header('Location: http://localhost/TimeShare/formReturn.php?success=[1|0]');) suggested. then on your script you check for that variable to see if you should show anything. e.g. if (isset($_GET["success"])){ if ($_GET["success"] == 1){ show success message } else { show error message } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Debugging - how do I execute code line by line? I am having a hard time debugging my C# app in Visual Studio. I can't figure out how to debug code line by line, but not at the moment the program starts (because I would have to F5 a lot of times as the program takes about 200 lines just to initialize). I mean let's assume I would like the debugging to start in a certain moment. Something like having a breakpoint in every line of code but without actually creating the breakpoints (which would take a lot of time every time I want them to be created). I hope I am somewhat clear. A: I think you want to use Step Into (F11) and Step Over (F10) which will step through your code one line at a time (after you have hit a breakpoint) Or use the toolbar, which is generally waht I do as I can't ever remember the F commands, and it has tooltips: From here: You can step through the code in a number of different methods, you can step through line by line using F11, step over using F10 or step out using (Shift+F11). Step Through: Each and every line of code executed will be debugged. When a method call is invoked the flow enters the method and returns to the calling line after it has completed. Step Over: As above, however you will not debug internal method calls. This is a better debug tool if you already know that a method is working and just wasn’t to call it without debugging. Step Out: If you entered a method using Step Through, Step Out will return you to the point that method was called. A: I'm not entirely clear what you're after... * *If you're not sure how to step line, by line, put a breakpoint where you want to start debugging line by line (or pause the app) then use F10 as "Step Over" or F11 as "Step Into" instead of F5 ("Go"). *If you're not sure how to break into the app when you want to, you can hit the "pause" button in the debugger at any time, or add a breakpoint where you want to stop even after the app has started. If neither of these is helpful, please give more information. A: Instead of clicking the Run button, click the Step Over button to start your project. You won't need any breakpoints (although they are helpful) and you can start running your code line by line. Just keep clicking Step Over (or Step Into if you want to step into a method's implementation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7528302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: How to detect non-busy machines over a LAN automatically? I'm writing an MPI program to be run over a local area network. These machines can be ssh'd to by any student at any time. Although I always test my program at night, the performance has been very inconsistent. My guess is that some nodes were busy when I ran the program. So my question is: can I write a script to detect non-busy machines and update the machine file? What's an easy way to write it? Thanks a lot. A: SSH into each machine, then read the /proc/loadavg file or determine the "business" in some other way. A: I think the easiest way would be installing the check_load[1] script from Nagios to every node you want to check and call it via ssh with some sensible parameters: # /usr/lib64/nagios/plugins/check_load -w 1,2,3 -c 3,4,5 OK - load average: 0.20, 0.43, 0.50|load1=0.200;1.000;3.000;0; load5=0.430;2.000;4.000;0; load15=0.500;3.000;5.000;0; # /usr/lib64/nagios/plugins/check_load -w 0.1,2,3 -c 3,4,5 WARNING - load average: 0.18, 0.43, 0.50|load1=0.180;0.100;3.000;0; load5=0.430;2.000;4.000;0; load15=0.500;3.000;5.000;0; # /usr/lib64/nagios/plugins/check_load -w 0.01,2,3 -c 0.1,4,5 CRITICAL - load average: 0.41, 0.46, 0.51|load1=0.410;0.010;0.100;0; load5=0.460;2.000;4.000;0; load15=0.510;3.000;5.000;0; CRITICAL would mean "really busy", WARNING could be "is kinda busy" and OK would mean "the machine is idle". You have to pay attention for the tresholds you have to give as 1/5/15 minute for warning and critical; for instance, a machine with 16 cores having a load of 3 is perfectly ok, while a load of 3 on a single-core machine would mean it's really really busy. Good luck! Alex. [1] http://nagiosplugins.org/man/check_load
{ "language": "en", "url": "https://stackoverflow.com/questions/7528311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove duplication code from methods that depend on return result of other method In ASP.NET MVC application in controller class I have a method protected ActionResult VerifySanctions(string sanction) { bool hasSanctions = this.qualificationSanctionsService.HasSanctions(sanction); if (hasSanctions) { return this.RedirectToAction("Index", "Home"); } return null; } This method contains common logic from different other actions from different controller I decided to create a base class for controller that will keep this method and derive other controller from it. But problem is in when I call this method from derived class actions I need to verify if not null and then return the result for example public ActionResult RegistrationTracking(EncryptedId sourceId) { // some code var registration = learnerRegistrationService.Get(sourceId); var result = this.VerifySanctions(registration.Qualification); if (result != null) { return result; } // some code return this.View(); } in other actions I need to verify if result not null again public ActionResult Index(EncryptedId achievableVersionId) { var achievableVersion = achievableVersionService.Get(achievableVersionId); var verificationResult = this.VerifySanctions(achievableVersion); if (verificationResult != null) { return verificationResult; } //some code return View(); } And I want to avoid duplication code, can anyone help me with example or advise? What I need that if don't pass verification by method VerifySanction() then do nothing, else return Action result. UPDATE the actions could like this public ActionResult ModifyUnits(EncryptedId sourceId) { var registration = learnerRegistrationService.Get(sourceId); Check.Require(registration != null); Check.Require(registration.Enrolment != null, "QualificationEnrolment is null - RegistrationAmendments / ModifyUnits"); var result = this.VerifySanctions(registration.Qualification, LookupOrganisationAchievableStatus.Sanction3); if (result != null) { return result; } if (!this.organisationAchievableService.IsAccessibleAchievableVersion(registration.Qualification.Id, this.GetOrganisationId())) { return new PopupFormResult().Notify(MUI.PleaseSelectACentre); } SetEnrolmentViewData(registration.Enrolment); ViewData["registrationId"] = sourceId; var isComposite = registration.Enrolment.IsComposite(); ViewData["isComposite"] = isComposite; this.SetSelectedUnitsViewData(registration, isComposite); this.SetSelectedQualificationUnitsViewData(isComposite, registration); return this.PartialView("ModifyUnits", new List<UnitDisplay>()); } Thanks in advance A: This should work: public ActionResult RegistrationTracking(EncryptedId sourceId) { var registration = learnerRegistrationService.Get(sourceId); return VerifySanctions(registration.Qualification, View()); } private ActionResult VerifySanctions(Sanction sanction, ViewResult view) { bool hasSanctions = this.qualificationSanctionsService.HasSanctions(sanction); if (hasSanctions) { return RedirectToAction("Index", "Home"); } return view; } A: You could add a method in a default controller extended by all your controller to embed this logic. For example, private ActionResult ViewWithSanction(string sanction, ActionResult default) { bool hasSanctions = this.qualificationSanctionsService.HasSanctions(sanction); if (hasSanctions) { return this.RedirectToAction("Index", "Home"); } return default; } And then your method could looks like public ActionResult RegistrationTracking(EncryptedId sourceId) { var registration = learnerRegistrationService.Get(sourceId); return ViewWithSanction (registration.Qualification, View()); } public ActionResult Index(EncryptedId achievableVersionId) { var achievableVersion = achievableVersionService.Get(achievableVersionId); return ViewWithSanction (achievableVersion, View()); } A: Pass the Func<ActionResult> that will execute when hasSanctions is false private ActionResult VerifySanctions(Sanction sanction, Func<ActionResult> whenNoSanctions) { bool hasSanctions = this.qualificationSanctionsService.HasSanctions(sanction); if (hasSanctions) { return RedirectToAction("Index", "Home"); } return whenNoSanctions(); } And calling return VerifySanctions(registration.Qualification, ()=> { //any code that returns ActionResult }); UPDATE: You could extract your not null part as separate method private ActionResult WhenNoSanctions() { if(!this.organisationAchievableService.IsAccessibleAchievableVersion(registration.Qualification.Id, this.GetOrganisationId())) { return new PopupFormResult().Notify(MUI.PleaseSelectACentre); } SetEnrolmentViewData(registration.Enrolment); ViewData["registrationId"] = sourceId; var isComposite = registration.Enrolment.IsComposite(); ViewData["isComposite"] = isComposite; this.SetSelectedUnitsViewData(registration, isComposite); this.SetSelectedQualificationUnitsViewData(isComposite, registration); return this.PartialView("ModifyUnits", new List<UnitDisplay>()); } And call VerifySanctions as return VerifySanctions(registration.Qualification, WhenNoSanctions);
{ "language": "en", "url": "https://stackoverflow.com/questions/7528318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java for-loop generating MAC addresses Trying to make a loop of MAC address values with: String macAddr = "AA:BB:CC:DD:"; char[] chars = {'A', 'B', 'C', 'D', 'E', 'F'}; String[] strings = {"0", "0", "0", "0"}; for (int i=0; i<strings.length; i++) { //counter from 0 to F for (int d = 0; d <= 9; d++) { strings[i] = ""+d; print(); } for (int d = 0; d< chars.length; d++) { strings[i] = ""+chars[d]; print(); } } where print() is: System.out.println(macAddr+strings[3]+strings[2]+":"+strings[1]+strings[0]); But i'm getting run-over: AA:BB:CC:DD:00:0D AA:BB:CC:DD:00:0E AA:BB:CC:DD:00:0F AA:BB:CC:DD:00:0F AA:BB:CC:DD:00:1F AA:BB:CC:DD:00:2F AA:BB:CC:DD:00:3F The two problems are the dual values at each crossover (e.g. AA:BB:CC:DD:00:0F) and the values stopping at F on each value. I'm trying to get them as: AA:BB:CC:DD:00:0D AA:BB:CC:DD:00:0E AA:BB:CC:DD:00:0F AA:BB:CC:DD:00:11 AA:BB:CC:DD:00:12 AA:BB:CC:DD:00:13 etc. Cheers :) A: Use a long to store your mac address and create a small function to convert it to a String. public static String toMacString(long mac) { if (mac > 0xFFFFFFFFFFFFL || mac < 0) throw new IllegalArgumentException("mac out of range"); StringBuffer m = new StringBuffer(Long.toString(mac, 16)); while (m.length() < 12) m.insert(0, "0"); for (int j = m.length() - 2; j >= 2; j-=2) m.insert(j, ":"); return m.toString().toUpperCase(); } public static void main(String[] args) { long mac = 0xAABBCCDD0000L; for (long i = 0; i < 1000; i++) System.out.println(toMacString(mac++)); } Example output: AA:BB:CC:DD:00:00 AA:BB:CC:DD:00:01 AA:BB:CC:DD:00:02 AA:BB:CC:DD:00:03 AA:BB:CC:DD:00:04 AA:BB:CC:DD:00:05 AA:BB:CC:DD:00:06 .... AA:BB:CC:DD:03:DF AA:BB:CC:DD:03:E0 AA:BB:CC:DD:03:E1 AA:BB:CC:DD:03:E2 AA:BB:CC:DD:03:E3 AA:BB:CC:DD:03:E4 AA:BB:CC:DD:03:E5 AA:BB:CC:DD:03:E6 AA:BB:CC:DD:03:E7 A: Try this for keeping it simple: public static void main(String... args) { String macAddr = "AA:BB:CC:DD:"; for (int i = 0; i < 256; i++) { for (int j = 0; j < 256; j++) { String fullAddr = String.format(macAddr + "%02X:%02X", i, j); System.out.println(fullAddr); } } } Output (abbreviated): AA:BB:CC:DD:00:00 AA:BB:CC:DD:00:01 AA:BB:CC:DD:00:.. AA:BB:CC:DD:00:10 AA:BB:CC:DD:00:0A AA:BB:CC:DD:00:.. AA:BB:CC:DD:00:0F AA:BB:CC:DD:00:10 AA:BB:CC:DD:00:.. AA:BB:CC:DD:00:FF AA:BB:CC:DD:01:00 AA:BB:CC:DD:..:.. AA:BB:CC:DD:FF:FF A: String[] Mac = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; Random rd = new Random(); rd.nextInt(15); String result=""; for(int i=0;i<6;i++){ String a = Mac[rd.nextInt(15)]; String b = Mac[rd.nextInt(15)]; result+=a+b; if(i<5){ result+=":"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7528319", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: gtk.PrintOperation reset status? Is it possible to reset status of printing somehow, or is it always necessary to create new PrintOperation? For example, if you show printPreview, it is necessary to recreate PrintOperation before calling it again. A: Seems that it is... PrintOperation is invalidated after finishing, so it has to be recreated for actual printing ie.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can COMET/ Server Push be achieved on Google app engine? I am new to both Stack overflow and Google app engine. in a Java Web application, how ddo I achieve COMET, are there limitations in terms of connection timeout or if that is not possible, can a websocket server be implemented on appengine ? A: If you need server-to-client push, you have to use Channel API for GAE. It not a COMET or WebSockets, technically, but it's same. And, I guess, I'll be functioning as a web sockets, sometimes in future (maybe it's already working, but i don't know where to get a browser that supports this feature, right now. Can anyone correct me there?). Btw, for you it'll be still same Channel API
{ "language": "en", "url": "https://stackoverflow.com/questions/7528325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why HashedSet forces loading lazy collection? I query items with lazy collections in via nHibernate. Items are queried without fetching collections. But when i try to create HashedSet var hashedSet = new HashedSet<Thing>(Session.Query<Thing>()) from those items all lazy stuff is fetched. Whats causing that? [Serializable] public class Thing { public virtual String Name { get; set; } public Thing() { OtherThings = new HashedSet<OtherThing>(); } public virtual ISet<OtherThing> OtherThings { get; set; } } A: Maybe you have overridden GetHashCode() in the entity (or any base class of it) and access the properties there?
{ "language": "en", "url": "https://stackoverflow.com/questions/7528328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Egit: Checking out two different versions What is the best way to checkout two different versions of a project in Eclipse Egit and have them show up in seperate directories? My situation is as follows. I was working on a project and made some good changes and some bad changes (State A). I want to check out a previous working version of my project (State B) and copy and paste some of the good changes from State A into State B. Every time I try to check anything out it just replaces the files shown in the package explorer. A: That's because one Git repository has one working directory, and the working directory reflects all branch changes etc. So if you want two versions, you need two repositories (just clone the one). Since you cannot import two projects with the same name in one Eclipse workspace, you have to rename one project after the checkout and before project importing. But you could also use the Compare mode. Select the project, choose Compare with -> Branch, Tag or Reference and select the other branch, with which you want to compare. Then you can just add the contents from the other branch to the current files. A: What you're asking for is not very git-ish, but here's how you'd do it. You'd take your existing repository and you'd clone it to a new repo. In that new repo, you'd check out your "to" version (either by branch or tag or commit ID) and in the old one you'd check out the "from" version. Then you'd point Eclipse at the two directories to create projects from them. Then you've got two projects in Eclipse, each containing a working directory that is the different versions, and you can manually move code from "from" to "to". Once your "to" project is the way you want it, commit that, delete the "from" repo and project, and Bob's your uncle. The git-ish way of doing this is to use git bisect to find the commit that contained the bad change, and then revert that commit either in whole or in part.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to check-out multiple files from various folders in TFS in a single operation Is there a way to check-out multiple files from various folders in TFS in a single operation. i have modified multiple files under muliple direcotries but i want them to check-out in a single click and check-in also in single click. Thanks. A: Yes, using the TFS command line client (tf.exe). If you have tf.exe available, you could do this using the checkout command. (If you don't, take a look at this question: How to get tf.exe (TFS command line client)?) * *Checkout command for Visual Studio 2013-2015: https://www.visualstudio.com/en-us/docs/tfvc/checkout-or-edit-command *Older versions: https://msdn.microsoft.com/en-us/library/1yft8zkw(v=vs.80).aspx Example: Separate multiple files by spaces tf checkout file2.cs file2.cs Example: Use a wildcard to search tf checkout *.csproj /recursive A: Yes, in the solution explorer hold down the control key as you select files and them check them out all at once.
{ "language": "en", "url": "https://stackoverflow.com/questions/7528335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }