Powershell how to make [string]::Format into a function - functional-programming

How can i change this string format into a callable function?
[string]::Format("param {0} param {1}, param {2} ",$param0, $param1, $param2)
So for example, I don't need to use [string]::format() each time i want to write-host
Something like the below.
logMessage("param {0} param {1}, param {2}", ,$param0, $param1, $param2)
Just not sure how to turn the [string]::format into a function.

How about something like:
function Log-Message {
param(
[string]$Format,
[Array]$Params = ""
)
$msg = [string]::Format( $Format, $Params )
# Do something to actually log it, instead of just printing it back out
# like I do on the next line...
$msg
}
# For Testing Above Function...
$param0 = "foo"
$param1 = "bar"
$param2 = 42
# Using Parameter Names (cleaner)
Log-Message -Format "param {0} param {1} param {2}" -Params ( $param0, $param1, $param2 )
# Closer to what you were asking for...
Log-Message "param {0} param {1} param {2}" $param0, $param1, $param2
Note: in the second example, there is no comma between the format string and the first parameter.
Running the above will give you something like the following:
param foo param bar param 42
param foo param bar param 42

Related

Convert a string into date in AIX unix

I need to extract the date part from a file in unix and add +1 day to the date and rename the file with the new date in it.
for ex:
sample file name: sample_file_name_01_31_2022_14_01_45_loadid.csv
I tried to extract the timestamp using substr which gives 01_31_2022_14_01_45. Now, the new date should be 02_01_2022_14_01_45 and the new file name should be sample_file_name_02_01_2022_14_01_45_loadid.csv
Given the AIX operating environment, which doesn't have GNU date installed by default (for the handy date -d ... functionality), I'd approach this problem with a perl script. The script below uses fairly common modules that should be available on an AIX system.
The basic idea behind the script is to loop over every given argument (one or more filenames) and:
extract the date/time fields from the filename
convert those fields into seconds-since-the epoch
add one day's worth of seconds
convert that new timestamp into the desired string format
rename the file
I encountered a slight complication while adding error-checking: the timelocal() function will croak (exit the script) if any of the given date/time fields are out of range. Because I wanted to be able to loop over any remaining arguments, I had to wrap that call in a Try-Catch block.
#!/usr/bin/perl -w
use strict;
use POSIX qw(strftime);
use Time::Local qw(timelocal);
use Try::Tiny;
sub rename_a_file {
my $filename = shift;
# extract date from filename
my ($prefix, $month, $day, $year, $hour, $minute, $second, $suffix);
unless (
($prefix, $month, $day, $year, $hour, $minute, $second, $suffix) =
$filename =~ /^(.*)_(\d{2})_(\d{2})_(\d{4})_(\d{2})_(\d{2})_(\d{2})_(.*)$/
) {
warn "Could not determine a timestamp from ${filename}; skipping\n";
return undef;
}
# local time in seconds-since-the-epoch
my $t;
# timelocal will die if any inputs are out of range; catch it
my $flag = 0;
try {
$t = timelocal($second, $minute, $hour, $day, $month - 1, $year - 1900);
} catch {
warn "Unable to convert time specification: $_";
$flag = 1;
};
return undef if $flag;
# add one day's worth of seconds
$t += 24 * 60 * 60;
# new timestamp in string format
my $newdate;
unless ($newdate = strftime("%m_%d_%Y_%H_%M_%S", localtime $t)) {
warn "Unable to convert new date to a string format: $!";
return undef;
}
# rename file using new date
unless (rename $filename, "${prefix}_${newdate}_${suffix}") {
warn "Unable to rename $filename: $!";
return undef;
}
return 1;
}
my $errors = 0;
for (#ARGV) {
unless (rename_a_file($_)) {
warn "Unable to rename: $_\n";
++$errors;
}
}
$errors = 255 if $errors > 255;
exit $errors;

Symfony Invalid parameter format, : given

