Dataset Viewer
Auto-converted to Parquet Duplicate
question
stringlengths
9
346
code
stringlengths
18
30.3k
answer
stringlengths
2
1.22k
src
stringclasses
3 values
Could you explain in as much detail as possible how you solved Task 3?
import elice_utils def give_average(): f = open("tpmon.txt",'r') year=1723 for line in f: if "MONTHLY" in line: continue p=line.strip().split(" ") temperatures=[] for i in p: if i != "": temperatures.append(i) Winter_average=(fl...
In No. 3, the lines were split with "", and only the number of index values that were not empty ("") was appended to the new list.In this list, we floated 0th, 1st, and added and then divided by 2 to get the winter average. Similarly, we floated the 6th and 7th to get the summer average.In the file format change functi...
cs1qa
What does the code produce ?
def calc_text_angle(start, end): text_angle = ((start + end) / 2.0) shift_angles = ((text_angle > (np.pi / 2)) & (text_angle < ((3 * np.pi) / 2))) text_angle[shift_angles] = (text_angle[shift_angles] + np.pi) return text_angle
a column of text angle values based on the bounds of the wedge
codeqa
What does the code get ?
def volume_type_get_all(context, inactive=False): return IMPL.volume_type_get_all(context, inactive)
all volume types
codeqa
Please explain the ‘r’ and ‘w’ variables of open().
import elice_utils from time import sleep def merge(input_filenames, output_filename): # Implement here # ... output = open(output_filename, 'w') for files in input_filenames: f = open(files, 'r') data=f.read() output.write(data) output.write('\n') f.close() ...
'r' stands for read and'w' stands for write, and it is a variable that opens the file as read-only and write-only, respectively.In addition to this, there is also an append of'a' to append to the existing file.
cs1qa
For what purpose does the average pcoa vector values return ?
def summarize_pcoas(master_pcoa, support_pcoas, method='IQR', apply_procrustes=True): if apply_procrustes: support_pcoas = [list(sp) for sp in support_pcoas] master_pcoa = list(master_pcoa) for (i, pcoa) in enumerate(support_pcoas): (master_std, pcoa_std, m_squared) = procrustes(master_pcoa[1], pcoa[1]) su...
for the support pcoas
codeqa
Finally, I'll ask you to explain task5.
from cs1robots import* load_world('worlds/harvest2.wld') hubo=Robot(beepers=36) for i in range(5): hubo.move() hubo.turn_left() hubo.move() def turn_right(): for i in range(3): hubo.turn_left() for i in range(6): for j in range(5): hubo.pick_beeper() turn_right() hubo.mov...
Task5 seems to have multiple answers. I’m going to take the process of picking up the beeper in the diagonal direction I thought I could repeat it 6 times I used a loop Depending on the condition of i, the process of moving to the next diagonal I think it should be a little different, so only that part I used condition...
cs1qa
def zig(): hubo.turn_left() while hubo.front_is_clear(): hubo.move() else: turn_right() hubo.move() def zag(): turn_right() while hubo.front_is_clear(): hubo.move() else: if hubo.left_is_clear(): hubo.turn_left() hubo.move() 이 함수 두개가 어떤 역할을 하는지 설명해주세요
from cs1robots import * create_world() hubo = Robot() hubo.set_trace("blue") def turn_right(): for i in range (3): hubo.turn_left() def zig(): hubo.turn_left() while hubo.front_is_clear(): hubo.move() else: turn_right() hubo.move() def zag(): turn_right() while hubo.front_is_clear(): hubo.move() els...
First of all, zig() plays the role of Hubo turning left and going forward until it meets the wall, then turns right when it meets the wall and moves forward one space. zag() plays the role of Hubo turning to the right and going forward until there is a wall in front of him, and when it encounters a wall, it turns left ...
cs1qa
What does the code take ?
def paginate_search_results(object_class, search_results, page_size, page): paginator = Paginator(search_results['results'], page_size) try: page_number = paginator.validate_number(page) except InvalidPage: if (page == 'last'): page_number = paginator.num_pages else: raise Http404("Page is not 'last',...
edx - search results
codeqa
What do multidimensional laplace filter use ?
@docfiller def gaussian_laplace(input, sigma, output=None, mode='reflect', cval=0.0, **kwargs): input = numpy.asarray(input) def derivative2(input, axis, output, mode, cval, sigma, **kwargs): order = ([0] * input.ndim) order[axis] = 2 return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs) re...
gaussian second derivatives
codeqa
What is showing utility ?
def test_sys_info(): out = StringIO() sys_info(fid=out) out = out.getvalue() assert_true(('numpy:' in out))
test info
codeqa
l = [] for i in range(n): l.append(i) What is the reason why l = range(n) without this
import random def drawing_integers(lb, ub, trials): """ Make a list of the integers :param lb: the lower bound of the integers :param ub: the upper bound of the integers :param trials: the number of trials :return: an integers list. Ex) [1, 4, 3, 5, 2] """ list = [] for i in range(i...
I think it’s because range(n) is a list
cs1qa
What does this function do?
def metadef_property_get(context, namespace_name, property_name, session=None): session = (session or get_session()) return metadef_property_api.get(context, namespace_name, property_name, session)
Get a metadef property or raise if it does not exist.
pcsd
What does this function do?
@bdd.when('selection is not supported') def selection_not_supported(qapp): if qapp.clipboard().supportsSelection(): pytest.skip('OS supports primary selection!')
Skip the test if selection is supported.
pcsd
What does this function do?
@conf.commands.register def is_promisc(ip, fake_bcast='ff:ff:00:00:00:00', **kargs): responses = srp1((Ether(dst=fake_bcast) / ARP(op='who-has', pdst=ip)), type=ETH_P_ARP, iface_hint=ip, timeout=1, verbose=0, **kargs) return (responses is not None)
Try to guess if target is in Promisc mode. The target is provided by its ip.
pcsd
Please briefly explain how jump_go() proceeds among the implemented functions.
from cs1robots import * load_world("worlds/hurdles1.wld") hubo=Robot(beepers=1) hubo.set_trace("green") def turn_right(): for i in range(3): hubo.turn_left() def jump_go(): hubo.turn_left() while not hubo.right_is_clear(): hubo.move() turn_right() hubo.move() turn_right() while hub...
It's a function over hurdles I consider a hurdle more than one height I made the jump_go function so that I can do a long move() using the While function. If you go up and the right side becomes empty, it changes direction like Task1.
cs1qa
Finally, please explain the is_valid function and check function that you wrote in task 3.Please also explain how you could match the cards!
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 0 correct_list = [] def initialize(): # initial...
is_valid is a function that checks whether the two numbers entered are different number pads between 0 and 23, which have not yet been matched and flipped, and check checks whether two cards are the same person for two valid numbers, visualizes it, and creates a list of correct answers.This is a function to update.
cs1qa
Please explain each function in Task3 Hurdle
from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. # load_world('worlds/hurdles1.wld') # load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3....
The def turn_right() function is a function that makes Hubo turn to the right, and def jump_one_hurdle() is a code to go forward until there is no obstacle in front, cross the obstacle, stop the code if it is on the beeper, and go forward until there is no obstacle again if it is not above.
cs1qa
What does the code verify with expected results for sigmoid correction with cutoff equal to one and gain of 5 ?
def test_adjust_sigmoid_cutoff_one(): image = np.arange(0, 255, 4, np.uint8).reshape((8, 8)) expected = np.array([[1, 1, 1, 2, 2, 2, 2, 2], [3, 3, 3, 4, 4, 4, 5, 5], [5, 6, 6, 7, 7, 8, 9, 10], [10, 11, 12, 13, 14, 15, 16, 18], [19, 20, 22, 24, 25, 27, 29, 32], [34, 36, 39, 41, 44, 47, 50, 54], [57, 61, 64, 68, 72, 76...
the output
codeqa
What do helper func provide ?
def tostring(element, *args, **kwargs): global modules _bootstrap() t = _get_type(element) etree = modules.get(t, None) if (not etree): raise RuntimeError(('Unable to find the etree implementation related to %r (type %r)' % (element, t))) return etree.tostring(element, *args, **kwargs)
easy access to the moving target that is c{et }
codeqa
What does this function do?
def asquare(cdfvals, axis=0): ndim = len(cdfvals.shape) nobs = cdfvals.shape[axis] slice_reverse = ([slice(None)] * ndim) islice = ([None] * ndim) islice[axis] = slice(None) slice_reverse[axis] = slice(None, None, (-1)) asqu = ((- ((((2.0 * np.arange(1.0, (nobs + 1))[islice]) - 1) * (np.log(cdfvals) + np.log((1 ...
vectorized Anderson Darling A^2, Stephens 1974
pcsd
What does the code install ?
def add_feature(feature, package=None, source=None, limit_access=False, enable_parent=False, image=None, restart=False): cmd = ['DISM', '/Quiet', ('/Image:{0}'.format(image) if image else '/Online'), '/Enable-Feature', '/FeatureName:{0}'.format(feature)] if package: cmd.append('/PackageName:{0}'.format(package)) i...
a feature using dism args
codeqa
What does this function do?
def competency(): s3.filter = (FS('person_id$human_resource.type') == 1) field = s3db.hrm_competency.person_id field.widget = S3PersonAutocompleteWidget(ajax_filter='~.human_resource.type=1') return s3db.hrm_competency_controller()
RESTful CRUD controller used to allow searching for people by Skill
pcsd
What does this function do?
def restart(old, new, node_state): return sequentially(changes=[in_parallel(changes=[sequentially(changes=[StopApplication(application=old), StartApplication(application=new, node_state=node_state)])])])
Construct the exact ``IStateChange`` that ``ApplicationNodeDeployer`` returns when it wants to restart a particular application on a particular node.
pcsd
What did the code set ?
def libvlc_media_player_set_media(p_mi, p_md): f = (_Cfunctions.get('libvlc_media_player_set_media', None) or _Cfunction('libvlc_media_player_set_media', ((1,), (1,)), None, None, MediaPlayer, Media)) return f(p_mi, p_md)
the media that will be used by the media_player
codeqa
What copies a file ?
@contextmanager def safe_file(path, suffix=None, cleanup=True): safe_path = u'{0}.{1}'.format(path, (suffix or uuid.uuid4())) if os.path.exists(path): shutil.copy(path, safe_path) try: (yield safe_path) if cleanup: shutil.move(safe_path, path) else: shutil.copy(safe_path, path) finally: if cleanup: ...
a with - context
codeqa
Can you see what the root1 function does?
from cs1robots import * create_world() hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def root1(): hubo.turn_left() for i in range(9): hubo.move() turn_right() hubo.move() turn_right() for i in range(9): hubo.move() for...
Zigzag up and down repeatedly I made it as a function
cs1qa
What does this function do?
def device_exists(device): return os.path.exists(('/sys/class/net/%s' % device))
Check if ethernet device exists.
pcsd
What does this function do?
def getDoubleForLetter(letter, splitLine): return getDoubleAfterFirstLetter(splitLine[getIndexOfStartingWithSecond(letter, splitLine)])
Get the double value of the word after the first occurence of the letter in the split line.
pcsd
What does this function do?
def __virtual__(algorithm='sha512'): if ((not hasattr(hashlib, 'algorithms')) and (not hasattr(hashlib, algorithm))): return (False, 'The random execution module cannot be loaded: only available in Python >= 2.7.') return __virtualname__
Sanity check for compatibility with Python 2.6 / 2.7
pcsd
What do n and m mean in Task5?
from cs1robots import * # Your code must work for empty worlds of all possible sizes. #create_world(avenues=10, streets=10) create_world(avenues=11, streets=8) # create_world(avenues=6, streets=9) # create_world(avenues=1, streets=3) # create_world(avenues=2, streets=1) # create_world(avenues=1, streets=2) # ... hub...
In the case of the nm variable in 5, the row and column of the world were not given as fixed values, so this value was used as a variable to check and store this value.I wrote the code taking into account that it becomes the subtracted value.
cs1qa
What does the code convert to printable format ?
def prt_bytes(num_bytes, human_flag): if (not human_flag): return ('%12s' % num_bytes) num = float(num_bytes) suffixes = ([None] + list('KMGTPEZY')) for suffix in suffixes[:(-1)]: if (num <= 1023): break num /= 1024.0 else: suffix = suffixes[(-1)] if (not suffix): return ('%4s' % num_bytes) elif (nu...
a number > 1024
codeqa
How does the code render the comment list ?
def render_comment_list(parser, token): return RenderCommentListNode.handle_token(parser, token)
through the comments / list
codeqa
What does this function do?
@task def sudo(command, show=True, *args, **kwargs): if show: print_command(command) with hide(u'running'): return _sudo(command, *args, **kwargs)
Runs a command as sudo on the remote server.
pcsd
Why did you make attribute 'value' here?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 #correct_list = [] c = 0 class Card(): def _in...
so that i could display the pictures which had already been chosen correctly
cs1qa
What does this function do?
def import_file_to_module(module_name, fpath): try: _ast = import_file_to_ast(fpath, module_name) mod = imp.new_module(module_name) mod.__file__ = fpath eval(ast_compile(_ast, fpath, 'exec'), mod.__dict__) except (HyTypeError, LexException) as e: if (e.source is None): with open(fpath, 'rt') as fp: e...
Import content from fpath and puts it into a Python module. Returns the module.
pcsd
What does a query invoke using a builtin function return the ?
def serialize_query_with_map_builtin_function(test, serial, fcn): t = symbol('t', discover(iris)) expr = t.species.map(fcn, 'int') query = {'expr': to_tree(expr)} response = test.post('/compute', data=serial.dumps(query), headers=mimetype(serial)) assert ('OK' in response.status) respdata = serial.loads(response....
the map operation
codeqa
What does this function do?
def convert_to_relative(basePath, fileName): if fileName.startswith(basePath): fileName = fileName.replace(basePath, u'') if fileName.startswith(os.path.sep): fileName = fileName[1:] return fileName
Convert a absolut path to relative based on its start with basePath.
pcsd
Please explain the function of the record_number() function
from cs1robots import * load_world('worlds/add2.wld') hubo = Robot(beepers=100) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def record_number(order): n=0 while hubo.on_beeper(): hubo.pick_beeper() n+=1 return n*10**(order-1) def record_line(): a=0 for i in r...
The record_number() function is a function that memorizes the number of each digit. If it is a thousand digits, it is designed by recording the number of beepers placed in that place and multiplying it by the cube of 10.
cs1qa
What do true and false mean in state?
import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] decks=[] bj_board = Canvas(600, 400, 'dark green', 'B...
Is it to evaluate whether to turn over or show the front side based on that? is
cs1qa
What does this function do?
@log_call @utils.no_4byte_params def metadef_object_create(context, namespace_name, values): global DATA object_values = copy.deepcopy(values) object_name = object_values['name'] required_attributes = ['name'] allowed_attributes = ['name', 'description', 'json_schema', 'required'] namespace = metadef_namespace_ge...
Create a metadef object
pcsd
What does this function do?
def KITTI(manifest_file, manifest_root, rois_per_img=256, height=375, width=1242, inference=False): CLASSES = ('__background__', 'Car', 'Van', 'Truck', 'Pedestrian', 'Person_sitting', 'Cyclist', 'Tram', 'Misc', 'DontCare') do_transforms = (not inference) image_decode_cfg = dict(height=height, width=width, flip_enabl...
Returns the aeon dataloader configuration for KITTI dataset.
pcsd
What does this function do?
def cuda_set_device(dev_id): err_code = _cudamat.cuda_set_device(ct.c_int(dev_id)) if err_code: raise generate_exception(err_code)
Selects the CUDA device with the given ID.
pcsd
What does this function do?
def has_unaccent(cr): cr.execute("SELECT proname FROM pg_proc WHERE proname='unaccent'") return (len(cr.fetchall()) > 0)
Test if the database has an unaccent function. The unaccent is supposed to be provided by the PostgreSQL unaccent contrib module but any similar function will be picked by OpenERP.
pcsd
What does this function do?
@require_admin_context def instance_type_destroy(context, name): session = get_session() with session.begin(): instance_type_ref = instance_type_get_by_name(context, name, session=session) instance_type_id = instance_type_ref['id'] session.query(models.InstanceTypes).filter_by(id=instance_type_id).soft_delete()...
Marks specific instance_type as deleted.
pcsd
What does this function do?
@pytest.mark.skipif('not HAS_PATHLIB') def test_votable_path_object(): fpath = pathlib.Path(get_pkg_data_filename('data/names.xml')) table = parse(fpath).get_first_table().to_table() assert (len(table) == 1) assert (int(table[0][3]) == 266)
Testing when votable is passed as pathlib.Path object #4412.
pcsd
What does this function do?
def show_keypair(kwargs=None, call=None): if (call != 'function'): log.error('The show_keypair function must be called with -f or --function.') return False if (not kwargs): kwargs = {} if ('keyname' not in kwargs): log.error('A keyname is required.') return False keypairs = list_keypairs(call='function')...
Show the details of an SSH keypair
pcsd
Where did the code get doubled plane angle ?
def getDoubledRoundZ(overhangingSegment, segmentRoundZ): endpoint = overhangingSegment[0] roundZ = (endpoint.point - endpoint.otherEndpoint.point) roundZ *= segmentRoundZ if (abs(roundZ) == 0.0): return complex() if (roundZ.real < 0.0): roundZ *= (-1.0) roundZLength = abs(roundZ) return ((roundZ * roundZ) / ...
around z
codeqa
What does this function do?
def supply_item_entity_status(row): if hasattr(row, 'supply_item_entity'): row = row.supply_item_entity else: return None db = current.db s3db = current.s3db etable = s3db.supply_item_entity ekey = etable._id.name try: instance_type = row.instance_type except AttributeError: return None try: entity_i...
Virtual field: status
pcsd
What does the code normalize so that it can be used as an attribute to a python object ?
def normalize(val): if (val.find('-') != (-1)): val = val.replace('-', '_') return val
a string
codeqa
What is the role of n in task1?
from cs1robots import* load_world("worlds/harvest3.wld") hubo=Robot() hubo.set_trace("blue") def turn_right(): for i in range(3): hubo.turn_left() def move_beeper(): hubo.move() if hubo.on_beeper(): hubo.pick_beeper() n=0 for i in range(3): while hubo.front_is_clear(): move_beep...
In the absence of n, sentences 24-26 are executed last and the robot does not stop at the desired location, but ends at another location. Therefore, I used sentences 24-26 to repeat only two times.
cs1qa
How did you create the csv file in Task3?
import elice_utils import csv f=open("tpmon.txt",'r') year=1723 g=open("tpmon.csv",'w',newline='') w=csv.writer(g) for lines in f.readlines(): if 'F'in lines: continue else: lines.lstrip() lines.rstrip() temp=lines.split(" ") winter_avg=(float(temp[1])+float(temp[2]))/2 ...
We created the name in csv file format, sorted the data with ,, and replaced it with \n.
cs1qa
What is Task 3 jump_one_hurdle?
from cs1robots import * # Your code should work with any of the world files below. # TIP: Press Ctrl + '/' (or Cmd + '/' if you are using a Mac) # to comment out or restore the whole line of the code in the editor. #load_world('worlds/hurdles1.wld') #load_world('worlds/hurdles2.wld') load_world('worlds/hurdles3.wl...
If the front is blocked by hurdles, it goes over the hurdles, and if the right direction is not blocked, it continues to the right.
cs1qa
In task4, did you use x to check if you came to the original position??
from cs1robots import * load_world('worlds/rain2.wld') hubo = Robot(beepers=100, avenue=2, street=6, orientation='E') hubo.set_trace('blue') x=0 def check(): global x if hubo.on_beeper(): x=x+1 def turn_right(): for i in range(3): hubo.turn_left() def turn_around(): f...
I made sure we're back to the starting position
cs1qa
What does Card.correct do in Task 1?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 class Card: pass def initialize(): for i ...
Cards that are matched in the game will have the Card.correct value set to True and will be used later when printing the cart or checking conditions.
cs1qa
What did flag options convert ?
def bool_option(arg): return True
to auto directives
codeqa
What does setDepth do when stacking cards in draw_card?Which variables were you stacked in order?
import random from cs1graphics import * img_path = './images/' suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] face_names = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] value = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] bj_board = Canvas(600, 400, 'dark green', 'Black Jac...
Set the depth The higher the depth, the lower the image is
cs1qa
What does this function do?
def dataset_map_from_iterable(iterable): return {dataset.dataset_id: dataset for dataset in iterable}
Turn a list of datasets into a map from their IDs to the datasets.
pcsd
What does this function do?
def upload_may_enroll_csv(_xmodule_instance_args, _entry_id, course_id, task_input, action_name): start_time = time() start_date = datetime.now(UTC) num_reports = 1 task_progress = TaskProgress(action_name, num_reports, start_time) current_step = {'step': 'Calculating info about students who may enroll'} task_pro...
For a given `course_id`, generate a CSV file containing information about students who may enroll but have not done so yet, and store using a `ReportStore`.
pcsd
What does this function do?
def pass_context(f): def new_func(*args, **kwargs): return f(get_current_context(), *args, **kwargs) return update_wrapper(new_func, f)
Marks a callback as wanting to receive the current context object as first argument.
pcsd
What does that add by repeating result ?
def _my_trans(data): data_t = fft(data) data_t = np.concatenate([data_t[:, :, None], data_t[:, :, None]], axis=2) return (data_t, None)
an additional dimension
codeqa
Is there a reason not to repeat the one_round() function 3 times in Task1?
from cs1robots import * load_world('worlds/harvest3.wld') hubo = Robot(beepers=1) hubo.set_trace('blue') def turn_right(): hubo.turn_left() hubo.turn_left() hubo.turn_left() def collect_beeper(): if hubo.on_beeper(): hubo.pick_beeper() def go_straight(): for i in range(5): hubo.move() ...
I didn't repeat 3 times since I didn't need to move one space to the right at the end.
cs1qa
Please explain why you wrote line 5
f = open("average-latitude-longitude-countries.csv", "r") list1 = [] list2 = [] list3 = [] l = f.readline() for l in f: i = l.split(',') if len(i) > 4: A = i[1] B = i[2] C = A+','+B i.pop(1) i.pop(1) i.insert(1, C) a = i[2] b = float(a) c =...
I used it to skip the first line in the file.
cs1qa
What does this function do?
def _get_all_permissions(opts, ctype): builtin = _get_builtin_permissions(opts) custom = list(opts.permissions) _check_permission_clashing(custom, builtin, ctype) return (builtin + custom)
Returns (codename, name) for all permissions in the given opts.
pcsd
Can you briefly explain why you repeated 4 times in the first for statement?
from cs1robots import * load_world('worlds/hurdles1.wld') hubo = Robot() hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() for i in range(4): hubo.move() hubo.turn_left() hubo.move() turn_right() hubo.move() turn_right() hubo.move() hubo.turn_...
I thought the same process was repeated 5 times, In the last 5th process, because I do not execute all the processes I wrote in the for statement After repeating 4 times, the 5th process was written separately.
cs1qa
What does this function do?
def choose_result_int(*inputs): bitwidth = choose_result_bitwidth(*inputs) signed = any((tp.signed for tp in inputs)) return types.Integer.from_bitwidth(bitwidth, signed)
Choose the integer result type for an operation on integer inputs, according to the integer typing NBEP.
pcsd
In step 3, climb and goDown are shown as the same function in the code. Is there a reason you used them separately?
from cs1robots import * load_world('worlds/newspaper.wld') hubo = Robot(beepers = 10) hubo.set_trace('blue') def turn_right(): for i in range(3): hubo.turn_left() def turn(): for i in range(2): hubo.turn_left() def climb(): hubo.move() hubo.turn_left() hubo.move() turn_right(...
The first thing I conceived is a function that goes up and a function that goes down When I tried to make a function that goes up after making a function that goes down, I found it to be the same.
cs1qa
What does this function do?
def get_settings(): return {'mysql': {'host': '127.0.0.1', 'port': 3306, 'user': '', 'passwd': '', 'db': 'zabbix'}, 'slaveid': 3, 'disallow': '[^a-zA-Z0-9\\-_\\.]', 'internal_metric_interval': 30, 'dbrefresh': 10, 'sqlitedb': '/tmp/zabbix_bridge.db'}
MySQL replication credentials.
pcsd
What does this function do?
def check_blacklist(host, port, path): blacklist = conf.BLACKLIST.get() if (not blacklist): return True has_trailing_slash = path.endswith('/') path_elems = path.split('/') path_elems = [p for p in path_elems if p] canon_url = ('%s:%s/%s' % (host, port, '/'.join(path_elems))) if has_trailing_slash: canon_url...
Return true if this host:port path combo is allowed to be proxied.
pcsd
What does this function do?
def _recursive_escape(value, esc=conditional_escape): if isinstance(value, dict): return type(value)(((esc(k), _recursive_escape(v)) for (k, v) in value.iteritems())) elif isinstance(value, (list, tuple)): return type(value)((_recursive_escape(v) for v in value)) elif isinstance(value, basestring): return esc(...
Recursively escapes strings in an object. Traverses dict, list and tuples. These are the data structures supported by the JSON encoder.
pcsd
What does this function do?
def get_tiles_height_width_ratio(n_tiles, width_ratio=1.0): width = int(np.ceil(np.sqrt((n_tiles * width_ratio)))) return get_tiles_height_width(n_tiles, desired_width=width)
Get a height x width size that will fit n_tiles tiles.
pcsd
Briefly explain the name and action of the function you add in Task1!
from cs1robots import * load_world('worlds/add34.wld') my_robot = Robot() ''' Abstract, Final, Static class "Logic". Contains useful logics, which are frequently used. Since I started programming with Java, "global functions" do not look so good for me :D ''' class Logic: @staticmethod def rpt(fu, i, ar...
solve_assignment. It repeats add_digit that adds the number of digits to the currently standing column, and performs retrieval and map end processing.
cs1qa
Please tell me the name of the function you are adding in Task1!
from cs1robots import * cnt=0 def go(a): for i in range(a): slave.move() def turn(a): for i in range(a): slave.turn_left() def pick_all(): global cnt while(slave.on_beeper()): slave.pick_beeper() cnt+=1 def drop_all(): global cnt for i in range(cnt): ...
First, number 1 is over_ten, which simply sums up the numbers above and below and then implements decimal rounding that needs to be executed.
cs1qa
What does valid range mean in is_valid function
from cs1graphics import * import time canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initialize cards ...
Refers to 0-23
cs1qa
What is vis?
from cs1graphics import * import time from random import * canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def vis(): a=len(corr...
The vis function is a function that puts the already matched cards back on the canvas because the canvas is cleared when you print_cards.
cs1qa
What does the code return ?
@register.simple_tag(takes_context=True) def zinnia_loop_template(context, default_template): (matching, context_object) = get_context_first_matching_object(context, ['category', 'tag', 'author', 'pattern', 'year', 'month', 'week', 'day']) context_positions = get_context_loop_positions(context) templates = loop_temp...
a selected template
codeqa
What do minions support ?
def __virtual__(): return ('sysctl.show' in __salt__)
sysctl
codeqa
Please explain how deposit works in task 1!
balance = 0 def deposit(money) : # Input : (Integer) The amount of money that a user wants to deposit # Output : (None) No Output global balance # Add the money to the current balance balance = balance + int(money) print("You deposited "+ str(money) + " won") ################# def withdraw...
In the deposit function, I made a function that converts the input money value from str to int form, adds it, and prints it.
cs1qa
How do files serve ?
def static(prefix, view=serve, **kwargs): if ((not settings.DEBUG) or (prefix and ('://' in prefix))): return [] elif (not prefix): raise ImproperlyConfigured('Empty static prefix not permitted') return [url(('^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/'))), view, kwargs=kwargs)]
in debug mode
codeqa
Why did you do num1-=1 and num2-=1 at the 138th and 139th?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] global num1 global num2 num1 = -...
The reason for substituting -1 for num1 and num2 was to print only the correct list when an incorrect answer was answered.
cs1qa
What d i referencing ?
def find_name(name, state, high): ext_id = [] if (name in high): ext_id.append((name, state)) elif (state == 'sls'): for (nid, item) in six.iteritems(high): if (item['__sls__'] == name): ext_id.append((nid, next(iter(item)))) else: for nid in high: if (state in high[nid]): if isinstance(high[nid...
the given name
codeqa
What does this function do?
def generateColorMap(): Map = cm.jet(np.arange(256)) stringColors = [] for i in range(Map.shape[0]): rgb = (int((255 * Map[i][0])), int((255 * Map[i][1])), int((255 * Map[i][2]))) stringColors.append(struct.pack('BBB', *rgb).encode('hex')) return stringColors
This function generates a 256 jet colormap of HTML-like hex string colors (e.g. FF88AA)
pcsd
What does this function do?
def split_on_newlines(s): res = [] for x in s.split('\r\n'): for y in x.split('\r'): res.extend(y.split('\n')) return res
Splits s on all of the three newline sequences: " ", "", or "
pcsd
For task 2, is there a way you put in ```while not hubo.on_beeper(): main()``` this code?
from cs1robots import * #create_world() load_world('worlds/hurdles1.wld') hubo= Robot() hubo.set_trace('blue') hubo.move() def right(): for i in range(3): hubo.turn_left() def main(): hubo.turn_left() hubo.move() right() hubo.move() right() hubo.move() hubo.turn_left() hubo.m...
so that the main() function get executed as long as hubo is not on beeper when hubo is on beeper, the loop stops and hubo pick up the beeper
cs1qa
How did you notice that there is a window in Task4?
from cs1robots import * # Your code must work for both of the worlds below. load_world('worlds/rain1.wld') # load_world('worlds/rain2.wld') # Initialize your robot at the door of the house. hubo = Robot(beepers=100, avenue=2, street=6, orientation='E') # Now close all the windows in the house! def turn_right(): ...
In Task 4, the difference between the window and the simply empty left was judged by whether there was a wall on the left even when one more space was taken. Because if it were a window, there would have to be a wall in front of it.
cs1qa
What does this function do?
def _search_by_lun(disks_service, lun_id): res = [disk for disk in disks_service.list(search='disk_type=lun') if (disk.lun_storage.id == lun_id)] return (res[0] if res else None)
Find disk by LUN ID.
pcsd
What does this function do?
def get_sql_flush(style, tables, sequences): sql = [('%s %s;' % (style.SQL_KEYWORD('TRUNCATE'), style.SQL_FIELD(quote_name(table)))) for table in tables]
Return a list of SQL statements required to remove all data from all tables in the database (without actually removing the tables themselves) and put the database in an empty \'initial\' state
pcsd
How did you write the merge function in Task 1?
import elice_utils from time import sleep def merge(input_filenames, output_filename): with open(output_filename, 'w') as f: for filename in input_filenames: file = open(filename, 'r') for line in file.readlines(): f.write(line) file.close() merge(['kais...
Simply open each input file and write it to a file (f) that combines the contents.
cs1qa
Why do I need to process float() after receiving input from Task 2?
def is_triangle(a, b, c): return ("YES" if (a < b + c) and (b < a + c) and (c < a + b) else "NO") a = float(input('Side a: ')) b = float(input('Side b: ')) c = float(input('Side c: ')) print(is_triangle(a,b,c))
Since all the contents obtained from the input function are treated as strings, we changed the data type!
cs1qa
What does this function do?
@utils.arg('--flavor', default=None, metavar='<flavor>', help=_("Name or ID of flavor (see 'nova flavor-list').")) @utils.arg('--image', default=None, metavar='<image>', help=_("Name or ID of image (see 'glance image-list'). ")) @utils.arg('--image-with', default=[], type=_key_value_pairing, action='append', metavar='<...
Boot a new server.
pcsd
Please also explain the average_integers() function in task2!
import random def drawing_integers(lb, ub, trials): """ Make a list of the integers :param lb: the lower bound of the integers :param ub: the upper bound of the integers :param trials: the number of trials :return: an integers list. Ex) [1, 4, 3, 5, 2] """ list1=[] for i in range(t...
A variable is created and all elements of the input list are added and assigned.After that, the variable is divided by the length of the input list and the average is calculated and returned.
cs1qa
I am curious what it means to have the word pass at the end of the function!!
def fibonacci(upper_bound): F=[0,1] while True: if F[-1]+F[-2]< upper_bound: F.append(F[-1]+F[-2]) else: return F pass print(fibonacci(10000))
Basically, it is supposed to work well even if you just run it before implementing it
cs1qa
What does the code rewrite ?
def rewrite_file(filename): with open(filename, 'rU') as file_obj: content_lines = file_obj.read().split('\n') new_content = [] for line in content_lines: new_content.append(transform_line(line)) with open(filename, 'w') as file_obj: file_obj.write('\n'.join(new_content))
a given pb2 modules
codeqa
What does this function do?
def _delete_current_allocs(conn, allocs): for alloc in allocs: rp_id = alloc.resource_provider.id consumer_id = alloc.consumer_id del_sql = _ALLOC_TBL.delete().where(sa.and_((_ALLOC_TBL.c.resource_provider_id == rp_id), (_ALLOC_TBL.c.consumer_id == consumer_id))) conn.execute(del_sql)
Deletes any existing allocations that correspond to the allocations to be written. This is wrapped in a transaction, so if the write subsequently fails, the deletion will also be rolled back.
pcsd
What does this function do?
def salt_token_tool(): x_auth = cherrypy.request.headers.get('X-Auth-Token', None) if x_auth: cherrypy.request.cookie['session_id'] = x_auth
If the custom authentication header is supplied, put it in the cookie dict so the rest of the session-based auth works as intended
pcsd
Can you see why it was so squeezed? Why did you write to come back
from cs1robots import * create_world () hubo = Robot () hubo.set_trace ( 'blue' ) def straight (): for i in range (9): hubo.move () def turn_right(): for i in range (3): hubo.turn_left () def updown (): straight () turn_right () hubo.move () turn_right () straight () def ...
If you don’t come back, you have to change direction and then eat one line again. I made it come back to use only one function for redirection.
cs1qa
What need to import this installation of scrapy ?
def get_testenv(): env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env
a os environment dict suitable to fork processes
codeqa
How did you implement the two cards to show a picture when checking two cards?
from cs1graphics import * import time import random canvas = Canvas(640, 580) canvas.setTitle("Memento") path = "./images/" names = ("Dohoo.jpg", "Jeongmin.jpg", "Jinyeong.jpg", "Minsuk.jpg", "Sangjae.jpg", "Sungeun.jpg") cards = [] num_pads = [] tries = 1 correct_list = [] def initialize(): # initial...
I modified the code of the print_cards function, so that the photos in the correct_list and or when num1 and num2 are displayed in the condition that the photos are visible!
cs1qa
For what purpose does a standard html response page return ?
def error_body_response(error_code, message, __warn=True): if __warn: warnings.warn('wsgilib.error_body_response is deprecated; use the wsgi_application method on an HTTPException object instead', DeprecationWarning, 2) return ('<html>\n <head>\n <title>%(error_code)s</title>\n </head>\n <body>...
for an http error
codeqa
What does this function do?
def _fake_exists(path): return False
Assume the path does not exist.
pcsd
How did you create the csv file in Task3?
import elice_utils temp = [] year = 1723 f1 = open("tpmon.txt","r") for line in f1: temp.append(line.strip().split()) del temp[0] f1.close() for i in temp: winter_avg = (float(i[0]) + float(i[1]))/2 summer_avg = (float(i[6]) + float(i[7]))/2 print("%d: %6.1f / %4.1f"%(year,winter_avg,summer_avg)) y...
When creating the file, the values are separated by,
cs1qa
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
26