Search Results

Search found 3977 results on 160 pages for 'filename'.

Page 12/160 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • How do I handle a missing mandatory argument in Ruby OptionParser?

    - by Rob Jones
    In OptionParser I can make an option mandatory, but if I leave out that value it will take the name of any following option as the value, screwing up the rest of the command line parsing. Here is a test case that echoes the values of the options: $ ./test_case.rb --input foo --output bar output bar input foo Now leave out the value for the first option: $ ./test_case.rb --input --output bar input --output Is there some way to prevent it taking another option name as a value? Thanks! Here is the test case code: #!/usr/bin/env ruby require 'optparse' files = Hash.new option_parser = OptionParser.new do |opts| opts.on('-i', '--input FILENAME', 'Input filename - required') do |filename| files[:input] = filename end opts.on('-o', '--output FILENAME', 'Output filename - required') do |filename| files[:output] = filename end end begin option_parser.parse!(ARGV) rescue OptionParser::ParseError $stderr.print "Error: " + $! + "\n" exit end files.keys.each do |key| print "#{key} #{files[key]}\n" end

    Read the article

  • Creating thumbnails PHP problem

    - by Wayne
    I have this source code where I got it from net tutsplus. I have configured it and made it work in one PHP file. It does work by transferring the original image, but it does not generate to the thumbnails folder. <?php $final_width_of_image = 100; $path_to_image_directory = "../../img/events/" . urldecode($_GET['name']) . "/"; $path_to_thumbs_directory = "../../img/events/" . urldecode($_GET['name']) . "/thumbnails/"; function createThumbnail($filename) { if(preg_match('/[.](jpg)$/', $filename)) { $im = imagecreatefromjpeg($path_to_image_directory . $filename); } elseif(preg_match('/[.](gif)$/', $filename)) { $im = imagecreatefromgif($path_to_image_directory . $filename); } elseif(preg_match('/[.](png)$/', $filename)) { $im = imagecreatefrompng($path_to_image_directory . $filename); } $ox = imagesx($im); $oy = imagesy($im); $nx = $final_width_of_image; $ny = floor($oy * ($final_width_of_image / $ox)); $nm = imagecreatetruecolor($nx, $ny); imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy); imagejpeg($nm, $path_to_thumbs_directory . $filename); $tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />'; echo $tn; } if(isset($_FILES['fupload'])) { if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) { $filename = $_FILES['fupload']['name']; $source = $_FILES['fupload']['tmp_name']; $target = $path_to_image_directory . $filename; move_uploaded_file($source, $target); createThumbnail($filename); } } ?> Basically it is supposed to generate a thumbnail of the uploaded image and store the original image into a different folder. The paths are correct, it works by getting the folder name in the URL, it does work, but nothing works for the thumbnails folder. BEFORE you ask this related question, yes, thumbnails generation does work on my server by the PHP GD, I have tested it separately. So this is not the problem. :) How do I get this to work? :(

    Read the article

  • file upload with php

    - by Rajanikant shukla
    Hi every body I am uploading file with php every thing is fine but move_uploded_file is not working every variable displayed record and all permission for file is set function uploadfile($filename) { $filetype=$filename["type"]; $filename=$filename['name']; $filetempname=$filename['tmp_name']; if($filetype=="application/msword") { move_uploaded_file($filetempname,"resume/".$filename); } }

    Read the article

  • Other test cases for this openFile function?

    - by igor
    I am trying to figure out why my function to open a file is failing this autograder I submit my homework into. What type of input would fail here, I can't think of anything else? Code: bool openFile(ifstream& ins) { char fileName[256]; cout << "Enter board filename: "; cin.getline(fileName,256); cout << endl << fileName << endl; ins.open(fileName); if(!ins) { ins.clear(); cout<<"Error opening file"<<endl; return false; } return true; } Here is output from the 'Autograder' of what my program's output is, and what the correct output is supposed to be (and I do not know what is in the file they use for the input) Autograder output: ******************************************* ***** ***** ***** Your output is: ***** ***** ***** ******************************************* Testing function openFile Enter board filename: test.txt 1 Enter board filename: not a fileName Error opening file 0 ******************************************* ***** ***** ***** Correct Output ***** ***** ***** ******************************************* Testing function openFile Enter board filename: 1 Enter board filename: Error opening file 0

    Read the article

  • Visual Studio File Groupings

    - by Daniel
    In Visual Studio 3 files are typically grouped together: filename.aspx filename.aspx.cs filename.aspx.designer.cs Is there a way to add another file that grouping so that it can be collapsed and out of view? filename.aspx filename.aspx.cs filename.aspx.designer.cs customfile.cs Thanks

    Read the article

  • How to use traceit to report function input variables in stack trace

    - by reckoner
    Hi, I've been using the following code to trace the execution of my programs: import sys import linecache import random def traceit(frame, event, arg): if event == "line": lineno = frame.f_lineno filename = frame.f_globals["__file__"] if filename == "<stdin>": filename = "traceit.py" if (filename.endswith(".pyc") or filename.endswith(".pyo")): filename = filename[:-1] name = frame.f_globals["__name__"] line = linecache.getline(filename, lineno) print "%s:%s:%s: %s" % (name, lineno,frame.f_code.co_name , line.rstrip()) return traceit def main(): print "In main" for i in range(5): print i, random.randrange(0, 10) print "Done." sys.settrace(traceit) main() Using this code, or something like it, is it possible to report the values of certain function arguments? In other words, the above code tells me "which" functions were called and I would like to know "what" the corresponding values of the input variables for those function calls. Thanks in advance.

    Read the article

  • unicode convertion problem

    - by bhoomi-nature
    Hai frnds i am bhoomi new to php,i am having having below problem in my coding please can you help anyone 1.first i want to open one word document which is having content and i wann to edit it 2.for that i am opening word document from the server and at that time its opening with garbage value(i thing its not converting to utf8 format) 3.wen i delete that garbage value and insert something from textarea to that file it is going to insert and next time onwords its its getting open properly. 4.actually i wann that doc file should open with english words wats there in that doc instead of garbage value..first time opening only its giving problem. i am using below code for that please do the needful $filename = 'test.doc'; if(isset($_REQUEST['Submit'])){ $somecontent = stripslashes($_POST['somecontent']); // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename) - Continue - "; fclose($handle); } else { echo "The file $filename is not writable"; } } else{ // get contents of a file into a string $handle = fopen($filename, 'r'); $somecontent = fread($handle, filesize($filename)); ? Edit file

    Read the article

  • How can I map URLs to filenames with perl?

    - by eugene y
    In a simple webapp I need to map URLs to filenames or filepaths. This app has a requirement that it can depend only on modules in the core Perl ditribution (5.6.0 and later). The problem is that filename length on most filesystems is limited to 255. Another limit is about 32k subdirectories in a single folder. My solution: my $filename = $url; if (length($filename) > $MAXPATHLEN) { # if filename longer than 255 my $part1 = substr($filename, 0, $MAXPATHLEN - 13); # first 242 chars my $part2 = crypt(0, substr($filename, $MAXPATHLEN - 13)); # 13 chars hash $filename = $part1.$part2; } $filename =~ s!/!_!g; # escape directory separator Is it reliable ? How can it be improved ?

    Read the article

  • PHP is truncating MSSQL Blob data (4096b), even after setting INI values. Am I missing one?

    - by Dutchie432
    I am writing a PHP script that goes through a table and extracts the varbinary(max) blob data from each record into an external file. The code is working perfectly, except when a file is over 4096b - the data is truncated at exactly 4096. I've modified the values for mssql.textlimit, mssql.textsize, and odbc.defaultlrl without any success. Am I missing something here? <?php ini_set("mssql.textlimit" , "2147483647"); ini_set("mssql.textsize" , "2147483647"); ini_set("odbc.defaultlrl", "0"); include_once('common.php'); $id=$_REQUEST['i']; $q = odbc_exec($connect, "Select id,filename,documentBin from Projectdocuments where id = $id"); if (odbc_fetch_row($q)){ echo "Trying $filename ... "; $fileName="projectPhotos/docs/".odbc_result($q,"filename"); if (file_exists($fileName)){ unlink($fileName); } if($fh = fopen($fileName, "wb")) { $binData=odbc_result($q,"documentBin"); fwrite($fh, $binData) ; fclose($fh); $size = filesize($fileName); echo ("$fileName<br />Done ($size)<br><br>"); }else { echo ("$fileName Failed<br>"); } } ?> OUTPUT Trying ... projectPhotos/docs/file1.pdf Done (4096) Trying ... projectPhotos/docs/file2.zip Done (4096) Trying ... projectPhotos/docsv3.pdf Done (4096) etc..

    Read the article

  • Creating .ics file from code sometimes givs "The file <filename>[<index>].ics" is not a valid intern

    - by KaJo
    Hi! I am building an ASP site where i use response.write to create an ics file where user can choose open or save dialog for the event. When the user choose open, outlook sometimes gives the error "The file [].ics" is not a valid internet Calender file"? It is always the same event that is written to the response. The code looks like this: this.Response.ContentType = "text/calendar"; this.Response.AddHeader("Cache-Control", "no-cache, must-revalidate"); this.Response.AddHeader("Pragma", "no-cache"); this.Response.Expires = -1; this.Response.AddHeader("Content-disposition", string.Format("attachment; filename={0}.ics",filename)); this.Response.Write("BEGIN:VCALENDAR"); this.Response.Write("\nVERSION:2.0"); this.Response.Write("\nMETHOD:PUBLISH"); this.Response.Write("\nBEGIN:VEVENT"); this.Response.Write("\nType:Single Meeting"); this.Response.Write("\nORGANIZER:MAILTO:" + organizer); this.Response.Write("\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat)); this.Response.Write("\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat)); this.Response.Write("\nLOCATION:" + location); this.Response.Write("\nUID:" + Guid.NewGuid().ToString()); this.Response.Write("\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat)); this.Response.Write("\nSUMMARY:" + summary); this.Response.Write("\nDESCRIPTION:" + description); this.Response.Write("\nPRIORITY:5"); this.Response.Write("\nCLASS:PUBLIC"); this.Response.Write("\nEND:VEVENT"); this.Response.Write("\nEND:VCALENDAR"); this.Response.End(); I usually get the error the first time I try to open the event in outlook, and the it works the second time? Does anyone knows how to solve this problem?

    Read the article

  • How to get current datetime on windows command line, in a suitable format for using in a filename?

    - by Rory
    What's a windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename? I want to have a .bat file that zips up a directory into an archive with the current date & time as part of the name, eg "Code_2008-10-14_2257.zip". Is there any easy way I can do this, independent of the regional settings of the machine? I don't really mind about the date format, ideally it'd be yyyy-mm-dd but anything simple is fine. So far I've got this, which on my machine gives me "Tue_10_14_2008_230050_91" rem Get the datetime in a format that can go in a filename. set _my_datetime=%date%_%time% set _my_datetime=%_my_datetime: =_% set _my_datetime=%_my_datetime::=% set _my_datetime=%_my_datetime:/=_% set _my_datetime=%_my_datetime:.=_% rem now use the timestamp by in a new zip file name "d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code I can live with this but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier. I'm using Windows Server 2003 and Win XP Pro. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).

    Read the article

  • how can we apply client side validation on fileupload control in ASP.NET to check filename contain s

    - by subodh
    I am working on ASP.NET3.5 platform. I have used a file upload control and a asp button to upload a file. Whenever i try to upload a file which contain special characterlike (file#&%.txt) it show crash and give the messeage Server Error in 'myapplication' Application. A potentially dangerous Request.Files value was detected from the client (filename="...\New Text &#.txt"). Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Files value was detected from the client (filename="...\New Text &#.txt"). Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. how can i prevent this crash using javascript at client side?

    Read the article

  • Improved technique to store a filename in a variable?

    - by SDGuero
    Greetings, I need to store the filename of a log into a variable so my script can perform some checks on the daily log files. These logs always have a different name because they have a timestamp in the name. Currently I'm using a hodge podged method that pipes an ls command to sed, sort, cut, and tail in order to get the name out. CRON_LOG=$(ls -1 $LOGS_DIR/fetch_cron_{true,false}_$CRON_DATE*.log 2> /dev/null | sed 's/^[^0-9][^0-9]*\([0-9][0-9]*\).*/\1 &/' | sort -n | cut -d ' ' -f2- | tail -1 ) UPDATE: $CRON_DATE is supplied as an argument to the script. It is the date (to the day) that the log was created on. Sometimes multiple logs will exist for the same day so I want this to get the most recent one. A typical filename is fetch_cron_false_031810090452.log I'm pretty sure I kluged this together from some stuff I found google a few months ago. it works now but I'm not really happy with the technique. I have some ideas about how to do this better but I have had great success on this site before and thought it might be best to refer to the stackoverflow gods first. All answers are greatly appreciated. Thanks, Ryan

    Read the article

  • asp.net get filename of a file inside the specific folder.

    - by kurt_jackson19
    hi folks, Good morning! I would like to ask some help from you guys on how do i do this problem. I'm using asp.net and my problem is on getting the list of filename inside the folder. Is there a function on this? I tried this on console apps there's a function like GetFileName. Hope somebody could help me on this. Thank you so much. Regards,

    Read the article

  • Setup filename convention? setup.exe vs install.exe vs others

    - by www.openidfrance.frfxkim
    Hi, I'm going to build an installer to deploy my application which is a Windows executable file(not a MSI file). I'm using NSIS. This application targets French people and "install" word is close to "installation" in French. Is there a filename convention? What is the best choice for you? It seems that "setup.exe" is the most popular name compare to "install.exe" What do you think? Thanks for your reply.

    Read the article

  • Fix for Visual Studio 2005 not showing filename or line on errors in web pages when compiling?

    - by spoulson
    A project I'm on requires Visual Studio 2005. One annoyance is that when a website project in the solution, any compile errors from .aspx or .ascx files show up like: (0,0): warning CS0168: The variable 'ex' is declared but never used (0,0): warning CS0162: Unreachable code detected (0,0): warning CS0168: The variable 'ex' is declared but never used (0,0): warning CS0168: The variable 'ex' is declared but never used How can I track these down? Is there an option I'm missing that gives me filename and line numbers?

    Read the article

  • How to change last letter of filename to lowercase if it is a letter?

    - by Robert Buckley
    I have been given data which cannot be interpreted by my software unless it has a lowercase letter at the end. The data was delivered with an uppercase letter at the end. Somehow I need to first recursively loop through all folders and find whether the filename ends with a letter and then change it to lowercase. I think python could do this, but I don´t know how,. Any help would be great! yours, Rob

    Read the article

  • Dynamic Document Template

    - by ell
    I would like to create a "C++ Class" document template, I know you can make static ones by putting them into ~/Templates, but I would like to be able for the content to change according to the file name on creation, for example, using a template like such (pseudocode): #ifndef $(filename)_HPP_INCLUDED #define $(filename)_HPP_INCLUDED class $(filename) { public: } #endif $(filename)_HPP_INCLUDED Is this possible? If so, how can I do it? Thanks in advance, ell.

    Read the article

  • Unity – Part 5: Injecting Values

    - by Ricardo Peres
    Introduction This is the fifth post on Unity. You can find the introductory post here, the second post, on dependency injection here, a third one on Aspect Oriented Programming (AOP) here and the latest so far, on writing custom extensions, here. This time we will talk about injecting simple values. An Inversion of Control (IoC) / Dependency Injector (DI) container like Unity can be used for things other than injecting complex class dependencies. It can also be used for setting property values or method/constructor parameters whenever a class is built. The main difference is that these values do not have a lifetime manager associated with them and do not come from the regular IoC registration store. Unlike, for instance, MEF, Unity won’t let you register as a dependency a string or an integer, so you have to take a different approach, which I will describe in this post. Scenario Let’s imagine we have a base interface that describes a logger – the same as in previous examples: 1: public interface ILogger 2: { 3: void Log(String message); 4: } And a concrete implementation that writes to a file: 1: public class FileLogger : ILogger 2: { 3: public String Filename 4: { 5: get; 6: set; 7: } 8:  9: #region ILogger Members 10:  11: public void Log(String message) 12: { 13: using (Stream file = File.OpenWrite(this.Filename)) 14: { 15: Byte[] data = Encoding.Default.GetBytes(message); 16: 17: file.Write(data, 0, data.Length); 18: } 19: } 20:  21: #endregion 22: } And let’s say we want the Filename property to come from the application settings (appSettings) section on the Web/App.config file. As usual with Unity, there is an extensibility point that allows us to automatically do this, both with code configuration or statically on the configuration file. Extending Injection We start by implementing a class that will retrieve a value from the appSettings by inheriting from ValueElement: 1: sealed class AppSettingsParameterValueElement : ValueElement, IDependencyResolverPolicy 2: { 3: #region Private methods 4: private Object CreateInstance(Type parameterType) 5: { 6: Object configurationValue = ConfigurationManager.AppSettings[this.AppSettingsKey]; 7:  8: if (parameterType != typeof(String)) 9: { 10: TypeConverter typeConverter = this.GetTypeConverter(parameterType); 11:  12: configurationValue = typeConverter.ConvertFromInvariantString(configurationValue as String); 13: } 14:  15: return (configurationValue); 16: } 17: #endregion 18:  19: #region Private methods 20: private TypeConverter GetTypeConverter(Type parameterType) 21: { 22: if (String.IsNullOrEmpty(this.TypeConverterTypeName) == false) 23: { 24: return (Activator.CreateInstance(TypeResolver.ResolveType(this.TypeConverterTypeName)) as TypeConverter); 25: } 26: else 27: { 28: return (TypeDescriptor.GetConverter(parameterType)); 29: } 30: } 31: #endregion 32:  33: #region Public override methods 34: public override InjectionParameterValue GetInjectionParameterValue(IUnityContainer container, Type parameterType) 35: { 36: Object value = this.CreateInstance(parameterType); 37: return (new InjectionParameter(parameterType, value)); 38: } 39: #endregion 40:  41: #region IDependencyResolverPolicy Members 42:  43: public Object Resolve(IBuilderContext context) 44: { 45: Type parameterType = null; 46:  47: if (context.CurrentOperation is ResolvingPropertyValueOperation) 48: { 49: ResolvingPropertyValueOperation op = (context.CurrentOperation as ResolvingPropertyValueOperation); 50: PropertyInfo prop = op.TypeBeingConstructed.GetProperty(op.PropertyName); 51: parameterType = prop.PropertyType; 52: } 53: else if (context.CurrentOperation is ConstructorArgumentResolveOperation) 54: { 55: ConstructorArgumentResolveOperation op = (context.CurrentOperation as ConstructorArgumentResolveOperation); 56: String args = op.ConstructorSignature.Split('(')[1].Split(')')[0]; 57: Type[] types = args.Split(',').Select(a => Type.GetType(a.Split(' ')[0])).ToArray(); 58: ConstructorInfo ctor = op.TypeBeingConstructed.GetConstructor(types); 59: parameterType = ctor.GetParameters().Where(p => p.Name == op.ParameterName).Single().ParameterType; 60: } 61: else if (context.CurrentOperation is MethodArgumentResolveOperation) 62: { 63: MethodArgumentResolveOperation op = (context.CurrentOperation as MethodArgumentResolveOperation); 64: String methodName = op.MethodSignature.Split('(')[0].Split(' ')[1]; 65: String args = op.MethodSignature.Split('(')[1].Split(')')[0]; 66: Type[] types = args.Split(',').Select(a => Type.GetType(a.Split(' ')[0])).ToArray(); 67: MethodInfo method = op.TypeBeingConstructed.GetMethod(methodName, types); 68: parameterType = method.GetParameters().Where(p => p.Name == op.ParameterName).Single().ParameterType; 69: } 70:  71: return (this.CreateInstance(parameterType)); 72: } 73:  74: #endregion 75:  76: #region Public properties 77: [ConfigurationProperty("appSettingsKey", IsRequired = true)] 78: public String AppSettingsKey 79: { 80: get 81: { 82: return ((String)base["appSettingsKey"]); 83: } 84:  85: set 86: { 87: base["appSettingsKey"] = value; 88: } 89: } 90: #endregion 91: } As you can see from the implementation of the IDependencyResolverPolicy.Resolve method, this will work in three different scenarios: When it is applied to a property; When it is applied to a constructor parameter; When it is applied to an initialization method. The implementation will even try to convert the value to its declared destination, for example, if the destination property is an Int32, it will try to convert the appSettings stored string to an Int32. Injection By Configuration If we want to configure injection by configuration, we need to implement a custom section extension by inheriting from SectionExtension, and registering our custom element with the name “appSettings”: 1: sealed class AppSettingsParameterInjectionElementExtension : SectionExtension 2: { 3: public override void AddExtensions(SectionExtensionContext context) 4: { 5: context.AddElement<AppSettingsParameterValueElement>("appSettings"); 6: } 7: } And on the configuration file, for setting a property, we use it like this: 1: <appSettings> 2: <add key="LoggerFilename" value="Log.txt"/> 3: </appSettings> 4: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 5: <container> 6: <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.ConsoleLogger, MyAssembly"/> 7: <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.FileLogger, MyAssembly" name="File"> 8: <lifetime type="singleton"/> 9: <property name="Filename"> 10: <appSettings appSettingsKey="LoggerFilename"/> 11: </property> 12: </register> 13: </container> 14: </unity> If we would like to inject the value as a constructor parameter, it would be instead: 1: <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 2: <sectionExtension type="MyNamespace.AppSettingsParameterInjectionElementExtension, MyAssembly" /> 3: <container> 4: <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.ConsoleLogger, MyAssembly"/> 5: <register type="MyNamespace.ILogger, MyAssembly" mapTo="MyNamespace.FileLogger, MyAssembly" name="File"> 6: <lifetime type="singleton"/> 7: <constructor> 8: <param name="filename" type="System.String"> 9: <appSettings appSettingsKey="LoggerFilename"/> 10: </param> 11: </constructor> 12: </register> 13: </container> 14: </unity> Notice the appSettings section, where we add a LoggerFilename entry, which is the same as the one referred by our AppSettingsParameterInjectionElementExtension extension. For more advanced behavior, you can add a TypeConverterName attribute to the appSettings declaration, where you can pass an assembly qualified name of a class that inherits from TypeConverter. This class will be responsible for converting the appSettings value to a destination type. Injection By Attribute If we would like to use attributes instead, we need to create a custom attribute by inheriting from DependencyResolutionAttribute: 1: [Serializable] 2: [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] 3: public sealed class AppSettingsDependencyResolutionAttribute : DependencyResolutionAttribute 4: { 5: public AppSettingsDependencyResolutionAttribute(String appSettingsKey) 6: { 7: this.AppSettingsKey = appSettingsKey; 8: } 9:  10: public String TypeConverterTypeName 11: { 12: get; 13: set; 14: } 15:  16: public String AppSettingsKey 17: { 18: get; 19: private set; 20: } 21:  22: public override IDependencyResolverPolicy CreateResolver(Type typeToResolve) 23: { 24: return (new AppSettingsParameterValueElement() { AppSettingsKey = this.AppSettingsKey, TypeConverterTypeName = this.TypeConverterTypeName }); 25: } 26: } As for file configuration, there is a mandatory property for setting the appSettings key and an optional TypeConverterName  for setting the name of a TypeConverter. Both the custom attribute and the custom section return an instance of the injector AppSettingsParameterValueElement that we implemented in the first place. Now, the attribute needs to be placed before the injected class’ Filename property: 1: public class FileLogger : ILogger 2: { 3: [AppSettingsDependencyResolution("LoggerFilename")] 4: public String Filename 5: { 6: get; 7: set; 8: } 9:  10: #region ILogger Members 11:  12: public void Log(String message) 13: { 14: using (Stream file = File.OpenWrite(this.Filename)) 15: { 16: Byte[] data = Encoding.Default.GetBytes(message); 17: 18: file.Write(data, 0, data.Length); 19: } 20: } 21:  22: #endregion 23: } Or, if we wanted to use constructor injection: 1: public class FileLogger : ILogger 2: { 3: public String Filename 4: { 5: get; 6: set; 7: } 8:  9: public FileLogger([AppSettingsDependencyResolution("LoggerFilename")] String filename) 10: { 11: this.Filename = filename; 12: } 13:  14: #region ILogger Members 15:  16: public void Log(String message) 17: { 18: using (Stream file = File.OpenWrite(this.Filename)) 19: { 20: Byte[] data = Encoding.Default.GetBytes(message); 21: 22: file.Write(data, 0, data.Length); 23: } 24: } 25:  26: #endregion 27: } Usage Just do: 1: ILogger logger = ServiceLocator.Current.GetInstance<ILogger>("File"); And off you go! A simple way do avoid hardcoded values in component registrations. Of course, this same concept can be applied to registry keys, environment values, XML attributes, etc, etc, just change the implementation of the AppSettingsParameterValueElement class. Next stop: custom lifetime managers.

    Read the article

  • Ubuntu + Wacom Intuos 4 + MyPaint HELP!

    - by Sativa
    Please keep in mind I'm not that computer savvy, but I will try any suggestion so please help me out! My tablet will stop working if the USB connection is ever broken, or the Ubuntu software is being updated. Sometimes it will stop working for no reason that I can see. The lights will still be on, but it won't be responsive. It doesn't work again until I restart the laptop with the tablet plugged in, which is grating if you have to do it every 25 min. or so... I'm not sure if the issue is with the port, the tablet/cable or the driver but any suggestions would be very welcome! Also, MyPaint is frequently having hiccups. It seems to save fine but at times it will randomly close down and when I open files they're often empty. They turn into 0Kb files and only contain a single empty layer. Also very grating, considering I lose days of work for no clear reason and without any heads up. Again, I'm not sure if the issue is with the port, the tablet/cable or the driver but any suggestions would be very welcome! The error message reads; Traceback (most recent call last): File "/usr/share/mypaint/gui/application.py", line 177, at_application_start(*junk=()) else: self.filehandler.open_file(fn) variables: {'fn': ('local', u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora'), 'self.filehandler.open_file': ('local', <bound method FileHandler.wrapper of <gui.filehandling.FileHandler object at 0x7fdb89063a10>>)} File "/usr/share/mypaint/gui/drawwindow.py", line 60, wrapper(self=<gui.filehandling.FileHandler object>, *args=(u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora',), **kwargs={}) try: func(self, *args, **kwargs) # gtk main loop may be called in here... variables: {'self': ('local', <gui.filehandling.FileHandler object at 0x7fdb89063a10>), 'args': ('local', (u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora',)), 'func': ('local', <function open_file at 0x7fdb8b397b90>), 'kwargs': ('local', {})} File "/usr/share/mypaint/gui/filehandling.py", line 231, open_file(self=<gui.filehandling.FileHandler object>, filename=u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora') try: self.doc.model.load(filename, feedback_cb=self.gtk_main_tick) except document.SaveLoadError, e: variables: {'self.doc.model.load': ('local', <bound method Document.load of <lib.document.Document instance at 0x7fdb8ab4f8c0>>), 'feedback_cb': (None, []), 'self.gtk_main_tick': ('local', <function gtk_main_tick at 0x7fdb8b397b18>), 'filename': ('local', u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora')} File "/usr/share/mypaint/lib/document.py", line 544, load(self=<lib.document.Document instance>, filename=u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora', **kwargs={'feedback_cb': <function gtk_main_tick>}) try: load(filename, **kwargs) except gobject.GError, e: variables: {'load': ('local', <bound method Document.load_ora of <lib.document.Document instance at 0x7fdb8ab4f8c0>>), 'kwargs': ('local', {'feedback_cb': <function gtk_main_tick at 0x7fdb8b397b18>}), 'filename': ('local', u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora')} File "/usr/share/mypaint/lib/document.py", line 772, load_ora(self=<lib.document.Document instance>, filename=u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora', feedback_cb=<function gtk_main_tick>) tempdir = tempdir.decode(sys.getfilesystemencoding()) z = zipfile.ZipFile(filename) print 'mimetype:', z.read('mimetype').strip() variables: {'zipfile.ZipFile': ('global', <class 'zipfile.ZipFile'>), 'z': (None, []), 'filename': ('local', u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora')} File "/usr/lib/python2.7/zipfile.py", line 770, __init__(self=<zipfile.ZipFile object>, file=u'/home/maria/Desktop/Drawings/WIPs/Sativa Chibi.ora', mode='r', compression=0, allowZip64=False) if key == 'r': self._RealGetContents() elif key == 'w': variables: {'self._RealGetContents': ('local', <bound method ZipFile._RealGetContents of <zipfile.ZipFile object at 0x7fdb9b952790>>)} File "/usr/lib/python2.7/zipfile.py", line 811, _RealGetContents(self=<zipfile.ZipFile object>) if not endrec: raise BadZipfile, "File is not a zip file" if self.debug > 1: variables: {'BadZipfile': ('global', <class 'zipfile.BadZipfile'>)} BadZipfile: File is not a zip file

    Read the article

  • AngularJS: download pdf file from the server

    - by Bartosz Bialecki
    I want to download a pdf file from the web server using $http. I use this code which works great, my file only is save as a html file, but when I open it it is opened as pdf but in the browser. I tested it on Chrome 36, Firefox 31 and Opera 23. This is my angularjs code (based on this code): UserService.downloadInvoice(hash).success(function (data, status, headers) { var filename, octetStreamMime = "application/octet-stream", contentType; // Get the headers headers = headers(); if (!filename) { filename = headers["x-filename"] || 'invoice.pdf'; } // Determine the content type from the header or default to "application/octet-stream" contentType = headers["content-type"] || octetStreamMime; if (navigator.msSaveBlob) { var blob = new Blob([data], { type: contentType }); navigator.msSaveBlob(blob, filename); } else { var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL; if (urlCreator) { // Try to use a download link var link = document.createElement("a"); if ("download" in link) { // Prepare a blob URL var blob = new Blob([data], { type: contentType }); var url = urlCreator.createObjectURL(blob); $window.saveAs(blob, filename); return; link.setAttribute("href", url); link.setAttribute("download", filename); // Simulate clicking the download link var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); link.dispatchEvent(event); } else { // Prepare a blob URL // Use application/octet-stream when using window.location to force download var blob = new Blob([data], { type: octetStreamMime }); var url = urlCreator.createObjectURL(blob); $window.location = url; } } } }).error(function (response) { $log.debug(response); }); On my server I use Laravel and this is my response: $headers = array( 'Content-Type' => $contentType, 'Content-Length' => strlen($data), 'Content-Disposition' => $contentDisposition ); return Response::make($data, 200, $headers); where $contentType is application/pdf and $contentDisposition is attachment; filename=" . basename($fileName) . '"' $filename - e.g. 59005-57123123.PDF My response headers: Cache-Control:no-cache Connection:Keep-Alive Content-Disposition:attachment; filename="159005-57123123.PDF" Content-Length:249403 Content-Type:application/pdf Date:Mon, 25 Aug 2014 15:56:43 GMT Keep-Alive:timeout=3, max=1 What am I doing wrong?

    Read the article

  • Trouble editing Word document with PHP

    - by bhoomi-nature
    I want to open a word document and edit it I am opening the word document from the server and at that time it's opening with garbage values (perhaps it's not being properly converted to UTF-8). When I delete those garbage values and insert something from a textarea to that file it is going to insert and from then on it opens properly. I would like the document to open with the English words in the document instead of garbage value - it's only the first opening that's broken at present. <? $filename = 'test.doc'; if(isset($_REQUEST['Submit'])){ $somecontent = stripslashes($_POST['somecontent']); // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'w')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened fi<form action="" method="get"></form>le. if (fwrite($handle, $somecontent) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote ($somecontent) to file ($filename) <a href=".$_SERVER['PHP_SELF']."> - Continue - "; fclose($handle); } else { echo "The file $filename is not writable"; } } else { // get contents of a file into a string $handle = fopen($filename, 'r'); $somecontent = fread($handle, filesize($filename)); ?> <h1>Edit file <? echo $filename ;?></h1> <form name="form1" method="post" action=""> <p> <textarea name="somecontent" cols="80" rows="10"><? echo $somecontent ;?></textarea> </p> <p> <input type="submit" name="Submit" value="Submit"> </p> </form> <? fclose($handle); } ?>

    Read the article

  • [PHP] Sanitizing strings to make them URL and filename safe?

    - by Xeoncross
    I am trying to come up with a function that does a good job of sanitizing certain strings so that they are safe to use in the URL (like a post slug) and also safe to use as file names. For example, when someone uploads a file I want to make sure that I remove all dangerous characters from the name. So far I have come up with the following function which I hope solves this problem and also allows foreign UTF-8 data also. /** * Convert a string to the file/URL safe "slug" form * * @param string $string the string to clean * @param bool $is_filename TRUE will allow additional filename characters * @return string */ function sanitize($string = '', $is_filename = FALSE) { // Replace all weird characters with dashes preg_replace('/[^\w\-'. ($is_filename ? '*~_\.' : ''). ']+/u', '-', $string); // Only allow one dash separator at a time (and make string lowercase) return mb_strtolower(preg_replace('/--+/u', '-', $string), 'UTF-8'); } Does anyone have any tricky sample data I can run against this - or know of a better way to safeguard our apps from bad names?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >