Regular expression search and replace in Sublime Text - regex

I have an array in Sublime Text with every city in the U.S as the value and a code which includes the state abbreviation as the key. It looks a little something like this:
$array = array(
"United States of America" => array(
"USAK0001" => "Adak",
"USAK0002" => "Adak Island",
"USAK0003" => "Akiachak",
"USAK0004" => "Akiak",
"USAK0005" => "Akutan",
"USAK0006" => "Alakanuk",
"USAK0007" => "Aleknagik",
"USAK0008" => "Allakaket",
"USAL0028" => "Arlington",
"USAL0029" => "Ashford",
"USAL0030" => "Ashland",
"USAL0031" => "Ashville",
"USAL0032" => "Athens",
"USAL0033" => "Atmore",
"USAL0034" => "Attalla",
"USAL0035" => "Auburn",
"USAL0036" => "Auburn University",
"USAL0037" => "Autaugaville",
"USAL0038" => "Axis",
"USAL0039" => "Baileyton",
)
);
What I need to do is a search and replace to append the state name to the value, based on finding the two letter state abbreviation in the array key code.
So for example, a search that finds "AK" in the key and adds "Alaska" to the value, so they would look like this:
"USAK0001" => "Alaska, Adak",
"USAK0002" => "Alaska, Adak Island",
"USAK0003" => "Alaska, Akiachak",
"USAK0004" => "Alaska, Akiak",
"USAK0005" => "Alaska, Akutan",
"USAK0006" => "Alaska, Alakanuk",
Every key is 8 characters long, but I really don't even know how to begin trying to do this in Sublime Text.

Thanks to nhahtdh, I did this quite easily with a PHP script to merge it. It ended up being as simple as the below, with no need for regex! (Huzzah!)
function merge_states_into_cities( $states, $cities ) {
foreach ( $cities as $key => $array ) {
foreach ( $array as $code => $city ) {
foreach ( $states as $abbrv => $state ) {
if ( strpos( $code, $abbrv, 2 ) ) {
echo '"' . $code . '" => "' . $state . ', ' . $city . '",<br>';
}
}
}
}
}

Related

500 Server Error from charge-credit-card.php Authorize.net

I am using the php spl package for the Authorize.net SDK. I verified that SimpleXML, cURL, and JSON are all installed on the server and PHP 5.6+ is being used.
I have verified that the SDK is building the $request object $request->setTransactionRequest( $transactionRequestType);
The returned object using print_r
net\authorize\api\contract\v1\CreateTransactionRequest Object ( [transactionRequest:net\authorize\api\contract\v1\CreateTransactionRequest:private] => net\authorize\api\contract\v1\TransactionRequestType Object ( [transactionType:net\authorize\api\contract\v1\TransactionRequestType:private] => authCaptureTransaction [amount:net\authorize\api\contract\v1\TransactionRequestType:private] => 151.51 [currencyCode:net\authorize\api\contract\v1\TransactionRequestType:private] => [payment:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\PaymentType Object ( [creditCard:net\authorize\api\contract\v1\PaymentType:private] => net\authorize\api\contract\v1\CreditCardType Object ( [cardCode:net\authorize\api\contract\v1\CreditCardType:private] => [isPaymentToken:net\authorize\api\contract\v1\CreditCardType:private] => [cryptogram:net\authorize\api\contract\v1\CreditCardType:private] => [cardNumber:net\authorize\api\contract\v1\CreditCardSimpleType:private] => 4111111111111111 [expirationDate:net\authorize\api\contract\v1\CreditCardSimpleType:private] => 2038-12 ) [bankAccount:net\authorize\api\contract\v1\PaymentType:private] => [trackData:net\authorize\api\contract\v1\PaymentType:private] => [encryptedTrackData:net\authorize\api\contract\v1\PaymentType:private] => [payPal:net\authorize\api\contract\v1\PaymentType:private] => [opaqueData:net\authorize\api\contract\v1\PaymentType:private] => ) [profile:net\authorize\api\contract\v1\TransactionRequestType:private] => [solution:net\authorize\api\contract\v1\TransactionRequestType:private] => [callId:net\authorize\api\contract\v1\TransactionRequestType:private] => [authCode:net\authorize\api\contract\v1\TransactionRequestType:private] => [refTransId:net\authorize\api\contract\v1\TransactionRequestType:private] => [splitTenderId:net\authorize\api\contract\v1\TransactionRequestType:private] => [order:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\OrderType Object ( [invoiceNumber:net\authorize\api\contract\v1\OrderType:private] => 101 [description:net\authorize\api\contract\v1\OrderType:private] => Golf Shirts ) [lineItems:net\authorize\api\contract\v1\TransactionRequestType:private] => Array ( [0] => net\authorize\api\contract\v1\LineItemType Object ( [itemId:net\authorize\api\contract\v1\LineItemType:private] => Shirts [name:net\authorize\api\contract\v1\LineItemType:private] => item1 [description:net\authorize\api\contract\v1\LineItemType:private] => golf shirt [quantity:net\authorize\api\contract\v1\LineItemType:private] => 1 [unitPrice:net\authorize\api\contract\v1\LineItemType:private] => 20.95 [taxable:net\authorize\api\contract\v1\LineItemType:private] => ) ) [tax:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\ExtendedAmountType Object ( [amount:net\authorize\api\contract\v1\ExtendedAmountType:private] => 4.5 [name:net\authorize\api\contract\v1\ExtendedAmountType:private] => level 2 tax name [description:net\authorize\api\contract\v1\ExtendedAmountType:private] => level 2 tax ) [duty:net\authorize\api\contract\v1\TransactionRequestType:private] => [shipping:net\authorize\api\contract\v1\TransactionRequestType:private] => [taxExempt:net\authorize\api\contract\v1\TransactionRequestType:private] => [poNumber:net\authorize\api\contract\v1\TransactionRequestType:private] => 15 [customer:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\CustomerDataType Object ( [type:net\authorize\api\contract\v1\CustomerDataType:private] => [id:net\authorize\api\contract\v1\CustomerDataType:private] => 15 [email:net\authorize\api\contract\v1\CustomerDataType:private] => foo#example.com [driversLicense:net\authorize\api\contract\v1\CustomerDataType:private] => [taxId:net\authorize\api\contract\v1\CustomerDataType:private] => ) [billTo:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\CustomerAddressType Object ( [phoneNumber:net\authorize\api\contract\v1\CustomerAddressType:private] => [faxNumber:net\authorize\api\contract\v1\CustomerAddressType:private] => [email:net\authorize\api\contract\v1\CustomerAddressType:private] => [firstName:net\authorize\api\contract\v1\NameAndAddressType:private] => Ellen [lastName:net\authorize\api\contract\v1\NameAndAddressType:private] => Johnson [company:net\authorize\api\contract\v1\NameAndAddressType:private] => Souveniropolis [address:net\authorize\api\contract\v1\NameAndAddressType:private] => 14 Main Street [city:net\authorize\api\contract\v1\NameAndAddressType:private] => Pecan Springs [state:net\authorize\api\contract\v1\NameAndAddressType:private] => TX [zip:net\authorize\api\contract\v1\NameAndAddressType:private] => 44628 [country:net\authorize\api\contract\v1\NameAndAddressType:private] => USA ) [shipTo:net\authorize\api\contract\v1\TransactionRequestType:private] => net\authorize\api\contract\v1\NameAndAddressType Object ( [firstName:net\authorize\api\contract\v1\NameAndAddressType:private] => Bayles [lastName:net\authorize\api\contract\v1\NameAndAddressType:private] => China [company:net\authorize\api\contract\v1\NameAndAddressType:private] => Thyme for Tea [address:net\authorize\api\contract\v1\NameAndAddressType:private] => 12 Main Street [city:net\authorize\api\contract\v1\NameAndAddressType:private] => Pecan Springs [state:net\authorize\api\contract\v1\NameAndAddressType:private] => TX [zip:net\authorize\api\contract\v1\NameAndAddressType:private] => 44628 [country:net\authorize\api\contract\v1\NameAndAddressType:private] => USA ) [customerIP:net\authorize\api\contract\v1\TransactionRequestType:private] => [cardholderAuthentication:net\authorize\api\contract\v1\TransactionRequestType:private] => [retail:net\authorize\api\contract\v1\TransactionRequestType:private] => [employeeId:net\authorize\api\contract\v1\TransactionRequestType:private] => [transactionSettings:net\authorize\api\contract\v1\TransactionRequestType:private] => [userFields:net\authorize\api\contract\v1\TransactionRequestType:private] => ) [merchantAuthentication:net\authorize\api\contract\v1\ANetApiRequestType:private] => net\authorize\api\contract\v1\MerchantAuthenticationType Object ( [name:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => *******[transactionKey:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => ***********[sessionToken:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => [password:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => [impersonationAuthentication:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => [fingerPrint:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => [mobileDeviceId:net\authorize\api\contract\v1\MerchantAuthenticationType:private] => ) [refId:net\authorize\api\contract\v1\ANetApiRequestType:private] => ref1453823618 )
The error seems to happen at:
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
Commenting either out one at a time causes the 500 error, if both removed it finishes the script.
The full script:
<?php
require '../../autoload.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
define("AUTHORIZENET_LOG_FILE", "phplog");
// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName("*********");
$merchantAuthentication->setTransactionKey("******************");
$refId = 'ref' . time();
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber( "4111111111111111" );
$creditCard->setExpirationDate( "2038-12");
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
// Order info
$order = new AnetAPI\OrderType();
$order->setInvoiceNumber("101");
$order->setDescription("Golf Shirts");
// Line Item Info
$lineitem = new AnetAPI\LineItemType();
$lineitem->setItemId("Shirts");
$lineitem->setName("item1");
$lineitem->setDescription("golf shirt");
$lineitem->setQuantity("1");
$lineitem->setUnitPrice(20.95);
$lineitem->setTaxable(false);
// Tax info
$tax = new AnetAPI\ExtendedAmountType();
$tax->setName("level 2 tax name");
$tax->setAmount(4.50);
$tax->setDescription("level 2 tax");
// Customer info
$customer = new AnetAPI\CustomerDataType();
$customer->setId("15");
$customer->setEmail("foo#example.com");
// PO Number
$ponumber = "15";
//Ship To Info
$shipto = new AnetAPI\NameAndAddressType();
$shipto->setFirstName("Bayles");
$shipto->setLastName("China");
$shipto->setCompany("Thyme for Tea");
$shipto->setAddress("12 Main Street");
$shipto->setCity("Pecan Springs");
$shipto->setState("TX");
$shipto->setZip("44628");
$shipto->setCountry("USA");
// Bill To
$billto = new AnetAPI\CustomerAddressType();
$billto->setFirstName("Ellen");
$billto->setLastName("Johnson");
$billto->setCompany("Souveniropolis");
$billto->setAddress("14 Main Street");
$billto->setCity("Pecan Springs");
$billto->setState("TX");
$billto->setZip("44628");
$billto->setCountry("USA");
//create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType( "authCaptureTransaction");
$transactionRequestType->setAmount(151.51);
$transactionRequestType->setPayment($paymentOne);
$transactionRequestType->setOrder($order);
$transactionRequestType->addToLineItems($lineitem);
$transactionRequestType->setTax($tax);
$transactionRequestType->setPoNumber($ponumber);
$transactionRequestType->setCustomer($customer);
$transactionRequestType->setBillTo($billto);
$transactionRequestType->setShipTo($shipto);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId( $refId);
$request->setTransactionRequest( $transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::SANDBOX);
if ($response != null)
{
$tresponse = $response->getTransactionResponse();
if (($tresponse != null) && ($tresponse->getResponseCode()=="1") )
{
echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
echo "Charge Credit Card TRANS ID : " . $tresponse->getTransId() . "\n";
}
else
{
echo "Charge Credit Card ERROR : Invalid response\n";
}
}
else
{
echo "Charge Credit card Null response returned";
}
?>
Thank you for any help or advice on establishing the connection properly

Test if a string contains the key of a hash in Perl

I have a string and want to tell if it contains the key of a hash and if it does I would like to print the value of the hash like so:
#!/usr/bin/perl -w
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
if ($str contains a key of %h){
print the value of that key; #i.e v1
}
Whats the best way to do this? (Preferably concise enough to contain in an if statement)
#!/bin/perl -w
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1\n";
while (($key, $value) = each %h) {
if (-1 != index($str, $key)) {
print "$value\n";
}
}
If you have to search through multiple strings but have just the one unchanging hash, it might be faster to compile the hash keys into a regexp upfront, and then apply that regexp to each string.
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $hash_keys = qr/${\ join('|', map quotemeta, keys %h) }/;
my #strings = (
"this is a string containing key1\n",
"another string containing key1\n",
"this is a string containing key2\n",
"but this does not\n",
);
foreach my $str (#strings) {
print "$str\n" if $str =~ $hash_keys;
}
In some cases (big hash, keys are words and you don't want them to match sub-words) this could be the right approach:
my %h = ( 'key1' => 'v1', 'key2' => 'v2', 'key3' => 'v3' );
my $str = "this is a string containing key1 and key3 but notkey2, at least not alone\n";
while ($str =~ /(\w+)/g) {
my $v = $h{$1};
print "$v\n" if defined $v;
}

I'm getting 'The request must contain the parameter Signature' although I'm actually supplying it

I'm trying the AWS Product Advertisement API in PhP.
Here is the PhP code that I've copied from net.
function callSOAPFunction($function, $array){
$timeStamp = gmdate("Y-m-d\TH:i:s\Z");
//service is always the same, $function is operation
$string = 'AWSECommerceService'.$function.$timeStamp;
$signature = base64_encode(hash_hmac("sha256", $string, 'MySecretKey', True));
$params = array('Service' => 'AWSECommerceService',
'AssociateTag' => 'Wassup?',
**'Signature' => $signature,**
'AWSAccessKeyId' => 'MyKey'
'Request' => array($array),
'Timestamp' => $timeStamp
);
$client = new
SoapClient("http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl",
array('exceptions' => 0));
return $client->__soapCall($function, array($params));
}
$array = array('Operation' => 'ItemSearchRequest',
'ItemPage' => 3,
'SearchIndex' => 'DVD',
'ResponseGroup' => 'Large',
'Keywords' => 'Karate');
$result = callSOAPFunction("ItemSearch", $array);
Although I'm including the signature parameter, I'm still getting the error.

Perl: Splitting a hash into several based on its keys?

Let's say that I have a hashref whose Data::Dumper output looks like this:
$VAR1 = {
foo_0 => 'foo_zero',
foo_1 => 'foo_one',
bar_0 => 'bar_zero',
bar_1 => 'bar_one'
}
I would like to split this hash into two based on its keys as shown below but I don't know how to do this:
$VAR1 = {
foo_0 => 'foo_zero',
foo_1 => 'foo_one'
},
$VAR2 = {
bar_0 => 'bar_zero',
bar_1 => 'bar_one'
}
The keys of the first hash match /foo_[\d]/ while those of the second hash match /bar_[\d]/.
If you could kindly tell me how to do this (or hint me some search keywords) I would appreciate it.
Regards,
Christopher Smith
The other solutions posted so far work, but are quick and dirty. They need to be changed when the input patterns change, and assume only two patterns. This generalised solution does not suffer from that: it needs no change, and it takes any number of patterns.
sub classify_hashref {
my ($href, %p) = #_;
my $r;
for my $hkey (keys %{ $href }) {
for my $pkey (keys %p) {
$r->{$pkey}{$hkey} = $href->{$hkey}
if $hkey =~ $p{$pkey};
}
}
return $r;
}
my $h = {
foo_0 => 'foo_zero',
foo_1 => 'foo_one',
bar_0 => 'bar_zero',
bar_1 => 'bar_one'
};
classify_hashref($h, foo_like => qr/^foo_/, looks_like_bar => qr/^bar_/);
# {
# looks_like_bar => {
# bar_0 => 'bar_zero',
# bar_1 => 'bar_one'
# },
# foo_like => {
# foo_0 => 'foo_zero',
# foo_1 => 'foo_one'
# }
# }
I'm assuming that your hash reference is $foo_ref. You didn't state what would happen if your hash key is neither a foo or a bar. You could do one of three things:
You have to hash references. One of foo keys and one of all other keys.
You throw out keys that are neither foo keys or bar keys. (This is what I did).
You have a third hash which stores all non-foo and non-bar keys.
The program below:
#! /usr/bin/env perl
use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
my $foo_re = qr/^foo_/;
my $bar_re = qr/^bar_/;
my $foo_ref = {
foo_0 => "foo_zero",
foo_1 => "foo_one",
bar_0 => "bar_zero",
bar_1 => "bar_one",
};
my $bar_ref = {};
foreach my $key (keys %{$foo_ref}) {
if (not $key =~ $foo_re) {
# Remove if clause to store all non-foo keys in $bar_re
$bar_ref->{$key} = $foo_ref->{$key} if $key =~ $bar_re;
delete $foo_ref->{$key}
}
}
say Dumper $foo_ref;
say Dumper $bar_ref;
I'm assuming that all your hash keys has one of the 2 provided patterns. If not, then you should specify more exactly what you have and what you expect.
If you want to process the output of the dump, I'm also assuming it has a correct format suitable for eval. Just put your output inside q( and ):
# ...
my $VAR1;
eval q(
$VAR1 = {
foo_0 => 'foo_zero',
foo_1 => 'foo_one',
bar_0 => 'bar_zero',
bar_1 => 'bar_one'
}
);
my $h1 = {};
my $h2 = {};
for my $k ( keys %{$VAR1} ) {
if ( $k =~ /foo_\d/ ) {
$h1->{$k} = $VAR1->{$k};
next;
}
$h2->{$k} = $VAR1->{$k}; # the remaining /bar_\d/ case
}
# use your new $h1 and $h2 hasrefs
# ...
You will get 2 new hasrefs $h1 and $h2.
If you have other cases besides these 2, you shoul put everyone inside an if, not only the first.
This is not a complete script, just a snippet.

normalizing results from the graph or fql.query

I'm running an application that calls both the graph and fql.query for Insights information. (It happens to impersonate dozens of apps and pulls stats) I get a couple different formats back when querying and I'm wondering if there's a better way to 'normalize' results?
It would be nice to have something like this in the SDK, since Facebook formats/ data changes all the time. Where do I make an SDK request?
Code to get key-value---
[code]
public function saveResults($application = null, $result = array())
{
// graph insights are under a data key
if(isset($result['data'])) {
$this->saveResults($application, $result['data']);
}
// graph insights are under a values array
elseif(isset($result['values'])) {
foreach($result['values'] as $k => $v) {
$this->saveResult($application, $result['name'], $v['value'], $result['period'], $v['end_time']);
}
}
// fql.query results have a metric and value
elseif(isset($result['metric'])) {
$this->saveResult($application, $result['metric'], $result['value'], $result['period'], $result['end_time']);
}
// otherwise save key values
elseif(is_array($result)) {
foreach($result as $key => $val) {
if(is_numeric($key) && is_array($val)) {
$this->saveResults($application, $val);
}
else {
$this->saveResult($application, $key, $val);
}
}
}
}
[/code]
Results from fql --
=> Array
(
[0] => Array
(
[app_id] => 1248...
[api_key] => 1248...
[canvas_name] => ABC123
[display_name] => ABC123
[company_name] =>
[developers] => Array
(
)
[restriction_info] => Array
(
)
[daily_active_users] => 0
[weekly_active_users] => 0
[monthly_active_users] => 8
)
)
=> Array
(
[0] => Array
(
[metric] => application_canvas_views
[value] => 0
[period] => 86400
[end_time] => 1317538800
)
)
Results from graph --
=> Array
(
[id] => 1248...
[name] => ABC123
[picture] => https://fbcdn-profile...
[link] => http://www.facebook.com/ABC123
[likes] => 58450
[category] => Product/service
[website] => http://www.ABC123..
=> Array
(
[data] => Array
(
[0] => Array
(
[id] => ABC123.../insights/page_like_adds/day
[name] => page_like_adds
[period] => day
[values] => Array
(
[0] => Array
(
[value] => 60
[end_time] => 2011-01-01T08:00:00+0000
)
[1] => Array
(
[value] => 15
[end_time] => 2011-01-02T08:00:00+0000
)
[2] => Array
(
[value] => 2
From my experience there's no 1:1 correlation between "object properties" being returned from the FQL tables to that of the new graph API objects. There's so many more properties on the FQL tables than there are in the graph from what I've seen. Trying to get them tied together would be like giving a cat a bath. It can be done, but it's going to be painful!!
My suggestions would be to determine from the project requirements what you're trying to accomplish and then determine whether FQL or Graph API is your best route to getting to each requirement. One requirement might be easier done with the graph, and another using FQL. Good luck.