Python Error - Google Foobar - python-2.7

To anyone who has done Google's Foobar challenge before, have you ever encountered an error like this?
Verifying solution...
{
"bytes" : "CAAaIgogQ291bGQgbm90IGZpbmQgJ2Fuc3dlcicgZnVuY3Rpb24"
}
I've tested my solution in Visual Studio, and it works fine, and it gives accurate output. I only have 36 hours remaining to submit my solution, and this is the final challenge, so I would really like to get credit for completing it. Here's the code I'm trying to verify:
from fractions import *
from math import factorial as fac
def cycle_index(n):
return [(coeff(term), term) for term in foo(n, n)]
def foo(n, lim):
soln_set = []
if n > 0:
for x in range(lim, 0, -1):
if x == 1:
soln_set.append([(1, n)])
else:
for y in range(int(n / x), 0, -1):
recurse = foo(n - x * y, x - 1)
if len(recurse) == 0:
soln_set.append([(x, y)])
for soln in recurse:
soln_set.append([(x, y)] + soln)
return soln_set
def coeff(term):
val = 1
for x, y in term:
val *= fac(y) * x ** y
return Fraction(1, val)
def cross(cycle_a, cycle_b):
term = []
for len_a, freq_a in cycle_a:
for len_b, freq_b in cycle_b:
lcm = len_a * len_b / gcd(len_a, len_b)
term.append((lcm, int(len_a * freq_a * len_b * freq_b / lcm)))
return term
def answer(w, h, s):
total = 0
cycidx_cols = cycle_index(w)
cycidx_rows = cycle_index(h)
for col_coeff, col_cycle in cycidx_cols:
for row_coeff, row_cycle in cycidx_rows:
coeff = col_coeff * row_coeff
cycle = cross(col_cycle, row_cycle)
value = 1
for _, power in cycle:
value *= s ** power
total += coeff * value
return total
I found someone else's solution last week and verified it through Foobar, but I wanted to write my own to get a deeper understanding. I've compared results side-by-side, and they are exact, so I know my code gives accurate results.
Out of curiosity, I just retried verifying the other person's solution again, and now I am getting the same error with a slightly different output even though it worked just fine when I tried last week:
Verifying solution...
{
"bytes" : "CAEQARABEAEQARABEAEQARABEAEQAQ"
}
I'm not sure where else to go. I was so excited that I had come up with my own solution to the challenge, but now I'm panicking that it won't matter. Any suggestions?
UPDATE - June 29, 2018, 6:00pm CST
The deadline passed for me last night, and I was unable to submit my code in time. I made sure to use the recruitme command before time ran out just in case I got booted out. However, I am still able to view my current status, and it let me request another Level 5 challenge. So, I will be checking periodically to see if the test cases start showing up again, and I will be sure to update this when they do. I would highly recommend that anyone on lower levels wait until I confirm that this issue is fixed before attempting to request another challenge.
UPDATE - June 30, 2018, 5:00am CST
According to the pattern found by #RobertAnsel, I have completed the challenge. I confirmed this pattern by hardcoding the answer function to output solutions to the test cases given in the instructions. The resulting errors matched exactly with the predicted output. I also found an interesting thread on Google's Support Forum (linked here) where something similar happened to a bunch of Foobar challengers. It seems like their error was fixed by Google after about three days, but unfortunately, it also looks like a lot of people who timed out were not given another chance. Nevertheless, this will probably resolve itself within the next day or two. I will continue trying to verify and submit my solution until I am successful.
UPDATE - July 4, 2018, 12:00am CST
This issue seems to have been more or less resolved. Refer to the chosen answer for more details. Thanks a ton to #RobertAnsel for all the help! Some additional info: I was able to verify my current challenge, but upon submission, I was told that my time for the problem had expired. After logging in again, I was able to request a new challenge. I noticed I was also able to use the recruitme command again. I am not sure if this means they did not receive the first request or if you are allowed to use that command multiple times. Regardless, I am relieved that I am able to continue forward with Foobar. Best of luck to the rest of you!