I need create multiply search by years. From request I get string like 2017,2018 and then I want get Questions which createdAt, between from start year and end year. I have query builder with part, and I'am not understand why I have this error
if ($paramFetcher->get('years')) {
$orXSearch = $qb->expr()->orX();
$yearData = trim($paramFetcher->get('years'));
foreach (explode(',', $yearData) as $key => $id) {
if (!$id) {
continue;
}
$orXSearch
->add($qb->expr()->between('q.createdAt', ':'.$key.'dateFrom', ':'.$key.'dateTo'));
$date = $this->additionalFunction->validateDateTime($id, 'Y');
$first = clone $date;
$first->setDate($date->format('Y'), 1, 1);
$first->setTime(0, 0, 0);
$last = clone $date;
$last->setDate($date->format('Y'), 12, 31);
$last->setTime(23, 59 , 59);
$qb
->setParameter($key.'dateFrom', $first->format('Y-m-d H:i:s'))
->setParameter($key.'dateTo', $last->format('Y-m-d H:i:s'));
}
$qb->andWhere($orXSearch);
}
error:
symfony Invalid parameter format, : given, but :<name> or ?<num> expected.
In your foreach loop, you’re looping over the result of an explode operation which yields a numeric array, i.e. $key will always have a numeric value.
Hence, your parameter placeholder is colon + number + string, i.e. :1dateFrom. This is not allowed. Either you reference a string value with a colon + string placeholder (:foo), or you reference a numeric value with a question mark + number value (?1).
Your problem is easy to solve: Simply add any letter between the colon and the number, and you’re good:
->add($qb->expr()->between(
'q.createdAt',
':x'.$key.'dateFrom',
':x'.$key.'dateTo'
));

coercing a paramter into an integer in Body Mapping Template, AWS API Gateway

I've been using a bit of arithmetic in the Body Mapping Template in Integration Request:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + 600)
{
"TableName": "events",
.... [ here get events between $now and $soon]
}
Recently I came to need to pass an offset through a parameter:
#set($now = $context.requestTimeEpoch/1000)
#set($soon = $now + $input.params('offset'))
{
"TableName": "events",
.... [ here get events between $now and $soon] ....
}
It turns out that if $now is 1518939082, with query paramter ?offset=600 $soon will be 1518939082600 - a concatenation. I have tried various ways to force the parameter being recognised as an integer, including:
#set($offset = $Integer.parseInt($input.params('offset')))
#set($offset = 0 + $input.params('offset'))
#set($offset = 1 * $input.params('offset'))
None of them works. I inserted #set($offset = 0) before each test so I can tell "nothing happens" from "a nothingness is returned".
In the first case, $offset prints an empty string, not 0. (This happens to $Integer.parseInt("1") too.)
In the second case, $offset prints a concatenation of "0" and the string value of "offset".
In the third case, $offset prints a 0, as if the entire line doesn't exist.
None of them successfully transformed the parameter to an integer.
Is there a way to use that parameter as an integer?

From VendorBundle:Entity to FQCN

Is there a way in Symfony to convert a string like
VendorBundle:Foo
into a FQCN like
Vendor\Bundle\Entity\Foo
Extra question
How Doctrine handle this? Because I've seen you can do something like (pseudocode)
->leftJoin( ..., ..., 'WITH', 'alias INSTANCE OF VendorBundle:Entity');
My question is due to
$foo = new \Vendor\Bundle\Entity\Foo();
$foo instanceof 'VendorBundle:Foo'; //false
You can use the php keyword ::class PHP.net
In your case, try something like Foo::class
This should output a string like Vendor\Bundle\Entity\Foo. If you see the comments at the link however, this is not guaranteed if you do not include the correct use statement in your code(use Vendor\Bundle\Entity\Foo) in your controller. If you correctly include that, then you can call Foo::class.
With doctrine functions, you can use the syntax you mentioned VendorBundle:Foo like this:
$manager = $this->getDoctrine()->getManager();
$fooRepository = $manager->getRepository('VendorBundle:Foo');
$fooBar = $fooRepository->find($someId);
For your verification, you have to check
$someStringToCheck = Foo::class;
$foo = new \Vendor\Bundle\Entity\Foo();
$foo instanceof $someStringToCheck //true
Oddly, if you do
$foo instanceof Foo::class
It returns an error
But to use VendorBundle:Foo, then take a look at the AbstractManagerRegistry.php in \Doctrine\Common\Persistence\AbstractManagerRegistry, at the function getManagerForClass($class). You can do something in your code like:
$doctrineStyleString = 'VendorBundle:Foo';
if (strpos($doctrineStyleString, ':') !== false)
{
list($namespaceAlias, $simpleClassName) = explode(':', $doctrineStyleString, 2);
$stringWithPath = $this->getDoctrine()->getAliasNamespace($namespaceAlias) . '\\' . $simpleClassName;
}
I took the code from that function and tried it out, so stringWithPath should print you Vendor\Bundle\Entity\Foo

How use Send() if the content has "" in it ? (autoIt)

Run("cmd.exe")
Global $String = "wmic process where name="example.exe" get commandline"
Send($String)
Result :
Global $String = "wmic process where name="example.exe" get commandline"
Global $String = "wmic process where name="^ ERROR
You just use single quotes to surround your string.
$string = 'test "example" and more stuff'
Or you can "escape" your double quotes by doubling them like stated in the Strings description of the Datatypes in AutoIt.
$string = "test ""example"" and more stuff"

Resources