Search Results

Search found 66 results on 3 pages for 'tempfile'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Output redirection still with colors in PowerShell

    - by stej
    Suppose I run msbuild like this: function Clean-Sln { param($sln) MSBuild.exe $sln /target:Clean } Clean-Sln c:\temp\SO.sln In Posh console the output is in colors. That's pretty handy - you spot colors just by watching the output. And e.g. not important messages are grey. Question I'd like to add ability to redirect it somewhere like this (simplified example): function Clean-Sln { param($sln) MSBuild.exe $sln /target:Clean | Redirect-AccordingToRedirectionVariable } $global:Redirection = 'Console' Clean-Sln c:\temp\SO.sln $global:Redirection = 'TempFile' Clean-Sln c:\temp\Another.sln If I use 'Console', the cmdlet/function Redirect-AccordingToRedirectionVariable should output the msbuild messages with colors the same way as the output was not piped. In other words - it should leave the output as it is. If I use 'TempFile', Redirect-AccordingToRedirectionVariable will store the output in a temp file. Is it even possible? I guess it is not :| Or do you have any advice how to achieve the goal? Possible solution: if ($Redirection -eq 'Console) { MSBuild.exe $sln /target:Clean | Redirect-AccordingToRedirectionVariable } else { MSBuild.exe $sln /target:Clean | Out-File c:\temp.txt } But if you imagine there can be many many msbuild calls, it's not ideal. Don't be shy to tell me any new suggestion how to cope with it ;) Any background info about redirections/coloring/outpu is welcome as well. (The problem is not msbuild specific, the problem touches any application that writes colored output)

    Read the article

  • PHP JQuery: Where to specify uploadify destination folder

    - by Eamonn
    I have an uploadify script running, basic setup. Works fine when I hard code the destination folder for the images into uploadify.php - now I want to make that folder dynamic. How do I do this? I have a PHP variable $uploadify_path which contains the path to the folder I want. I have switched out my hard coded $targetPath = path/to/directory for $targetPath = $uploadify_path in both uploadify.php and check_exists.php, but it does not work. The file upload animation runs, says it is complete, yet the directory remains empty. The file is not hiding out somewhere else either. I see there is an option in the Javascript to specify a folder. I tried this also, but to no avail. If anyone could educate me on how to pass this variable destination to uploadify, I'd be very grateful. I include my current code for checking (basically default): The Javascript <script type="text/javascript"> $(function() { $('#file_upload').uploadify({ 'swf' : 'uploadify/uploadify.swf', 'uploader' : 'uploadify/uploadify.php', // Put your options here }); }); </script> uploadify.php $targetPath = $_SERVER['DOCUMENT_ROOT'] . $uploadify_path; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetFile = $targetPath . $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('jpg','jpeg','gif','png'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } }

    Read the article

  • Saving temporary file name after uploading file with uplodify

    - by mIRU
    I have this script if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = dirname(__FILE__).$_POST['folder'] . '/'; $pathinfoFile = pathinfo($_FILES['Filedata']['name']); $targetFile = str_replace('//','/',$targetPath) .uniqid().'.'.$pathinfoFile['extension']; move_uploaded_file($tempFile,$targetFile); } this script is from uplodify , modified for saving the file with unique name , i need after user will upload the file , this unique name and original name , to save temporary , when user will submit the form , this temporary variables i will insert in database , the problem is that in firebug console , i can not see all the actions of this script , and i can not understand the way how to fix it, I tried to save in $_SESSION but i have problems , is not saving , i found why is not working with $_SESSION , http://uploadify.com/forum/viewtopic.php?f=5&t=43 , i tried the solution from forum but without result , exist a more easy way to solve this problem ? , or what is better way to do it ? . Sorry for so silly question , i ran out of ideas . Thanks a lot for helping me , and sorry again for my English

    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

  • Uploadify Hanging at random on 100%

    - by Matty
    I am using Uploadify (http://www.uploadify.com/) to enable my users to upload images via my web application. The problem I am having is that every now and then (at what appears to be random) when the progress bar reaches 100% it 'hangs' and does nothing. I was wondering if any developers familiar with uploadify may have any idea how to solve this? I am in desperate need of some help. Here is my front-end code: jQuery(document).ready(function() { jQuery("#uploadify").uploadify({ 'uploader' : 'javascripts/uploadify.swf', 'script' : 'upload-file2.php', 'cancelImg' : 'css/images/cancel.png', 'folder' : 'uploads/personal_images/' + profileOwner, 'queueID' : 'fileQueue', 'auto' : true, 'multi' : true, 'fileDesc' : 'Image files', 'fileExt' : '.jpg;.jpeg;.gif;.png', 'sizeLimit' : '2097152', 'onComplete': function(event, queueID, fileObj, response, data) { processPersonalImage(fileObj.name); arrImgNames.push(fileObj.name); showUploadedImages(true); document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')"; }, 'onAllComplete' : function() { completionMessage(arrFailedNames); document.getElementById("displayImageButton").style.display = "inline"; document.getElementById("photos").style.backgroundImage = "url('css/images/minicam.png')"; }, 'onCancel' : function() { arrImgNames.push(fileObj.name); arrFailedNames.push(fileObj.name); showUploadedImages(false); }, 'onError' : function() { arrImgNames.push(fileObj.name); arrFailedNames.push(fileObj.name); showUploadedImages(false); } }); }); And server side: if (!empty($_FILES)) { //Get user ID from the file path for use later.. $userID = getIdFromFilePath($_REQUEST['folder'], 3); $row = mysql_fetch_assoc(getRecentAlbum($userID, "photo_album_personal")); $subFolderName = $row['pk']; //Prepare target path / file.. $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/'.$subFolderName.'/'; $targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name']; //Move uploaded file from temp directory to new folder move_uploaded_file($tempFile,$targetFile); //Now add a record to DB to reflect this personal image.. if(file_exists($targetFile)) { //add photo record to DB $directFilePath = $_REQUEST['folder'] . '/'.$subFolderName.'/' . $_FILES['Filedata']['name']; addPersonalPhotoRecordToDb($directFilePath, $row['pk']); } echo "1"; die(true); } thanks for any help!!

    Read the article

  • tmpfile and gzip combination problem

    - by Vojtech R.
    I have problem with this code: file = tempfile.TemporaryFile(mode='wrb') file.write(base64.b64decode(data)) file.flush() os.fsync(file) # file.seek(0) f = gzip.GzipFile(mode='rb', fileobj=file) print f.read() I dont know why it doesn't print out anything. If I uncomment file.seek then error occurs: File "/usr/lib/python2.5/gzip.py", line 263, in _read self._read_gzip_header() File "/usr/lib/python2.5/gzip.py", line 162, in _read_gzip_header magic = self.fileobj.read(2) IOError: [Errno 9] Bad file descriptor Just for information this version works fine: x = open("test.gzip", 'wb') x.write(base64.b64decode(data)) x.close() f = gzip.GzipFile('test.gzip', 'rb') print f.read()

    Read the article

  • Django1.1 file based session backend multi-threaded solution

    - by Satoru.Logic
    Hi, all. I read django.contrib.sessions.backend.file today, in the save method of SessionStore there is something as the following that's used to achieve multi-threaded saving integrity: output_file_fd, output_file_name = tempfile.mkstemp(dir=dir, prefix=prefix + '_out_') renamed = False try: try: os.write(output_file_fd, self.encode(session_data)) finally: os.close(output_file_fd) os.rename(output_file_name, session_file_name) renamed = True finally: if not renamed: os.unlink(output_file_name) I don't quite understand how this solve the integrity problem.

    Read the article

  • Why is this RMagick call generating a segmentation fault?

    - by Grant Heaslip
    I've been banging my head against the wall for the better part of an hour trying to figure out what's going wrong here, and I'm sure (or rather hoping) it's something fairly obvious that I'm overlooking. I'm using Ruby 1.9.1, Sinatra 1.0, and RMagick 2.13.1. ImageMagick and RMagick are correctly installed and functional—I've successfully manipulated and saved images from irb. The relevant part of the params array (formatting changes for the sake of readability): {"admin_user_new_image_file"=> { :filename=>"freddie-on-shetland-pony.png", :type=>"image/png", :name=>"admin_user_new_image_file", :tempfile=>#<File:/var/folders/a7/a7pO5jMcGLCww9XBGRvWfE+++TI/-Tmp-/RackMultipart20100514-20700-o2tkqu-0>, :head=>"Content-Disposition: form-data; name=\"admin_user_new_image_file\"; filename=\"freddie-on-shetland-pony.png\"\r\nContent-Type: image/png\r\n" } } The relevant code: post "/admin/user/:account_name/image/new/" do if params[:admin_user_new_image_file][:tempfile] thumbnail = Magick::Image.read("png:"+params[:admin_user_new_image_file][:tempfile].path).first end end The error (line 229 is the line starting with "thumbnail = ": config.ru:229: [BUG] Segmentation fault ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-darwin10.3.0] -- control frame ---------- c:0042 p:---- s:0196 b:0196 l:000195 d:000195 CFUNC :read c:0041 p:0121 s:0192 b:0192 l:001ab8 d:000191 LAMBDA config.ru:229 c:0040 p:---- s:0189 b:0189 l:000188 d:000188 FINISH c:0039 p:---- s:0187 b:0187 l:000186 d:000186 CFUNC :call c:0038 p:0018 s:0184 b:0184 l:001d78 d:000183 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865 c:0037 p:---- s:0182 b:0182 l:000181 d:000181 FINISH c:0036 p:---- s:0180 b:0180 l:000179 d:000179 CFUNC :instance_eval c:0035 p:0016 s:0177 b:0175 l:000174 d:000174 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521 c:0034 p:0024 s:0171 b:0171 l:000148 d:000170 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500 c:0033 p:---- s:0169 b:0169 l:000168 d:000168 FINISH c:0032 p:---- s:0167 b:0167 l:000166 d:000166 CFUNC :catch c:0031 p:0140 s:0163 b:0163 l:000148 d:000162 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497 c:0030 p:---- s:0154 b:0154 l:000153 d:000153 FINISH c:0029 p:---- s:0152 b:0152 l:000151 d:000151 CFUNC :each c:0028 p:0073 s:0149 b:0149 l:000148 d:000148 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476 c:0027 p:0076 s:0141 b:0141 l:000140 d:000140 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601 c:0026 p:0009 s:0137 b:0137 l:000138 d:000136 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411 c:0025 p:---- s:0135 b:0135 l:000134 d:000134 FINISH c:0024 p:---- s:0133 b:0133 l:000132 d:000132 CFUNC :instance_eval c:0023 p:0012 s:0130 b:0130 l:000121 d:000129 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566 c:0022 p:---- s:0128 b:0128 l:000127 d:000127 FINISH c:0021 p:---- s:0126 b:0126 l:000125 d:000125 CFUNC :catch c:0020 p:0013 s:0122 b:0122 l:000121 d:000121 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566 c:0019 p:0098 s:0115 b:0115 l:000138 d:000138 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411 c:0018 p:0019 s:0108 b:0108 l:000107 d:000107 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399 c:0017 p:0014 s:0104 b:0104 l:000103 d:000103 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24 c:0016 p:0150 s:0098 b:0098 l:000097 d:000097 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24 c:0015 p:0031 s:0092 b:0092 l:000091 d:000091 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18 c:0014 p:0018 s:0084 b:0084 l:002080 d:000083 BLOCK /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979 c:0013 p:0032 s:0082 b:0082 l:000081 d:000081 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005 c:0012 p:0011 s:0078 b:0078 l:002080 d:002080 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979 c:0011 p:0100 s:0074 b:0074 l:000ff0 d:000ff0 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47 c:0010 p:0022 s:0068 b:0068 l:000067 d:000067 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35 c:0009 p:0014 s:0064 b:0064 l:000063 d:000063 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24 c:0008 p:0031 s:0058 b:0058 l:000057 d:000057 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18 c:0007 p:0014 s:0050 b:0050 l:000049 d:000049 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13 c:0006 p:0320 s:0042 b:0042 l:000041 d:000041 METHOD /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48 c:0005 p:0256 s:0030 b:0030 l:000029 d:000029 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111 c:0004 p:0382 s:0020 b:0020 l:000019 d:000019 METHOD /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70 c:0003 p:0123 s:0009 b:0009 l:000bc8 d:000008 BLOCK /usr/local/lib/ruby/1.9.1/webrick/server.rb:183 c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH c:0001 p:---- s:0002 b:0002 l:000001 d:000001 TOP --------------------------- -- Ruby level backtrace information----------------------------------------- config.ru:229:in `read' config.ru:229:in `block (2 levels) in <main>' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:865:in `block in route' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `instance_eval' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:521:in `route_eval' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:500:in `block (2 levels) in route!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `catch' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:497:in `block in route!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `each' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:476:in `route!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:601:in `dispatch!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `block in call!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `instance_eval' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `block in invoke' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `catch' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:566:in `invoke' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:411:in `call!' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:399:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/methodoverride.rb:24:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `block in call' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:1005:in `synchronize' /usr/local/lib/ruby/gems/1.9.1/gems/sinatra-1.0/lib/sinatra/base.rb:979:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:47:in `_call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/lint.rb:35:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/showexceptions.rb:24:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/commonlogger.rb:18:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/content_length.rb:13:in `call' /usr/local/lib/ruby/gems/1.9.1/gems/rack-1.1.0/lib/rack/handler/webrick.rb:48:in `service' /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service' /usr/local/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run' /usr/local/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread' -- C level backtrace information ------------------------------------------- 0x10010cd8d 0 libruby.dylib 0x000000010010cd8d rb_vm_bugreport + 77 0x10002b184 1 libruby.dylib 0x000000010002b184 report_bug + 260 0x10002b318 2 libruby.dylib 0x000000010002b318 rb_bug + 200 0x1000b7124 3 libruby.dylib 0x00000001000b7124 sigsegv + 132 0x7fff8301c80a 4 libSystem.B.dylib 0x00007fff8301c80a _sigtramp + 26 0x1032313ac 5 libMagickCore.3.dylib 0x00000001032313ac Splay + 300 0x103119245 6 libMagickCore.3.dylib 0x0000000103119245 AcquirePixelCache + 325 0x1031cb317 7 libMagickCore.3.dylib 0x00000001031cb317 AcquireImage + 375 0x10333035b 8 libMagickCore.3.dylib 0x000000010333035b ReadPNGImage + 155 0x1031418fd 9 libMagickCore.3.dylib 0x00000001031418fd ReadImage + 2221 0x101f1b72b 10 RMagick2.bundle 0x0000000101f1b72b rd_image + 339 0x101f1b59b 11 RMagick2.bundle 0x0000000101f1b59b Image_read + 36 0x1000fd0e4 12 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 13 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 14 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 15 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x100106643 16 libruby.dylib 0x0000000100106643 rb_vm_invoke_proc + 691 0x100106ccd 17 libruby.dylib 0x0000000100106ccd vm_call0 + 1085 0x1000317c6 18 libruby.dylib 0x00000001000317c6 rb_method_call + 406 0x1000fd0e4 19 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 20 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 21 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 22 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x100105ce6 23 libruby.dylib 0x0000000100105ce6 yield_under + 710 0x100106188 24 libruby.dylib 0x0000000100106188 specific_eval + 72 0x1000fd0e4 25 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 26 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 27 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 28 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x10010b6bf 29 libruby.dylib 0x000000010010b6bf rb_f_catch + 639 0x1000fd0e4 30 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 31 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 32 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 33 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x10010aac9 34 libruby.dylib 0x000000010010aac9 rb_yield + 505 0x100007902 35 libruby.dylib 0x0000000100007902 rb_ary_each + 82 0x1000fd0e4 36 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 37 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 38 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 39 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x100105ce6 40 libruby.dylib 0x0000000100105ce6 yield_under + 710 0x100106188 41 libruby.dylib 0x0000000100106188 specific_eval + 72 0x1000fd0e4 42 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 43 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 44 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 45 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x10010b6bf 46 libruby.dylib 0x000000010010b6bf rb_f_catch + 639 0x1000fd0e4 47 libruby.dylib 0x00000001000fd0e4 vm_call_cfunc + 340 0x1000fe9b0 48 libruby.dylib 0x00000001000fe9b0 vm_call_method + 896 0x1000ff8fc 49 libruby.dylib 0x00000001000ff8fc vm_exec_core + 3180 0x100104b93 50 libruby.dylib 0x0000000100104b93 vm_exec + 1203 0x100106643 51 libruby.dylib 0x0000000100106643 rb_vm_invoke_proc + 691 0x100111803 52 libruby.dylib 0x0000000100111803 thread_start_func_2 + 835 0x100111921 53 libruby.dylib 0x0000000100111921 thread_start_func_1 + 17 0x7fff82ff58b6 54 libSystem.B.dylib 0x00007fff82ff58b6 _pthread_start + 331 0x7fff82ff5769 55 libSystem.B.dylib 0x00007fff82ff5769 thread_start + 13 [NOTE] You may encounter a bug of Ruby interpreter. Bug reports are welcome. For details: http://www.ruby-lang.org/bugreport.html Abort trap Anyone have any idea what's going on? Thanks!

    Read the article

  • how to execute two thread simultaneously in java swing?

    - by jcrshankar
    My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those. To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar. Could anyone please help me out on this? import java.awt.*; import javax.swing.*; import javax.swing.table.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class JTableHeaderCheckBox extends JFrame implements ActionListener { Object colNames[] = {"", "Path"}; Object[][] data = {}; DefaultTableModel dtm; JTable table; JButton but; java.util.List list; public void buildGUI() { dtm = new DefaultTableModel(data,colNames); table = new JTable(dtm); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); int vColIndex = 0; TableColumn col = table.getColumnModel().getColumn(vColIndex); int width = 10; col.setPreferredWidth(width); int vColIndex1 = 1; TableColumn col1 = table.getColumnModel().getColumn(vColIndex1); int width1 = 500; col1.setPreferredWidth(width1); JFileChooser chooser = new JFileChooser(); //chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle("Choose workSpace Path"); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setAcceptAllFileFilterUsed(false); if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION){ System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory()); System.out.println("getSelectedFile() : " + chooser.getSelectedFile().getAbsolutePath()); } String path= chooser.getSelectedFile().getAbsolutePath(); File folder = new File(path); Here I need progress bar GatheringFiles ob = new GatheringFiles(); list=ob.returnlist(folder); for(int x = 0; x < list.size(); x++) { dtm.addRow(new Object[]{new Boolean(false),list.get(x).toString()}); } JPanel pan = new JPanel(); JScrollPane sp = new JScrollPane(table); TableColumn tc = table.getColumnModel().getColumn(0); tc.setCellEditor(table.getDefaultEditor(Boolean.class)); tc.setCellRenderer(table.getDefaultRenderer(Boolean.class)); tc.setHeaderRenderer(new CheckBoxHeader(new MyItemListener())); but = new JButton("REMOVE"); JFrame f = new JFrame(); pan.add(sp); but.move(650, 50); but.addActionListener(this); pan.add(but); f.add(pan); f.setSize(700, 100); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } class MyItemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { Object source = e.getSource(); if (source instanceof AbstractButton == false) return; boolean checked = e.getStateChange() == ItemEvent.SELECTED; for(int x = 0, y = table.getRowCount(); x < y; x++) { table.setValueAt(new Boolean(checked),x,0); } } } public static void main (String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run(){ new JTableHeaderCheckBox().buildGUI(); } }); } public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource()==but) { System.err.println("table.getRowCount()"+table.getRowCount()); for(int x = 0, y = table.getRowCount(); x < y; x++) { if("true".equals(table.getValueAt(x, 0).toString())) { System.err.println(table.getValueAt(x, 0)); System.err.println(list.get(x).toString()); delete(list.get(x).toString()); } } } } public void delete(String a) { String delete = "C:"; System.err.println(a); try { File inFile = new File(a); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(inFile)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()) != null) { System.err.println(line); line = line.replace(delete, " "); pw.println(line); pw.flush(); } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } class CheckBoxHeader extends JCheckBox implements TableCellRenderer, MouseListener { protected CheckBoxHeader rendererComponent; protected int column; protected boolean mousePressed = false; public CheckBoxHeader(ItemListener itemListener) { rendererComponent = this; rendererComponent.addItemListener(itemListener); } public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { rendererComponent.setForeground(header.getForeground()); rendererComponent.setBackground(header.getBackground()); rendererComponent.setFont(header.getFont()); header.addMouseListener(rendererComponent); } } setColumn(column); rendererComponent.setText("Check All"); setBorder(UIManager.getBorder("TableHeader.cellBorder")); return rendererComponent; } protected void setColumn(int column) { this.column = column; } public int getColumn() { return column; } protected void handleClickEvent(MouseEvent e) { if (mousePressed) { mousePressed=false; JTableHeader header = (JTableHeader)(e.getSource()); JTable tableView = header.getTable(); TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) { doClick(); } } } public void mouseClicked(MouseEvent e) { handleClickEvent(e); ((JTableHeader)e.getSource()).repaint(); } public void mousePressed(MouseEvent e) { mousePressed = true; } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } ****************** import java.io.File; import java.util.*; public class GatheringFiles { public static List returnlist(File folder) { List<File> list = new ArrayList<File>(); List<File> list1 = new ArrayList<File>(); getFiles(folder, list); return list; } private static void getFiles(File folder, List<File> list) { folder.setReadOnly(); File[] files = folder.listFiles(); for(int j = 0; j < files.length; j++) { if( "MANI.txt".equals(files[j].getName())) { list.add(files[j]); } if(files[j].isDirectory()) getFiles(files[j], list); } } }

    Read the article

  • Installation error: INSTALL_FAILED_OLDER_SDK in eclipse

    - by user3014909
    I have an unexpe`ted problem with my Android project. I have a real android device with ice_cream sandwich installed. My app was working fine during the development but after I added a class to the project, I got an error: Installation error: INSTALL_FAILED_OLDER_SDK The problem is that everything is good in the manifest file. The minSdkversion is 8. Here is my manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="zabolotnii.pavel.timer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18 " /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="zabolotnii.pavel.timer.TimerActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> I don't know, if there is any need to attach the new class ,but I didn't any changes to other code that should led to this error: package zabolotnii.pavel.timer; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Environment; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.*; import android.widget.*; import java.io.File; import java.io.FilenameFilter; import java.util.*; public class OpenFileDialog extends AlertDialog.Builder { private String currentPath = Environment.getExternalStorageDirectory().getPath(); private List<File> files = new ArrayList<File>(); private TextView title; private ListView listView; private FilenameFilter filenameFilter; private int selectedIndex = -1; private OpenDialogListener listener; private Drawable folderIcon; private Drawable fileIcon; private String accessDeniedMessage; public interface OpenDialogListener { public void OnSelectedFile(String fileName); } private class FileAdapter extends ArrayAdapter<File> { public FileAdapter(Context context, List<File> files) { super(context, android.R.layout.simple_list_item_1, files); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); File file = getItem(position); if (view != null) { view.setText(file.getName()); if (file.isDirectory()) { setDrawable(view, folderIcon); } else { setDrawable(view, fileIcon); if (selectedIndex == position) view.setBackgroundColor(getContext().getResources().getColor(android.R.color.holo_blue_dark)); else view.setBackgroundColor(getContext().getResources().getColor(android.R.color.transparent)); } } return view; } private void setDrawable(TextView view, Drawable drawable) { if (view != null) { if (drawable != null) { drawable.setBounds(0, 0, 60, 60); view.setCompoundDrawables(drawable, null, null, null); } else { view.setCompoundDrawables(null, null, null, null); } } } } public OpenFileDialog(Context context) { super(context); title = createTitle(context); changeTitle(); LinearLayout linearLayout = createMainLayout(context); linearLayout.addView(createBackItem(context)); listView = createListView(context); linearLayout.addView(listView); setCustomTitle(title) .setView(linearLayout) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (selectedIndex > -1 && listener != null) { listener.OnSelectedFile(listView.getItemAtPosition(selectedIndex).toString()); } } }) .setNegativeButton(android.R.string.cancel, null); } @Override public AlertDialog show() { files.addAll(getFiles(currentPath)); listView.setAdapter(new FileAdapter(getContext(), files)); return super.show(); } public OpenFileDialog setFilter(final String filter) { filenameFilter = new FilenameFilter() { @Override public boolean accept(File file, String fileName) { File tempFile = new File(String.format("%s/%s", file.getPath(), fileName)); if (tempFile.isFile()) return tempFile.getName().matches(filter); return true; } }; return this; } public OpenFileDialog setOpenDialogListener(OpenDialogListener listener) { this.listener = listener; return this; } public OpenFileDialog setFolderIcon(Drawable drawable) { this.folderIcon = drawable; return this; } public OpenFileDialog setFileIcon(Drawable drawable) { this.fileIcon = drawable; return this; } public OpenFileDialog setAccessDeniedMessage(String message) { this.accessDeniedMessage = message; return this; } private static Display getDefaultDisplay(Context context) { return ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); } private static Point getScreenSize(Context context) { Point screeSize = new Point(); getDefaultDisplay(context).getSize(screeSize); return screeSize; } private static int getLinearLayoutMinHeight(Context context) { return getScreenSize(context).y; } private LinearLayout createMainLayout(Context context) { LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setMinimumHeight(getLinearLayoutMinHeight(context)); return linearLayout; } private int getItemHeight(Context context) { TypedValue value = new TypedValue(); DisplayMetrics metrics = new DisplayMetrics(); context.getTheme().resolveAttribute(android.R.attr.listPreferredItemHeightSmall, value, true); getDefaultDisplay(context).getMetrics(metrics); return (int) TypedValue.complexToDimension(value.data, metrics); } private TextView createTextView(Context context, int style) { TextView textView = new TextView(context); textView.setTextAppearance(context, style); int itemHeight = getItemHeight(context); textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, itemHeight)); textView.setMinHeight(itemHeight); textView.setGravity(Gravity.CENTER_VERTICAL); textView.setPadding(15, 0, 0, 0); return textView; } private TextView createTitle(Context context) { TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_DialogWindowTitle); return textView; } private TextView createBackItem(Context context) { TextView textView = createTextView(context, android.R.style.TextAppearance_DeviceDefault_Small); Drawable drawable = getContext().getResources().getDrawable(android.R.drawable.ic_menu_directions); drawable.setBounds(0, 0, 60, 60); textView.setCompoundDrawables(drawable, null, null, null); textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { File file = new File(currentPath); File parentDirectory = file.getParentFile(); if (parentDirectory != null) { currentPath = parentDirectory.getPath(); RebuildFiles(((FileAdapter) listView.getAdapter())); } } }); return textView; } public int getTextWidth(String text, Paint paint) { Rect bounds = new Rect(); paint.getTextBounds(text, 0, text.length(), bounds); return bounds.left + bounds.width() + 80; } private void changeTitle() { String titleText = currentPath; int screenWidth = getScreenSize(getContext()).x; int maxWidth = (int) (screenWidth * 0.99); if (getTextWidth(titleText, title.getPaint()) > maxWidth) { while (getTextWidth("..." + titleText, title.getPaint()) > maxWidth) { int start = titleText.indexOf("/", 2); if (start > 0) titleText = titleText.substring(start); else titleText = titleText.substring(2); } title.setText("..." + titleText); } else { title.setText(titleText); } } private List<File> getFiles(String directoryPath) { File directory = new File(directoryPath); List<File> fileList = Arrays.asList(directory.listFiles(filenameFilter)); Collections.sort(fileList, new Comparator<File>() { @Override public int compare(File file, File file2) { if (file.isDirectory() && file2.isFile()) return -1; else if (file.isFile() && file2.isDirectory()) return 1; else return file.getPath().compareTo(file2.getPath()); } }); return fileList; } private void RebuildFiles(ArrayAdapter<File> adapter) { try { List<File> fileList = getFiles(currentPath); files.clear(); selectedIndex = -1; files.addAll(fileList); adapter.notifyDataSetChanged(); changeTitle(); } catch (NullPointerException e) { String message = getContext().getResources().getString(android.R.string.unknownName); if (!accessDeniedMessage.equals("")) message = accessDeniedMessage; Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } } private ListView createListView(Context context) { ListView listView = new ListView(context); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) { final ArrayAdapter<File> adapter = (FileAdapter) adapterView.getAdapter(); File file = adapter.getItem(index); if (file.isDirectory()) { currentPath = file.getPath(); RebuildFiles(adapter); } else { if (index != selectedIndex) selectedIndex = index; else selectedIndex = -1; adapter.notifyDataSetChanged(); } } }); return listView; } }

    Read the article

  • Syntax for piping varnish logs to rotatelogs

    - by jetboy
    Ubuntu 12.04 Server x64, Varnish 3.0.2 I'm trying to pipe varnishncsa's logs through Apache's rotatelogs, and running from the shell, things work fine: sudo varnishncsa -a -P /var/run/varnishncsa/varnishncsa.pid |/usr/sbin/rotatelogs /var/log/varnish/varnish.log.%Y%m%d%H 3600 creates a new logfile in /var/log/varnish, with rotation every hour (3600 seconds). However, I'm struggling to get things working the same way inside /etc/init.d/varnishncsa: PATH=/sbin:/bin:/usr/sbin:/usr/bin DAEMON=/usr/bin/$NAME PIDFILE=/var/run/$NAME/$NAME.pid LOGFILE=/var/log/varnish/varnishncsa.log USER=varnishlog DAEMON_OPTS="-a -P ${PIDFILE}" DAEMON_PIPE="|/usr/sbin/rotatelogs /var/log/varnish/varnish.log.%Y%m%d%H 3600" ... start_varnishncsa() { output=$(/bin/tempfile -s.varnish) log_daemon_msg "Starting $DESC" "$NAME" create_pid_directory if start-stop-daemon --start --verbose --pidfile ${PIDFILE} \ --chuid $USER --exec ${DAEMON} -- ${DAEMON_OPTS} \ > ${output} 2>&1; then log_end_msg 0 else log_end_msg 1 cat $output exit 1 fi rm $output } Where should I put DAEMON_PIPE in the above code? I've tried at the end of: if start-stop-daemon --start --verbose --pidfile ${PIDFILE} which is where additional command line parameters usually go, but it isn't creating a logfile.

    Read the article

  • C++ and system exceptions

    - by Abyx
    Why standard C++ doesn't respect system (foreign or hardware) exceptions? E.g. when null pointer dereference occurs, stack isn't unwound, destructors aren't called, and RAII doesn't work. The common advice is "to use system API". But on certain systems, specifically Win32, this doesn't work. To enable stack unwinding for this C++ code // class Foo; // void bar(const Foo&); bar(Foo(1, 2)); one should generate something like this C code Foo tempFoo; Foo_ctor(&tempFoo); __try { bar(&tempFoo); } __finally { Foo_dtor(&tempFoo); } Foo_dtor(&tempFoo); and it's impossible to implement this as C++ library. Upd: Standard doesn't forbid handling system exceptions. But it seems that popular compilers like g++ doesn't respect system exceptions on any platforms just because standard doesn't require this. The only thing that I want - is to use RAII to make code readable and program reliable. I don't want to put hand-crafted try\finally around every call to unknown code. For example in this reusable code, AbstractA::foo is such unknown code: void func(AbstractA* a, AbstractB* b) { TempFile file; a->foo(b, file); } Maybe one will pass to func such implementation of AbstractA, which every Friday will not check if b is NULL, so access violation will happen, application will terminate and temporary file will not be deleted. How many months uses will suffer because of this issue, until either author of func or author of AbstractA will do something with it? Related: Is `catch(...) { throw; }` a bad practice?

    Read the article

  • Unsure about TRIM enabled on my SSD

    - by user84750
    I have a SSD OCZ Vertex4 installed on my laptop. I'm running Ubuntu 12.04 LTS. I have enable TRIM by adding "discard" to my fstab file. (also added option noatime). I rebooted my Ubuntu and followed These instructions here to test TRIM. The end results of my tempfile was all ffff's, when it should have read all zero's, which is telling me TRIM is not really working or enabled correctly. Did I miss something? Also, will it be a problem if only my /home directory is encrypted. AND if you ask why I have swap on my SSD, it's because I let Ubuntu set up my partition. When I have my SSD, I just wanted to install Ubuntu as fast as possible. =) I've done testing to see at which point it will start to use swap and it took a lot of applications open to finally use swap. I currently have 4 GB of memory. I might shrink this to like 512 MB or 1 GB the most. Here's some info about my file system setup. sudo hdparm -I /dev/sda1 | grep "TRIM supported" Data Set Management TRIM supported (limit 16 blocks) sudo fdisk -l /dev/sda Device Boot Start End Blocks Id System /dev/sda1 * 2048 242016255 121007104 83 Linux /dev/sda2 242018302 250068991 4025345 5 Extended /dev/sda5 242018304 250068991 4025344 82 Linux swap / Solaris ls /dev/mapper control cryptswap1

    Read the article

  • file doesn't open, running outside of debugger results in seg fault (c++)

    - by misterich
    Hello (and thanks in advance) I'm in a bit of a quandry, I cant seem to figure out why I'm seg faulting. A couple of notes: It's for a course -- and sadly I am required to use use C-strings instead of std::string. Please dont fix my code (I wont learn that way and I will keep bugging you). please just point out the flaws in my logic and suggest a different function/way. platform: gcc version 4.4.1 on Suse Linux 11.2 (2.6.31 kernel) Here's the code main.cpp: // /////////////////////////////////////////////////////////////////////////////////// // INCLUDES (C/C++ Std Library) #include <cstdlib> /// EXIT_SUCCESS, EXIT_FAILURE #include <iostream> /// cin, cout, ifstream #include <cassert> /// assert // /////////////////////////////////////////////////////////////////////////////////// // DEPENDENCIES (custom header files) #include "dict.h" /// Header for the dictionary class // /////////////////////////////////////////////////////////////////////////////////// // PRE-PROCESSOR CONSTANTS #define ENTER '\n' /// Used to accept new lines, quit program. #define SPACE ' ' /// One way to end the program // /////////////////////////////////////////////////////////////////////////////////// // CUSTOM DATA TYPES /// File Namespace -- keep it local namespace { /// Possible program prompts to display for the user. enum FNS_Prompts { fileName_, /// prints out the name of the file noFile_, /// no file was passed to the program tooMany_, /// more than one file was passed to the program noMemory_, /// Not enough memory to use the program usage_, /// how to use the program word_, /// ask the user to define a word. notFound_, /// the word is not in the dictionary done_, /// the program is closing normally }; } // /////////////////////////////////////////////////////////////////////////////////// // Namespace using namespace std; /// Nothing special in the way of namespaces // /////////////////////////////////////////////////////////////////////////////////// // FUNCTIONS /** prompt() prompts the user to do something, uses enum Prompts for parameter. */ void prompt(FNS_Prompts msg /** determines the prompt to use*/) { switch(msg) { case fileName_ : { cout << ENTER << ENTER << "The file name is: "; break; } case noFile_ : { cout << ENTER << ENTER << "...Sorry, a dictionary file is needed. Try again." << endl; break; } case tooMany_ : { cout << ENTER << ENTER << "...Sorry, you can only specify one dictionary file. Try again." << endl; break; } case noMemory_ : { cout << ENTER << ENTER << "...Sorry, there isn't enough memory available to run this program." << endl; break; } case usage_ : { cout << "USAGE:" << endl << " lookup.exe [dictionary file name]" << endl << endl; break; } case done_ : { cout << ENTER << ENTER << "like Master P says, \"Word.\"" << ENTER << endl; break; } case word_ : { cout << ENTER << ENTER << "Enter a word in the dictionary to get it's definition." << ENTER << "Enter \"?\" to get a sorted list of all words in the dictionary." << ENTER << "... Press the Enter key to quit the program: "; break; } case notFound_ : { cout << ENTER << ENTER << "...Sorry, that word is not in the dictionary." << endl; break; } default : { cout << ENTER << ENTER << "something passed an invalid enum to prompt(). " << endl; assert(false); /// something passed in an invalid enum } } } /** useDictionary() uses the dictionary created by createDictionary * - prompts user to lookup a word * - ends when the user enters an empty word */ void useDictionary(Dictionary &d) { char *userEntry = new char; /// user's input on the command line if( !userEntry ) // check the pointer to the heap { cout << ENTER << MEM_ERR_MSG << endl; exit(EXIT_FAILURE); } do { prompt(word_); // test code cout << endl << "----------------------------------------" << endl << "Enter something: "; cin.getline(userEntry, INPUT_LINE_MAX_LEN, ENTER); cout << ENTER << userEntry << endl; }while ( userEntry[0] != NIL && userEntry[0] != SPACE ); // GARBAGE COLLECTION delete[] userEntry; } /** Program Entry * Reads in the required, single file from the command prompt. * - If there is no file, state such and error out. * - If there is more than one file, state such and error out. * - If there is a single file: * - Create the database object * - Populate the database object * - Prompt the user for entry * main() will return EXIT_SUCCESS upon termination. */ int main(int argc, /// the number of files being passed into the program char *argv[] /// pointer to the filename being passed into tthe program ) { // EXECUTE /* Testing code * / char tempFile[INPUT_LINE_MAX_LEN] = {NIL}; cout << "enter filename: "; cin.getline(tempFile, INPUT_LINE_MAX_LEN, '\n'); */ // uncomment after successful debugging if(argc <= 1) { prompt(noFile_); prompt(usage_); return EXIT_FAILURE; /// no file was passed to the program } else if(argc > 2) { prompt(tooMany_); prompt(usage_); return EXIT_FAILURE; /// more than one file was passed to the program } else { prompt(fileName_); cout << argv[1]; // print out name of dictionary file if( !argv[1] ) { prompt(noFile_); prompt(usage_); return EXIT_FAILURE; /// file does not exist } /* file.open( argv[1] ); // open file numEntries >> in.getline(file); // determine number of dictionary objects to create file.close(); // close file Dictionary[ numEntries ](argv[1]); // create the dictionary object */ // TEMPORARY FILE FOR TESTING!!!! //Dictionary scrabble(tempFile); Dictionary scrabble(argv[1]); // creaate the dicitonary object //*/ useDictionary(scrabble); // prompt the user, use the dictionary } // exit return EXIT_SUCCESS; /// terminate program. } Dict.h/.cpp #ifndef DICT_H #define DICT_H // /////////////////////////////////////////////////////////////////////////////////// // DEPENDENCIES (Custom header files) #include "entry.h" /// class for dictionary entries // /////////////////////////////////////////////////////////////////////////////////// // PRE-PROCESSOR MACROS #define INPUT_LINE_MAX_LEN 256 /// Maximum length of each line in the dictionary file class Dictionary { public : // // Do NOT modify the public section of this class // typedef void (*WordDefFunc)(const char *word, const char *definition); Dictionary( const char *filename ); ~Dictionary(); const char *lookupDefinition( const char *word ); void forEach( WordDefFunc func ); private : // // You get to provide the private members // // VARIABLES int m_numEntries; /// stores the number of entries in the dictionary Entry *m_DictEntry_ptr; /// points to an array of class Entry // Private Functions }; #endif ----------------------------------- // /////////////////////////////////////////////////////////////////////////////////// // INCLUDES (C/C++ Std Library) #include <iostream> /// cout, getline #include <fstream> // ifstream #include <cstring> /// strchr // /////////////////////////////////////////////////////////////////////////////////// // DEPENDENCIES (custom header files) #include "dict.h" /// Header file required by assignment //#include "entry.h" /// Dicitonary Entry Class // /////////////////////////////////////////////////////////////////////////////////// // PRE-PROCESSOR MACROS #define COMMA ',' /// Delimiter for file #define ENTER '\n' /// Carriage return character #define FILE_ERR_MSG "The data file could not be opened. Program will now terminate." #pragma warning(disable : 4996) /// turn off MS compiler warning about strcpy() // /////////////////////////////////////////////////////////////////////////////////// // Namespace reference using namespace std; // /////////////////////////////////////////////////////////////////////////////////// // PRIVATE MEMBER FUNCTIONS /** * Sorts the dictionary entries. */ /* static void sortDictionary(?) { // sort through the words using qsort } */ /** NO LONGER NEEDED?? * parses out the length of the first cell in a delimited cell * / int getWordLength(char *str /// string of data to parse ) { return strcspn(str, COMMA); } */ // /////////////////////////////////////////////////////////////////////////////////// // PUBLIC MEMBER FUNCTIONS /** constructor for the class * - opens/reads in file * - creates initializes the array of member vars * - creates pointers to entry objects * - stores pointers to entry objects in member var * - ? sort now or later? */ Dictionary::Dictionary( const char *filename ) { // Create a filestream, open the file to be read in ifstream dataFile(filename, ios::in ); /* if( dataFile.fail() ) { cout << FILE_ERR_MSG << endl; exit(EXIT_FAILURE); } */ if( dataFile.is_open() ) { // read first line of data // TEST CODE in.getline(dataFile, INPUT_LINE_MAX_LEN) >> m_numEntries; // TEST CODE char temp[INPUT_LINE_MAX_LEN] = {NIL}; // TEST CODE dataFile.getline(temp,INPUT_LINE_MAX_LEN,'\n'); dataFile >> m_numEntries; /** Number of terms in the dictionary file * \todo find out how many lines in the file, subtract one, ingore first line */ //create the array of entries m_DictEntry_ptr = new Entry[m_numEntries]; // check for valid memory allocation if( !m_DictEntry_ptr ) { cout << MEM_ERR_MSG << endl; exit(EXIT_FAILURE); } // loop thru each line of the file, parsing words/def's and populating entry objects for(int EntryIdx = 0; EntryIdx < m_numEntries; ++EntryIdx) { // VARIABLES char *tempW_ptr; /// points to a temporary word char *tempD_ptr; /// points to a temporary def char *w_ptr; /// points to the word in the Entry object char *d_ptr; /// points to the definition in the Entry int tempWLen; /// length of the temp word string int tempDLen; /// length of the temp def string char tempLine[INPUT_LINE_MAX_LEN] = {NIL}; /// stores a single line from the file // EXECUTE // getline(dataFile, tempLine) // get a "word,def" line from the file dataFile.getline(tempLine, INPUT_LINE_MAX_LEN); // get a "word,def" line from the file // Parse the string tempW_ptr = tempLine; // point the temp word pointer at the first char in the line tempD_ptr = strchr(tempLine, COMMA); // point the def pointer at the comma *tempD_ptr = NIL; // replace the comma with a NIL ++tempD_ptr; // increment the temp def pointer // find the string lengths... +1 to account for terminator tempWLen = strlen(tempW_ptr) + 1; tempDLen = strlen(tempD_ptr) + 1; // Allocate heap memory for the term and defnition w_ptr = new char[ tempWLen ]; d_ptr = new char[ tempDLen ]; // check memory allocation if( !w_ptr && !d_ptr ) { cout << MEM_ERR_MSG << endl; exit(EXIT_FAILURE); } // copy the temp word, def into the newly allocated memory and terminate the strings strcpy(w_ptr,tempW_ptr); w_ptr[tempWLen] = NIL; strcpy(d_ptr,tempD_ptr); d_ptr[tempDLen] = NIL; // set the pointers for the entry objects m_DictEntry_ptr[ EntryIdx ].setWordPtr(w_ptr); m_DictEntry_ptr[ EntryIdx ].setDefPtr(d_ptr); } // close the file dataFile.close(); } else { cout << ENTER << FILE_ERR_MSG << endl; exit(EXIT_FAILURE); } } /** * cleans up dynamic memory */ Dictionary::~Dictionary() { delete[] m_DictEntry_ptr; /// thou shalt not have memory leaks. } /** * Looks up definition */ /* const char *lookupDefinition( const char *word ) { // print out the word ---- definition } */ /** * prints out the entire dictionary in sorted order */ /* void forEach( WordDefFunc func ) { // to sort before or now.... that is the question } */ Entry.h/cpp #ifndef ENTRY_H #define ENTRY_H // /////////////////////////////////////////////////////////////////////////////////// // INCLUDES (C++ Std lib) #include <cstdlib> /// EXIT_SUCCESS, NULL // /////////////////////////////////////////////////////////////////////////////////// // PRE-PROCESSOR MACROS #define NIL '\0' /// C-String terminator #define MEM_ERR_MSG "Memory allocation has failed. Program will now terminate." // /////////////////////////////////////////////////////////////////////////////////// // CLASS DEFINITION class Entry { public: Entry(void) : m_word_ptr(NULL), m_def_ptr(NULL) { /* default constructor */ }; void setWordPtr(char *w_ptr); /// sets the pointer to the word - only if the pointer is empty void setDefPtr(char *d_ptr); /// sets the ponter to the definition - only if the pointer is empty /// returns what is pointed to by the word pointer char getWord(void) const { return *m_word_ptr; } /// returns what is pointed to by the definition pointer char getDef(void) const { return *m_def_ptr; } private: char *m_word_ptr; /** points to a dictionary word */ char *m_def_ptr; /** points to a dictionary definition */ }; #endif -------------------------------------------------- // /////////////////////////////////////////////////////////////////////////////////// // DEPENDENCIES (custom header files) #include "entry.h" /// class header file // /////////////////////////////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /* * only change the word member var if it is in its initial state */ void Entry::setWordPtr(char *w_ptr) { if(m_word_ptr == NULL) { m_word_ptr = w_ptr; } } /* * only change the def member var if it is in its initial state */ void Entry::setDefPtr(char *d_ptr) { if(m_def_ptr == NULL) { m_word_ptr = d_ptr; } }

    Read the article

  • Uploadify Minimum Image Width And Height

    - by Richard Knop
    So I am using the Uplodify plugin to allow users to upload multiple images at once. The problem is I need to set a minimum width and height for images. Let's say 150x150px is the smallest image users can upload. How can I set this limitation in the Uploadify plugin? When user tries to upload smaller picture, I would like to display some error message as well. Here is the PHP file that is called bu the plugin to upload images: <?php define('BASE_PATH', substr(dirname(dirname(__FILE__)), 0, -22)); // set the include path set_include_path(BASE_PATH . '/../library' . PATH_SEPARATOR . BASE_PATH . '/library' . PATH_SEPARATOR . get_include_path()); // autoload classes from the library function __autoload($class) { include str_replace('_', '/', $class) . '.php'; } $configuration = new Zend_Config_Ini(BASE_PATH . '/application' . '/configs/application.ini', 'development'); $dbAdapter = Zend_Db::factory($configuration->database); Zend_Db_Table_Abstract::setDefaultAdapter($dbAdapter); function _getTable($table) { include BASE_PATH . '/application/modules/default/models/' . $table . '.php'; return new $table(); } $albums = _getTable('Albums'); $media = _getTable('Media'); if (false === empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $extension = end(explode('.', $_FILES['Filedata']['name'])); // insert temporary row into the database $data = array(); $data['type'] = 'photo'; $data['type2'] = 'public'; $data['status'] = 'temporary'; $data['user_id'] = $_REQUEST['user_id']; $paths = $media->add($data, $extension, $dbAdapter); // save the photo move_uploaded_file($tempFile, BASE_PATH . '/public/' . $paths[0]); // create a thumbnail include BASE_PATH . '/library/My/PHPThumbnailer/ThumbLib.inc.php'; $thumb = PhpThumbFactory::create(BASE_PATH . '/public/' . $paths[0]); $thumb->adaptiveResize(85, 85); $thumb->save(BASE_PATH . '/public/' . $paths[1]); // add watermark to the bottom right corner $pathToFullImage = BASE_PATH . '/public/' . $paths[0]; $size = getimagesize($pathToFullImage); switch ($extension) { case 'gif': $im = imagecreatefromgif($pathToFullImage); break; case 'jpg': $im = imagecreatefromjpeg($pathToFullImage); break; case 'png': $im = imagecreatefrompng($pathToFullImage); break; } if (false !== $im) { $white = imagecolorallocate($im, 255, 255, 255); $font = BASE_PATH . '/public/fonts/arial.ttf'; imagefttext($im, 13, // font size 0, // angle $size[0] - 132, // x axis (top left is [0, 0]) $size[1] - 13, // y axis $white, $font, 'HunnyHive.com'); switch ($extension) { case 'gif': imagegif($im, $pathToFullImage); break; case 'jpg': imagejpeg($im, $pathToFullImage, 100); break; case 'png': imagepng($im, $pathToFullImage, 0); break; } imagedestroy($im); } echo "1"; } And here's the javascript: $(document).ready(function() { $('#photo').uploadify({ 'uploader' : '/flash-uploader/scripts/uploadify.swf', 'script' : '/flash-uploader/scripts/upload-public-photo.php', 'cancelImg' : '/flash-uploader/cancel.png', 'scriptData' : {'user_id' : 'USER_ID'}, 'queueID' : 'fileQueue', 'auto' : true, 'multi' : true, 'sizeLimit' : 2097152, 'fileExt' : '*.jpg;*.jpeg;*.gif;*.png', 'wmode' : 'transparent', 'onComplete' : function() { $.get('/my-account/temporary-public-photos', function(data) { $('#temporaryPhotos').html(data); }); } }); $('#upload_public_photo').hover(function() { var titles = '{'; $('.title').each(function() { var title = $(this).val(); if ('Title...' != title) { var id = $(this).attr('name'); id = id.substr(5); title = jQuery.trim(title); if (titles.length > 1) { titles += ','; } titles += '"' + id + '"' + ':"' + title + '"'; } }); titles += '}'; $('#titles').val(titles); }); }); Now bear in mind that I know how to check images dimensions in the PHP file. But I'm not sure how to modify the javascript so it won't upload images with very small dimensions.

    Read the article

  • How to debug move_uploaded_file() in PHP

    - by iamdadude
    move_uploaded_file() won't work for me anymore, it was working fine and just stopped out of nowhere. Is there a way for me to check why it's not working anymore? Here's what I currently have, but it only returns TRUE or FALSE. $status = move_uploaded_file($tempFile, $targetFile); if($status) { echo 'its good'; } else { echo 'it failed'; } I know the path is 100% correct and the directory is CHMOD 755. Is there anything I might be doing wrong?

    Read the article

  • FileUtils.mv adding linebreaks in Windows

    - by Lowgain
    I am streaming wav data from a flash application. If I get the data and do the following: f = File.open('c:/test.wav') f << wav_data.pack('c'*wav_data.length) f.close The wav file works perfectly. If I do this: f = Tempfile.new('test.wav') f << wav_data.pack('c'*wav_data.length) f.close FileUtils.mv(f.path, 'c:/') The file is there, but sounds all garbled. Checking in a hex editor shows that everywhere the working file had an 0A (or \n), the garbled version had 0D0A (or \r\n) I am using this in conjuction with rails+paperclip, and am going to be using a combination of Heroku and S3 for the live app, so I am hoping this problem will solve itself, but I'd like to get this working on my local machine for the time being. Does anybody know of any reason FileUtils.mv would be doing this, and if there is a way to change its behaviour?

    Read the article

  • Why is this the output of this python program?

    - by Andrew Moffat
    Someone from #python suggested that it's searching for module "herpaderp" and finding all the ones listed as its searching. If this is the case, why doesn't it list every module on my system before raising ImportError? Can someone shed some light on what's happening here? import sys class TempLoader(object): def __init__(self, path_entry): if path_entry == 'test': return raise ImportError def find_module(self, fullname, path=None): print fullname, path return None sys.path.insert(0, 'test') sys.path_hooks.append(TempLoader) import herpaderp output: 16:00:55 $> python wtf.py herpaderp None apport None subprocess None traceback None pickle None struct None re None sre_compile None sre_parse None sre_constants None org None tempfile None random None __future__ None urllib None string None socket None _ssl None urlparse None collections None keyword None ssl None textwrap None base64 None fnmatch None glob None atexit None xml None _xmlplus None copy None org None pyexpat None problem_report None gzip None email None quopri None uu None unittest None ConfigParser None shutil None apt None apt_pkg None gettext None locale None functools None httplib None mimetools None rfc822 None urllib2 None hashlib None _hashlib None bisect None Traceback (most recent call last): File "wtf.py", line 14, in <module> import herpaderp ImportError: No module named herpaderp

    Read the article

  • Creating an Extremely Large Index in Oracle

    - by Rudiger
    Can someone look at the linked reference and explain to me the precise statements to run? Oracle DBA's Guide: Creating a Large Index Here's what I came up with... CREATE TEMPORARY TABLESPACE ts_tmp TEMPFILE 'E:\temp01.dbf' SIZE 10000M REUSE AUTOEXTEND ON EXTENT MANAGEMENT LOCAL; ALTER USER me TEMPORARY TABLESPACE ts_tmp; CREATE UNIQUE INDEX big_table_idx ON big_table ( record_id ); DROP TABLESPACE ts_tmp; Edit 1 After this index was created, I ran an explain plan for a simple query and get this error: ORA-00959: tablespace 'TS_TMP' does not exist It seems like it's not temporary at all... :(

    Read the article

  • Java URL("file://") doesn't work on Windows XP

    - by Soumya Simanta
    For some reason the following code doesn't work on Windows XP. new URL("file://" + tempfile.getAbsolutePath()); I'm using Java 1.6. Java(TM) SE Runtime Environment (build 1.6.0_31-b05) Java HotSpot(TM) Client VM (build 20.6-b01, mixed mode, sharing) However, the same code just works fine in OS X (Lion) and Java 1.6 java version "1.6.0_29" Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11M3527) Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode) Linux (Linux 2.6.32-38-generic #83-Ubuntu x86_64 GNU/Linux) with Java 1.6 java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode) Based on this the above code should work.

    Read the article

  • Shell script exiting the loop after calling another script

    - by Johnyy
    Hi Guys, I have a shell script s1 calling another script s2 in a loop. However s1 can not seem to continue the loop after s2 returns. Commenting out the line that calls s2 will enable the loop to continue. s2 does copy of one file, s1 checks conditions and copy several files using s2. Can anyone give a pointer what is going on here? ... while read line s2 param1 param2 param3 echo "copy done" done < $tempfile echo "out of loop" ... "copy done" is printed, so is "out of loop"

    Read the article

  • getting a pyserial not loaded error

    - by skinnyTOD
    I'm getting a "pyserial not loaded" error with the python script fragment below (running OSX 10.7.4). I'm trying to run a python app called Myro for controlling the Parallax Scribbler2 robot - figured it would be a fun way to learn a bit of Python - but I'm not getting out of the gate here. I've searched out all the Myro help docs but like a lot in-progress open source programs, they are a moving target and conflicting, out of date, or not very specific about OSX. I have MacPorts installed and installed py27-serial without error. MacPorts lists the python versions I have installed, along with the active version: Available versions for python: none python24 python25 python25-apple python26 python26-apple python27 python27-apple (active) python32 Perhaps stuff is getting installed in the wrong places or my PATH is wrong (I don't much know what I am doing in Terminal and have probably screwed something up). Trying to find out about my sys.path - here's what I get: import sys sys.path ['', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC', '/Library/Python/2.7/site-packages'] Is that a mess? Can I fix it? Anyway, thanks for reading this far. Here's the python bit that is throwing the error. The error occurs on 'try import serial'. # Global variable robot, to set SerialPort() robot = None pythonVer = "?" rbString = None ptString = None statusText = None # Now, let's import things import urllib import tempfile import os, sys, time try: import serial except: print("WARNING: pyserial not loaded: can't upgrade!") sys.exit() try: input = raw_input # Python 2.x except: pass # Python 3 and better, input is defined try: from tkinter import * pythonver = "3" except: try: from Tkinter import * pythonver = "2" except: pythonver = "?"

    Read the article

  • Load testing multipart form

    - by JacobM
    I'm trying to load-test a Rails application using JMeter. A critical part of the application involves a form that includes both text inputs and file uploads. It works fine in a browser, but when I try to post that page in JMeter, Rails is saving all of the parts of the multipart form as temp files, which causes things to break when it's looking for a string and gets a tempfile instead. It appears that the difference is that, from a browser, the piece of the multipart request that contains a text input looks like this: -----------------------------7d93b4186074c Content-Disposition: form-data; name="field_name" test -----------------------------7d93b4186074c while from JMeter it looks like this: -----------------------------7d159c1302d0y0 Content-Disposition: form-data; name="field_name" Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit test -----------------------------7d159c1302d0y0 So apparently Rails sees the former and interprets it as a plain text value and treats it as a string, but sees the latter and saves it to a temp file. I have not been able to find a setting to convince JMeter not to send the additional headers in the multipart form for non-file fields. Is there a way to convince Rails to ignore those headers and treat the text/plain text as strings instead of text files? Or a quick way to put a filter in front of my controller that will strip the extra headers? Alternately, is there a better tool to load-test a Rails application that includes file upload?

    Read the article

  • How to replace openSSL calls with C# code?

    - by fonix232
    Hey there again! Today I ran into a problem when I was making a new theme creator for chrome. As you may know, Chrome uses a "new" file format, called CRX, to manage it's plugins and themes. It is a basic zip file, but a bit modified: "Cr24" + derkey + signature + zipFile And here comes the problem. There are only two CRX creators, written in Ruby or Python. I don't know neither language too much (had some basic experience in Python though, but mostly with PyS60), so I would like to ask you to help me convert this python app to a C# code that doesn't depend on external programs. Also, here is the source of crxmake.py: #!/usr/bin/python # Cribbed from http://github.com/Constellation/crxmake/blob/master/lib/crxmake.rb # and http://src.chromium.org/viewvc/chrome/trunk/src/chrome/tools/extensions/chromium_extension.py?revision=14872&content-type=text/plain&pathrev=14872 # from: http://grack.com/blog/2009/11/09/packing-chrome-extensions-in-python/ import sys from array import * from subprocess import * import os import tempfile def main(argv): arg0,dir,key,output = argv # zip up the directory input = dir + ".zip" if not os.path.exists(input): os.system("cd %(dir)s; zip -r ../%(input)s . -x '.svn/*'" % locals()) else: print "'%s' already exists using it" % input # Sign the zip file with the private key in PEM format signature = Popen(["openssl", "sha1", "-sign", key, input], stdout=PIPE).stdout.read(); # Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header derkey = Popen(["openssl", "rsa", "-pubout", "-inform", "PEM", "-outform", "DER", "-in", key], stdout=PIPE).stdout.read(); out=open(output, "wb"); out.write("Cr24") # Extension file magic number header = array("l"); header.append(2); # Version 2 header.append(len(derkey)); header.append(len(signature)); header.tofile(out); out.write(derkey) out.write(signature) out.write(open(input).read()) os.unlink(input) print "Done." if __name__ == '__main__': main(sys.argv) Please could you help me?

    Read the article

< Previous Page | 1 2 3  | Next Page >