This may not be the answer you're looking for, but that first "bytes" string is a base64 encoding of the following error message:
"Could not find 'answer' function".
I've done the Foobar challenge myself, and that should only happen if you are trying to verify a file that is missing a defined "answer" function, which obviously you are not. Are you certain that the spec they provide has 3 arguments vs an array with 3 items?
The second message (CAEQARABEAEQARABEAEQARABEAEQAQ), while valid base64, doesn't map to ASCII or UTF-8. After some closer analysis of some of the other strings others have posted, I've concluded that this is the base64 encoded version of the test output. It isn't very human readable, but I believe it is 11 2-byte chunks, the first of which is unhelpful, but the following 10 are the test result for each of the corresponding test cases. In the case of this message it converts to binary as:
0000100000000001 <- unknown pre-pended info
0001000000000001 <- passing test 1
0001000000000001 <- passing test 2
0001000000000001 <- passing test 3
0001000000000001 <- passing test 4
0001000000000001 <- passing test 5
0001000000000001 <- passing test 6
0001000000000001 <- passing test 7
0001000000000001 <- passing test 8
0001000000000001 <- passing test 9
0001000000000001 <- passing test 10
The '1's at the end of each of these lines indicates that all 10 tests are passing.
A failing test case is represented by the following string:
0001000000000000 <- failing test case
This should help you (and others) continue testing to achieve fully passing tests (you can complete your own analysis with tools like this one: https://cryptii.com/base64-to-binary), but unfortunately this will not help you move forward with your final submission until Google remediates the issue on their end.
UPDATE: July 2, 8PM PDT
After reaching out to a couple of Google recruiters about the issue they were able to confirm that the issue was identified and is believed to be resolved today.
If you re-save your code after making a change to it (whitespace should be fine), you should be able to test and submit correctly. Alternatively, you may now be able to request a new challenge anyway.

There will be nothing for you to solve this issue, it is a issue on Google's site, as the Google Foobar API is responding with this message as I've found out.
Notherless your best bet will be to use the feedback command and give Google Foobar a feedback and mark it as a bug. This will be more likely to reach their attention and helping them to fix this issue!

Related

How to define tolerance level in CBC solver using pyomo's solverfactory?

I am trying to solve a MIP with CBC using pyomo's solver factory, however running into some infeasibility issues. I wanted to first try configuring the tolerance level and see if that works before diving deep into the data points that could cause the infeasibility.
However when I use this command, the cbc solver outputs an error:
options = {
'tol': 0.0001
}
solver = SolverFactory(solver_type)
solver.options.update(options)
Can anyone help me with the understanding how to define tolerance level in cbc? Thanks!
So, it depends a bit. Assuming you are looking for the tolerance for a mixed integer program, the keyword for CBC is 'ratio'.
Here is a setup that runs 6 threads, max 20 seconds, ratio of 0.02 (2% gap)
### SOLVE
solver = pyo.SolverFactory('cbc')
solver.options = {'sec': 20, 'threads': 6, 'ratio': 0.02}
results = solver.solve(mdl)
print(results)
There are several different types of syntax that are acceptable here... You can pass the options in to the SolverFactory, etc... but this works fine for me.
As another trick, I always get hung up on the correct keywords for these solvers.... If you have CBC installed properly, you can just go to the terminal, open CBC with the command cbc, which should give you the 'coin' prompt and type "?" to see the commands. Then you can use the command and double '??' to get details. This also works for glpk which is super helpful.
For instance:
% cbc
Welcome to the CBC MILP Solver
Version: 2.10.5
Build Date: Dec 5 2021
CoinSolver takes input from arguments ( - switches to stdin)
Enter ? for list of commands or help
Coin:?
In argument list keywords have leading - , -stdin or just - switches to stdin
One command per line (and no -)
abcd? gives list of possibilities, if only one + explanation
abcd?? adds explanation, if only one fuller help
abcd without value (where expected) gives current value
abcd value sets value
Commands are:
Double parameters:
dualB(ound) dualT(olerance) primalT(olerance) primalW(eight) psi
zeroT(olerance)
Branch and Cut double parameters:
allow(ableGap) cuto(ff) inc(rement) integerT(olerance) preT(olerance)
pumpC(utoff) ratio(Gap) sec(onds)
Integer parameters:
force(Solution) idiot(Crash) maxF(actor) maxIt(erations) output(Format)
randomS(eed) slog(Level) sprint(Crash)
Branch and Cut integer parameters:
cutD(epth) cutL(ength) depth(MiniBab) hot(StartMaxIts) log(Level) maxN(odes)
maxSaved(Solutions) maxSo(lutions) passC(uts) passF(easibilityPump)
passT(reeCuts) pumpT(une) randomC(bcSeed) slow(cutpasses) strat(egy)
strong(Branching) trust(PseudoCosts)
Keyword parameters:
allC(ommands) chol(esky) crash cross(over) direction error(sAllowed)
fact(orization) keepN(ames) mess(ages) perturb(ation) presolve
printi(ngOptions) scal(ing) timeM(ode)

How to use tf.contrib.rnn.convLSTMCell class in tensorflow

I would like to use a convolution LSTM in my research but I'm having a difficult time figuring out the exact way to implement this class in tensorflow. Here is what I have so far. I get no errors, but I am seriously doubting my implementation. Can anyone confirm if I am doing this correctly?
n_input = 4
x = tf.placeholder(tf.float32,shape=[None,n_input,HEIGHT,WIDTH,2])
y = tf.placeholder(tf.float32,shape=[None,HEIGHT,WIDTH,2])
convLSTM_cell = tf.contrib.rnn.ConvLSTMCell(
conv_ndims=2,
input_shape = [HEIGHT,WIDTH,DEPTH],
output_channels=2,
kernel_shape=[3,3]
)
outputs, states = tf.nn.dynamic_rnn(convLSTM_cell, x, dtype=tf.float32)
weights = tf.Variable(tf.random_normal([3,3,2,2]))
biases = tf.Variable(tf.random_normal([2]))
conv_out = tf.nn.conv2d(outputs[-1],weights,strides=[1,1,1,1],padding='SAME')
out = tf.nn.sigmoid(conv_out + biases)
UPDATE:
printing the size of outputs gives the shape=(?,4,436,1024,2) but I think I want (?,5,436,1024,2) or (?,1,436,1024,2).
UPDATE2:
So according to a fellow lab mate, the 4 outputs corresponds to the lstm outputs for each frame and so it is working correctly. Apparently all I have to do is take output #4 and that is the predicted future time frame.
A stackoverflow confirmation would put my mind at ease on this whole thing.
Yes, you are correct!
The output dimension will match the input dimension. If you actually want the (?,5,436,1024,2) output, you will have to look at the history, state.h. the last four [-4] of it will still correspond to the output.

Declaring variables in Python 2.7x to avoid issues later

I am new to Python, coming from MATLAB, and long ago from C. I have written a script in MATLAB which simulates sediment transport in rivers as a Markov Process. The code randomly places circles of a random diameter within a rectangular area of a specified dimension. The circles are non-uniform is size, drawn randomly from a specified range of sizes. I do not know how many times I will step through the circle placement operation so I use a while loop to complete the process. In an attempt to be more community oriented, I am translating the MATLAB script to Python. I used the online tool OMPC to get started, and have been working through it manually from the auto-translated version (was not that helpful, which is not surprising). To debug the code as I go, I use the
MATLAB generated results to generally compare and contrast against results in Python. It seems clear to me that I have declared variables in a way that introduces problems as calculations proceed in the script. Here are two examples of consistent problems between different instances of code execution. First, the code generated what I think are arrays within arrays because the script is returning results which look like:
array([[ True]
[False]], dtype=bool)
This result was generated for the following code snippet at the overlap_logix operation:
CenterCoord_Array = np.asarray(CenterCoordinates)
Diameter_Array = np.asarray(Diameter)
dist_check = ((CenterCoord_Array[:,0] - x_Center) ** 2 + (CenterCoord_Array[:,1] - y_Center) ** 2) ** 0.5
radius_check = (Diameter_Array / 2) + radius
radius_check_update = np.reshape(radius_check,(len(radius_check),1))
radius_overlap = (radius_check_update >= dist_check)
# Now actually check the overalp condition.
if np.sum([radius_overlap]) == 0:
# The new circle does not overlap so proceed.
newCircle_Found = 1
debug_value = 2
elif np.sum([radius_overlap]) == 1:
# The new circle overlaps with one other circle
overlap = np.arange(0,len(radius_overlap), dtype=int)
overlap_update = np.reshape(overlap,(len(overlap),1))
overlap_logix = (radius_overlap == 1)
idx_true = overlap_update[overlap_logix]
radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
A similar result for the same run was produced for variables:
radius_check_update
radius_overlap
overlap_update
Here is the same code snippet for the working MATLAB version (as requested):
distcheck = ((Circles.CenterCoordinates(1,:)-x_Center).^2 + (Circles.CenterCoordinates(2,:)-y_Center).^2).^0.5;
radius_check = (Circles.Diameter ./ 2) + radius;
radius_overlap = (radius_check >= distcheck);
% Now actually check the overalp condition.
if sum(radius_overlap) == 0
% The new circle does not overlap so proceed.
newCircle_Found = 1;
debug_value = 2;
elseif sum(radius_overlap) == 1
% The new circle overlaps with one other circle
temp = 1:size(radius_overlap,2);
idx_true = temp(radius_overlap == 1);
radius = distcheck(1,idx_true) - (Circles.Diameter(1,idx_true)/2);
In the Python version I have created arrays from lists to more easily operate on the contents (the first two lines of the code snippet). The array within array result and creating arrays to access data suggests to me that I have incorrectly declared variable types, but I am not sure. Furthermore, some variables have a size, for example, (2L,) (the numerical dimension will change as circles are placed) where there is no second dimension. This produces obvious problems when I try to use the array in an operation with another array with a size (2L,1L). Because of these problems I started reshaping arrays, and then I stopped because I decided these were hacks because I had declared one, or more than one variable incorrectly. Second, for the same run I encountered the following error:
TypeError: 'numpy.ndarray' object is not callable
for the operation:
radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
which occurs at the bottom of the above code snippet. I have posted the entire script at the following link because it is probably more useful to execute the script for oneself:
https://github.com/smchartrand/MarkovProcess_Bedload
I have set-up the code to run with some initial parameter values so decisions do not need to be made; these parameter values produce the expected results in the MATLAB-based script, which look something like this when plotted:
So, I seem to specifically be having issues with operations on lines 151-165, depending on the test value np.sum([radius_overlap]) and I think it is because I incorrectly declared variable types, but I am really not sure. I can say with confidence that the Python version and the MATLAB version are consistent in output through the first step of the while loop, and code line 127 which is entering the second step of the while loop. Below this point in the code the above documented issues eventually cause the script to crash. Sometimes the script executes to 15% complete, and sometimes it does not make it to 5% - this is due to the random nature of circle placement. I am preparing the code in the Spyder (Python 2.7) IDE and will share the working code publicly as a part of my research. I would greatly appreciate any help that can be offered to identify my mistakes and misapplications of python coding practice.
I believe I have answered my own question, and maybe it will be of use for someone down the road. The main sources of instruction for me can be found at the following three web pages:
Stackoverflow Question 176011
SciPy FAQ
SciPy NumPy for Matlab users
The third web page was very helpful for me coming from MATLAB. Here is the modified and working python code snippet which relates to the original snippet provided above:
dist_check = ((CenterCoordinates[0,:] - x_Center) ** 2 + (CenterCoordinates[1,:] - y_Center) ** 2) ** 0.5
radius_check = (Diameter / 2) + radius
radius_overlap = (radius_check >= dist_check)
# Now actually check the overalp condition.
if np.sum([radius_overlap]) == 0:
# The new circle does not overlap so proceed.
newCircle_Found = 1
debug_value = 2
elif np.sum([radius_overlap]) == 1:
# The new circle overlaps with one other circle
overlap = np.arange(0,len(radius_overlap[0]), dtype=int).reshape(1, len(radius_overlap[0]))
overlap_logix = (radius_overlap == 1)
idx_true = overlap[overlap_logix]
radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2)
In the end it was clear to me that it was more straightforward for this example to use numpy arrays vs. lists to store results for each iteration of filling the rectangular area. For the corrected code snippet this means I initialized the variables:
CenterCoordinates, and
Diameter
as numpy arrays whereas I initialized them as lists in the posted question. This made a few mathematical operations more straightforward. I was also incorrectly indexing into variables with parentheses () as opposed to the correct method using brackets []. Here is an example of a correction I made which helped the code execute as envisioned:
Incorrect: radius = dist_check(idx_true,1) - (Diameter(idx_true,1) / 2)
Correct: radius = dist_check[idx_true] - (Diameter[0,idx_true] / 2)
This example also shows that I had issues with array dimensions which I corrected variable by variable. I am still not sure if my working code is the most pythonic or most efficient way to fill a rectangular area in a random fashion, but I have tested it about 100 times with success. The revised and working code can be downloaded here:
Working Python Script to Randomly Fill Rectangular Area with Circles
Here is an image of a final results for a successful run of the working code:
The main lessons for me were (1) numpy arrays are more efficient for repetitive numerical calculations, and (2) dimensionality of arrays which I created were not always what I expected them to be and care must be practiced when establishing arrays. Thanks to those who looked at my question and asked for clarification.

