Getting Variable does not exist: String in an apex method - salesforce

I am getting the error "Variable does not exist: String" on the nextOne() method when calling String.fromCharArray(). I'm not sure how I'm losing scope of String or it's static methods.
public with sharing class NextLetterGenerator {
public List<String> InputArray;
public Map<String, Integer>Letters;
public Map<Integer, String>Numbers;
public UserIdGenerator(String input) {
InputArray = input.toUpperCase().split('');
InputArray.remove(0);
SetLetters();
SetNumbers();
}
public void SetLetters() {
Letters = new Map<String, Integer> {'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10,
'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19,
'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26
};
}
public void SetNumbers() {
Numbers = new Map<Integer, String> {1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E'};
}
public String nextOne() {
if (InputArray[InputArray.size() - 1] != 'Z') {
Integer temp = Letters.get(InputArray[InputArray.size() - 1]);
InputArray[InputArray.size() - 1] = Numbers.get(temp + 1);
}
return String.fromCharArray(InputArray);
}
}

So this turns out to be an issue of a bad compiler error message. What the issue was is that I wasn't using the correct signature for fromCharArray. It required a List of integers and I'm passing a List of String. In the long run I didn't want that method anyway. What helped me come to this conclusion was calling return System.String.fromCharArray(InputArray) and it showed me that I may be using an incorrect signature for that method. Hope this helps others debug their Apex code.

Please look through the list of String static methods. You can find here that there is not such methods with signature String.fromCharArray(List<String> charArray) but exist the next one String.fromCharArray(List<Integer> charArray)/

Related

Typescript Convert Enum to Constant Class

How do I convert an Enum to a Constant Class like this, in Typescript? Currently using React Typescript, with functional components .
This question is slightly different: TypeScript enum to object array
export enum ProductStatus {
Draft = 1,
Review = 2,
Approved = 3,
Rejected = 4,
Billed = 5,
Collected = 6,
Unpayable = 7,
WorkInProgress = 8,
ReadyToReview = 9,
NeedsRevision = 10,
Failed = 11,
}
export const ProductStatus = {
Draft: 1,
Review: 2,
Approved: 3,
Rejected: 4,
Billed: 5,
Collected: 6,
Unpayable: 7,
WorkInProgress: 8,
ReadyToReview: 9,
NeedsRevision: 10,
Failed: 11,
};
loop throught the keys and use ethe reduce function
const newConst = React.useMemo(() => {
return Object.keys(ProductStatus).reduce((acc, key) => {
if (isNaN(Number(key))) {
acc[key] = ProductStatus[key];
}
return acc;
}, {});
}, []);
console.log(newConst );
https://stackblitz.com/edit/react-ts-ivfxqw?file=App.tsx
We can use Object.values to get the values from the enum and convert them to an object using reduce.
const ProductStatusObject = Object.values(ProductStatus)
.filter((v): v is keyof typeof ProductStatus => typeof v !== "number")
.reduce((p, c) => {
p[c] = ProductStatus[c]
return p
}, {} as Record<keyof typeof ProductStatus, number>)
ProductStatusObject
// ^? Record<"Draft" | "Review" | "Approved" | ..., number>
As you may know, enums contain a mapping in both directions. We need to filter out the values which are not of type string to only get the keys of the enum. The filter callback also needs a type predicate to indicate to TypeScript that the resulting array only contains values of type keyof typeof ProductStatus.
The reduce method takes the elements of the array and assigns them as keys to an object using the corresponding enum value. I typed the object as Record<keyof typeof ProductStatus, number> to get a useful return type.
console.log(ProductStatusObject)
/*
{
"Draft": 1,
"Review": 2,
"Approved": 3,
"Rejected": 4,
"Billed": 5,
"Collected": 6,
"Unpayable": 7,
"WorkInProgress": 8,
"ReadyToReview": 9,
"NeedsRevision": 10,
"Failed": 11
}
*/
Playground

How to return all even numbers inside an array inside of a hash?

I've been given the following data structure:
users = {
"Jonathan" => {
:twitter => "tronathan",
:favorite_numbers => [12, 42, 75],
},
"Erik" => {
:twitter => "sferik",
:favorite_numbers => [8, 12, 24],
},
"Anil" => {
:twitter => "bridgpal",
:favorite_numbers => [12, 14, 85],
},
}
I need to return all of Anils favourite numbers that are even.
This is what I have so far:
users["Anil"][:favorite_numbers].each do |evennum|
if evennum.even?
puts evennum
end
end
You could do something like this
anil_favorite_even_numbers = users['Anil'][:favorite_numbers].select(&:even?)
This takes for granted that a user Anil exists and the favourite_numbers inside it too and that's an array. Otherwise we need a little bit of extra work.

perl: Plotting data from multiple arrays

In my perl code, I have several arrays with the name 'a', 'b', 'c'.... 'e', 'f'. I am sending them as the argument while calling 'MyFunc'. There I want to plot any two arrays, for example, 'e' vs 'f'.
I tried in the following way (please look at the code), but I get a message that no data points are available in the line where my $gd = $graph->plot(\#e,\#f) or die $graph->error; command is being executed.
How to make it work?
MyFunc(
'a' => [0, 1,2,3,4],
'c' => [0, -1,2,-3,6],
'c' => [0, 2,4,2,5],
'd' => [0, 1,2,3,4],
'e' => [0, 9,2,1,7],
'f' => [-2, 5,-1,1,7],
'g' => [5, 1,8,-2,5],
);
sub MyFunc {
use GD::Graph::lines;
my $graph = GD::Graph::lines->new;
$graph->set(
x_label => 'X Label',
y_label => 'Y label',
title => 'Some simple graph',
y_max_value => 8,
y_tick_number => 8,
y_label_skip => 2
) or die $graph->error;
my $gd = $graph->plot(\#e,\#f) or die $graph->error;
open(IMG, '>file.gif') or die $!;
binmode IMG;
print IMG $gd->gif;
close IMG;
};
Passing an argument 'e' => [0,9,2,1,7] to a subroutine does not automatically create a variable called #e inside the subroutine. Your subroutine does do not do any processing of arguments whatsoever. Consider something like this to do what you seem to want:
sub MyFunc {
my %params = #_;
...
my $gd = $graph->plot( [$params{"e"}, $params{"f"}] ) ...
...
}

Hash with array of hashes inside hash

I have a hash like this:
document = {
"results" => {[
{"ip" => 10, "host" => 12},
{"ip" => 13, "host" => 17}
]}
}
It's a one item hash with an array of hashes inside the hash. I specified a value of ip = 10.
If the ip is more than 10, I want to print both keys with values. This hash is very complicated and I don't know how to access these values. Can you help me?
Edit:
What if I had hash like this
document = { "results" => [{"ip" => 10, "host" => 12, "temp" => yes},{"ip" => 13, "host" => 17, "temp" => yes}] } and wanted print only ip and host after matching ip with 10?
document["results"].each do |result|
if result["ip"] > 10
puts result # will print ip and host
end
end
I would use select:
document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }
puts document['results'].select { |hash| hash['ip'] > 10 }
#=> {"ip"=>13, "host"=>17}
Explanation:
document['results']
returns the array of hashes:
[{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}]
In the next step select is called on that returned array:
document['results'].select { |hash| hash['ip'] > 10 }
This returns all sub-hashes with an value > 10 assigned to the key 'ip'.
puts just prints the result to STDOUT
I have another problem today. Here is my code:
require 'rubygems'
require 'json'
document = JSON.load File.new("hosts.txt")
file = JSON.load File.new("admins.txt")
first_table = document["results"]
second_table = file["admins"]
new_one = first_table | second_table
First hash looks like this:
document = { "results" => [{"ip" => 10, "host" => 12},{"ip" => 13, "host" => 17}] }
The second hash is
file = { "admins" => [{"host" => 12, "name" => 12},{"host" => 17, "name" => 17}] }
I want merge these two hashes matching them by host by the same value to get
{ "new_one" => [{"ip" => 10, "host" => 12, "name" => 12}, {"ip" => 13, "host" => 17}, "name" => 17]
When I try new_one = first_table | second_tableit says test.rb:24:in <main>': undefined method|' for #Hash:0x00000002ca8be8 (NoMethodError) and when I try new_one = first_table.merge(second_table)its says test.rb:26:in <main>': undefined methodmerge' for #Array:0x00000002ce88b0(NoMethodError). So what is wrong with these hashes? One time they are hashes and the second time they are arrays? How to mach these hashes? The keys and values of host the same in both hashes.

How can I delete empty arrays/refs from a Perl hash?

Lets say I have the following Perl hash:
%hash = (
'A' => {
'B' => ['C', 'D', 'E'],
'F' => { 'G' => [], 'H' => [] },
'I' => []
} );
and I'd like to get rid of the []'s to get the hash result below:
%hash = (
'A' => [
'B' => ['C', 'D', 'E'],
'F' => [ 'G', 'H', 'I' ]
]
)
(I hope I got my {} and [] balanced, my apologies if not, but) essentially I'd like to make it so that no empty arrays/ref's exist. I'm sure this is possible/simple, but I'm not sure whether delete() will work, or if there's a better method or a Perl module out there. Can someone steer me in the right direction?
It appears like your data might be nested arbitrarily, and you want to walk through it recursively, rewriting certain patterns to others. For that, I'd be using Data::Visitor.
use Data::Visitor::Callback;
use List::MoreUtils 'all';
my $visitor = Data::Visitor::Callback->new(
hash => sub {
my ($self, $href) = #_;
# fold hashrefs with only empty arrayrefs as values into arrayrefs
if (all { ref $_ eq 'ARRAY' && !#{ $_ } } values %{ $href }) {
return [ keys %{ $href } ];
}
# strip k/v pairs with an empty arrayref as a value
return {
map {
$_ => $href->{$_}
} grep {
ref $href->{$_} ne 'ARRAY' || #{ $href->{$_} }
} keys %{ $href }
};
},
);
my %new_hash = %{ $visitor->visit(\%hash) };
This just illustrates the basic approach I'd use, and happens to work for the example input you gave. It might need various tweaks depending on what you want to do in the corner-cases pointed out in the other comments.
[This should be a comment, but I need the formatting.]
Your question is puzzling. (1) By what principle does the I key (from the original hash) end up inside the list for the F key (in the expected hash)? (2) And what should happen if F were to contain stuff besides the empty array refs (see my addition to the original hash)?
my %hash_orig = (
'A' => {
'B' => ['C', 'D', 'E'],
'F' => {
'G' => [],
'H' => [],
'Z' => ['FOO', 'BAR'], # Not in the OP's original.
},
'I' => [],
},
);
my %hash_expected = (
'A' => [
'B' => ['C', 'D', 'E'],
'F' => [ 'G', 'H', 'I'], # Where should the Z info go?
],
);
Walking a hash (tree, whatever) is a technique that any programmer should know. rafl uses a visitor module, but in some cases I think the cure is almost worse than the disease.
Is your expected output what you intended? It seems different that what you said in the text, as FM says. I use his hash in my example.
It's pretty easy if you use a queue. You start with the top-level hash. Every time you run into a hash ref, you add it to the queue. When you run into an array ref, you check that it has values and delete that key if it doesn't. Everything else you leave alone:
#!perl
use strict;
use warnings;
use 5.010;
my %hash = ( # From FM
'A' => {
'B' => ['C', 'D', 'E'],
'F' => {
'G' => [],
'H' => [],
'Z' => ['FOO', 'BAR'], # Not in the OP's original.
},
'I' => [],
},
);
my #queue = ( \%hash );
while( my $ref = shift #queue ) {
next unless ref $ref eq ref {};
KEY: foreach my $key ( keys %$ref ) {
if( ref $ref->{$key} eq ref {} ) {
push #queue, $ref->{$key};
next KEY;
}
elsif( ref $ref->{$key} eq ref [] ) {
delete $ref->{$key} if #{$ref->{$key}} == 0;
}
}
}
use Data::Dumper;
print Dumper( \%hash );
My output is:
$VAR1 = {
'A' => {
'F' => {
'Z' => [
'FOO',
'BAR'
]
},
'B' => [
'C',
'D',
'E'
]
}
};
That output sounds more like what you are asking for, rather than the reorganization that you specify. Can you clarify the output?

Resources