I have a command which I want to repeat when a certain error occurs. To make this generic I would like to come up with a function that can take any other function to basically wrap that behaviour, very similar to repeat in ZSH.
So what I would like to have is something like this:
repeatWhenError { someFunction() }
This would repeat the function within the braces until it succeeds successfully. Is there an easy way to implement this in ZSH?
From my dotfiles:
retry () {
retry-limited 0 "$#"
}
retry-limited () {
retry-limited-eval "$1" "$(gquote "${#:2}")"
}
retry-limited-eval () {
local retry_sleep="${retry_sleep:-0.1}"
local limit=0
local ecode=0
until {
test "$1" -gt 0 && test $limit -ge "$1"
} || {
eval "${#:2}" && ecode=0
}
do
ecode="$?"
ecerr Tried eval "${#:2}" "..."
sleep $retry_sleep
limit=$((limit+1))
done
return "$ecode"
}
gquote () {
\noglob : Use this to control quoting centrally.
print -r -- "${(q+#)#}"
}
ecerr () {
print -r -- "$#" >&2
}
Usage:
retry someFunction
I'm trying to use R to write some perl script to a text file. I just cannot figure out how to escape certain characters?
I've used backslash (single and double), square brackets, "\\Q...\\E", etc. but still can't make it work.
Any assistance would be appreciated. Thanks in advance!
taskFilename = "example.txt"
cat("
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use File::Temp qw(tempfile);
my #imagedir_roots = ("/Users/Ross/Desktop/images");
my $parallel = 8;
my $exiftool_command = 'exiftool -all= -tagsfromfile # -all:all --gps:all --xmp:geotag -unsafe -icc_profile -overwrite_original';
# Create the (temporary) -# files
my #atfiles;
my #atfilenames;
for (my $i = 0; $i < $parallel; ++$i) {
my ($fh, $filename) = tempfile(UNLINK => 1);
push #atfiles, $fh;
push #atfilenames, $filename;
}
# Gather all JPG image files and distribute them over the -# files
my $nr = 0;
find(sub { print { $atfiles[$nr++ % $parallel] } "$File::Find::name\n" if (-f && /\.(?:jpg|jpeg)/i); }, #imagedir_roots);
# Process all images in parallel
printf("Processing %d JPG files...\n", $nr);
for (my $i = 0; $i < $parallel; ++$i) {
close($atfiles[$i]);
my $pid = fork();
if (!$pid) {
# Run exiftool in the background
system qq{$exiftool_command -# \"$atfilenames[$i]\"};
last;
}
}
# Wait for processes to finish
while (wait() != -1) {}
", fill = TRUE, file = taskFilename
)
I also played around with this once. If I remember correctly:
the double quotes you need to escape with \
if you want to write a \ you also need to escape it with \
if you want to write a \" you need to \\"
taskFilename = "example.txt"
cat("
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use File::Temp qw(tempfile);
my #imagedir_roots = (\"/Users/Ross/Desktop/images\");
my $parallel = 8;
my $exiftool_command = 'exiftool -all= -tagsfromfile # -all:all --gps:all --xmp:geotag -unsafe -icc_profile -overwrite_original';
# Create the (temporary) -# files
my #atfiles;
my #atfilenames;
for (my $i = 0; $i < $parallel; ++$i) {
my ($fh, $filename) = tempfile(UNLINK => 1);
push #atfiles, $fh;
push #atfilenames, $filename;
}
# Gather all JPG image files and distribute them over the -# files
my $nr = 0;
find(sub { print { $atfiles[$nr++ % $parallel] } \"$File::Find::name\n\" if (-f && /\\.(?:jpg|jpeg)/i); }, #imagedir_roots);
# Process all images in parallel
printf(\"Processing %d JPG files...\n\", $nr);
for (my $i = 0; $i < $parallel; ++$i) {
close($atfiles[$i]);
my $pid = fork();
if (!$pid) {
# Run exiftool in the background
system qq{$exiftool_command -# \\\"$atfilenames[$i]\\\"};
last;
}
}
# Wait for processes to finish
while (wait() != -1) {}
", fill = TRUE, file = taskFilename
)
I have an environment variable $R_HISTFILE pointing to /home/my.username/.RHistory and the following code in my .Rprofile in my home directory:
.Last <- function() {
if (!any(commandArgs()=='--no-readline') && interactive()){
require(utils)
try(savehistory(Sys.getenv("R_HISTFILE")))
}
}
Still whenever I open R, and I do history() I can't see the commands that I typed in earlier sessions. Moreover, the files .RHistory is pretty much empty with only three lines, (not at all reflecting commands I typed in the past).
How can I automatically save my history of commands across R sessions?
How did you set the environment variable? You should be able to put it in your .Renviron file.
To make sure the environment variable is being set correctly, confirm that this gives you "/home/my.username/.RHistory"
$ R --slave -e 'Sys.getenv("R_HISTFILE")'
Otherwise, are you starting R with --vanilla or similar? Are you in your home directory when you start R?
It works for me:
gMac:~ garrett$ R_HISTFILE=~/.RHistory R --vanilla -q
> .Last <- function() {
+ if (!any(commandArgs()=='--no-readline') && interactive()){
+ require(utils)
+ try(savehistory(Sys.getenv("R_HISTFILE")))
+ }
+ }
> a <- 5
> b <- 10
> q()
gMac:~ garrett$ R_HISTFILE=~/.RHistory R -q
> history()
which gives me a file with the following contents:
.Last <- function() {
if (!any(commandArgs()=='--no-readline') && interactive()){
require(utils)
try(savehistory(Sys.getenv("R_HISTFILE")))
}
}
a <- 5
b <- 10
q()
history()
If all else fails, you could put loadhistory(Sys.getenv("R_HISTFILE")) in .First in your .Rprofile.
In an effort to setup a "cron job" like scheduled task on Windows I've setup a Powershell script using code recommended via previous stackoverflow question.
I have some backups that I need to cleanup daily and delete old backups so I created a asp.net script to perform this task - the file name is BackupCleanup.aspx and I have confirmed that the ASP.net script does work when executed on its own by visiting the above url - I however cannot get it to execute using the Powershell script below.
The Powershell Script code I'm using is:
$request = [System.Net.WebRequest]::Create("http://127.0.0.1/BackupCleanup.aspx")
$response = $request.GetResponse()
$response.Close()
I have created this file with a PS1 extension, it shows properly in my os (Windows 2008) - I have tried both manually executing this task by right clicking and choosing "Run with Powershell" and also have scheduled this as a task - both to no avail.
I cannot figure out why the script does not work - any help would be GREATLY appreciated.
Here is the Powershell script I use to call up web pages using IE. Hopefully this will work for you as well.
Function NavigateTo([string] $url, [int] $delayTime = 100)
{
Write-Verbose "Navigating to $url"
$global:ie.Navigate($url)
WaitForPage $delayTime
}
Function WaitForPage([int] $delayTime = 100)
{
$loaded = $false
while ($loaded -eq $false) {
[System.Threading.Thread]::Sleep($delayTime)
#If the browser is not busy, the page is loaded
if (-not $global:ie.Busy)
{
$loaded = $true
}
}
$global:doc = $global:ie.Document
}
Function SetElementValueByName($name, $value, [int] $position = 0) {
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Value = $value
}
else {
Write-Warning "Couldn't find any element with name ""$name"""
}
}
Function ClickElementById($id)
{
$element = $global:doc.getElementById($id)
if ($element -ne $null) {
$element.Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with id ""$id"""
break
}
}
Function ClickElementByName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with name ""$name"" at position ""$position"""
break
}
}
Function ClickElementByTagName($name, [int] $position = 0)
{
if ($global:doc -eq $null) {
Write-Error "Document is null"
break
}
$elements = #($global:doc.getElementsByTagName($name))
if ($elements.Count -ne 0) {
$elements[$position].Click()
WaitForPage
}
else {
Write-Error "Couldn't find element with tag name ""$name"" at position ""$position"""
break
}
}
#Entry point
# Setup references to IE
$global:ie = New-Object -com "InternetExplorer.Application"
$global:ie.Navigate("about:blank")
$global:ie.visible = $true
# Call the page
NavigateTo "http://127.0.0.1/BackupCleanup.aspx"
# Release resources
$global:ie.Quit()
$global:ie = $null
I had the same issue. I manually opened powershell and executed my script and I received "WebPage.ps1 cannot be loaded because running scripts is disabled on this system.".
You have to allow scripts to run
Execute the below in PowerShell
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
How do I ask PowerShell where something is?
For instance, "which notepad" and it returns the directory where the notepad.exe is run from according to the current paths.
The very first alias I made once I started customizing my profile in PowerShell was 'which'.
New-Alias which get-command
To add this to your profile, type this:
"`nNew-Alias which get-command" | add-content $profile
The `n at the start of the last line is to ensure it will start as a new line.
Here is an actual *nix equivalent, i.e. it gives *nix-style output.
Get-Command <your command> | Select-Object -ExpandProperty Definition
Just replace with whatever you're looking for.
PS C:\> Get-Command notepad.exe | Select-Object -ExpandProperty Definition
C:\Windows\system32\notepad.exe
When you add it to your profile, you will want to use a function rather than an alias because you can't use aliases with pipes:
function which($name)
{
Get-Command $name | Select-Object -ExpandProperty Definition
}
Now, when you reload your profile you can do this:
PS C:\> which notepad
C:\Windows\system32\notepad.exe
I usually just type:
gcm notepad
or
gcm note*
gcm is the default alias for Get-Command.
On my system, gcm note* outputs:
[27] » gcm note*
CommandType Name Definition
----------- ---- ----------
Application notepad.exe C:\WINDOWS\notepad.exe
Application notepad.exe C:\WINDOWS\system32\notepad.exe
Application Notepad2.exe C:\Utils\Notepad2.exe
Application Notepad2.ini C:\Utils\Notepad2.ini
You get the directory and the command that matches what you're looking for.
Try this example:
(Get-Command notepad.exe).Path
My proposition for the Which function:
function which($cmd) { get-command $cmd | % { $_.Path } }
PS C:\> which devcon
C:\local\code\bin\devcon.exe
A quick-and-dirty match to Unix which is
New-Alias which where.exe
But it returns multiple lines if they exist so then it becomes
function which {where.exe command | select -first 1}
I like Get-Command | Format-List, or shorter, using aliases for the two and only for powershell.exe:
gcm powershell | fl
You can find aliases like this:
alias -definition Format-List
Tab completion works with gcm.
To have tab list all options at once:
set-psreadlineoption -editmode emacs
This seems to do what you want (I found it on http://huddledmasses.org/powershell-find-path/):
Function Find-Path($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
## You could comment out the function stuff and use it as a script instead, with this line:
#param($Path, [switch]$All = $false, [Microsoft.PowerShell.Commands.TestPathType]$type = "Any")
if($(Test-Path $Path -Type $type)) {
return $path
} else {
[string[]]$paths = #($pwd);
$paths += "$pwd;$env:path".split(";")
$paths = Join-Path $paths $(Split-Path $Path -leaf) | ? { Test-Path $_ -Type $type }
if($paths.Length -gt 0) {
if($All) {
return $paths;
} else {
return $paths[0]
}
}
}
throw "Couldn't find a matching path of type $type"
}
Set-Alias find Find-Path
Check this PowerShell Which.
The code provided there suggests this:
($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe
Try the where command on Windows 2003 or later (or Windows 2000/XP if you've installed a Resource Kit).
BTW, this received more answers in other questions:
Is there an equivalent of 'which' on Windows?
PowerShell equivalent to Unix which command?
If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:
function which($name) {
if ($name) { $input = $name }
Get-Command $input | Select-Object -ExpandProperty Path
}
copy-paste the command to your profile (notepad $profile).
Examples:
❯ echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe
❯ which clang.exe
C:\Program Files\LLVM\bin\clang.exe
I have this which advanced function in my PowerShell profile:
function which {
<#
.SYNOPSIS
Identifies the source of a PowerShell command.
.DESCRIPTION
Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
(which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
provided; aliases are expanded and the source of the alias definition is returned.
.INPUTS
No inputs; you cannot pipe data to this function.
.OUTPUTS
.PARAMETER Name
The name of the command to be identified.
.EXAMPLE
PS C:\Users\Smith\Documents> which Get-Command
Get-Command: Cmdlet in module Microsoft.PowerShell.Core
(Identifies type and source of command)
.EXAMPLE
PS C:\Users\Smith\Documents> which notepad
C:\WINDOWS\SYSTEM32\notepad.exe
(Indicates the full path of the executable)
#>
param(
[String]$name
)
$cmd = Get-Command $name
$redirect = $null
switch ($cmd.CommandType) {
"Alias" { "{0}: Alias for ({1})" -f $cmd.Name, (. { which $cmd.Definition } ) }
"Application" { $cmd.Source }
"Cmdlet" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Function" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"Workflow" { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
"ExternalScript" { $cmd.Source }
default { $cmd }
}
}
Use:
function Which([string] $cmd) {
$path = (($Env:Path).Split(";") | Select -uniq | Where { $_.Length } | Where { Test-Path $_ } | Get-ChildItem -filter $cmd).FullName
if ($path) { $path.ToString() }
}
# Check if Chocolatey is installed
if (Which('cinst.bat')) {
Write-Host "yes"
} else {
Write-Host "no"
}
Or this version, calling the original where command.
This version also works better, because it is not limited to bat files:
function which([string] $cmd) {
$where = iex $(Join-Path $env:SystemRoot "System32\where.exe $cmd 2>&1")
$first = $($where -split '[\r\n]')
if ($first.getType().BaseType.Name -eq 'Array') {
$first = $first[0]
}
if (Test-Path $first) {
$first
}
}
# Check if Curl is installed
if (which('curl')) {
echo 'yes'
} else {
echo 'no'
}
You can install the which command from https://goprogram.co.uk/software/commands, along with all of the other UNIX commands.
If you have scoop you can install a direct clone of which:
scoop install which
which notepad
There also always the option of using which. there are actually three ways to access which from Windows powershell, the first (not necessarily the best) wsl -e which command (this requires installation of windows subsystem for Linux and a running distro). B. gnuwin32 which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers option three, install msys2 (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.
There also always the option of using which. there are actually three ways to access which from Windows powershell
The first, (though not the best) is wsl(windows subsystem for linux)
wsl -e which command
This requires installation of windows subsystem for Linux and a running distro.
Next is gnuwin32 which is a port of several gnu binaries in .exe format as standle alone bundled lanunchers
Third, install msys2 (cross compiler platform) if you go where it installed in /usr/bin you'll find many many gnu utils that are more up-to-date. most of them work as stand alone exe and can be copied from the bin folder to your home drive somewhere amd added to your PATH.