w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How do I enumerate through a directory in Objective-C, and essentially clear out all the directories of non-directory files?
Something like this will work: NSURL *rootURL = ... // File URL of the root directory you need NSFileManager *fm = [NSFileManager defaultManager]; NSDirectoryEnumerator *dirEnumerator = [fm enumeratorAtURL:rootURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles errorHandler:nil]; for (NSURL *url in dirEnumerator) { NSNumber *isDirectory; [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; if (![isDirectory boolValue]) { // This is a file - remove it [fm removeItemAtURL:url error:NULL]; } }

Categories : Objective C

I'm trying to compress some files from one directory to another but I'm getting access denied on one of the directories why?
It doesn't work because you pass a directory name for the second parameter to CompressDirectory. You should pass a file name like.... string output = Path.Combine(zippedFileDirectory, "MyZipFile.7z"); ..... compressor.CompressDirectory(source, output);

Categories : C#

How to access a file in a directory from other directory, when both are in same parent directory with HTML
if dir1 and dir2 are in the same parent directory then this is how you access 2.html from 1.html: <a href="../dir2/2.html">link to 2.html</a> hope it helped :)

Categories : HTML

Copy files from source directory to target directory and exclude specific file types from specified directories
This is one way to do it $SourceDirectory = 'C:Source' $DestinationDirectory = 'C:Destination' $ExcludeExtentions = '*.txt*', '*.xml*' $ExcludeSubDirectory = 'C:Sourcead_directory1', 'C:Sourcead_directory2' Get-ChildItem $SourceDirectory -Recurse -Exclude $ExcludeExtentions | Where-Object { $ExcludeSubDirectory -notcontains $_.DirectoryName } | Copy-Item -Destination $DestinationDirectory Your best friend here is Where-Object, or where. It takes a scriptblock as parameter and uses that scriptblock to validate each object that goes through pipeline. Only objects that make script return $true are passed through Where-Object. Also, take a look at the object that represents a file you get from Get-ChildItem. It has Name, Directory and DirectoryName containing pieces of file's FullNam

Categories : File

Python joining current directory and parent directory with os.path.join
You can use normpath, realpath or abspath: import os goal_dir = os.path.join(os.getcwd(), "../../my_dir") print goal_dir # prints C:/here/I/am/../../my_dir print os.path.normpath(goal_dir) # prints C:/here/my_dir print os.path.realpath(goal_dir) # prints C:/here/my_dir print os.path.abspath(goal_dir) # prints C:/here/my_dir

Categories : Python

Gracefully reloading gunicorn after switching the current symlink to a new directory
I got this working by using the USR2 signal. This is my init.d file, and after a deploy I'll just run service gunicorn start_or_reload which either starts or gracefully reloads the code based on the new location. It technically spawns another master inside the current master, then kills off the old workers and master and finally promotes the newly spawned master. I went with this solution to later add smoke tests before killing off the old master and things like that. I hope this helps someone! #!/bin/sh ### BEGIN INIT INFO # Provides: thin # Required-Start: $local_fs $remote_fs # Required-Stop: $local_fs $remote_fs # Default-Start: 2 3 4 5 # Default-Stop: S 0 1 6 # Short-Description: thin initscript # Description: thin ### END INIT INFO # Original author:

Categories : Python

