Search Results

Search found 2136 results on 86 pages for 'dominik str'.

Page 9/86 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • C++ stringstream, string, and char* conversion confusion

    - by Graphics Noob
    My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*? This code example will explain it better than I can #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; } The assumption that stringstream.str().c_str() could be assigned to a const char* led to a bug that took me a while to track down. For bonus points, can anyone explain why replacing the cout statement with cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???) prints the strings correctly? I'm compiling in Visual Studio 2008.

    Read the article

  • Java: Generics, Class.isaAssignableFrom, and type casting

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • system out output for double numbers in a java program

    - by Nikunj Chauhan
    I have a program where I am generating two double numbers by adding several input prices from a file based on a condition. String str; double one = 0.00; double two = 0.00; BufferedReader in = new BufferedReader(new FileReader(myFile)); while((str = in.readLine()) != null){ if(str.charAt(21) == '1'){ one += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51)); } else{ two += Double.parseDouble(str.substring(38, 49) + "." + str.substring(49, 51)); } } in.close(); System.out.println("One: " + one); System.out.println("Two: " + two); The output is like: One: 2773554.02 Two: 6.302505836000001E7 Question: None of the input have more then two decimals in them. The way one and two are getting calculated exactly same. Then why the output format is like this. What I am expecting is: One: 2773554.02 Two: 63025058.36 Why the printing is in two different formats ? I want to write the outputs again to a file and thus there must be only two digits after decimal.

    Read the article

  • Python: Copying files with special characters in path

    - by erikderwikinger
    Hi is there any possibility in Python 2.5 to copy files having special chars (Japanese chars, cyrillic letters) in their path? shutil.copy cannot handle this. here is some example code: import copy, os,shutil,sys fname=os.getenv("USERPROFILE")+"\\Desktop\\testfile.txt" print fname print "type of fname: "+str(type(fname)) fname0 = unicode(fname,'mbcs') print fname0 print "type of fname0: "+str(type(fname0)) fname1 = unicodedata.normalize('NFKD', fname0).encode('cp1251','replace') print fname1 print "type of fname1: "+str(type(fname1)) fname2 = unicode(fname,'mbcs').encode(sys.stdout.encoding) print fname2 print "type of fname2: "+str(type(fname2)) shutil.copy(fname2,'C:\\') the output on a Russian Windows XP C:\Documents and Settings\+????????????\Desktop\testfile.txt type of fname: <type 'str'> C:\Documents and Settings\?????????????\Desktop\testfile.txt type of fname0: <type 'unicode'> C:\Documents and Settings\+????????????\Desktop\testfile.txt type of fname1: <type 'str'> C:\Documents and Settings\?????????????\Desktop\testfile.txt type of fname2: <type 'str'> Traceback (most recent call last): File "C:\Test\getuserdir.py", line 23, in <module> shutil.copy(fname2,'C:\\') File "C:\Python25\lib\shutil.py", line 80, in copy copyfile(src, dst) File "C:\Python25\lib\shutil.py", line 46, in copyfile fsrc = open(src, 'rb') IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\\x80\ xa4\xac\xa8\xad\xa8\xe1\xe2\xe0\xa0\xe2\xae\xe0\\Desktop\\testfile.txt'

    Read the article

  • Java: Typecasting to Generics

    - by bguiz
    This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings. This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries. This is the code that I have got, and it is obviously broken. private <T extends Object> Map<String, T> fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz) { Map<String, T> val = new HashMap<String, T>(); List<Entry> jxents = jxval.getEntry(); T value; String str; for (Entry jxent : jxents) { str = jxent.getValue(); value = null; if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } else if (clasz.isAssignableFrom(Float.class)) { value = (T)(Float.parseFloat(str)); } else { logger.warn("Unsupported value type encountered in key-value pairs, continuing anyway: " + clasz.getName()); } val.put(jxent.getKey(), value); } return val; } This is the bit that I want to solve: if (clasz.isAssignableFrom(Boolean.class)) { value = (T)(Boolean.parseBoolean(str)); } else if (clasz.isAssignableFrom(Integer.class)) { value = (T)(Integer.parseInt(str)); } I get: Inconvertible types required: T found: Boolean Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom. Any suggestions? Sample method invocation: Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

    Read the article

  • gwt get array button value

    - by graybow
    My gwt project have flexTable show data of image and button on each row and coll. But my button won't work properly. this is my current code: private Button[] b = new Button[]{new Button("a"),...,new Button("j")}; private int z=0; ... public void UpdateTabelGallery(JsArray str){ for(int i=0; i str.length(); i++){ b[i].setText(str.gettitle()); UpdateTabelGallery(str.get(i)); } } public void UpdateTabelGallery(GalleryData str){ Image img = new Image(); img.setUrl(str.getthumburl()); HTML himage= new HTML("a href="+str.geturl()+""+ img +"/a" + b[z] ); TabelGaleri.setWidget(y, x, himage); //is here th right place? b[z].addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { Window.alert("I wan to show the clicked button text" + b[z].getText()); } }); z++; } I'm still confuse where I should put my button handler. With this current code seems the clickhandler didn't work inside a looping. And if I put it outside loop its not working because I need to know which button clicked. I need to get my index button.but how? Is there any option than array button? thanks

    Read the article

  • How to receive sms from a special phone number?

    - by Pariya
    I wrote a send and receive sms in android successfully. I want my program to be able to receive sms from a special number("+9856874236"). But, if the SMS is from any other number, it should go to the phone's message inbox and not to my application. import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; import android.util.Log; public class SmsReceiver extends BroadcastReceiver { public String str = ""; @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object messages[] = (Object[]) bundle.get("pdus"); SmsMessage[] msgs = null; if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage smsMessage[] = new SmsMessage[messages.length]; String msg_from=""; for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]); msg_from += msgs[n].getOriginatingAddress(); } String receivedMessage = smsMessage[0].getMessageBody().toString().toUpperCase(); if(msg_from .equals("+989124236870")) { for (int n = 0; n < messages.length; n++) { smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]); str += "SMS from " + msgs[n].getOriginatingAddress(); str += " :"; //str += "sms az shomare makhsus"; str += msgs[n].getMessageBody().toString(); str += "\n"; abortBroadcast(); } Intent act = new Intent(context, MainActivity.class); act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); act.putExtra("message", str); context.startActivity(act); } } } }

    Read the article

  • Linked lists in Java - Help with writing methods

    - by user368241
    Representation of a string in linked lists In every intersection in the list there will be 3 fields : The letter itself. The number of times it appears consecutively. A pointer to the next intersection in the list. The following class CharNode represents a intersection in the list : public class CharNode { private char _data; private int _value; private charNode _next; public CharNode (char c, int val, charNode n) { _data = c; _value = val; _next = n; } public charNode getNext() { return _next; } public void setNext (charNode node) { _next = node; } public int getValue() { return _value; } public void setValue (int v) { value = v; } public char getData() { return _data; } public void setData (char c) { _data = c; } } The class StringList represents the whole list : public class StringList { private charNode _head; public StringList() { _head = null; } public StringList (CharNode node) { _head = node; } } Add methods to the class StringList according to the details : (I will add methods gradually according to my specific questions) (Pay attention, these are methods from the class String and we want to fulfill them by the representation of a string by a list as explained above) Pay attention to all the possible error cases. Write what is the time complexity and space complexity of every method that you wrote. Make sure the methods you wrote are effective. It is NOT allowed to use ready classes of Java. It is NOT allowed to move to string and use string operations. 1) public int indexOf (int ch) - returns the index in the string it is operated on of the first appeareance of the char "ch". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex isn't in the range, returns -1. Here is my try : public int indexOf (int ch) { int count = 0; charNode pos = _head; if (pos == null ) { return -1; } for (pos = _head; pos!=null && pos.getData()!=ch; pos = pos.getNext()) { count = count + pos.getValue(); } if (pos==null) return -1; return count; } Time complexity = O(N) Space complexity = O(1) EDIT : I have a problem. I tested it in BlueJ and if the char ch doesn't appear it returns -1 but if it does, it always returns 0 and I don't understand why... I am confused. How can the compiler know that the value is the number of times the letter appears consecutively? Can I assume this because its given on the question or what? If it's true and I can assume this, then my code should be correct right? Ok I just spoke with my instructor and she said it isn't required to write it in the exercise but in order for me to test that it indeed works, I need to open a new class and write a code for making a list so that the the value of every node is the number of times the letter appears consecutively. Can someone please assist me? So I will copy+paste to BlueJ and this way I will be able to test all the methods. Meanwhile I am moving on to the next methods. 2) public int indexOf (int ch, int fromIndex) - returns the index in the string it is operated on of the first appeareance of the char "ch", as the search begins in the index "fromIndex". If the char "ch" doesn't appear in the string, returns -1. If the value of fromIndex doesn't appear in the range, returns -1. Here is my try: public int indexOf (int ch, int fromIndex) { int count = 0, len=0, i; charNode pos = _head; CharNode cur = _head; for (pos = _head; pos!=null; pos = pos.getNext()) { len = len+1; } if (fromIndex<0 || fromIndex>=len) return -1; for (i=0; i<fromIndex; i++) { cur = cur.getNext(); } if (cur == null ) { return -1; } for (cur = _head; cur!=null && cur.getData()!=ch; cur = cur.getNext()) { count = count + cur.getValue(); } if (cur==null) return -1; return count; } Time complexity = O(N) ? Space complexity = O(1) 3) public StringList concat (String str) - returns a string that consists of the string that it is operated on and in its end the string "str" is concatenated. Here is my try : public StringList concat (String str) { String str = ""; charNode pos = _head; if (str == null) return -1; for (pos = _head; pos!=null; pos = pos.getNext()) { str = str + pos.getData(); } str = str + "str"; return str; } Time complexity = O(N) Space complexity = O(1)

    Read the article

  • Python script is exiting with no output and I have no idea why

    - by Adam Tuttle
    I'm attempting to debug a Subversion post-commit hook that calls some python scripts. What I've been able to determine so far is that when I run post-commit.bat manually (I've created a wrapper for it to make it easier) everything succeeds, but when SVN runs it one particular step doesn't work. We're using CollabNet SVNServe, which I know from the documentation removes all environment variables. This had caused some problems earlier, but shouldn't be an issue now. Before Subversion calls a hook script, it removes all variables - including $PATH on Unix, and %PATH% on Windows - from the environment. Therefore, your script can only run another program if you spell out that program's absolute name. The relevant portion of post-commit.bat is: echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log set SITENAME=staging set SVNPATH=branches/staging/wwwroot/ "C:\Python3\python.exe" C:\svn-repos\company\hooks\svn2ftp.py ^ --svnUser="svnusername" ^ --svnPass="svnpassword" ^ --ftp-user=ftpuser ^ --ftp-password=ftppassword ^ --ftp-remote-dir=/ ^ --access-url=svn://10.0.100.6/company ^ --status-file="C:\svn-repos\company\hooks\svn2ftp-%SITENAME%.dat" ^ --project-directory=%SVNPATH% "staging.company.com" %1 %2 >> c:\svn-repos\company\hooks\svn2ftp.out.log echo -------------------------- >> c:\svn-repos\company\hooks\svn2ftp.out.log When I run post-commit.bat manually, for example: post-commit c:\svn-repos\company 12345, I see output like the following in svn2ftp.out.log: -------------------------- args1: c:\svn-repos\company args0: staging.company.com abspath: c:\svn-repos\company project_dir: branches/staging/wwwroot/ local_repos_path: c:\svn-repos\company getting youngest revision... done, up-to-date -------------------------- However, when I commit something to the repo and it runs automatically, the output is: -------------------------- -------------------------- svn2ftp.py is a bit long, so I apologize but here goes. I'll have some notes/disclaimers about its contents below it. #!/usr/bin/env python """Usage: svn2ftp.py [OPTION...] FTP-HOST REPOS-PATH Upload to FTP-HOST changes committed to the Subversion repository at REPOS-PATH. Uses svn diff --summarize to only propagate the changed files Options: -?, --help Show this help message. -u, --ftp-user=USER The username for the FTP server. Default: 'anonymous' -p, --ftp-password=P The password for the FTP server. Default: '@' -P, --ftp-port=X Port number for the FTP server. Default: 21 -r, --ftp-remote-dir=DIR The remote directory that is expected to resemble the repository project directory -a, --access-url=URL This is the URL that should be used when trying to SVN export files so that they can be uploaded to the FTP server -s, --status-file=PATH Required. This script needs to store the last successful revision that was transferred to the server. PATH is the location of this file. -d, --project-directory=DIR If the project you are interested in sending to the FTP server is not under the root of the repository (/), set this parameter. Example: -d 'project1/trunk/' This should NOT start with a '/'. 2008.5.2 CKS Fixed possible Windows-related bug with tempfile, where the script didn't have permission to write to the tempfile. Replaced this with a open()-created file created in the CWD. 2008.5.13 CKS Added error logging. Added exception for file-not-found errors when deleting files. 2008.5.14 CKS Change file open to 'rb' mode, to prevent Python's universal newline support from stripping CR characters, causing later comparisons between FTP and SVN to report changes. """ try: import sys, os import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='svn2ftp.debug.log', filemode='a' ) console = logging.StreamHandler() console.setLevel(logging.ERROR) logging.getLogger('').addHandler(console) import getopt, tempfile, smtplib, traceback, subprocess from io import StringIO import pysvn import ftplib import inspect except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) print(stack_trace) #end capture sys.exit(1) #defaults host = "" user = "anonymous" password = "@" port = 21 repo_path = "" local_repos_path = "" status_file = "" project_directory = "" remote_base_directory = "" toAddrs = "[email protected]" youngest_revision = "" def email(toAddrs, message, subject, fromAddr='[email protected]'): headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromAddr, toAddrs, subject) message = headers + message logging.info('sending email to %s...' % toAddrs) server = smtplib.SMTP('smtp.company.com') server.set_debuglevel(1) server.sendmail(fromAddr, toAddrs, message) server.quit() logging.info('email sent') def captureErrorMessage(e): sout = StringIO() traceback.print_exc(file=sout) errorMessage = '\n'+('*'*80)+('\n%s'%e)+('\n%s\n'%sout.getvalue())+('*'*80) return errorMessage def usage_and_exit(errmsg): """Print a usage message, plus an ERRMSG (if provided), then exit. If ERRMSG is provided, the usage message is printed to stderr and the script exits with a non-zero error code. Otherwise, the usage message goes to stdout, and the script exits with a zero errorcode.""" if errmsg is None: stream = sys.stdout else: stream = sys.stderr print(__doc__, file=stream) if errmsg: print("\nError: %s" % (errmsg), file=stream) sys.exit(2) sys.exit(0) def read_args(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision try: opts, args = getopt.gnu_getopt(sys.argv[1:], "?u:p:P:r:a:s:d:SU:SP:", ["help", "ftp-user=", "ftp-password=", "ftp-port=", "ftp-remote-dir=", "access-url=", "status-file=", "project-directory=", "svnUser=", "svnPass=" ]) except getopt.GetoptError as msg: usage_and_exit(msg) for opt, arg in opts: if opt in ("-?", "--help"): usage_and_exit() elif opt in ("-u", "--ftp-user"): user = arg elif opt in ("-p", "--ftp-password"): password = arg elif opt in ("-SU", "--svnUser"): svnUser = arg elif opt in ("-SP", "--svnPass"): svnPass = arg elif opt in ("-P", "--ftp-port"): try: port = int(arg) except ValueError as msg: usage_and_exit("Invalid value '%s' for --ftp-port." % (arg)) if port < 1 or port > 65535: usage_and_exit("Value for --ftp-port must be a positive integer less than 65536.") elif opt in ("-r", "--ftp-remote-dir"): remote_base_directory = arg elif opt in ("-a", "--access-url"): repo_path = arg elif opt in ("-s", "--status-file"): status_file = os.path.abspath(arg) elif opt in ("-d", "--project-directory"): project_directory = arg if len(args) != 3: print(str(args)) usage_and_exit("host and/or local_repos_path not specified (" + len(args) + ")") host = args[0] print("args1: " + args[1]) print("args0: " + args[0]) print("abspath: " + os.path.abspath(args[1])) local_repos_path = os.path.abspath(args[1]) print('project_dir:',project_directory) youngest_revision = int(args[2]) if status_file == "" : usage_and_exit("No status file specified") def main(): global host global user global password global port global repo_path global local_repos_path global status_file global project_directory global remote_base_directory global youngest_revision read_args() #repository,fs_ptr #get youngest revision print("local_repos_path: " + local_repos_path) print('getting youngest revision...') #youngest_revision = fs.youngest_rev(fs_ptr) assert youngest_revision, "Unable to lookup youngest revision." last_sent_revision = get_last_revision() if youngest_revision == last_sent_revision: # no need to continue. we should be up to date. print('done, up-to-date') return if last_sent_revision or youngest_revision < 10: # Only compare revisions if the DAT file contains a valid # revision number. Otherwise we risk waiting forever while # we parse and uploading every revision in the repo in the case # where a repository is retroactively configured to sync with ftp. pysvn_client = pysvn.Client() pysvn_client.callback_get_login = get_login rev1 = pysvn.Revision(pysvn.opt_revision_kind.number, last_sent_revision) rev2 = pysvn.Revision(pysvn.opt_revision_kind.number, youngest_revision) summary = pysvn_client.diff_summarize(repo_path, rev1, repo_path, rev2, True, False) print('summary len:',len(summary)) if len(summary) > 0 : print('connecting to %s...' % host) ftp = FTPClient(host, user, password) print('connected to %s' % host) ftp.base_path = remote_base_directory print('set remote base directory to %s' % remote_base_directory) #iterate through all the differences between revisions for change in summary : #determine whether the path of the change is relevant to the path that is being sent, and modify the path as appropriate. print('change path:',change.path) ftp_relative_path = apply_basedir(change.path) print('ftp rel path:',ftp_relative_path) #only try to sync path if the path is in our project_directory if ftp_relative_path != "" : is_file = (change.node_kind == pysvn.node_kind.file) if str(change.summarize_kind) == "delete" : print("deleting: " + ftp_relative_path) try: ftp.delete_path("/" + ftp_relative_path, is_file) except ftplib.error_perm as e: if 'cannot find the' in str(e) or 'not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise elif str(change.summarize_kind) == "added" or str(change.summarize_kind) == "modified" : local_file = "" if is_file : local_file = svn_export_temp(pysvn_client, repo_path, rev2, change.path) print("uploading file: " + ftp_relative_path) ftp.upload_path("/" + ftp_relative_path, is_file, local_file) if is_file : os.remove(local_file) elif str(change.summarize_kind) == "normal" : print("skipping 'normal' element: " + ftp_relative_path) else : raise str("Unknown change summarize kind: " + str(change.summarize_kind) + ", path: " + ftp_relative_path) ftp.close() #write back the last revision that was synced print("writing last revision: " + str(youngest_revision)) set_last_revision(youngest_revision) # todo: undo def get_login(a,b,c,d): #arguments don't matter, we're always going to return the same thing try: return True, "svnUsername", "svnPassword", True except Exception as e: logging.error(e) #capture the location of the error frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace) #end capture sys.exit(1) #functions for persisting the last successfully synced revision def get_last_revision(): if os.path.isfile(status_file) : f=open(status_file, 'r') line = f.readline() f.close() try: i = int(line) except ValueError: i = 0 else: i = 0 f = open(status_file, 'w') f.write(str(i)) f.close() return i def set_last_revision(rev) : f = open(status_file, 'w') f.write(str(rev)) f.close() #augmented ftp client class that can work off a base directory class FTPClient(ftplib.FTP) : def __init__(self, host, username, password) : self.base_path = "" self.current_path = "" ftplib.FTP.__init__(self, host, username, password) def cwd(self, path) : debug_path = path if self.current_path == "" : self.current_path = self.pwd() print("pwd: " + self.current_path) if not os.path.isabs(path) : debug_path = self.base_path + "<" + path path = os.path.join(self.current_path, path) elif self.base_path != "" : debug_path = self.base_path + ">" + path.lstrip("/") path = os.path.join(self.base_path, path.lstrip("/")) path = os.path.normpath(path) #by this point the path should be absolute. if path != self.current_path : print("change from " + self.current_path + " to " + debug_path) ftplib.FTP.cwd(self, path) self.current_path = path else : print("staying put : " + self.current_path) def cd_or_create(self, path) : assert os.path.isabs(path), "absolute path expected (" + path + ")" try: self.cwd(path) except ftplib.error_perm as e: for folder in path.split('/'): if folder == "" : self.cwd("/") continue try: self.cwd(folder) except: print("mkd: (" + path + "):" + folder) self.mkd(folder) self.cwd(folder) def upload_path(self, path, is_file, local_path) : if is_file: (path, filename) = os.path.split(path) self.cd_or_create(path) # Use read-binary to avoid universal newline support from stripping CR characters. f = open(local_path, 'rb') self.storbinary("STOR " + filename, f) f.close() else: self.cd_or_create(path) def delete_path(self, path, is_file) : (path, filename) = os.path.split(path) print("trying to delete: " + path + ", " + filename) self.cwd(path) try: if is_file : self.delete(filename) else: self.delete_path_recursive(filename) except ftplib.error_perm as e: if 'The system cannot find the' in str(e) or '550 File not found' in str(e): # Log, but otherwise ignore path-not-found errors # when deleting, since it's not a disaster if the file # we want to delete is already gone. logging.error(captureErrorMessage(e)) else: raise def delete_path_recursive(self, path): if path == "/" : raise "WARNING: trying to delete '/'!" for node in self.nlst(path) : if node == path : #it's a file. delete and return self.delete(path) return if node != "." and node != ".." : self.delete_path_recursive(os.path.join(path, node)) try: self.rmd(path) except ftplib.error_perm as msg : sys.stderr.write("Error deleting directory " + os.path.join(self.current_path, path) + " : " + str(msg)) # apply the project_directory setting def apply_basedir(path) : #remove any leading stuff (in this case, "trunk/") and decide whether file should be propagated if not path.startswith(project_directory) : return "" return path.replace(project_directory, "", 1) def svn_export_temp(pysvn_client, base_path, rev, path) : # Causes access denied error. Couldn't deduce Windows-perm issue. # It's possible Python isn't garbage-collecting the open file-handle in time for pysvn to re-open it. # Regardless, just generating a simple filename seems to work. #(fd, dest_path) = tempfile.mkstemp() dest_path = tmpName = '%s.tmp' % __file__ exportPath = os.path.join(base_path, path).replace('\\','/') print('exporting %s to %s' % (exportPath, dest_path)) pysvn_client.export( exportPath, dest_path, force=False, revision=rev, native_eol=None, ignore_externals=False, recurse=True, peg_revision=rev ) return dest_path if __name__ == "__main__": logging.info('svnftp.start') try: main() logging.info('svnftp.done') except Exception as e: # capture the location of the error for debug purposes frame = inspect.currentframe() stack_trace = traceback.format_stack(frame) logging.debug(stack_trace[:-1]) print(stack_trace) # end capture error_text = '\nFATAL EXCEPTION!!!\n'+captureErrorMessage(e) subject = "ALERT: SVN2FTP Error" message = """An Error occurred while trying to FTP an SVN commit. repo_path = %(repo_path)s\n local_repos_path = %(local_repos_path)s\n project_directory = %(project_directory)s\n remote_base_directory = %(remote_base_directory)s\n error_text = %(error_text)s """ % globals() email(toAddrs, message, subject) logging.error(e) Notes/Disclaimers: I have basically no python training so I'm learning as I go and spending lots of time reading docs to figure stuff out. The body of get_login is in a try block because I was getting strange errors saying there was an unhandled exception in callback_get_login. Never figured out why, but it seems fine now. Let sleeping dogs lie, right? The username and password for get_login are currently hard-coded (but correct) just to eliminate variables and try to change as little as possible at once. (I added the svnuser and svnpass arguments to the existing argument parsing.) So that's where I am. I can't figure out why on earth it's not printing anything into svn2ftp.out.log. If you're wondering, the output for one of these failed attempts in svn2ftp.debug.log is: 2012-09-06 15:18:12,496 INFO svnftp.start 2012-09-06 15:18:12,496 INFO svnftp.done And it's no different on a successful run. So there's nothing useful being logged. I'm lost. I've gone way down the rabbit hole on this one, and don't know where to go from here. Any ideas?

    Read the article

  • Annotations (@EJB, @Resource, ...) within a RESTful Service

    - by Dominik
    Hi! I'm trying to inject a EJB within my RESTful Service (RESTEasy) via Annotations. public class MyServelet implements MyServeletInterface { ... @EJB MyBean mybean; ... } Unfortunately there is no compilation or AS error, the variable "mybean" is just null and I get a NullPointerException when I try to use it. What I'm doing wrong? Here are some side-informations about my architecture: JBoss 4.2.2.GA Java version: 1.5.0_17 local MDB-Project remote EJB-Project WAR Project with the RESTful Service which uses the remote EJB and sends messages to the local MDB-Project Thanks in advance! br Dominik p.s: everything is working fine when I use normal context lookup.

    Read the article

  • Where is the Android Metamodel located?

    - by Dominik
    Hey, I would like to use Android for Model-Driven-Software-Development. For this, I need to locate the Android Model in the SDK. I already searched a while for it, but were not able to find it. Has anyone an idea where it could be? Is it possible, that it is the AndroidManifest.xml-File in the folder android-sdk-\platforms\android-x\android.jar? After unpacking this file, I am not able to open that file correctly on Windows XP, because a lot of characters have the wrong character set. Or is it also possible, that it is only located in the source code? Thanks in advance, Dominik

    Read the article

  • JNI_CreateJavaVM: Buffer overrun if I throw an exception in case of failure

    - by Dominik Fretz
    Hi, In a C++ project, I use the JNI invocation API to launch a JVM. I've done a little wrapper arount the JVM so I can use all the needed parts in a OO fashion. So far that works great. Now, if the JVM does not start (JNI_CreateJavaVM returns a value < 0) I'd like to raise an exception within my C++ code.But if I throw an exception after JNI_CreateJavaVM, I get a buffer overrun. If I raise the exception without the JNI_CreateJavaVM call, it works as expected. Does anyone have a clue on what the issue could be here? Or how to debug this? Environment: Windows, Visual Studio 2008 JDK: jrockit27.6jdk16005, but happens with SUN stock one as well Cheers Dominik

    Read the article

  • Presenting UIModalViews in Landscap mode

    - by Dominik
    Hello, I'm trying to present some UIModalFormSheets in a my iPad application. It's working without any problems, except one thing: When I have my iPad in landscape mode my modal form sheet is moving to the center of the screen and THEN rotates into the appropiate angle. All I want is to present the modal form sheet in the right angle according to the view mode (portrait or landscape), BEFORE it is displayed, so that the user doesn't see this rotation. I have tried all the modes for modalTransitionStyle and modalPresentationStyle, but nothing seems to prevent the modal form sheet from rotating after it is displayed. This is what I'm doing: NewFavouriteSheet *newFavouriteSheet = [[NewFavouriteSheet alloc] initWithNibName:@"NewFavouriteSheet" bundle:nil]; newFavouriteSheet.modalPresentationStyle = UIModalPresentationFormSheet; [self presentModalViewController:newFavouriteSheet animated:NO]; Does anyone has a suggestion on how to show the modal view in a correct way? Thanks for help. Dominik

    Read the article

  • a non recursive approach to the problem of generating combinations at fault

    - by mark
    Hi, I wanted a non recursive approach to the problem of generating combination of certain set of characters or numbers. So, given a subset k of numbers n, generate all the possible combination n!/k!(n-k)! The recursive method would give a combination, given the previous one combination. A non recursive method would generate a combination of a given value of loop index i. I approached the problem with this code: Tested with n = 4 and k = 3, and it works, but if I change k to a number 3 it does not work. Is it due to the fact that (n-k)! in case of n = 4 and k = 3 is 1. and if k 3 it will be more than 1? Thanks. int facto(int x); int len,fact,rem=0,pos=0; int str[7]; int avail[7]; str[0] = 1; str[1] = 2; str[2] = 3; str[3] = 4; str[4] = 5; str[5] = 6; str[6] = 7; int tot=facto(n) / facto(n-k) / facto(k); for (int i=0;i<tot;i++) { avail[0]=1; avail[1]=2; avail[2]=3; avail[3]=4; avail[4]=5; avail[5]=6; avail[6]=7; rem = facto(i+1)-1; cout<<rem+1<<". "; for(int j=len;j>0;j--) { int div = facto(j); pos = rem / div; rem = rem % div; cout<<avail[pos]<<" "; avail[pos]=avail[j]; } cout<<endl; } int facto(int x) { int fact=1; while(x0) fact*=x--; return fact; }

    Read the article

  • Creating a tiled map with blender

    - by JamesB
    I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constructing an image of 25600 x 25600 What I need is a script for blender that can create the tiles from the model. I've never written in python before so I've been trying to adapt a couple of the scripts which are already there. So far I've come up with a script, but it doesn't work very well. I'm having real difficulties getting the tiles to line up seamlessly. I'm not too concerned about changing the height of the camera as I can always create the same zoomed out tiles at 6400 x 6400 images and split the resulting images into the correct tiles. Here is what I've got so far... #!BPY """ Name: 'Export Map Tiles' Blender: '242' Group: 'Export' Tip: 'Export to Map' """ import Blender from Blender import Scene,sys from Blender.Scene import Render def init(): thumbsize = 200 CameraHeight = 4.4 YStart = -8 YMove = 4 XStart = -8 XMove = 4 ZoomLevel = 1 Path = "/Images/Map/" Blender.drawmap = [thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path] def show_prefs(): buttonthumbsize = Blender.Draw.Create(Blender.drawmap[0]); buttonCameraHeight = Blender.Draw.Create(Blender.drawmap[1]) buttonYStart = Blender.Draw.Create(Blender.drawmap[2]) buttonYMove = Blender.Draw.Create(Blender.drawmap[3]) buttonXStart = Blender.Draw.Create(Blender.drawmap[4]) buttonXMove = Blender.Draw.Create(Blender.drawmap[5]) buttonZoomLevel = Blender.Draw.Create(Blender.drawmap[6]) buttonPath = Blender.Draw.Create(Blender.drawmap[7]) block = [] block.append(("Image Size", buttonthumbsize, 0, 500)) block.append(("Camera Height", buttonCameraHeight, -0, 10)) block.append(("Y Start", buttonYStart, -10, 10)) block.append(("Y Move", buttonYMove, 0, 5)) block.append(("X Start", buttonXStart,-10, 10)) block.append(("X Move", buttonXMove, 0, 5)) block.append(("Zoom Level", buttonZoomLevel, 1, 10)) block.append(("Export Path", buttonPath,0,200,"The Path to save the tiles")) retval = Blender.Draw.PupBlock("Draw Map: Preferences" , block) if retval: Blender.drawmap[0] = buttonthumbsize.val Blender.drawmap[1] = buttonCameraHeight.val Blender.drawmap[2] = buttonYStart.val Blender.drawmap[3] = buttonYMove.val Blender.drawmap[4] = buttonXStart.val Blender.drawmap[5] = buttonXMove.val Blender.drawmap[6] = buttonZoomLevel.val Blender.drawmap[7] = buttonPath.val Export() def Export(): scn = Scene.GetCurrent() context = scn.getRenderingContext() def cutStr(str): #cut off path leaving name c = str.find("\\") while c != -1: c = c + 1 str = str[c:] c = str.find("\\") str = str[:-6] return str #variables from gui: thumbsize,CameraHeight,YStart,YMove,XStart,XMove,ZoomLevel,Path = Blender.drawmap XMove = XMove / ZoomLevel YMove = YMove / ZoomLevel Camera = Scene.GetCurrent().getCurrentCamera() Camera.LocZ = CameraHeight / ZoomLevel YStart = YStart + (YMove / 2) XStart = XStart + (XMove / 2) #Point it straight down Camera.RotX = 0 Camera.RotY = 0 Camera.RotZ = 0 TileCount = 4**ZoomLevel #Because the first thing we do is move the camera, start it off the map Camera.LocY = YStart - YMove for i in range(0,TileCount): Camera.LocY = Camera.LocY + YMove Camera.LocX = XStart - XMove for j in range(0,TileCount): Camera.LocX = Camera.LocX + XMove Render.EnableDispWin() context.extensions = True context.renderPath = Path #setting thumbsize context.imageSizeX(thumbsize) context.imageSizeY(thumbsize) #could be put into a gui. context.imageType = Render.PNG context.enableOversampling(0) #render context.render() #save image ZasString = '%s' %(int(ZoomLevel)) XasString = '%s' %(int(j+1)) YasString = '%s' %(int((3-i)+1)) context.saveRenderedImage("Z" + ZasString + "X" + XasString + "Y" + YasString) #close the windows Render.CloseRenderWindow() try: type(Blender.drawmap) except: #print 'initialize extern variables' init() show_prefs()

    Read the article

  • jQuery: How to grab RadioButton selection?

    - by Matt
    I need to grab the value of the radiobutton option selected with jQuery. I am using the following code but "str" is undefined in Firebug: //handling Feed vs. Ingredient RadioButton $('[id$=rdoCheck]').change(function() { str = $("input[name='rdoCheck']:checked").val(); //ingredients if (str == "ing") { $('[id$="lblDescription"]').text("Ingredient") } //finished feed else if (str == "ffc") { $('[id$="lblDescription"]').text("Finished") } });

    Read the article

  • How to split a string of words and add to an array - Objective C

    - by user1412469
    Let's say I have this: NSString *str = @"This is a sample string"; How will I split the string in a way that each word will be added into a NSMutableArray? In VB.net you can do this: Dim str As String Dim strArr() As String Dim count As Integer str = "vb.net split test" strArr = str.Split(" ") For count = 0 To strArr.Length - 1 MsgBox(strArr(count)) Next So how to do this in Objective-C? Thanks

    Read the article

  • String replacement in batch file

    - by Faisal
    We can replace strings in a batch file using the following command set str="jump over the chair" set str=%str:chair=table% These lines work fine and change the string "jump over the chair" to "jump over the table". Now I want to replace the word "chair" in the string with some variable and I don't know how to do it. set word=table set str="jump over the chair" ?? Any ideas?

    Read the article

  • Define polynomial function

    - by user1822707
    How can I define a function - say, def polyToString(poly) - to return a string containing the polynomial poly in standard form? For example: the polynomial represented by [-1, 2, -3, 4, -5] would be returned as: "-5x**4 + 4x**3 -3x**2 + 2x**1 - 1x**0" def polyToString(poly): standard_form='' n=len(poly) - 1 while n >=0: if poly[n]>=0: if n==len(poly)-1: standard_form= standard_form + ' '+ str(poly[n]) + 'x**%d'%n else: standard_form= standard_form + ' + '+str(poly[n]) + 'x**%d'%n else: standard_form= standard_form + ' - ' + str(abs(poly[n])) + 'x**' + str(n) n=n-1 return standard_form

    Read the article

  • Iterating over key and value of defaultdict dictionaries

    - by gf
    The following works as expected: d = [(1,2), (3,4)] for k,v in d: print "%s - %s" % (str(k), str(v)) But this fails: d = collections.defaultdict(int) d[1] = 2 d[3] = 4 for k,v in d: print "%s - %s" % (str(k), str(v)) With: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable Why? How can i fix it?

    Read the article

  • php: regex remove bracket in string

    - by apis17
    hi, similiar like this example, http://stackoverflow.com/questions/1336672/php-remove-brackets-contents-from-a-string i have no idea to replace $str = '(ABC)some text' into $str = 'ABC'; currently use $str = preg_replace('/(.)/','',$str); but not works. how to fix this?

    Read the article

  • Does Java have something like C#'s ref and out keywords?

    - by devoured elysium
    Something like the following: ref example: void changeString(ref String str) { str = "def"; } void main() { String abc = "abc"; changeString(ref abc); System.out.println(abc); //prints "def" } out example: void setString(out String str) { str = "def"; } void main() { String abc; changeString(out abc); System.out.println(abc); //prints "def" }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >