Search Results

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

Page 18/160 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • Enumerating all strings in resx

    - by Erik Hesselink
    We would like to enumerate all strings in a resource file in .NET (resx file). We want this to generate a javascript object containing all these key-value pairs. We do this now for satellite assemblies with code like this (this is VB.NET, but any example code is fine): Dim rm As ResourceManager rm = New ResourceManager([resource name], [your assembly]) Dim Rs As ResourceSet Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True) For Each Kvp As DictionaryEntry In Rs [Write out Kvp.Key and Kvp.Value] Next However, we haven't found a way to do this for .resx files yet, sadly. How can we enumerate all localization strings in a resx file? UPDATE: Following Dennis Myren's comment and the ideas from here, I built a ResXResourceManager. Now I can do the same with .resx files as I did with the embedded resources. Here is the code. Note that Microsoft made a needed constructor private, so I use reflection to access it. You need full trust when using this. Imports System.Globalization Imports System.Reflection Imports System.Resources Imports System.Windows.Forms Public Class ResXResourceManager Inherits ResourceManager Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String) Me.New(BaseName, ResourceDir, GetType(ResXResourceSet)) End Sub Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type) Dim BaseType As Type = Me.GetType().BaseType Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing) Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing) End Sub Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String Dim FileName As String FileName = MyBase.GetResourceFileName(culture) If FileName IsNot Nothing AndAlso FileName.Length > 10 Then Return FileName.Substring(0, FileName.Length - 10) & ".resx" End If Return Nothing End Function End Class

    Read the article

  • PHP File Downloading Questions

    - by nsearle
    Hey All! I am currently running into some problems with user's downloading a file stored on my server. I have code set up to auto download a file once the user hits the download button. It is working for all files, but when the size get's larger than 30 MB it is having issues. Is there a limit on user download? Also, I have supplied my example code and am wondering if there is a better practice than using the PHP function 'file_get_contents'. Thank You all for the help! $path = $_SERVER['DOCUMENT_ROOT'] . '../path/to/file/'; $filename = 'filename.zip'; $filesize = filesize($path . $filename); @header("Content-type: application/zip"); @header("Content-Disposition: attachment; filename=$filename"); @header("Content-Length: $filesize") echo file_get_contents($path . $filename);

    Read the article

  • Django Upload form to S3 img and form validation

    - by citadelgrad
    I'm fairly new to both Django and Python. This is my first time using forms and upload files with django. I can get the uploads and saves to the database to work fine but it fails to valid email or check if the users selected a file to upload. I've spent a lot of time reading documentation trying to figure this out. Thanks! views.py def submit_photo(request): if request.method == 'POST': def store_in_s3(filename, content): conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) bucket = conn.create_bucket(AWS_STORAGE_BUCKET_NAME) mime = mimetypes.guess_type(filename)[0] k = Key(bucket) k.key = filename k.set_metadata("Content-Type", mime) k.set_contents_from_file(content) k.set_acl('public-read') if imghdr.what(request.FILES['image_url']): qw = request.FILES['image_url'] filename = qw.name image = filename content = qw.file url = "http://bpd-public.s3.amazonaws.com/" + image data = {image_url : url, user_email : request.POST['user_email'], user_twittername : request.POST['user_twittername'], user_website : request.POST['user_website'], user_desc : request.POST['user_desc']} s = BeerPhotos(data) if s.is_valid(): #import pdb; pdb.set_trace() s.save() store_in_s3(filename, content) return HttpResponseRedirect(reverse('photos.views.thanks')) return s.errors else: return errors else: form = BeerPhotoForm() return render_to_response('photos/submit_photos.html', locals(),context_instance=RequestContext(request) forms.py class BeerPhotoForm(forms.Form): image_url = forms.ImageField(widget=forms.FileInput, required=True,label='Beer',help_text='Select a image of no more than 2MB.') user_email = forms.EmailField(required=True,help_text='Please type a valid e-mail address.') user_twittername = forms.CharField() user_website = forms.URLField(max_length=128,) user_desc = forms.CharField(required=True,widget=forms.Textarea,label='Description',) template.html <div id="stylized" class="myform"> <form action="." method="post" enctype="multipart/form-data" width="450px"> <h1>Photo Submission</h1> {% for field in form %} {{ field.errors }} {{ field.label_tag }} {{ field }} {% endfor %} <label><span>Click here</span></label> <input type="submit" class="greenbutton" value="Submit your Photo" /> </form> </div>

    Read the article

  • rename files with the same name

    - by snorpey
    Hi. I use the following function to rename thumbnails. For example, if I upload a file called "image.png" to an upload folder, and this folder already has a file named "image.png" in it, the new file automatically gets renamed to "image-copy-1.png". If there also is a file called "image-copy-1.png" it gets renamed to "image-copy-2.png" and so on. The following function returns the new filename. At least that's what it is supposed to do... The renaming doesn't seeem to work correctly, though. Sometimes it produces strange results, like: 1.png 1-copy-1.png 1-copy-2.png 1-copy-2-copy-1.png 1-copy-2-copy-3.png I hope you understand my problem, despite my description being somewhat complex... Can you tell me what went wrong here? (bonus question: Is regular expressions the right tool for doing this kind of stuff?) <?php function renameDuplicates($path, $file) { $fileName = pathinfo($path . $file, PATHINFO_FILENAME); $fileExtension = "." . pathinfo($path . $file, PATHINFO_EXTENSION); if(file_exists($path . $file)) { $fileCopy = $fileName . "-copy-1"; if(file_exists($path . $fileCopy . $fileExtension)) { if ($contains = preg_match_all ("/.*?(copy)(-)(\\d+)/is", $fileCopy, $matches)) { $copyIndex = $matches[3][0]; $fileName = substr($fileCopy, 0, -(strlen("-copy-" . $copyIndex))) . "-copy-" . ($copyIndex + 1); } } else { $fileName .= "-copy-1"; } } $returnValue = $fileName . $fileExtension; return $returnValue; }?>

    Read the article

  • AS3: Array of objects parsed from XML remains with zero length

    - by Joel Alejandro
    I'm trying to parse an XML file and create an object array from its data. The data is converted to MediaAlbum classes (class of my own). The XML is parsed correctly and the object is loaded, but when I instantiate it, the Albums array is of zero length, even when the data is loaded correctly. I don't really know what the problem could be... any hints? import Nem.Media.*; var mg:MediaGallery = new MediaGallery("test.xml"); trace(mg.Albums.length); MediaGallery class: package Nem.Media { import flash.net.URLRequest; import flash.net.URLLoader; import flash.events.*; public class MediaGallery { private var jsonGalleryData:Object; public var Albums:Array = new Array(); public function MediaGallery(xmlSource:String) { var loader:URLLoader = new URLLoader(); loader.load(new URLRequest(xmlSource)); loader.addEventListener(Event.COMPLETE, loadGalleries); } public function loadGalleries(e:Event):void { var xmlData:XML = new XML(e.target.data); var album; for each (album in xmlData.albums) { Albums.push(new MediaAlbum(album.attribute("name"), album.photos)); } } } } XML test source: <gallery <albums <album name="Fútbol 9" <photos <photo width="600" height="400" filename="foto1.jpg" / <photo width="600" height="400" filename="foto2.jpg" / <photo width="600" height="400" filename="foto3.jpg" / </photos </album <album name="Fútbol 8" <photos <photo width="600" height="400" filename="foto4.jpg" / <photo width="600" height="400" filename="foto5.jpg" / <photo width="600" height="400" filename="foto6.jpg" / </photos </album </albums </gallery

    Read the article

  • Automatically release resources RAII-style in Perl

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • How to develop JSP/Servlets Web App using MVC pattern?

    - by A.S al-shammari
    I'm developing a JSP/Servlets web app (no frameworks). I want to use MVC pattern. I designed my project like this : Controller :a servlet that reads a request, extracts the values,communicates with model objects and gives information to a JSP page. View : JSP Pages. Model : Java Classes / Java Beans .. etc . The problem : Index.jsp is the starting point (default page) in my web site. So, the Index.jsp becomes the controller to parse the request! .For example , the following request : index.jsp?section=article&id=10 parsed in index.jsp as following : <div class="midcol"> <!-- Which section? --> <%String fileName = request.getParameter("section"); if (fileName == null) { fileName = "WEB-INF/jspf/frontpage.jsp"; } else { fileName = "WEB-INF/jspf/" + fileName + ".jsp"; } %> <jsp:include page='<%= fileName%>' /> </div> Here, I can't force the servlet to be a controller .. because the index.jsp is the controller here since it's the starting point! Is there any solution to forward the request from index.jsp to the servlet and then go back to index.jsp ? Or any solution that achieves the MVC goal - the servlet should be the controller - ? I'm thinking of making a FrontPageController servlet as default page instead of index.jsp ! but I don't know if it's a perfect idea ?!

    Read the article

  • c++ passing unknown type to a function and any Class type definition

    - by user259789
    I am trying to create a generic class to write and read Objects to/from file. Called it ActiveRecord class only has one method, which saves the class itself: void ActiveRecord::saveRecord(){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (this), sizeof(ActiveRecord)); stream.close(); } now I'm extending this class with User class: class User : public ActiveRecord { public: User(void); ~User(void); string name; string lastName; }; to create and save the user I would like to do something like: User user = User(); user.name = "John"; user.lastName = "Smith" user.save(); how can I get this ActiveRecord::saveRecord() method to take any object, and class definition so it writes whatever i send it: to look like: void ActiveRecord::saveRecord(foo_instance, FooClass){ string fileName = "data.dat"; ofstream stream(fileName.c_str(), ios::out); if (!stream) { cerr << "Error opening file: " << fileName << endl; exit(1); } stream.write(reinterpret_cast<const char *> (foo_instance), sizeof(FooClass)); stream.close(); } and while we're at it, what is the default Object type in c++. eg. in objective-c it's id in java it's Object in AS3 it's Object what is it in C++??

    Read the article

  • Excel VBA - export to UTF-8

    - by Tom
    The macro I created works fine, I just need to sort out the saving business. Now I get a popup asking me where to save it, but I would like it to save it under a default name and path AND encoded in UTF-8. This is my full code I use, the bottom part saves the document I presume. Public Sub ExportToTextFile(FName As String, Sep As String, SelectionOnly As Boolean, AppendData As Boolean) Dim WholeLine As String Dim fnum As Integer Dim RowNdx As Long Dim ColNdx As Integer Dim StartRow As Long Dim EndRow As Long Dim StartCol As Integer Dim EndCol As Integer Dim CellValue As String Dim teller As Integer 'Teller aangemaakt ter controle voor het aantal velden 'teller = 1 Application.ScreenUpdating = False On Error GoTo EndMacro: fnum = FreeFile If SelectionOnly = True Then With Selection StartRow = .Cells(1).Row StartCol = .Cells(26).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With Else With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(26).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(26).Column End With End If If AppendData = True Then Open FName For Append Access Write As #fnum Else Open FName For Output Access Write As #fnum End If For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = "" Else CellValue = Cells(RowNdx, ColNdx).Value End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) Print #fnum, WholeLine, "" 'Print #fnum, teller, WholeLine, "" 'teller = teller + 1 Next RowNdx EndMacro: On Error GoTo 0 Application.ScreenUpdating = True Close #fnum End Sub Sub Dump4Mini() Dim FileName As Variant Dim Sep As String FileName = Application.GetSaveAsFilename(InitialFileName:=Blank, filefilter:="Text (*.txt),*.txt") If FileName = False Then Exit Sub End If Sep = "|" If Sep = vbNullString Then Exit Sub End If Debug.Print "FileName: " & FileName, "Separator: " & Sep ExportToTextFile FName:=CStr(FileName), Sep:=CStr(Sep), SelectionOnly:=False, AppendData:=False End Sub

    Read the article

  • How can I automatically release resources RAII-style in Perl?

    - by Philip Potter
    Say I have a resource (e.g. a filehandle or network socket) which has to be freed: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; process($fh); close $fh or die "Couldn't close filename: $!"; Suppose that process might die. Then the code block exits early, and $fh doesn't get closed. I could explicitly check for errors: open my $fh, "<", "filename" or die "Couldn't open filename: $!"; eval {process($fh)}; my $saved_error = $@; close $fh or die "Couldn't close filename: $!"; die $saved_error if $saved_error; but this kind of code is notoriously difficult to get right, and only gets more complicated when you add more resources. In C++ I would use RAII to create an object which owns the resource, and whose destructor would free it. That way, I don't have to remember to free the resource, and resource cleanup happens correctly as soon as the RAII object goes out of scope - even if an exception is thrown. Unfortunately in Perl a DESTROY method is unsuitable for this purpose as there are no guarantees for when it will be called. Is there a Perlish way to ensure resources are automatically freed like this even in the presence of exceptions? Or is explicit error checking the only option?

    Read the article

  • Data Modeling of Entity with Attributes

    - by StackOverflowNewbie
    I'm storing some very basic information "data sources" coming into my application. These data sources can be in the form of a document (e.g. PDF, etc.), audio (e.g. MP3, etc.) or video (e.g. AVI, etc.). Say, for example, I am only interested in the filename of the data source. Thus, I have the following table: DataSource Id (PK) Filename For each data source, I also need to store some of its attributes. Example for a PDF would be "numbe of pages." Example for audio would be "bit rate." Example for video would be "duration." Each DataSource will have different requirements for the attributes that need to be stored. So, I have modeled "data source attribute" this way: DataSourceAttribute Id (PK) DataSourceId (FK) Name Value Thus, I would have records like these: DataSource->Id = 1 DataSource->Filename = 'mydoc.pdf' DataSource->Id = 2 DataSource->Filename = 'mysong.mp3' DataSource->Id = 3 DataSource->Filename = 'myvideo.avi' DataSourceAttribute->Id = 1 DataSourceAttribute->DataSourceId = 1 DataSourceAttribute->Name = 'TotalPages' DataSourceAttribute->Value = '10' DataSourceAttribute->Id = 2 DataSourceAttribute->DataSourceId = 2 DataSourceAttribute->Name = 'BitRate' DataSourceAttribute->Value '16' DataSourceAttribute->Id = 3 DataSourceAttribute->DataSourceId = 3 DataSourceAttribute->Name = 'Duration' DataSourceAttribute->Value = '1:32' My problem is that this doesn't seem to scale. For example, say I need to query for all the PDF documents along with thier total number of pages: Filename, TotalPages 'mydoc.pdf', '10' 'myotherdoc.pdf', '23' ... The JOINs needed to produce the above result is just too costly. How should I address this problem?

    Read the article

  • Multiple calls to preg_replace alters result

    - by Hurpe
    I have a bunch of files that were named in a somewhat standard format. The standard form is basically this: [integer]_word1_word2_word3_ ... _wordn where a word could really be anything, but all words are separated by an underscore. There is really only 3 things I want to do to the text: 1.) I want to modify the integer, which is always at the beginning, so that something like "200" would become $ 200.00. 2.) replace any "words" of the form "with", "With", "w/", or "W/" with "with". 3.) Replace all underscores with a space. I wrote three different preg_replace calls to do the trick. They are as follows: 1.) $filename = preg_replace("/(^[0-9]+)/","$ $1.00",$filename) 2.) $filename = preg_replace("/_([wW]|[wW]ith)_/"," with ",$filename) 3.) $filename = preg_replace("/_/"," ",$filename); Each replacement works as expected when run individually, but when all three are run, the 2nd replacement is ignored. Why would something like that occur? Thanks for the help!

    Read the article

  • How can I modify a scalar reference passed to a subroutine reference

    - by Mark
    I have a function to convert documents into different formats, which then calls another function based on the type document. It's pretty straight forward for everything aside from HTML documents which require a bit of cleaning up, and that cleaning up is different based on where it's come from. So I had the idea that I could pass a reference to a subroutine to the convert function so the caller has the opportunity to modify the HTML, kinda like so (I'm not at work so this isn't copy-and-pasted): package Converter; ... sub convert { my ($self, $filename, $coderef) = @_; if ($filename =~ /html?$/i) { $self->_convert_html($filename, $coderef); } } sub _convert_html { my ($self, $filename, $coderef) = @_; my $html = $self->slurp($filename); $coderef->(\$html); #this modifies the html $self->save_to_file($filename, $html); } which is then called by: Converter->new->convert("./whatever.html", sub { s/<html>/<xml>/i }); I've tried a couple of different things along these lines but I keep on getting 'Use of uninitialized value in substitution (s///)'. Is there any way of doing what I'm trying to do? Thanks

    Read the article

  • php how to serialize array of objects?

    - by hequ
    Hello, I have small class called 'Call' and I need to store these calls into a flat file. I've made another class called 'CallStorage' which contains an array where I put these calls into. My problem is that I would like to store this array to disk so I could later read it back and get the calls from that array. I've tried to achieve this using serialize() and unserialize() but these seems to act somehow strange and part of the information gets lost. This is what I'm doing: //write array to disk $filename = $path . 'calls-' . $today; $serialized = serialize($this->array); $fp = fopen($filename, 'a'); fwrite($fp, $serialized); fclose($fp); //read array from serialized file $filename = $path . 'calls-' . $today; if (file_exists($filename)) { $handle = fopen($filename, 'r'); $contents = fread($handle, filesize($filename)); fclose($handle); $unserialized = unserialize($contents); $this->setArray($unserialized); } Can someone see what I'm doing wrong, or what. I've also tried to serialize and write arrays that contains plain strings. I didn't manage to get that working either.. I have a Java background so I just can't see why I couldn't just write an array to disk if it's serialized. :)

    Read the article

  • Can someone answer this for me?

    - by Dcurvez
    okay I am totally stuck. I have been getting some help off and on throughout this project and am anxious to get this problem solved so I can continue on with the rest of this project. I have a gridview that is set to save to a file, and has the option to import into excel. I keep getting an error of this: Invalid cast exception was unhandled. At least one element in the source array could not be cast down to the destination array type. Can anyone tell me in layman easy to understand what this error is speaking of? This is the code I am trying to use: Dim fileName As String = "" Dim dlgSave As New SaveFileDialog dlgSave.Filter = "Text files (*.txt)|*.txt|CSV Files (*.csv)|*.csv" dlgSave.AddExtension = True dlgSave.DefaultExt = "txt" If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then fileName = dlgSave.FileName SaveToFile(fileName) End If End Sub Private Sub SaveToFile(ByVal fileName As String) If DataGridView1.RowCount > 0 AndAlso DataGridView1.Rows(0).Cells(0) IsNot Nothing Then Dim stream As New System.IO.FileStream(fileName, IO.FileMode.Append, IO.FileAccess.Write) Dim sw As New System.IO.StreamWriter(stream) For Each row As DataGridViewRow In DataGridView1.Rows Dim arrLine(9) As String Dim line As String **row.Cells.CopyTo(arrLine, 0)** line = arrLine(0) line &= ";" & arrLine(1) line &= ";" & arrLine(2) line &= ";" & arrLine(3) line &= ";" & arrLine(4) line &= ";" & arrLine(5) line &= ";" & arrLine(6) line &= ";" & arrLine(7) line &= ";" & arrLine(8) sw.WriteLine(line) Next sw.Flush() sw.Close() End If I bolded the line where it shows in debug, and I really dont see what all the fuss is about LOL

    Read the article

  • FileInput Help/Advice

    - by user559142
    I have a fileinput class. It has a string parameter in the constructor to load the filename supplied. However it just exits if the file doesn't exist. I would like it to output a message if the file doesn't exist - but not sure how.... Here is the class: public class FileInput extends Input { /** * Construct <code>FileInput</code> object given a file name. */ public FileInput(final String fileName) { try { scanner = new Scanner(new FileInputStream(fileName)); } catch (FileNotFoundException e) { System.err.println("File " + fileName + " could not be found."); System.exit(1); } } /** * Construct <code>FileInput</code> object given a file name. */ public FileInput(final FileInputStream fileStream) { super(fileStream); } } And its implementation: private void loadFamilyTree() { out.print("Enter file name: "); String fileName = in.nextLine(); FileInput input = new FileInput(fileName); family.load(input); input.close(); }

    Read the article

  • I need to take the first three letters of a filename and set it into a text file, in a certain fashion. How can I do this?

    - by JuniorD
    Okay, so I need to take the first three letters of a file from a list of files, and place this into a text file in a certain manner. I will provide examples below. Lets say that I have two file names in the same directory, one called cougar.txt and the other bear.txt. These are in the animals directory. I need to take the first three letters of these words, and transpose them into a text file along with the directory, in the following format: BEA = "animals/bear.txt" COU = "animals/cougar.txt" This should happen with any random thing that might be in the list. I'm fairly new to this sort of coding, so I'm not quite sure which language to use, and I'm learning as I go. This new challenge seems fairly daunting to me, and I would be much appreciated if you guys could help. Also, I'm using Windows 7. Been attempting at this all day, to no avail. Preferably done in batch, but if that is impossible I'm open to recommendations.

    Read the article

  • Threading across multiple files

    - by Zach M.
    My program is reading in files and using thread to compute the highest prime number, when I put a print statement into the getNum() function my numbers are printing out. However, it seems to just lag no matter how many threads I input. Each file has 1 million integers in it. Does anyone see something apparently wrong with my code? Basically the code is giving each thread 1000 integers to check before assigning a new thread. I am still a C noobie and am just learning the ropes of threading. My code is a mess right now because I have been switching things around constantly. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <pthread.h> #include <math.h> #include <semaphore.h> //Global variable declaration char *file1 = "primes1.txt"; char *file2 = "primes2.txt"; char *file3 = "primes3.txt"; char *file4 = "primes4.txt"; char *file5 = "primes5.txt"; char *file6 = "primes6.txt"; char *file7 = "primes7.txt"; char *file8 = "primes8.txt"; char *file9 = "primes9.txt"; char *file10 = "primes10.txt"; char **fn; //file name variable int numberOfThreads; int *highestPrime = NULL; int fileArrayNum = 0; int loop = 0; int currentFile = 0; sem_t semAccess; sem_t semAssign; int prime(int n)//check for prime number, return 1 for prime 0 for nonprime { int i; for(i = 2; i <= sqrt(n); i++) if(n % i == 0) return(0); return(1); } int getNum(FILE* file) { int number; char* tempS = malloc(20 *sizeof(char)); fgets(tempS, 20, file); tempS[strlen(tempS)-1] = '\0'; number = atoi(tempS); free(tempS);//free memory for later call return(number); } void* findPrimality(void *threadnum) //main thread function to find primes { int tNum = (int)threadnum; int checkNum; char *inUseFile = NULL; int x=1; FILE* file; while(currentFile < 10){ if(inUseFile == NULL){//inUseFIle being used to check if a file is still being read sem_wait(&semAccess);//critical section inUseFile = fn[currentFile]; sem_post(&semAssign); file = fopen(inUseFile, "r"); while(!feof(file)){ if(x % 1000 == 0 && tNum !=1){ //go for 1000 integers and then wait sem_wait(&semAssign); } checkNum = getNum(file); /* * * * * I think the issue is here * * * */ if(checkNum > highestPrime[tNum]){ if(prime(checkNum)){ highestPrime[tNum] = checkNum; } } x++; } fclose(file); inUseFile = NULL; } currentFile++; } } int main(int argc, char* argv[]) { if(argc != 2){ //checks for number of arguements being passed printf("To many ARGS\n"); return(-1); } else{//Sets thread cound to user input checking for correct number of threads numberOfThreads = atoi(argv[1]); if(numberOfThreads < 1 || numberOfThreads > 10){ printf("To many threads entered\n"); return(-1); } time_t preTime, postTime; //creating time variables int i; fn = malloc(10 * sizeof(char*)); //create file array and initialize fn[0] = file1; fn[1] = file2; fn[2] = file3; fn[3] = file4; fn[4] = file5; fn[5] = file6; fn[6] = file7; fn[7] = file8; fn[8] = file9; fn[9] = file10; sem_init(&semAccess, 0, 1); //initialize semaphores sem_init(&semAssign, 0, numberOfThreads); highestPrime = malloc(numberOfThreads * sizeof(int)); //create an array to store each threads highest number for(loop = 0; loop < numberOfThreads; loop++){//set initial values to 0 highestPrime[loop] = 0; } pthread_t calculationThread[numberOfThreads]; //thread to do the work preTime = time(NULL); //start the clock for(i = 0; i < numberOfThreads; i++){ pthread_create(&calculationThread[i], NULL, findPrimality, (void *)i); } for(i = 0; i < numberOfThreads; i++){ pthread_join(calculationThread[i], NULL); } for(i = 0; i < numberOfThreads; i++){ printf("this is a prime number: %d \n", highestPrime[i]); } postTime= time(NULL); printf("Wall time: %ld seconds\n", (long)(postTime - preTime)); } } Yes I am trying to find the highest number over all. So I have made some head way the last few hours, rescucturing the program as spudd said, currently I am getting a segmentation fault due to my use of structures, I am trying to save the largest individual primes in the struct while giving them the right indices. This is the revised code. So in short what the first thread is doing is creating all the threads and giving them access points to a very large integer array which they will go through and find prime numbers, I want to implement semaphores around the while loop so that while they are executing every 2000 lines or the end they update a global prime number. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <pthread.h> #include <math.h> #include <semaphore.h> //Global variable declaration char *file1 = "primes1.txt"; char *file2 = "primes2.txt"; char *file3 = "primes3.txt"; char *file4 = "primes4.txt"; char *file5 = "primes5.txt"; char *file6 = "primes6.txt"; char *file7 = "primes7.txt"; char *file8 = "primes8.txt"; char *file9 = "primes9.txt"; char *file10 = "primes10.txt"; int numberOfThreads; int entries[10000000]; int entryIndex = 0; int fileCount = 0; char** fileName; int largestPrimeNumber = 0; //Register functions int prime(int n); int getNum(FILE* file); void* findPrimality(void *threadNum); void* assign(void *num); typedef struct package{ int largestPrime; int startingIndex; int numberCount; }pack; //Beging main code block int main(int argc, char* argv[]) { if(argc != 2){ //checks for number of arguements being passed printf("To many threads!!\n"); return(-1); } else{ //Sets thread cound to user input checking for correct number of threads numberOfThreads = atoi(argv[1]); if(numberOfThreads < 1 || numberOfThreads > 10){ printf("To many threads entered\n"); return(-1); } int threadPointer[numberOfThreads]; //Pointer array to point to entries time_t preTime, postTime; //creating time variables int i; fileName = malloc(10 * sizeof(char*)); //create file array and initialize fileName[0] = file1; fileName[1] = file2; fileName[2] = file3; fileName[3] = file4; fileName[4] = file5; fileName[5] = file6; fileName[6] = file7; fileName[7] = file8; fileName[8] = file9; fileName[9] = file10; FILE* filereader; int currentNum; for(i = 0; i < 10; i++){ filereader = fopen(fileName[i], "r"); while(!feof(filereader)){ char* tempString = malloc(20 *sizeof(char)); fgets(tempString, 20, filereader); tempString[strlen(tempString)-1] = '\0'; entries[entryIndex] = atoi(tempString); entryIndex++; free(tempString); } } //sem_init(&semAccess, 0, 1); //initialize semaphores //sem_init(&semAssign, 0, numberOfThreads); time_t tPre, tPost; pthread_t coordinate; tPre = time(NULL); pthread_create(&coordinate, NULL, assign, (void**)numberOfThreads); pthread_join(coordinate, NULL); tPost = time(NULL); } } void* findPrime(void* pack_array) { pack* currentPack= pack_array; int lp = currentPack->largestPrime; int si = currentPack->startingIndex; int nc = currentPack->numberCount; int i; int j = 0; for(i = si; i < nc; i++){ while(j < 2000 || i == (nc-1)){ if(prime(entries[i])){ if(entries[i] > lp) lp = entries[i]; } j++; } } return (void*)currentPack; } void* assign(void* num) { int y = (int)num; int i; int count = 10000000/y; int finalCount = count + (10000000%y); int sIndex = 0; pack pack_array[(int)num]; pthread_t workers[numberOfThreads]; //thread to do the workers for(i = 0; i < y; i++){ if(i == (y-1)){ pack_array[i].largestPrime = 0; pack_array[i].startingIndex = sIndex; pack_array[i].numberCount = finalCount; } pack_array[i].largestPrime = 0; pack_array[i].startingIndex = sIndex; pack_array[i].numberCount = count; pthread_create(&workers[i], NULL, findPrime, (void *)&pack_array[i]); sIndex += count; } for(i = 0; i< y; i++) pthread_join(workers[i], NULL); } //Functions int prime(int n)//check for prime number, return 1 for prime 0 for nonprime { int i; for(i = 2; i <= sqrt(n); i++) if(n % i == 0) return(0); return(1); }

    Read the article

  • How to use GWT when downloading Files with a Servlet?

    - by molleman
    Hello Guys I am creating a simple project that will allow me to upload and download files using gwt. i am having trouble with the downloading of files that are on my server. For the file upload i used http://code.google.com/p/gwtupload/ and followed the instructions there. My file is stored on the server outside of the website container(on the hard drive), Now when it comes to the downloading of a file, i want a user to press a download button and whatever item is currently selected will download. i dont really know how this will be done i know i need a download servlet public class DownloadAttachmentServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String fileName = (String) req.getSession().getAttribute("fileName"); YFUser user = (YFUser) req.getSession().getAttribute(TestServiceImpl.SESSION_USER); if (user == null) throw new ServletException("Invalid Session"); InputStream in = null; OutputStream out = resp.getOutputStream(); FileInputStream fIn = new FileInputStream(fileName); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.flush(); } } for the moment i will just pass a fileName string to retrieve the file for testing now i am lost at what to do on the client side, i have a simple public class DownloadFilePanel extends Composite { public DownloadFilePanel(final YFUser user , final String fileName){ final Element downloadIframe = RootPanel.get("__download").getElement(); VerticalPanel content = new VerticalPanel(); content.add(new Label("Download For this File : " + fileName)); Button button = new Button("Download"); button.addClickHandler(new ClickHandler(){ @Override public void onClick(ClickEvent event) { // i do not know what to do here }); content.add(button); initWidget(content); } } above is a simple widget that will supply a panel that will allow for the download of a file based on a fileName as you can see above, i do not know what to do to be able to download the file is there any one that can point me in the right direction?

    Read the article

  • Squid proxy not serving modified html content

    - by Matthew
    I'm trying to use squid to modify the page content of web page requests. I followed the upside-down-ternet tutorial which showed instructions for how to flip images on pages. I need to change the actual html of the page. I've been trying to do the same thing as in the tutorial, but instead of editing the image I'm trying to edit the html page. Below is a php script I'm using to try to do it. All jpg images get flipped, but the content on the page does not get edited. The edited index.html files written contain the edited content, but the pages the users receive don't contain the edited content. #!/usr/bin/php <?php $temp = array(); while ( $input = fgets(STDIN) ) { $micro_time = microtime(); // Split the output (space delimited) from squid into an array. $temp = split(' ', $input); //Flip jpg images, this works correctly if (preg_match("/.*\.jpg/i", $temp[0])) { system("/usr/bin/wget -q -O /var/www/cache/$micro_time.jpg ". $temp[0]); system("/usr/bin/mogrify -flip /var/www/cache/$micro_time.jpg"); echo "http://127.0.0.1/cache/$micro_time.jpg\n"; } //Don't edit files that are obviously not html. $temp[0] contains url of file to get elseif (preg_match("/(jpg|png|gif|css|js|\(|\))/i", $temp[0], $matches)) { echo $input; } //Otherwise, could be html (e.g. `wget http://www.google.com` downloads index.html) else{ $time = time() . microtime(); //For unique directory names $time = preg_replace("/ /", "", $time); //Simplify things by removing the spaces mkdir("/var/www/cache/". $time); //Create unique folder system("/usr/bin/wget -q --directory-prefix=\"/var/www/cache/$time/\" ". $temp[0]); $filename = system("ls /var/www/cache/$time/"); //Get filename of downloaded file //File is html, edit the content (this does not work) if(preg_match("/.*\.html/", $filename)){ //Get the html file contents $contentfh = fopen("/var/www/cache/$time/". $filename, 'r'); $content = fread($contentfh, filesize("/var/www/cache/$time/". $filename)); fclose($contentfh); //Edit the html file contents $content = preg_replace("/<\/body>/i", "<!-- content served by proxy --></body>", $content); //Write the edited file $contentfh = fopen("/var/www/cache/$time/". $filename, 'w'); fwrite($contentfh, $content); fclose($contentfh); //Return the edited page echo "http://127.0.0.1/cache/$time/$filename\n"; } //Otherwise file is not html, don't edit else{ echo $input; } } } ?>

    Read the article

  • Difficulty getting Saxon into XQuery mode instead of XSLT

    - by Rosarch
    I'm having difficulty getting XQuery to work. I downloaded Saxon-HE 9.2. It seems to only want to work with XSLT. When I type: java -jar saxon9he.jar I get back usage information for XSLT. When I use the command syntax for XQuery, it doesn't recognize the parameters (like -q), and gives XSLT usage information. Here are some command line interactions: >java -jar saxon9he.jar No source file name Saxon-HE 9.2.0.6J from Saxonica Usage: see http://www.saxonica.com/documentation/using-xsl/commandline.html Options: -a Use xml-stylesheet PI, not -xsl argument -c:filename Use compiled stylesheet from file -config:filename Use configuration file -cr:classname Use collection URI resolver class -dtd:on|off Validate using DTD -expand:on|off Expand defaults defined in schema/DTD -explain[:filename] Display compiled expression tree -ext:on|off Allow|Disallow external Java functions -im:modename Initial mode -ief:class;class;... List of integrated extension functions -it:template Initial template -l:on|off Line numbering for source document -m:classname Use message receiver class -now:dateTime Set currentDateTime -o:filename Output file or directory -opt:0..10 Set optimization level (0=none, 10=max) -or:classname Use OutputURIResolver class -outval:recover|fatal Handling of validation errors on result document -p:on|off Recognize URI query parameters -r:classname Use URIResolver class -repeat:N Repeat N times for performance measurement -s:filename Initial source document -sa Use schema-aware processing -strip:all|none|ignorable Strip whitespace text nodes -t Display version and timing information -T[:classname] Use TraceListener class -TJ Trace calls to external Java functions -tree:tiny|linked Select tree model -traceout:file|#null Destination for fn:trace() output -u Names are URLs not filenames -val:strict|lax Validate using schema -versionmsg:on|off Warn when using XSLT 1.0 stylesheet -warnings:silent|recover|fatal Handling of recoverable errors -x:classname Use specified SAX parser for source file -xi:on|off Expand XInclude on all documents -xmlversion:1.0|1.1 Version of XML to be handled -xsd:file;file.. Additional schema documents to be loaded -xsdversion:1.0|1.1 Version of XML Schema to be used -xsiloc:on|off Take note of xsi:schemaLocation -xsl:filename Stylesheet file -y:classname Use specified SAX parser for stylesheet --feature:value Set configuration feature (see FeatureKeys) -? Display this message param=value Set stylesheet string parameter +param=filename Set stylesheet document parameter ?param=expression Set stylesheet parameter using XPath !option=value Set serialization option >java -jar saxon9he.jar -q:"..\w3xQueryTut.xq" Unknown option -q:..\w3xQueryTut.xq Saxon-HE 9.2.0.6J from Saxonica Usage: see http://www.saxonica.com/documentation/using-xsl/commandline.html Options: -a Use xml-stylesheet PI, not -xsl argument // etc... >java net.sf.saxon.Query -q:"..\w3xQueryTut.xq" Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/saxon/Query Caused by: java.lang.ClassNotFoundException: net.sf.saxon.Query // etc... Could not find the main class: net.sf.saxon.Query. Program will exit. I'm probably making some stupid mistake. Do you know what it could be?

    Read the article

  • Problem with displaying and downloading email attachments using the zend framework

    - by Ali
    Hi guys I'm trying to display emails in my inbox and their respective attachments. At the same time I also wish to be able to download the attachments however I'm kinda stuck here. Here is the code I use to display the attachments: $one_message = $mail->getMessage($i); $one_message->id = $i; $one_message->UID = $mail->getUniqueId($i); // get the contact of this message $email = array_pop(extract_emails_from($one_message->from)); $one_message->contactFrom = $contact_manager->get_person_from_email($email); $one_message->parts = array(); foreach (new RecursiveIteratorIterator($mail->getMessage($i)) as $ii=>$part) { try { $tpart = $part; $one_message->parts[$ii] = $tpart; // put the part of the message indexed with what I assume is its position if (strtok($part->contentType, ';') == 'text/html') { $b = $part->getContent(); $h2t->set_html($b); $one_message->body = $h2t->get_text(); } if (strtok($part->contentType, ';') == 'text/plain') { $b = $part->getContent(); $one_message->body = $part->getContent(); } } catch (Zend_Mail_Exception $e) { // ignore } } And I display the attachments using the following link: ?action=download&element=email-attachment&box=inbox&uid=<?php echo $one_message->UID;?>&id=<?php echo $one_message->id;?>&part=<?php echo $ii;?> The part variable is the index taken from the loop above However when I try to download using the exact same code as above modified slightly: $id = $_GET['id']; $pid = $_GET['part']; $one_message = $mail->getMessage($id); foreach (new RecursiveIteratorIterator($mail->getMessage($id)) as $ii=>$part) { if($pid == $ii): $content = base64_decode($part->getContent()); $cnt_typ = explode(";" , $part->contentType); $name = explode("=",$cnt_typ[1]); $filename = $name[1];//It is the file name of the attachement in browser //This for avoiding " from the file name when sent from yahoomail $filename = str_replace('"'," ",$filename); $filename = trim($filename); header("Cache-Control: public"); header("Content-Type: ".$cn_typ[1]); header("Content-Disposition: attachment; filename=\"" . $filename . "\""); header("Content-Transfer-Encoding: binary"); echo $content; exit; endif; } For some reason it doesn't work at all. I did a var dump and noticed that in the for loop with the reverseiterator teh indexes $ii returned are 1 - 2 - 2 !! Whats going on here how can the indexes be repeated? How can I tell one part from the others?

    Read the article

  • Trying to output variables into repeater

    - by Phil
    I have a downloads box which attaches to the bottom of the page and gives the user file downloads (icon, filesize, description) like this; <asp:Repeater ID="DownloadsRepeater" runat="server"> <HeaderTemplate> <table width="70%"> <tr> <td colspan="3"><h2>Files you can download:</h2></td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td width="10%"> <a href="/documents/<%=Session("folder")%>/<%=filename%>"> <img src="images/<%=filename%>" border="0" alt="<%=filename%>" /></a> </td> <td width="25%"><% =filesize%></td> <td><a href="/documents/<%=Session("folder")%>/<%=filename%>"><%=description%></a></td> </tr> </table> </ItemTemplate> </asp:Repeater> Then I have code in my code behind to get the data etc like this; s = "select documents.filename, documents.description, documents.filesize from documents, contentdocuments, content where contentdocuments.contentid = content.id and content.id = @contentid and contentdocuments.documentsid = documents.id ORDER BY documents.description" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", SqlDbType.Int) x.Parameters("@contentid").Value = contentid c.Open() r = x.ExecuteReader While r.Read If r.HasRows Then filename = getimage(r("filename")) If r("filesize") > String.Empty Then filesize = (r("filesize") / 1000) & "kb" End If description = r("description") End If DownloadsRepeater.DataSource = r DownloadsRepeater.DataBind() End While The desired result is that the user sees a file download icon, the filesize and the description. with the icon and the description being linked to the file. Can someone point out where I am going wrong and possibly post a sample of correct syntax for achieving this. Thanks!

    Read the article

  • .NET C# Filestream writing to file and reading the bfile

    - by pythonrg7
    I have a web service that checks a dictionary to see if a file exists and then if it does exist it reads the file, otherwise it saves to the file. This is from a web app. I wonder what is the best way to do this because I occasionally get a FileNotFoundException exception if the same file is accessed at the same time. Here's the relevant parts of the code: String signature; signature = "FILE," + value1 + "," + value2 + "," + value3 + "," + value4; // this is going to be the filename string result; MultipleRecordset mrSummary = new MultipleRecordset(); // MultipleRecordset is an object that retrieves data from a sql server database if (mrSummary.existsFile(signature)) { result = mrSummary.retrieveFile(signature); } else { result = mrSummary.getMultipleRecordsets(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString.ToString(), value1, value2, value3, value4); mrSummary.saveFile(signature, result); } Here's the code to see if the file already exists: private static Dictionary dict = new Dictionary(); public bool existsFile(string signature) { if (dict.ContainsKey(signature)) { return true; } else { return false; } } Here's what I use to retrieve if it already exists: try { byte[] buffer; FileStream fileStream = new FileStream(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename, FileMode.Open, FileAccess.Read, FileShare.Read); try { int length = 0x8000; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read JSONstring = ""; while ((count = fileStream.Read(buffer, 0, length)) > 0) { JSONstring += System.Text.ASCIIEncoding.ASCII.GetString(buffer, 0, count); } } finally { fileStream.Close(); } } catch (Exception e) { JSONstring = "{\"error\":\"" + e.ToString() + "\"}"; } If the file doesn't previously exist it saves the JSON to the file: try { if (dict.ContainsKey(filename) == false) { dict.Add(filename, true); } else { this.retrieveFile(filename, ipaddress); } } catch { } try { TextWriter tw = new StreamWriter(@System.Configuration.ConfigurationManager.AppSettings["CACHEPATH"] + filename); tw.WriteLine(JSONstring); tw.Close(); } catch { } Here are the details to the exception I sometimes get from running the above code: System.IO.FileNotFoundException: Could not find file 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75'. File name: 'E:\inetpub\wwwroot\cache\FILE,36,36.25,14.5,14.75' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at com.myname.business.MultipleRecordset.retrieveFile(String filename, String ipaddress)

    Read the article

  • Php miniserver downloader bandwidth

    - by snikolov
    $httpsock = @socket_create_listen("9090"); if (!$httpsock) { print "Socket creation failed!\n"; exit; } while (1) { $client = socket_accept($httpsock); $input = trim(socket_read ($client, 4096)); $input = explode(" ", $input); $input = $input[1]; $fileinfo = pathinfo($input); switch ($fileinfo['extension']) { default: $mime = "text/html"; } if ($input == "/") { $input = "index.html"; } $input = ".$input"; if (file_exists($input) && is_readable($input)) { echo "Serving $input\n"; $contents = file_get_contents($input); $output = "HTTP/1.0 200 OK\r\nServer: APatchyServer\r\nConnection: close\r\nContent-Type: $mime\r\n\r\n$contents"; } else { //$contents = "The file you requested doesn't exist. Sorry!"; //$output = "HTTP/1.0 404 OBJECT NOT FOUND\r\nServer: BabyHTTP\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n$contents"; $filename = "dada"; $file = fopen($filename, 'r'); $filesize = filesize($filename); $buffer = fread($file, $filesize); $send = array("Output"=$buffer,"filesize"=$filesize,"filename"=$filename); $file = $send['filename']; $filesize = $send['filesize']; $output = 'HTTP/1.0 200 OK\r\n'; $output .= "Content-type: application/octet-stream\r\n"; $output .= 'Content-Disposition: attachment; filename="'.$file.'"\r\n'; $output .= "Content-Length:$filesize\r\n"; $output .= "Accept-Ranges: bytes\r\n"; $output .= "Cache-Control: private\n\n"; $output .= $send['Output']; $output .= "Content-Transfer-Encoding: binary"; $output .= "Connection: Keep-Alive\r\n"; } socket_write($client, $output); socket_close ($client); } socket_close ($httpsock); Hello i have create a code here to work as a webserver downloader the client can request files and download, i got it working at last however, i would like to know if the webserver can show much bandwidth the user request via sockets, perl has the same option as php but its more hardcore than php, i dont understand much about perl, i even saw that a miniwebserver can show much the client user pulls from the server would it be possible that you can assist me with this coding, i much aprreciate it thank you guys.

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >