I'm trying to copy and rename a folder in Swift. I went about this by saving all of the original folder's contents to a new address. However, it seems to be creating .exe files instead of folders. Any ideas how I can fix the below code?
func moveAssets () {
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderName)!
while let element = enumerator.nextObject() as? String {
if (element != "main.js") {
var dataPath = documentsFolder.stringByAppendingPathComponent(timeStamp)
var tPath = folderName.stringByAppendingPathComponent(element)
fileManager.copyItemAtPath(tPath, toPath: dataPath, error: nil)
}
}
}
Found a solution here:
var error: NSError?
if filemgr.moveItemAtPath(filepath1, toPath: filepath2, error: &error) {
println("Move successful")
} else {
println("Moved failed with error: \(error!.localizedDescription)")
}
I will have to manually delete the .js file though
Related
I'm trying to build a web server in Rust, and i'm having a few issues trying to upload file into the server. With text based files it uploads fine, but whenever i try to upload other type of media (images, videos, etc), if the file is small enough, it will save, but corrupted, as showned.
original file raw data
file save on the server raw data
And when the file is too big, multer-rs library panicks with "received with incomplete data".
Error log
async fn parse_body(content_type: Option<&String>, body: String) -> HashMap<String, String> {
match content_type {
Some(content_type) => {
let ct = content_type.as_str();
if ct.contains("application/x-www-form-urlencoded") {
let buffer = body.replace("\r\n\r\n", "");
let _body = from_bytes::<Vec<(String, String)>>(buffer.as_bytes()).unwrap();
return _body.into_iter().collect();
}
if ct.contains("multipart/form-data") {
let boundary = multer::parse_boundary(ct).unwrap();
let data = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(body)) });
let mut multipart = multer::Multipart::new(data, boundary);
let mut _body: HashMap<String, String> = HashMap::new();
// Iterate over the fields, use `next_field()` to get the next field.
while let Some(mut field) = multipart.next_field().await.unwrap() {
// Get field name.
let name = field.name().unwrap().to_string();
// Get the field's filename if provided in "Content-Disposition" header.
//
// Process the field data chunks e.g. store them in a file.
while let Some(chunk) = field.chunk().await.unwrap() {
// Do something with field chunk.
if let Some(file_name) = field.file_name() {
let file_dir = format!("src\\static\\temp\\{}", file_name);
let current_dir: &Path = Path::new(&file_dir);
let path = env::current_dir().unwrap().join(current_dir);
if let Ok(mut file) = std::fs::File::create(path) {
file.write_all(&chunk).unwrap();
}
} else {
_body.insert(name.clone(), String::from_utf8(chunk.to_vec()).unwrap());
}
}
}
return _body;
}
},
None => return HashMap::new()
}
HashMap::new()
}
I have a project structure like
There are approx 10 JS files in com. lab1 and lab2 has a config.json file which tells, out of 10 files which files to be concatenated and placed as app-min.js in dist/lab1 or dist/lab2.
In the gulp file I've created something like this.
var filesArr = [];
var labName;
// Player Task
gulp.task('player', function () {
return gulp.src(filesArr)
.pipe(eslint())
.pipe(babel())
.pipe(concat('app-min.js'))
.pipe(uglify({
compress: {
drop_console: true
}
}).on('error', gutil.log))
.pipe(gulp.dest('dist/' + labName));
});
// Clean
gulp.task('clean', function () {
if (readJson()) {
return del([
'dist/' + labName
]);
}
return null;
});
// Watch
gulp.task('watch', function () {
gulp.watch(filesArr, gulp.series('player'));
});
// Read Json and create JS Array
function readJson() {
// LAB STRUCTURE
var _n = prompt('Specify the LAB name. ');
labName = _n;
var _path = path.resolve('./src/' + _n);
var _exists = fs.existsSync(_path);
if (_exists) {
var _json = fs.readFileSync(path.resolve(_path + '/labstructure.json'), 'utf-8');
var _jObj = JSON.parse(_json).labObj.components;
for (var i = 0; i < _jObj.length; i++) {
var _jsName = 'src/com/component/' + _jObj[i].ref + '.js';
if (filesArr.indexOf(_jsName) === -1) {
filesArr.push(_jsName);
}
}
}
return _exists;
}
gulp.task('default', gulp.series('clean', 'player', 'watch'));
Here the filesArr looks like:
[ 'src/com/component/ColorActClass.js',
'src/com/component/PanelCompClass.js',
'src/com/component/ToggleCompClass.js',
'src/com/component/SliderCompClass.js',
'src/com/component/CheckBoxCompClass.js',
'src/com/component/ButtonCompClass.js',
'src/com/component/LabelCompClass.js',
'src/com/component/InputBoxClass.js',
'src/com/component/ColorMonitorClass.js',
'src/com/component/MsgBoxClass.js',
'src/com/component/ConfBoxClass.js',
'src/com/component/NumberPadClass.js',
'src/com/main/lib/webfontloader.js',
'src/com/main/lib/howler.core.min.js',
'src/com/main/PlayerClass.js',
'src/kl1001_color/BrainClass.js' ]
This works perfectly fine at the first place. But when any JS is modified then in watch player task throws eslint error on some files which are untouched. This doesn't happen always rather if watch is running for 10-20 mins then it throws error. Like this:
In this case CheckBoxCompClass.js is not the file which is modified, but still got the issue. On top of that, the semicolon is in place. If this file has issue then eslint should have thrown the error at the first place.
Please help.
Accidentally, my NVM was set to an older version. Solved the issue after updating the NVM and by setting the current NVM version to the latest one.
As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});
So i recently found this google drive script and tried to use it.
The script should normally get file names and url on my google drive folder and copy them in a spreadsheet.
When i click Run, I get no error and nothing happens in my drive.
Is there variables i should change to make it work ?
PS : I'm very new to coding and can't seem to find what is wrong with this code
Thanks in advance for your help !
Here is the code :
function myFunction() {
function listFilesInFolder(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
niceFileType( file.getMimeType() )
];
sheet.appendRow(data);
}
}
}
Two issues. This needs to be ran in a script attached to a spreadsheet and you have a nested function.
Your code:
function myFunction() {
function listFilesInFolder(foldername) {
...
}
}
remove the outer function decleration and its matching closing bracket. The code will run.
It should look like:
function listFilesInFolder(foldername) {
...
}
Try this modified code in spreadsheet instead:
function myfunction(){
//Declaring the function listFolders to temp
var temp = function listFolders(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(data);
}
}
// calls the function listFolders below
temp()
}
My Requirement is to copy files/ image from a existing folder to another folder. How can i achieve it using SAILS JS
I tried with this :
var imagePath = photoName; //image source path
var proImagePath = './assets/images/profilePics/'; //image destination
var stream = fs.createReadStream(imagePath);
stream.on('error', function (error)
{
console.log("Caught", error);
});
stream.on('readable', function ()
{
stream.read();
var desti = fs.createWriteStream(proImagePath); //desti
stream.pipe(desti);
stream.on('end',function() {
stream.close();
return res.json(200, {status: 1, message: 'Success.'});
});
But consoling an error with :
Caught { [Error: ENOENT, open 'http://192.168.1.64:9002/images/userimages/sijobhai/91121438-7219-4c0f-b27c-516b289614a2.jpg']
errno: 34,
code: 'ENOENT',
path: 'http://192.168.1.64:9002/images/userimages/sijobhai/91121438-7219-4c0f-b27c-516b289614a2.jpg' }
//use this code
var fs = require('fs');
var source = fs.createReadStream('source_file_path');
var desti = fs.createWriteStream('destination_file_path');
source.pipe(desti);
source.on('end',function() {
source.close();
//if you want to delete file fron origin.
fs.unlink(source_file_path);
});