Java - Printing a maze using a formatted Stringbuilder - printing

I would like to create a maze with a StringBuilder that must have a certain format to match a specific output. I am using the following code to do that, but it shaves off the first row of the output.
The given example is a single string that looks like this:
final String EXAMPLE01 = "############## ## ############ # # ## # # ##### ## # # # ## ### # # # ## # # # # #### # # # # ## # # #### ####### ## ##############";
Here is the code to format the string:
private void init(Maze z) {
/**
* initializes de.uniwue.gdp.labyrinth.Explorer
*/
maze = z; //set maze
pov = POV.SOUTH; //set default point of view to South
idx = maze.width() + 1; //set default index to (1,1) || starting index
str = new StringBuilder(); //init empty StringBuilder
for (int i = 0; i < maze.width() * maze.height(); ++i) {
if (str.length() != 0 && (str.length() % maze.width() == 0)){ //use modulo to find linebreaks
str.append("\n");
}
str.append('#'); //set all fields to not explored or wall
}
str.setCharAt(idx, ' '); //set starting field to explored
updateDirections(); //init numMarks & validDirections
}
the output looks like this:
But should look like this:
Thank you very much in advance!

On this line:
for (int i = 0; i < maze.width() * maze.height(); ++i)
Try i++ instead of ++i.
'++' before 'i' increments it prior to evaluation '++' after 'i' increments it after evaluation. In the case the loop may be starting at 1 instead of 0.

Related

Handling error with regressions inside a parallel foreach loop

Hi I am having issues regarding a foreach loop where in every iteration I estimate a regression on a subset of the data with a different list of controls on several outcomes. The problem is that for some outcomes in some countries I only have missing values and therefore the regression function returns an error message. I would like to be able to run the loop, get the output with NAs or a string saying "Error" for example instead of the coefficient table. I tried several things but they don't quite work with the .combine = rbind option and if I use .combine = c I get a very messy output. Thanks in advance for any help.
reg <- function(y, d, c){
if (missing(c))
feols(as.formula(paste0(y, "~ 0 + treatment")), data = d)
else {
feols(as.formula(paste0(y, "~ 0 + treatment + ", c)), data = d)
}
}
# Here we set up the parallelization to run the code on the server
n.cores <- 9 #parallel::detectCores() - 1
#create the cluster
my.cluster <- parallel::makeCluster(
n.cores,
type = "PSOCK"
)
# print(my.cluster)
#register it to be used by %dopar%
doParallel::registerDoParallel(cl = my.cluster)
# #check if it is registered (optional)
# foreach::getDoParRegistered()
# #how many workers are available? (optional)
# foreach::getDoParWorkers()
# Here is the cycle to parallel regress each outcome on the global treatment
# variable for each RCT with strata control
tables <- foreach(
n = 1:9, .combine = rbind, .packages = c('data.table', 'fixest'),
.errorhandling = "pass"
) %dopar% {
dt_target <- dt[country == n]
c <- controls[n]
est <- lapply(outcomes, function(x) reg(y = x, d = dt_target, c))
table <- etable(est, drop = "!treatment", cluster = "uid", fitstat = "n")
table
}

JavaScript eval how to use in groovy or grails

I want to assign a value to an existing variable, but the name of the variable is dynamic. How do I do that
def a1 = 0;
def b = 1;
eval("a${b} =1;");
print a1
No need for javascript here:
def name = 'someName';
def value = 'someValue';
new GroovyShell(this.binding).evaluate("${name} = '${value}'")
assert someName == value;
Though this doesn't answer your question exactly, an easy way around this is to drop your dynamic variables as map keys instead... avoid needing to eval them
def b = 1
def map = [:]
map."a${b}" = 1
assert map."a${b}" == 1
println(map) // result is [a1:1]

Using AKSampleDescriptor

Using AKSamplerDescriptor
I am using an adapted AKSampler example, in which I try to use the sforzando output of Fluid.sf3 melodicSounds. Sforzando creates .sfz files for each instrument, but all pointing for the global sample to a huge .wav file.
In all the instrument.sfz files there is an offset and endpoint description for the part of the wave file to be used.
When I load the .sfz file I get a crash due to memory problems. It seems that for every defined region in the .sfz file the complete .wav file (140 mB) is loaded again.
The most likely is that loading the sample file with the AKSampleDescriptor as done in the AKSampler example will ignore offset and endpoint (AKSampleDescriptor.startPoint and AKSampleDescriptor.endPoint) while reloading the complete .wav file.
Is there a way to load just the part start-to-end wanted from the sample file, because the complete file has al the sample data for all the instruments (I know and use polyphony that extracts only one instrument at the time and works fine, but this is for other use)
Or, and that seems the best to me, just load the file once and than have the sampledescriptors point to the data in memory
Good suggestions, Rob. I just ran into this one-giant-WAV issue myself, having never seen it before. I was also using Sforzando for conversion. I'll look into adding the necessary capabilities to AKSampler. In the meantime, it might be easier to write a program to cut up the one WAV file into smaller pieces and adjust the SFZ accordingly.
Here is some Python 2.7 code to do this, which I have used successfully with a Sforzando-converted sf2 soundfont. It might need changes to work for you--there is huge variability among sfz files--but at least it might help you get started. This code requires the PyDub library for manipulating WAV audio.
import os
import re
from pydub import AudioSegment
def stripComments(text):
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return " " # note: a space and not an empty string
else:
return s
pattern = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
re.DOTALL | re.MULTILINE
)
return re.sub(pattern, replacer, text)
def updateSplitList(splitList, regionLabels, values):
if len(values) > 3:
start = int(values['offset'])
length = int(values['end']) - start
name = regionLabels.pop(0)
splitList.add((name, start, length))
def lookupSplitName(splitList, offset, end):
for (name, start, end) in splitList:
if offset == start and end == end:
return name
return None
def outputGroupAndRegion(outputFile, splitList, values):
if values.has_key('lokey') and values.has_key('hikey') and values.has_key('pitch_keycenter'):
outputFile.write('<group> lokey=%s hikey=%s pitch_keycenter=%s\n' % (values['lokey'], values['hikey'], values['pitch_keycenter']))
elif values.has_key('key') and values.has_key('pitch_keycenter'):
outputFile.write('<group> key=%s pitch_keycenter=%s\n' % (values['key'], values['pitch_keycenter']))
if len(values) > 3:
outputFile.write(' <region> ')
if values.has_key('lovel') and values.has_key('hivel'):
outputFile.write('lovel=%s hivel=%s ' % (values['lovel'], values['hivel']))
if values.has_key('tune'):
outputFile.write('tune=%s ' % values['tune'])
if values.has_key('volume'):
outputFile.write('volume=%s ' % values['volume'])
if values.has_key('offset'):
outputFile.write('offset=0 ')
if values.has_key('end'):
outputFile.write('end=%d ' % (int(values['end']) - int(values['offset'])))
if values.has_key('loop_mode'):
outputFile.write('loop_mode=%s ' % values['loop_mode'])
if values.has_key('loop_start'):
outputFile.write('loop_start=%d ' % (int(values['loop_start']) - int(values['offset'])))
if values.has_key('loop_end'):
outputFile.write('loop_end=%d ' % (int(values['loop_end']) - int(values['offset'])))
outputFile.write('sample=samples/%s' % lookupSplitName(splitList, int(values['offset']), int(values['end'])) + '.wav\n')
def process(inputFile, outputFile):
# create a list of region labels
regionLabels = list()
for line in open(inputFile):
if line.strip().startswith('region_label'):
regionLabels.append(line.strip().split('=')[1])
# read entire input SFZ file
sfz = open(inputFile).read()
# strip comments and create a mixed list of <header> tags and key=value pairs
sfz_list = stripComments(sfz).split()
inSection = "none"
default_path = ""
global_sample = None
values = dict()
splitList = set()
# parse the input SFZ data and build up splitList
for item in sfz_list:
if item.startswith('<'):
inSection = item
updateSplitList(splitList, regionLabels, values)
values.clear()
continue
elif item.find('=') < 0:
#print 'unknown:', item
continue
key, value = item.split('=')
if inSection == '<control>' and key == 'default_path':
default_path = value.replace('\\', '/')
elif inSection == '<global>' and key == 'sample':
global_sample = value.replace('\\', '/')
elif inSection == '<region>':
values[key] = value
# split the wav file
bigWav = AudioSegment.from_wav(global_sample)
#print "%d channels, %d bytes/sample, %d frames/sec" % (bigWav.channels, bigWav.sample_width, bigWav.frame_rate)
frate = float(bigWav.frame_rate)
for (name, start, length) in splitList:
startMs = 1000 * start / frate
endMs = 1000 * (start + length) / frate
wav = bigWav[startMs : endMs]
wavName = 'samples/' + name + '.wav'
wav.export(wavName, format='wav')
# parse the input SFZ data again and generate the output SFZ
for item in sfz_list:
if item.startswith('<'):
inSection = item
outputGroupAndRegion(outputFile, splitList, values)
values.clear()
continue
elif item.find('=') < 0:
#print 'unknown:', item
continue
key, value = item.split('=')
if inSection == '<control>' and key == 'default_path':
default_path = value.replace('\\', '/')
elif inSection == '<global>' and key == 'sample':
global_sample = value.replace('\\', '/')
elif inSection == '<region>':
values[key] = value
dirPath = '000'
fileNameList = os.listdir(dirPath)
for fileName in fileNameList:
if fileName.endswith('.sfz'):
inputFile = os.path.join(dirPath, fileName)
outputFile = open(fileName, 'w')
print fileName
process(inputFile, outputFile)

Emulate string to label dict

Since Bazel does not provide a way to map labels to strings, I am wondering how to work around this via Skylark.
Following my partial horrible "workaround".
First the statics:
_INDEX_COUNT = 50
def _build_label_mapping():
lmap = {}
for i in range(_INDEX_COUNT):
lmap ["map_name%s" % i] = attr.string()
lmap ["map_label%s" % i] = attr.label(allow_files = True)
return lmap
_LABEL_MAPPING = _build_label_mapping()
And in the implementation:
item_pairs = {}
for i in range(_INDEX_COUNT):
id = getattr(ctx.attr, "map_name%s" % i)
if not id:
continue
mapl = getattr(ctx.attr, "map_label%s" % i)
if len(mapl.files):
item_pairs[id] = list(mapl.files)[0].path
else:
item_pairs[id] = ""
if item_pairs:
arguments += [
"--map", str(item_pairs), # Pass json data
]
And then the rule:
_foo = rule(
implementation = _impl,
attrs = dict({
"srcs": attr.label_list(allow_files = True, mandatory = True),
}.items() + _LABEL_MAPPING.items()),
Which needs to be wrapped like:
def foo(map={}, **kwargs):
map_args = {}
# TODO: Check whether order of items is defined
for i, item in enumerate(textures.items()):
key, value = item
map_args["map_name%s" % i] = key
map_args["map_label%s" % i] = value
return _foo(
**dict(map_args.items() + kwargs.items())
)
Is there a better way of doing that in Skylark?
To rephrase your question, you want to create a rule attribute mapping from string to label?
This is currently not supported (see list of attributes), but you can file a feature request for this.
Do you think using "label_keyed_string_dict" is a reasonable workaround? (it won't work if you have duplicated keys)

How to print the whole queue/array with UVM utility functions?

For UVM objects using `uvm_field_queue_int utility macro, UVM does not print out the whole queue when calling my_object.print()
# -----------------------------------------
# Name Type Size Value
# -----------------------------------------
# my_object my_object - #443
# data_q da(integral) 16 -
# [0] integral 32 'h203f922b
# [1] integral 32 'he4b3cd56
# [2] integral 32 'hd7477801
# [3] integral 32 'h3a55c481
# [4] integral 32 'h2abf98c4
# ... ... ... ...
# [11] integral 32 'hac0d672b
# [12] integral 32 'h3ba2cb5d
# [13] integral 32 'hbe924197
# [14] integral 32 'h3cc6d490
# [15] integral 32 'h69ae79da
# -----------------------------------------
What's the best way to have UVM print the whole queue?
The example code on EDA Playground: http://www.edaplayground.com/x/rS
Full credit goes to this forum post: http://forums.accellera.org/topic/1002-uvm-print-with-array-objects/
The UVM print() accepts an uvm_printer argument. Create a new uvm_table_printer object (child of uvm_printer), change it knobs values, and pass it to the print() method.
uvm_table_printer printer;
my_uvm_object m;
// ...
printer = new();
m = my_uvm_object::type_id::create("my_uvm_object");
printer.knobs.begin_elements = -1; // this indicates to print all
m.print(printer);
//Optionally you can specify numbers for begin/end
printer.knobs.begin_elements = 10; // prints the first 10; default: 5
printer.knobs.end_elements = 2; // also print the last 2; default: 5
m.print(printer);
This is useful when you want to affect the with in a particular uvm_object can can be made scalable by overriding the do_print() method.
Alternatively, if the change is intended to be global, there is a default printer that automatically created at root called uvm_default_printer. Changing the knob values of this printer will alter the printing behavior of all prints using default.
uvm_default_printer.knobs.begin_elements=-1; // this indicates to print all
m.print(); // will print all elements
//Optionally you can specify numbers for begin/end
uvm_default_printer.knobs.begin_elements = 2; // prints the first 2; default: 5
uvm_default_printer.knobs.end_elements = 3; // also print the last 3; default: 5
m.print(); // will print the first 2 and last 3 elements
working example: http://www.edaplayground.com/x/Ze

Resources