Why is GLSL log returning the wrong result? (Intel Driver)

I am doing some maths on the GPU and reading the result.
And I am getting the wrong value From log. I have verified this for values 0 - 10, 20, 30, 40.
If I hard code the value (as you can see bellow under verify) I get the right result spat out. However if I use log with the hard coded value that should return the same result, I get the wrong result spat out.
This is the kind of thing I have been doing in my function.
vec4 IScale(vec4 value)
{
switch(uScaleType_i)
{
case Log:
//value = log(value);
value = vec4(1,1,1,1);
value.r = log(5);
//verifiy
//value.r = 0.698970004
break;
case Sqrt:
value = sqrt(value);
break;
case None:
break;
}
return value;
}
I am wondering is there any sense here. I have added the results of what I am getting back into excel and done a graph. At first Its almost like its double the correct value but its not quite that clean, it gets further and further away.
Is there any other explanation for this other than a driver issue? I cant think of anything else to check!
And if so how can i possibly work around it, other than refactoring my code to do it on the CPU? And why can't I find evidence online to back this up? I am completely utterly baffled!
I am running on a laptop with:
(Intel(R) HD Graphics 4000 with 132 ext.)
p.s. Sqrt is fine and I get the values I would expect.
p.p.s I checked, I have not accidentally created a function called "log"
I believe you are tripping over the base used for the log. In Excel the base is 10 however in glsl it is e.
To get the right result you should divide the result with the log of the base you want.
value = log(value)/log(10);
Or in excel you can use LN(RC[-1])
This is as per the specification. log() will return the natural logarithm, i.e. the logarithm to the base e. Not the base 10 logarithm.

OverflowError in a for loop

I'm working on problem 3 of Project Euler using Python, but I can't seem to solve the problem without running into the following error: "OverflowError: range() result has too many items"
I'm wondering if there's a way to increase the allowed range? My code looks as follows:
target = 600851475143
largest_prime_factor = 1
#find largest prime factor of target
for possible_factor in range(2,(target/2)+1):
if target % possible_factor == 0:
is_prime = True
for i in range(2,(possible_factor/2)+1):
if possible_factor % i == 0:
is_prime = False
break
if is_prime:
largest_prime_factor = possible_factor
print largest_prime_factor
If you run into limitations of your computer or language while trying to solve a puzzle problem, or if it takes too long, it is an indication that probably there exists a better way (read: algorithm) to solve the problem. In your case, you do not need to loop to target / 2 + 1 (though that is a good educated upper bound). You only need to go as far as ceil(sqrt(target)).
And, as a sidenote, you can overcome this limitation by using xrange, which will create a generator, instead of range for Python 2, which creates a list. In Python 3, range will return a sequence type instead of a list by default.
Thanks to #Fernando for the clarification in the comments.