How to print the name of my current directory's parent directory
You can use ${PWD%/*}: $ echo $PWD /home/me/test/t $ echo ${PWD%/*} /home/me/test As the expression ${string%substring} Strips shortest match of $substring from back of $string (reference).

Categories : Shell

Symlink directory tree to one directory
This should do it: cd Directory; find * -type f -print0 | xargs -l -0 bash -c 'filename=`echo "$0" | tr '/' -`; ln -s $(pwd)/$0 ../DirectoryDest/$filename' This will result in these files: user@machine:~$ ls -l DirectoryDest/ total 0 lrwxrwxrwx 1 user user 51 Jul 27 23:02 DirectoryA-DirectoryAA-FileAA1 -> /home/user/Directory/DirectoryA/DirectoryAA/FileAA1 lrwxrwxrwx 1 user user 51 Jul 27 23:02 DirectoryA-DirectoryAA-FileAA2 -> /home/user/Directory/DirectoryA/DirectoryAA/FileAA2 lrwxrwxrwx 1 user user 38 Jul 27 23:02 DirectoryA-FileA1 -> /home/user/Directory/DirectoryA/FileA1 lrwxrwxrwx 1 user user 38 Jul 27 23:02 DirectoryA-FileA2 -> /home/user/Directory/DirectoryA/FileA2 lrwxrwxrwx 1 user user 38 Jul 27 23:02 DirectoryB-FileB1 -> /home/user/Directory/DirectoryB/FileB1

Categories : Linux

Does fsync of a parent directory guarantee synchronization of meta data of all recursive sub directories?
When fsync is called on a directory the operation treats its target more like a file than a container of files. From the file system's perspective a directory is a special kind of file that just happens to contain metadata about other files. When fsync is applied to a directory, this metadata about the contained files is synchronized but not the subdirectories/files themselves. If you want to ensure that all of the contents are properly synchronized, then you should fsync them explicitly.

Categories : Android

How can I list files and directories with them directory levels
I think you can use file path as key and level number as value using dictionary. and parse the file path string to calculate level number, use string.split string[] words = s.Split('\');

Categories : C#

Batch Command to Move Files from Sub Directories to New Directory
Try using For /F "TOKENS=1 DELIMS=%_TabSpace%" %%B In ('dir %1 /a-d /S /B /OD') DO ( the /s will cause recursion. The downside is that the output of the dir command is then d:pathfile.ext - which may not marry well with your "TOKENS=1 DELIMS=%_TabSpace%". You'd probably need to use "delims=" (ie, no delimiters, hence entire line in token1). You can then retrieve the various parts of the full-filename as %%~dB, %%~pB, %%~nB and %%~xB (the drive, path, naem and extension - and you can combine these parts if you wish by using %%~nxB for name+extension, for instance. Supplemental info - batch commented. @ECHO OFF SETLOCAL :: The above two lines are a traditional batch introduction. :: The first turns `ECHO`ing of the command to the console OFF :: The second makes all changes to the en

Categories : Windows

How to output CSS files to single directory from several input directories?
Consider creating a sass directory with dummy files for each of your components: project/ css/ foo.css bar.css baz.css modules/ foo/ foo.scss bar/ bar.scss baz/ baz.scss sass/ foo.scss bar.scss baz.scss Each dummy file should import the corresponding component. sass/foo.scss: @import "../modules/foo/foo.scss"; When you have all dummy files set up, run sass --update sass:css from the root of your project.

Categories : CSS

Replace multiple files in sub directories with file from a different directory
try this: cd /d "C:Users----DocumentsTrainRuns" FOR /D /R %%a IN (*) do if exist "%%~a est1.hfl" echo copy /y "test1.hfl" "%%~a" Look at the output and remove the word echo if it looks good. Accepting an answer - how does it work?

Categories : Windows

PHP FILES Recursive backup of directories, deleting main directory
As shown from your function-output, the directories are not empty. I suppose that the data is of low value and just needs to be backed up. I assume you are running Linux from your choice of a slash rather than a backslash. Naturally directories incur links or inodes, with metadata, which in linux can be checked via df -hi The Inode-Ids of files can be shown via the -i flag of ls ls -i filename ls -iltr ls -ltri `echo $HOME` Inodes take up space, and introduce overhead in file-system operations. So much to the motivation to remove the directories. PHP's rmdir function to remove directories requires that The directory must be empty, and the relevant permissions must permit this. It is also non-recursive. Approach 1: flatten filenames and move the files to a backup directory, t

Categories : PHP

searching for values stored in an arraylist through all the files within a directory and its sub directories
List all the files in a directory. `public void listFilesAndFilesSubDirectories(String directoryName){ File directory = new File(directoryName); //get all the files from a directory File[] fList = directory.listFiles(); for (File file : fList){ if (file.isFile()){ System.out.println(file.getAbsolutePath()); } else if (file.isDirectory()){ listFilesAndFilesSubDirectories(file.getAbsolutePath()); } } }` Now loop through your list of files reading each one. Now iterate the list containing the words, check with each word. If you find the word, add the file name in another list. See to that you iterate the file in the outer loop and the word inside the file loop.

Categories : Java

How to change the current working directory to a specific directory and execute a program under the specific directory?
One of your principal problems is that you don't capture the return value (output) of the command in backticks. You are merely throwing away the output you want. Do something like: my $output = `perl ./script.pl` system("perl ./script.pl")

Categories : Perl

jQuery/JS: Get current URL parent directory
Fiddle var a = "http://www.site.com/example/index.html"; var b = a.substring(0, a.lastIndexOf('/'))+"/";

Categories : Javascript

How can I manage Linux settings (config) files in different directories in a single Git repo in another directory?
You can use symlinks. It is indeed what dotfiles managers such as homesick do. It is helpful to have a script to generate all the links automatically for you, in case you want to clone your setup to another box.

Categories : Linux

After I deleted a directory, it always prompts "shell-init error retrieving current directory getcwd solve" when log on bash
When opening a new shell or xterm, it's started in the working directory of the process that started it. If you e.g. cd /proc && xterm, the new terminal will place you in /proc. Whatever's starting your terminal had positioned itself in /home/desktop/zeno, and now all the terminals are trying to start there. If you make that process change directory (by rebooting, for example), the terminals will start in a directory that exists and you will no longer get this error.

Categories : Linux

How to get current user's default movie directory and other default directories?
If you just want to get access to common directories like Documents, Desktop, Movies, etc., -[NSFileManager URLsForDirectory:inDomains:] is the API you're looking for. You'll want to use the NSUserDomainMask for the domains parameter and one of the NSSearchPathDirectory constants (like NSMoviesDirectory) for the directory parameter. If you're actually trying to get the list of folders the current user has in the "Favorites" section of their Finder sidebar (users can customize this list), this Stack Overflow question may have some answers for you.

Categories : Osx

Zip together all HTML files under current directory
What about this? find /your/path/ -type f -name "*.html" | xargs zip all_html_files.zip looks for all .html files under the directory /your/path (change it for yours). Then, pipes the result to xargs, which creates the zip file. Edit To junk the paths, add -j option: find /your/path/ -type f -name "*.html" | xargs zip -j all_html_files.zip

Categories : Linux

How do I make FindFirst look for files in the current directory?
The path '*.*' is relative to the root directory of the drive of the current working directory. You probably mean to pass GetCurrentDir + '*' to FindFirst. Or even better, TPath.Combine(GetCurrentDir, '*'). For example, this program demonstrates that you code works correctly provided that you pass an appropriate path to FindFirst. program FindFirstDemo; {$APPTYPE CONSOLE} uses SysUtils, IOUtils; var SR: TSearchRec; begin Writeln(GetCurrentDir); if FindFirst(TPath.Combine(GetCurrentDir, '*'),faAnyFile,SR)=0 then begin repeat Writeln(SR.Name); until FindNext(SR)<>0; FindClose(SR); end; Readln; end.

Categories : Delphi

Using batch files to copy all files from a directory tree to a single directory
@echo off set "COPY_FROM=C:UsersmeDesktopDisc 1" set "COPY_TO=C:Testing est" md "%copy_to%" 2>nul cd /d "%COPY_FROM%" for /f "delims=" %%a in ('dir /b /s /a-d') do copy "%%a" "%COPY_TO%" pause

Categories : Batch File

Print out all files in current directory and subdirectories in Python
It's only a little more difficult using os.walk import os for dirpath, dirnames, filenames in os.walk('.'): for f in filenames: print os.path.join(dirpath, f) You can also express this as a generator expression for filename in (os.path.join(dp, f) for dp, dn, fn in os.walk('.') for f in fn): # do something with filename

Categories : Python

How to execute files added to .bashrc out of current directory?
Here is the solution: Composer showed an error that I was running the CGI version of php (stupid I know, I know). That was because I had an symlink in my bin dir to the cgi version. I changed the link it shows now to the CLI version of php. Now it works :)

Categories : Linux

PHP loop through current directory files for image resize
There's two ways to solve this. You can use one of PHP's "Magic Constants," __PATH__ to show the path to that current file. However, ot all PHP installs have this built in. The function getcwd() returns the current directory you're looking at, which may not be where your file lives. You can try this: <?php chdir( dirname( __FILE__ ) ); echo getcwd(); ?> Once you pull the directory, you can feed it into your script as it is. Hope this helps.

Categories : PHP

How to redirect all sub-directory pages to parent directory?
Add this to your .htaccess file RedirectMatch 301 ^/folder/$ http://example.com/folder What this basically does in corresponding to your question is redirect anything (be it sub directories, or files) inside the folder directory to your parent folder.

Categories : PHP

Gitolite unable to disable access to directory
According to the documentation your configuration looks good. Before continuing with anything else I would update to a newer git version - 1.7.1 is really old and there were plenty of bugfixes. I bet this solves your problems.

Categories : GIT

what is the best way to check in C# .NET if a directory has access to list files or a unauthorized access exception would rise
The best way to check the permission, is try to access the direcoty (read/write/list) & catch the UnauthorizedAccessException. However for some reason out there, if you want to check permissions, following code should satisfy your need. You need to read Access Rules for the directory. private bool DirectoryCanListFiles(string folder) { bool hasAccess = false; //Step 1. Get the userName for which, this app domain code has been executing string executingUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name; NTAccount acc = new NTAccount(executingUser); SecurityIdentifier secId = acc.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier; DirectorySecurity dirSec = Directory.GetAccessControl(folder); //Step 2. Get directory permission det

Categories : C#

Moveuploaded files function in PHP moves the file to the temp directory but not to the destination directory
First time you called move_uploaded_file() you moved that file from temporary folder to $workDir. After that, uploaded file no longer exists in temporary directory. Just use rename() function to move that file from $workDir."/".$tmpName to final destination. // moves file from workdir to final destination rename($workDir."/".$tmpName, $_POST['filetype'].'/'.$rightname);

Categories : PHP

getting the full filenames from all top directory files in a specific directory and suppressing the occuring error
Did I understand correctly that you only need the File-names with directory-names. This code works for me, no elevations needed. private void button1_Click(object sender, EventArgs e) { string folder = @"C:windowsprefetch"; string filemask = @"*.pf"; string[] filelist = Directory.GetFiles(folder, (filemask)); //now use filelist[i] for any operations. }

Categories : C#

Makefile: copy perl/python files from source directory into build directory
Basically, when you run make X, you are telling Make to find target X in your Makefile. So if you have no install: target, nothing will happen. All of this really depends what is in your Makefiles. If you want to copy your perl/python files into the build directory, one way to do so is to write a Makefile target that runs a *sh command like mv dir2/*.pyc build; mv dir2/*.pl build, and require that target somewhere else in your Makefile. If you need a good Makefile tutorial, here's one that I started with.

Categories : C++

How can I copy only files and folder created in the past hour in one directory to a new directory?
Robocopy doesn't have the granularity, but XXcopy seems to handle it. /DA#30m selects files made within the last 30 minutes. XXcopy is free for non commercial use and can be downloaded from http://www.xxcopy.com XXcopy is xcopy on steroids.

Categories : Batch File

Gallery Is Missing Files From Directory- How To Retrieve All Files From Directory
An alternative approach you may want to use to secure your list of thumbnails: $directory = 'thumb'; //where the gallery thumbnail images are located $files = glob($directory."/*.{jpg,jpeg,gif,png}", GLOB_BRACE); natsort($files); //sort by filename Then to render it out simply do this: <?php for($x = 0; $x < count($files); $x++): $thumb = $files[$x]; $file = basename($thumb); $nomargin = $x%4 == 0?" nomargin":""; $title = htmlspecialchars($file); ?> <div class="thumbs fancybox<?= $nomargin ?>" style="background:url('<?= $thumb ?>') no-repeat 50% 50%;"> <a rel="group" href="images/'.<?= $file ?>" title="<?= $title ?>"><?= $title ?></a> </div> <?php endfor;

Categories : PHP

Import a directory with files and force-overwrite even if the directory already exists
Read svn help import and use it. If you task really is Add unversion tree from custom location into existing repository svn import /PATH/TO/PROJECT protocol://URL/IN/REPOSITORY will add as result Project as child to URL/IN/REPOSITORY Just to note: import will appear as commit in repository

Categories : Svn

Unable to move mp4 files to another directory in ubuntu using python
When python I/O is given a filename, it assumes that the file is in the current directory, or somewhere on it's path; if it's not in any of those places, it yields an IOError. Therefore, when you are accessing files in directories other than your current directory, it's important to specific the path to that file. In your code, calling shutils.move with f is just supplying the function a file name---the path to that filename has been stripped off. Therefore, your call to shutils.move should look like shutil.move(os.path.join(root, f), dest)

Categories : Python

Unable to copy files from directory in shell script
change cp -r /Users/ajay/Documents/ServerObserverRepo/* /WebServer/Documents/ServerObserver/ to cp -r /Users/ajay/Documents/ServerObserverRepo/* /WebServer/Documents/ServerObserver/.

Categories : Shell

Is directory traversal via request.url possible?
I was gonna say that you can be sure that it's not possible, then I tried and I have to say that no, it doesn't seem like the http module removes '/../'. The redirection you saw is done in the browser. So whether it's a security risk or not depends on how your static handler is implemented. Proof of concept: // Server var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(req.url); }).listen(1337); Curl it: curl "http://localhost:1337/static/../app.js" # /static/../app.js So if you use a homebuilt static handler that just uses path.resolve() you're screwed. Hopefully popular ones like express.static have thought about this, but i haven't tried it. Update Express indeed responds with a 404 "Error: Forbidd

Categories : Node Js

Does my code prevent directory traversal in C#?
Since the Guid is the only thing passed in, and a Guid cannot be of the form ...., I think you would be safe from a Directory Traversal Attack. The only other input is ConfigurationManager.AppSettings["LogFilePath"]. This could be of the form X:Example.., but it could also be X:, so I do not see this as a problem. Either way, you will be adding @"ErrorLogsLogs" to the path you are writing. I would also recommend using Path.Combine, so you dont have to get lost in 's string varpath = Path.Combine(ConfigurationManager.AppSettings["LogFilePath"] .ToString(), @"ErrorLogsLogs");

Categories : C#

How to check for pipes in directory traversal?
You don't really need to test for pipes explicitly, you only want to look for files. Use os.path.isfile(); it'll return False for a pipe, but True for an actual file: $ ls -l total 0 -rw-rw-r-- 1 mj mj 0 Sep 7 12:27 actualfile prw-rw-r-- 1 mj mj 0 Sep 7 12:25 pipe >>> os.path.isfile('pipe') False >>> os.path.isfile('actualfile') True

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.