text
stringlengths
94
87.1k
code_tokens
sequence
avg_line_len
float64
7.91
668
score
sequence
def write_id (self): """Write ID for current URL.""" self.writeln(u"<tr>") self.writeln(u'<td>%s</td>' % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
[ "def", "write_id", "(", "self", ")", ":", "self", ".", "writeln", "(", "u\"<tr>\"", ")", "self", ".", "writeln", "(", "u'<td>%s</td>'", "%", "self", ".", "part", "(", "\"id\"", ")", ")", "self", ".", "write", "(", "u\"<td>%d</td></tr>\"", "%", "self", ".", "stats", ".", "number", ")" ]
40.2
[ 0.1, 0.05128205128205128, 0.06896551724137931, 0.037037037037037035, 0.03389830508474576 ]
def draw(self, img, pixmapper, bounds): '''draw a polygon on the image''' if self.hidden: return self._pix_points = [] for i in range(len(self.points)-1): if len(self.points[i]) > 2: colour = self.points[i][2] else: colour = self.colour self.draw_line(img, pixmapper, self.points[i], self.points[i+1], colour, self.linewidth)
[ "def", "draw", "(", "self", ",", "img", ",", "pixmapper", ",", "bounds", ")", ":", "if", "self", ".", "hidden", ":", "return", "self", ".", "_pix_points", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "points", ")", "-", "1", ")", ":", "if", "len", "(", "self", ".", "points", "[", "i", "]", ")", ">", "2", ":", "colour", "=", "self", ".", "points", "[", "i", "]", "[", "2", "]", "else", ":", "colour", "=", "self", ".", "colour", "self", ".", "draw_line", "(", "img", ",", "pixmapper", ",", "self", ".", "points", "[", "i", "]", ",", "self", ".", "points", "[", "i", "+", "1", "]", ",", "colour", ",", "self", ".", "linewidth", ")" ]
37.75
[ 0.02564102564102564, 0.04878048780487805, 0.08695652173913043, 0.1111111111111111, 0.06896551724137931, 0.046511627906976744, 0.05128205128205128, 0.047619047619047616, 0.11764705882352941, 0.05555555555555555, 0.039473684210526314, 0.08 ]
def _cache_key_select_daterange(method, self, field_id, field_title, style=None): """ This function returns the key used to decide if method select_daterange has to be recomputed """ key = update_timer(), field_id, field_title, style return key
[ "def", "_cache_key_select_daterange", "(", "method", ",", "self", ",", "field_id", ",", "field_title", ",", "style", "=", "None", ")", ":", "key", "=", "update_timer", "(", ")", ",", "field_id", ",", "field_title", ",", "style", "return", "key" ]
43.166667
[ 0.024691358024691357, 0.2857142857142857, 0.03125, 0.2857142857142857, 0.037037037037037035, 0.14285714285714285 ]
def register_id(self, cmd_type, obj): """Registers an object (through its integration id) to receive update notifications. This is the core mechanism how Output and Keypad objects get notified when the controller sends status updates.""" ids = self._ids.setdefault(cmd_type, {}) if obj.id in ids: raise IntegrationIdExistsError self._ids[cmd_type][obj.id] = obj
[ "def", "register_id", "(", "self", ",", "cmd_type", ",", "obj", ")", ":", "ids", "=", "self", ".", "_ids", ".", "setdefault", "(", "cmd_type", ",", "{", "}", ")", "if", "obj", ".", "id", "in", "ids", ":", "raise", "IntegrationIdExistsError", "self", ".", "_ids", "[", "cmd_type", "]", "[", "obj", ".", "id", "]", "=", "obj" ]
48
[ 0.02702702702702703, 0.0273972602739726, 0.02531645569620253, 0.05263157894736842, 0.045454545454545456, 0.09523809523809523, 0.08333333333333333, 0.05405405405405406 ]
def set_scan_target_progress( self, scan_id, target, host, progress): """ Sets host's progress which is part of target. """ self.scan_collection.set_target_progress( scan_id, target, host, progress)
[ "def", "set_scan_target_progress", "(", "self", ",", "scan_id", ",", "target", ",", "host", ",", "progress", ")", ":", "self", ".", "scan_collection", ".", "set_target_progress", "(", "scan_id", ",", "target", ",", "host", ",", "progress", ")" ]
46.8
[ 0.06896551724137931, 0.058823529411764705, 0.03278688524590164, 0.061224489795918366, 0.06818181818181818 ]
def encode(self) -> str: """ Create a token based on the data held in the class. :return: A new token :rtype: str """ payload = {} payload.update(self.registered_claims) payload.update(self.payload) return encode(self.secret, payload, self.alg, self.header)
[ "def", "encode", "(", "self", ")", "->", "str", ":", "payload", "=", "{", "}", "payload", ".", "update", "(", "self", ".", "registered_claims", ")", "payload", ".", "update", "(", "self", ".", "payload", ")", "return", "encode", "(", "self", ".", "secret", ",", "payload", ",", "self", ".", "alg", ",", "self", ".", "header", ")" ]
29.090909
[ 0.041666666666666664, 0.18181818181818182, 0.03389830508474576, 0, 0.10714285714285714, 0.15789473684210525, 0.18181818181818182, 0.1, 0.043478260869565216, 0.05555555555555555, 0.030303030303030304 ]
def update_group(group,**kwargs): """ Update a group. If new attributes are present, they will be added to the group. The non-presence of attributes does not remove them. """ user_id = kwargs.get('user_id') try: group_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id == group.id).one() except NoResultFound: raise ResourceNotFoundError("group %s not found"%(group.id)) group_i.network.check_write_permission(user_id) group_i.name = group.name if group.name != None else group_i.name group_i.description = group.description if group.description else group_i.description if group.attributes is not None: _update_attributes(group_i, group.attributes) if group.types is not None: hdb.add_resource_types(group_i, group.types) db.DBSession.flush() return group_i
[ "def", "update_group", "(", "group", ",", "*", "*", "kwargs", ")", ":", "user_id", "=", "kwargs", ".", "get", "(", "'user_id'", ")", "try", ":", "group_i", "=", "db", ".", "DBSession", ".", "query", "(", "ResourceGroup", ")", ".", "filter", "(", "ResourceGroup", ".", "id", "==", "group", ".", "id", ")", ".", "one", "(", ")", "except", "NoResultFound", ":", "raise", "ResourceNotFoundError", "(", "\"group %s not found\"", "%", "(", "group", ".", "id", ")", ")", "group_i", ".", "network", ".", "check_write_permission", "(", "user_id", ")", "group_i", ".", "name", "=", "group", ".", "name", "if", "group", ".", "name", "!=", "None", "else", "group_i", ".", "name", "group_i", ".", "description", "=", "group", ".", "description", "if", "group", ".", "description", "else", "group_i", ".", "description", "if", "group", ".", "attributes", "is", "not", "None", ":", "_update_attributes", "(", "group_i", ",", "group", ".", "attributes", ")", "if", "group", ".", "types", "is", "not", "None", ":", "hdb", ".", "add_resource_types", "(", "group_i", ",", "group", ".", "types", ")", "db", ".", "DBSession", ".", "flush", "(", ")", "return", "group_i" ]
32.846154
[ 0.06060606060606061, 0.2857142857142857, 0.08695652173913043, 0.028169014084507043, 0.03333333333333333, 0.2857142857142857, 0.05714285714285714, 0.25, 0.031914893617021274, 0.08, 0.04411764705882353, 0, 0.0392156862745098, 0, 0.043478260869565216, 0.033707865168539325, 0, 0.05555555555555555, 0.03773584905660377, 0, 0.06451612903225806, 0.038461538461538464, 0, 0.08333333333333333, 0, 0.1111111111111111 ]
def get_first_and_last(year, month): """Returns two datetimes: first day and last day of given year&month""" ym_first = make_aware( datetime.datetime(year, month, 1), get_default_timezone() ) ym_last = make_aware( datetime.datetime(year, month, monthrange(year, month)[1], 23, 59, 59, 1000000-1), get_default_timezone() ) return ym_first, ym_last
[ "def", "get_first_and_last", "(", "year", ",", "month", ")", ":", "ym_first", "=", "make_aware", "(", "datetime", ".", "datetime", "(", "year", ",", "month", ",", "1", ")", ",", "get_default_timezone", "(", ")", ")", "ym_last", "=", "make_aware", "(", "datetime", ".", "datetime", "(", "year", ",", "month", ",", "monthrange", "(", "year", ",", "month", ")", "[", "1", "]", ",", "23", ",", "59", ",", "59", ",", "1000000", "-", "1", ")", ",", "get_default_timezone", "(", ")", ")", "return", "ym_first", ",", "ym_last" ]
39.272727
[ 0.027777777777777776, 0.02531645569620253, 0.1, 0.043478260869565216, 0.058823529411764705, 0.3333333333333333, 0.10344827586206896, 0.031914893617021274, 0.058823529411764705, 0.3333333333333333, 0.0625 ]
def get_vep_info(vep_string, vep_header): """Make the vep annotations into a dictionaries A vep dictionary will have the vep column names as keys and the vep annotations as values. The dictionaries are stored in a list Args: vep_string (string): A string with the CSQ annotation vep_header (list): A list with the vep header Return: vep_annotations (list): A list of vep dicts """ vep_annotations = [ dict(zip(vep_header, vep_annotation.split('|'))) for vep_annotation in vep_string.split(',') ] return vep_annotations
[ "def", "get_vep_info", "(", "vep_string", ",", "vep_header", ")", ":", "vep_annotations", "=", "[", "dict", "(", "zip", "(", "vep_header", ",", "vep_annotation", ".", "split", "(", "'|'", ")", ")", ")", "for", "vep_annotation", "in", "vep_string", ".", "split", "(", "','", ")", "]", "return", "vep_annotations" ]
29.136364
[ 0.024390243902439025, 0.0392156862745098, 0.5, 0.04411764705882353, 0.05263157894736842, 0.044444444444444446, 0, 0.15384615384615385, 0.046153846153846156, 0.05263157894736842, 0.25, 0.13333333333333333, 0.05454545454545454, 0.5, 0.2857142857142857, 0.5, 0.13043478260869565, 0.05263157894736842, 0.0392156862745098, 0.6, 0.5, 0.07692307692307693 ]
def render_default(path, cp): """ This is the default function that will render a template to a string of HTML. The string will be for a drop-down tab that contains a link to the file. If the file extension requires information to be read, then that is passed to the content variable (eg. a segmentlistdict). """ # define filename and slug from path filename = os.path.basename(path) slug = filename.replace('.', '_') # initializations content = None if path.endswith('.xml') or path.endswith('.xml.gz'): # segment or veto file return a segmentslistdict instance try: wf_file = SegFile.from_segment_xml(path) # FIXME: This is a dictionary, but the code wants a segmentlist # for now I just coalesce. wf_file.return_union_seglist() except Exception as e: print('No segment table found in %s : %s' % (path, e)) # render template template_dir = pycbc.results.__path__[0] + '/templates/files' env = Environment(loader=FileSystemLoader(template_dir)) env.globals.update(abs=abs) env.globals.update(open=open) env.globals.update(path_exists=os.path.exists) template = env.get_template('file_default.html') context = {'path' : path, 'filename' : filename, 'slug' : slug, 'cp' : cp, 'content' : content} output = template.render(context) return output
[ "def", "render_default", "(", "path", ",", "cp", ")", ":", "# define filename and slug from path", "filename", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "slug", "=", "filename", ".", "replace", "(", "'.'", ",", "'_'", ")", "# initializations", "content", "=", "None", "if", "path", ".", "endswith", "(", "'.xml'", ")", "or", "path", ".", "endswith", "(", "'.xml.gz'", ")", ":", "# segment or veto file return a segmentslistdict instance", "try", ":", "wf_file", "=", "SegFile", ".", "from_segment_xml", "(", "path", ")", "# FIXME: This is a dictionary, but the code wants a segmentlist", "# for now I just coalesce.", "wf_file", ".", "return_union_seglist", "(", ")", "except", "Exception", "as", "e", ":", "print", "(", "'No segment table found in %s : %s'", "%", "(", "path", ",", "e", ")", ")", "# render template", "template_dir", "=", "pycbc", ".", "results", ".", "__path__", "[", "0", "]", "+", "'/templates/files'", "env", "=", "Environment", "(", "loader", "=", "FileSystemLoader", "(", "template_dir", ")", ")", "env", ".", "globals", ".", "update", "(", "abs", "=", "abs", ")", "env", ".", "globals", ".", "update", "(", "open", "=", "open", ")", "env", ".", "globals", ".", "update", "(", "path_exists", "=", "os", ".", "path", ".", "exists", ")", "template", "=", "env", ".", "get_template", "(", "'file_default.html'", ")", "context", "=", "{", "'path'", ":", "path", ",", "'filename'", ":", "filename", ",", "'slug'", ":", "slug", ",", "'cp'", ":", "cp", ",", "'content'", ":", "content", "}", "output", "=", "template", ".", "render", "(", "context", ")", "return", "output" ]
36.5
[ 0.034482758620689655, 0.033707865168539325, 0.027777777777777776, 0, 0.03529411764705882, 0.06666666666666667, 0.2857142857142857, 0, 0.05, 0.05405405405405406, 0.05405405405405406, 0, 0.09523809523809523, 0.1111111111111111, 0, 0.03508771929824561, 0.03076923076923077, 0.16666666666666666, 0.038461538461538464, 0.02666666666666667, 0.044444444444444446, 0.047619047619047616, 0.06666666666666667, 0.030303030303030304, 0, 0.09523809523809523, 0.03076923076923077, 0.03333333333333333, 0.06451612903225806, 0.06060606060606061, 0.04, 0.038461538461538464, 0.12121212121212122, 0.10810810810810811, 0.12121212121212122, 0.12903225806451613, 0.1388888888888889, 0.05405405405405406, 0, 0.11764705882352941 ]
def mouse_up(self, evt, wx_obj=None): "Release the selected object (pass a wx_obj if the event was captured)" self.resizing = False if self.current: wx_obj = self.current if self.parent.wx_obj.HasCapture(): self.parent.wx_obj.ReleaseMouse() self.current = None if self.overlay: # When the mouse is released we reset the overlay and it # restores the former content to the window. dc = wx.ClientDC(wx_obj) odc = wx.DCOverlay(self.overlay, dc) odc.Clear() del odc self.overlay.Reset() self.overlay = None pos = evt.GetPosition() # convert to relative client coordinates of the container: if evt.GetEventObject() != wx_obj: pos = evt.GetEventObject().ClientToScreen(pos) # frame pos = wx_obj.ScreenToClient(pos) # panel # finish the multiple selection using the mouse: rect = wx.RectPP(self.pos, pos) for obj in wx_obj.obj: # only check child controls (not menubar/statusbar) if isinstance(obj, Control): obj_rect = obj.wx_obj.GetRect() if rect.ContainsRect(obj_rect): self.select(obj, keep_selection=True) self.pos = None if self.inspector and wx_obj: self.inspector.inspect(wx_obj.obj) if DEBUG: print "SELECTION", self.selection
[ "def", "mouse_up", "(", "self", ",", "evt", ",", "wx_obj", "=", "None", ")", ":", "self", ".", "resizing", "=", "False", "if", "self", ".", "current", ":", "wx_obj", "=", "self", ".", "current", "if", "self", ".", "parent", ".", "wx_obj", ".", "HasCapture", "(", ")", ":", "self", ".", "parent", ".", "wx_obj", ".", "ReleaseMouse", "(", ")", "self", ".", "current", "=", "None", "if", "self", ".", "overlay", ":", "# When the mouse is released we reset the overlay and it ", "# restores the former content to the window. ", "dc", "=", "wx", ".", "ClientDC", "(", "wx_obj", ")", "odc", "=", "wx", ".", "DCOverlay", "(", "self", ".", "overlay", ",", "dc", ")", "odc", ".", "Clear", "(", ")", "del", "odc", "self", ".", "overlay", ".", "Reset", "(", ")", "self", ".", "overlay", "=", "None", "pos", "=", "evt", ".", "GetPosition", "(", ")", "# convert to relative client coordinates of the container:", "if", "evt", ".", "GetEventObject", "(", ")", "!=", "wx_obj", ":", "pos", "=", "evt", ".", "GetEventObject", "(", ")", ".", "ClientToScreen", "(", "pos", ")", "# frame", "pos", "=", "wx_obj", ".", "ScreenToClient", "(", "pos", ")", "# panel", "# finish the multiple selection using the mouse:", "rect", "=", "wx", ".", "RectPP", "(", "self", ".", "pos", ",", "pos", ")", "for", "obj", "in", "wx_obj", ".", "obj", ":", "# only check child controls (not menubar/statusbar)", "if", "isinstance", "(", "obj", ",", "Control", ")", ":", "obj_rect", "=", "obj", ".", "wx_obj", ".", "GetRect", "(", ")", "if", "rect", ".", "ContainsRect", "(", "obj_rect", ")", ":", "self", ".", "select", "(", "obj", ",", "keep_selection", "=", "True", ")", "self", ".", "pos", "=", "None", "if", "self", ".", "inspector", "and", "wx_obj", ":", "self", ".", "inspector", ".", "inspect", "(", "wx_obj", ".", "obj", ")", "if", "DEBUG", ":", "print", "\"SELECTION\"", ",", "self", ".", "selection" ]
46.942857
[ 0.02702702702702703, 0.02531645569620253, 0.06896551724137931, 0.12, 0.06060606060606061, 0.0425531914893617, 0.04081632653061224, 0.06451612903225806, 0.07142857142857142, 0.0410958904109589, 0.04918032786885246, 0.05, 0.038461538461538464, 0.07407407407407407, 0.08695652173913043, 0.057692307692307696, 0.05714285714285714, 0.05128205128205128, 0.02702702702702703, 0.04, 0.02666666666666667, 0.02666666666666667, 0.03125, 0.0425531914893617, 0.05263157894736842, 0.028169014084507043, 0.041666666666666664, 0.03636363636363636, 0.03636363636363636, 0.03076923076923077, 0.09375, 0, 0.05405405405405406, 0.043478260869565216, 0.058823529411764705 ]
def DSP_capture_add_samples_stereo(self,new_data_left,new_data_right): """ Append new samples to the data_capture_left array and the data_capture_right array and increment the sample counter. If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0 then new values are not appended to the data_capture array. """ self.capture_sample_count = self.capture_sample_count + len(new_data_left) + len(new_data_right) if self.Tcapture > 0: self.data_capture_left = np.hstack((self.data_capture_left,new_data_left)) self.data_capture_right = np.hstack((self.data_capture_right,new_data_right)) if (len(self.data_capture_left) > self.Ncapture): self.data_capture_left = self.data_capture_left[-self.Ncapture:] if (len(self.data_capture_right) > self.Ncapture): self.data_capture_right = self.data_capture_right[-self.Ncapture:]
[ "def", "DSP_capture_add_samples_stereo", "(", "self", ",", "new_data_left", ",", "new_data_right", ")", ":", "self", ".", "capture_sample_count", "=", "self", ".", "capture_sample_count", "+", "len", "(", "new_data_left", ")", "+", "len", "(", "new_data_right", ")", "if", "self", ".", "Tcapture", ">", "0", ":", "self", ".", "data_capture_left", "=", "np", ".", "hstack", "(", "(", "self", ".", "data_capture_left", ",", "new_data_left", ")", ")", "self", ".", "data_capture_right", "=", "np", ".", "hstack", "(", "(", "self", ".", "data_capture_right", ",", "new_data_right", ")", ")", "if", "(", "len", "(", "self", ".", "data_capture_left", ")", ">", "self", ".", "Ncapture", ")", ":", "self", ".", "data_capture_left", "=", "self", ".", "data_capture_left", "[", "-", "self", ".", "Ncapture", ":", "]", "if", "(", "len", "(", "self", ".", "data_capture_right", ")", ">", "self", ".", "Ncapture", ")", ":", "self", ".", "data_capture_right", "=", "self", ".", "data_capture_right", "[", "-", "self", ".", "Ncapture", ":", "]" ]
62.3125
[ 0.04225352112676056, 0.08333333333333333, 0.023529411764705882, 0.03488372093023256, 0.034482758620689655, 0.02857142857142857, 0.1111111111111111, 0.08333333333333333, 0.01904761904761905, 0.1, 0.034482758620689655, 0.03333333333333333, 0.04838709677419355, 0.024691358024691357, 0.047619047619047616, 0.036585365853658534 ]
def update(self): """ updates a row. This is a blind update call. All validation and cleaning needs to happen prior to calling this. """ if self.instance is None: raise CQLEngineException("DML Query intance attribute is None") assert type(self.instance) == self.model null_clustering_key = False if len(self.instance._clustering_keys) == 0 else True static_changed_only = True statement = UpdateStatement(self.column_family_name, ttl=self._ttl, timestamp=self._timestamp, conditionals=self._conditional, if_exists=self._if_exists) for name, col in self.instance._clustering_keys.items(): null_clustering_key = null_clustering_key and col._val_is_null(getattr(self.instance, name, None)) updated_columns = set() # get defined fields and their column names for name, col in self.model._columns.items(): # if clustering key is null, don't include non static columns if null_clustering_key and not col.static and not col.partition_key: continue if not col.is_primary_key: val = getattr(self.instance, name, None) val_mgr = self.instance._values[name] if val is None: continue if not val_mgr.changed and not isinstance(col, columns.Counter): continue static_changed_only = static_changed_only and col.static statement.add_update(col, val, previous=val_mgr.previous_value) updated_columns.add(col.db_field_name) if statement.assignments: for name, col in self.model._primary_keys.items(): # only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error if (null_clustering_key or static_changed_only) and (not col.partition_key): continue statement.add_where(col, EqualsOperator(), getattr(self.instance, name)) self._execute(statement) if not null_clustering_key: # remove conditions on fields that have been updated delete_conditionals = [condition for condition in self._conditional if condition.field not in updated_columns] if self._conditional else None self._delete_null_columns(delete_conditionals)
[ "def", "update", "(", "self", ")", ":", "if", "self", ".", "instance", "is", "None", ":", "raise", "CQLEngineException", "(", "\"DML Query intance attribute is None\"", ")", "assert", "type", "(", "self", ".", "instance", ")", "==", "self", ".", "model", "null_clustering_key", "=", "False", "if", "len", "(", "self", ".", "instance", ".", "_clustering_keys", ")", "==", "0", "else", "True", "static_changed_only", "=", "True", "statement", "=", "UpdateStatement", "(", "self", ".", "column_family_name", ",", "ttl", "=", "self", ".", "_ttl", ",", "timestamp", "=", "self", ".", "_timestamp", ",", "conditionals", "=", "self", ".", "_conditional", ",", "if_exists", "=", "self", ".", "_if_exists", ")", "for", "name", ",", "col", "in", "self", ".", "instance", ".", "_clustering_keys", ".", "items", "(", ")", ":", "null_clustering_key", "=", "null_clustering_key", "and", "col", ".", "_val_is_null", "(", "getattr", "(", "self", ".", "instance", ",", "name", ",", "None", ")", ")", "updated_columns", "=", "set", "(", ")", "# get defined fields and their column names", "for", "name", ",", "col", "in", "self", ".", "model", ".", "_columns", ".", "items", "(", ")", ":", "# if clustering key is null, don't include non static columns", "if", "null_clustering_key", "and", "not", "col", ".", "static", "and", "not", "col", ".", "partition_key", ":", "continue", "if", "not", "col", ".", "is_primary_key", ":", "val", "=", "getattr", "(", "self", ".", "instance", ",", "name", ",", "None", ")", "val_mgr", "=", "self", ".", "instance", ".", "_values", "[", "name", "]", "if", "val", "is", "None", ":", "continue", "if", "not", "val_mgr", ".", "changed", "and", "not", "isinstance", "(", "col", ",", "columns", ".", "Counter", ")", ":", "continue", "static_changed_only", "=", "static_changed_only", "and", "col", ".", "static", "statement", ".", "add_update", "(", "col", ",", "val", ",", "previous", "=", "val_mgr", ".", "previous_value", ")", "updated_columns", ".", "add", "(", "col", ".", "db_field_name", ")", "if", "statement", ".", "assignments", ":", "for", "name", ",", "col", "in", "self", ".", "model", ".", "_primary_keys", ".", "items", "(", ")", ":", "# only include clustering key if clustering key is not null, and non static columns are changed to avoid cql error", "if", "(", "null_clustering_key", "or", "static_changed_only", ")", "and", "(", "not", "col", ".", "partition_key", ")", ":", "continue", "statement", ".", "add_where", "(", "col", ",", "EqualsOperator", "(", ")", ",", "getattr", "(", "self", ".", "instance", ",", "name", ")", ")", "self", ".", "_execute", "(", "statement", ")", "if", "not", "null_clustering_key", ":", "# remove conditions on fields that have been updated", "delete_conditionals", "=", "[", "condition", "for", "condition", "in", "self", ".", "_conditional", "if", "condition", ".", "field", "not", "in", "updated_columns", "]", "if", "self", ".", "_conditional", "else", "None", "self", ".", "_delete_null_columns", "(", "delete_conditionals", ")" ]
49.42
[ 0.058823529411764705, 0.18181818181818182, 0.09090909090909091, 0.05555555555555555, 0.0392156862745098, 0.06666666666666667, 0.18181818181818182, 0.06060606060606061, 0.02666666666666667, 0.041666666666666664, 0.033707865168539325, 0.058823529411764705, 0.0392156862745098, 0.06382978723404255, 0.03125, 0.02727272727272727, 0, 0.06451612903225806, 0.0392156862745098, 0.03773584905660377, 0.0273972602739726, 0.0375, 0.08333333333333333, 0.05263157894736842, 0.03571428571428571, 0.03773584905660377, 0, 0.06451612903225806, 0.07142857142857142, 0, 0.0375, 0.07142857142857142, 0, 0.027777777777777776, 0.02531645569620253, 0.037037037037037035, 0, 0.06060606060606061, 0.03225806451612903, 0.023076923076923078, 0.03260869565217391, 0.07142857142857142, 0.03409090909090909, 0.05555555555555555, 0, 0.05714285714285714, 0.03125, 0.0379746835443038, 0.046296296296296294, 0.034482758620689655 ]
def from_sky(cls, magnitudelimit=None): ''' Create a Constellation from a criteria search of the whole sky. Parameters ---------- magnitudelimit : float Maximum magnitude (for Ve = "estimated V"). ''' # define a query for cone search surrounding this center criteria = {} if magnitudelimit is not None: criteria[cls.defaultfilter + 'mag'] = '<{}'.format(magnitudelimit) v = Vizier(columns=cls.columns, column_filters=criteria) v.ROW_LIMIT = -1 # run the query print('querying Vizier for {}, for {}<{}'.format(cls.name, cls.defaultfilter, magnitudelimit)) table = v.query_constraints(catalog=cls.catalog, **criteria)[0] # store the search parameters in this object c = cls(cls.standardize_table(table)) c.standardized.meta['catalog'] = cls.catalog c.standardized.meta['criteria'] = criteria c.standardized.meta['magnitudelimit'] = magnitudelimit or c.magnitudelimit #c.magnitudelimit = magnitudelimit or c.magnitudelimit return c
[ "def", "from_sky", "(", "cls", ",", "magnitudelimit", "=", "None", ")", ":", "# define a query for cone search surrounding this center", "criteria", "=", "{", "}", "if", "magnitudelimit", "is", "not", "None", ":", "criteria", "[", "cls", ".", "defaultfilter", "+", "'mag'", "]", "=", "'<{}'", ".", "format", "(", "magnitudelimit", ")", "v", "=", "Vizier", "(", "columns", "=", "cls", ".", "columns", ",", "column_filters", "=", "criteria", ")", "v", ".", "ROW_LIMIT", "=", "-", "1", "# run the query", "print", "(", "'querying Vizier for {}, for {}<{}'", ".", "format", "(", "cls", ".", "name", ",", "cls", ".", "defaultfilter", ",", "magnitudelimit", ")", ")", "table", "=", "v", ".", "query_constraints", "(", "catalog", "=", "cls", ".", "catalog", ",", "*", "*", "criteria", ")", "[", "0", "]", "# store the search parameters in this object", "c", "=", "cls", "(", "cls", ".", "standardize_table", "(", "table", ")", ")", "c", ".", "standardized", ".", "meta", "[", "'catalog'", "]", "=", "cls", ".", "catalog", "c", ".", "standardized", ".", "meta", "[", "'criteria'", "]", "=", "criteria", "c", ".", "standardized", ".", "meta", "[", "'magnitudelimit'", "]", "=", "magnitudelimit", "or", "c", ".", "magnitudelimit", "#c.magnitudelimit = magnitudelimit or c.magnitudelimit", "return", "c" ]
33.787879
[ 0.02564102564102564, 0.18181818181818182, 0.028169014084507043, 0, 0.1111111111111111, 0.1111111111111111, 0.1, 0.09090909090909091, 0.18181818181818182, 0, 0, 0.03125, 0, 0.09523809523809523, 0.05263157894736842, 0.02564102564102564, 0, 0.07692307692307693, 0.11627906976744186, 0.08333333333333333, 0, 0.08695652173913043, 0.029411764705882353, 0, 0.028169014084507043, 0, 0.038461538461538464, 0.044444444444444446, 0.038461538461538464, 0.04, 0.036585365853658534, 0.04838709677419355, 0.125 ]
def _insert_missing_rows(self, indexes): """ Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for that index, inserting into the index. This requires the Series to be sorted=True :param indexes: list of indexes :return: nothing """ new_indexes = [x for x in indexes if x not in self._index] for x in new_indexes: self._insert_row(bisect_left(self._index, x), x)
[ "def", "_insert_missing_rows", "(", "self", ",", "indexes", ")", ":", "new_indexes", "=", "[", "x", "for", "x", "in", "indexes", "if", "x", "not", "in", "self", ".", "_index", "]", "for", "x", "in", "new_indexes", ":", "self", ".", "_insert_row", "(", "bisect_left", "(", "self", ".", "_index", ",", "x", ")", ",", "x", ")" ]
43.727273
[ 0.025, 0.18181818181818182, 0.035398230088495575, 0.045454545454545456, 0, 0.07692307692307693, 0.125, 0.18181818181818182, 0.030303030303030304, 0.06896551724137931, 0.03333333333333333 ]
async def _send_packet(self, pkt): """Queue a packet to be sent to the server.""" if self.state != 'connected': return await self.queue.put(pkt) self.logger.info( 'Sending packet %s data %s', packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
[ "async", "def", "_send_packet", "(", "self", ",", "pkt", ")", ":", "if", "self", ".", "state", "!=", "'connected'", ":", "return", "await", "self", ".", "queue", ".", "put", "(", "pkt", ")", "self", ".", "logger", ".", "info", "(", "'Sending packet %s data %s'", ",", "packet", ".", "packet_names", "[", "pkt", ".", "packet_type", "]", ",", "pkt", ".", "data", "if", "not", "isinstance", "(", "pkt", ".", "data", ",", "bytes", ")", "else", "'<binary>'", ")" ]
40.222222
[ 0.029411764705882353, 0.037037037037037035, 0.05405405405405406, 0.1111111111111111, 0.06060606060606061, 0.12, 0.05, 0.04081632653061224, 0.041666666666666664 ]
def send_error_message(sender, error_message): """Send an error message to the listeners. Error messages represents and error. It usually replace the previous message since an error has been happened. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param error_message: An instance of our rich error message class. :type error_message: ErrorMessage """ dispatcher.send( signal=ERROR_MESSAGE_SIGNAL, sender=sender, message=error_message)
[ "def", "send_error_message", "(", "sender", ",", "error_message", ")", ":", "dispatcher", ".", "send", "(", "signal", "=", "ERROR_MESSAGE_SIGNAL", ",", "sender", "=", "sender", ",", "message", "=", "error_message", ")" ]
28.333333
[ 0.021739130434782608, 0.043478260869565216, 0, 0.027777777777777776, 0.044444444444444446, 0, 0.12, 0, 0.1, 0.125, 0, 0.04285714285714286, 0.08108108108108109, 0.2857142857142857, 0.15, 0.08333333333333333, 0.13636363636363635, 0.13333333333333333 ]
def probe_dtz(self, board: chess.Board) -> int: """ Probes DTZ tables for distance to zero information. Both DTZ and WDL tables are required in order to probe for DTZ. Returns a positive value if the side to move is winning, ``0`` if the position is a draw and a negative value if the side to move is losing. More precisely: +-----+------------------+--------------------------------------------+ | WDL | DTZ | | +=====+==================+============================================+ | -2 | -100 <= n <= -1 | Unconditional loss (assuming 50-move | | | | counter is zero), where a zeroing move can | | | | be forced in -n plies. | +-----+------------------+--------------------------------------------+ | -1 | n < -100 | Loss, but draw under the 50-move rule. | | | | A zeroing move can be forced in -n plies | | | | or -n - 100 plies (if a later phase is | | | | responsible for the blessed loss). | +-----+------------------+--------------------------------------------+ | 0 | 0 | Draw. | +-----+------------------+--------------------------------------------+ | 1 | 100 < n | Win, but draw under the 50-move rule. | | | | A zeroing move can be forced in n plies or | | | | n - 100 plies (if a later phase is | | | | responsible for the cursed win). | +-----+------------------+--------------------------------------------+ | 2 | 1 <= n <= 100 | Unconditional win (assuming 50-move | | | | counter is zero), where a zeroing move can | | | | be forced in n plies. | +-----+------------------+--------------------------------------------+ The return value can be off by one: a return value -n can mean a losing zeroing move in in n + 1 plies and a return value +n can mean a winning zeroing move in n + 1 plies. This is guaranteed not to happen for positions exactly on the edge of the 50-move rule, so that (with some care) this never impacts the result of practical play. Minmaxing the DTZ values guarantees winning a won position (and drawing a drawn position), because it makes progress keeping the win in hand. However the lines are not always the most straightforward ways to win. Engines like Stockfish calculate themselves, checking with DTZ, but only play according to DTZ if they can not manage on their own. >>> import chess >>> import chess.syzygy >>> >>> with chess.syzygy.open_tablebase("data/syzygy/regular") as tablebase: ... board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1") ... print(tablebase.probe_dtz(board)) ... -53 Probing is thread-safe when done with different *board* objects and if *board* objects are not modified during probing. :raises: :exc:`KeyError` (or specifically :exc:`chess.syzygy.MissingTableError`) if the position could not be found in the tablebase. Use :func:`~chess.syzygy.Tablebase.get_dtz()` if you prefer to get ``None`` instead of an exception. Note that probing corrupted table files is undefined behavior. """ v = self.probe_dtz_no_ep(board) if not board.ep_square or self.variant.captures_compulsory: return v v1 = -3 # Generate all en-passant moves. for move in board.generate_legal_ep(): board.push(move) try: v0_plus, _ = self.probe_ab(board, -2, 2) v0 = -v0_plus finally: board.pop() if v0 > v1: v1 = v0 if v1 > -3: v1 = WDL_TO_DTZ[v1 + 2] if v < -100: if v1 >= 0: v = v1 elif v < 0: if v1 >= 0 or v1 < -100: v = v1 elif v > 100: if v1 > 0: v = v1 elif v > 0: if v1 == 1: v = v1 elif v1 >= 0: v = v1 else: if all(board.is_en_passant(move) for move in board.generate_legal_moves()): v = v1 return v
[ "def", "probe_dtz", "(", "self", ",", "board", ":", "chess", ".", "Board", ")", "->", "int", ":", "v", "=", "self", ".", "probe_dtz_no_ep", "(", "board", ")", "if", "not", "board", ".", "ep_square", "or", "self", ".", "variant", ".", "captures_compulsory", ":", "return", "v", "v1", "=", "-", "3", "# Generate all en-passant moves.", "for", "move", "in", "board", ".", "generate_legal_ep", "(", ")", ":", "board", ".", "push", "(", "move", ")", "try", ":", "v0_plus", ",", "_", "=", "self", ".", "probe_ab", "(", "board", ",", "-", "2", ",", "2", ")", "v0", "=", "-", "v0_plus", "finally", ":", "board", ".", "pop", "(", ")", "if", "v0", ">", "v1", ":", "v1", "=", "v0", "if", "v1", ">", "-", "3", ":", "v1", "=", "WDL_TO_DTZ", "[", "v1", "+", "2", "]", "if", "v", "<", "-", "100", ":", "if", "v1", ">=", "0", ":", "v", "=", "v1", "elif", "v", "<", "0", ":", "if", "v1", ">=", "0", "or", "v1", "<", "-", "100", ":", "v", "=", "v1", "elif", "v", ">", "100", ":", "if", "v1", ">", "0", ":", "v", "=", "v1", "elif", "v", ">", "0", ":", "if", "v1", "==", "1", ":", "v", "=", "v1", "elif", "v1", ">=", "0", ":", "v", "=", "v1", "else", ":", "if", "all", "(", "board", ".", "is_en_passant", "(", "move", ")", "for", "move", "in", "board", ".", "generate_legal_moves", "(", ")", ")", ":", "v", "=", "v1", "return", "v" ]
44.429907
[ 0.02127659574468085, 0.18181818181818182, 0.03389830508474576, 0, 0.028169014084507043, 0, 0.03896103896103896, 0.02564102564102564, 0.08695652173913043, 0, 0.02531645569620253, 0.05063291139240506, 0.46835443037974683, 0.08860759493670886, 0.06329113924050633, 0.06329113924050633, 0.02531645569620253, 0.06329113924050633, 0.06329113924050633, 0.10126582278481013, 0.0759493670886076, 0.02531645569620253, 0.06329113924050633, 0.02531645569620253, 0.06329113924050633, 0.05063291139240506, 0.10126582278481013, 0.0759493670886076, 0.02531645569620253, 0.0759493670886076, 0.06329113924050633, 0.06329113924050633, 0.02531645569620253, 0, 0.041666666666666664, 0.038461538461538464, 0.045454545454545456, 0.025974025974025976, 0.0410958904109589, 0.06060606060606061, 0, 0.06329113924050633, 0.03896103896103896, 0.02564102564102564, 0.02666666666666667, 0.028169014084507043, 0, 0.125, 0.0967741935483871, 0.2727272727272727, 0.04938271604938271, 0.027777777777777776, 0.061224489795918366, 0.18181818181818182, 0.18181818181818182, 0, 0.05333333333333334, 0.05084745762711865, 0, 0.1836734693877551, 0.07894736842105263, 0.047619047619047616, 0.06756756756756757, 0.06666666666666667, 0, 0.02702702702702703, 0.18181818181818182, 0.05128205128205128, 0, 0.029850746268656716, 0.1, 0, 0.13333333333333333, 0, 0.05, 0.043478260869565216, 0.07142857142857142, 0.125, 0.03571428571428571, 0.06896551724137931, 0.1, 0.07407407407407407, 0, 0.08695652173913043, 0.08695652173913043, 0, 0.10526315789473684, 0.05714285714285714, 0.08333333333333333, 0.07407407407407407, 0.07692307692307693, 0.08695652173913043, 0.05, 0.07692307692307693, 0.08, 0.07692307692307693, 0.07692307692307693, 0.08695652173913043, 0.07407407407407407, 0.07692307692307693, 0.08, 0.09090909090909091, 0.11764705882352941, 0.03296703296703297, 0.07692307692307693, 0, 0.125 ]
def Boolean(): """ Creates a validator that attempts to convert the given value to a boolean or raises an error. The following rules are used: ``None`` is converted to ``False``. ``int`` values are ``True`` except for ``0``. ``str`` values converted in lower- and uppercase: * ``y, yes, t, true`` * ``n, no, f, false`` """ @wraps(Boolean) def built(value): # Already a boolean? if isinstance(value, bool): return value # None if value == None: return False # Integers if isinstance(value, int): return not value == 0 # Strings if isinstance(value, str): if value.lower() in { 'y', 'yes', 't', 'true' }: return True elif value.lower() in { 'n', 'no', 'f', 'false' }: return False # Nope raise Error("Not a boolean value.") return built
[ "def", "Boolean", "(", ")", ":", "@", "wraps", "(", "Boolean", ")", "def", "built", "(", "value", ")", ":", "# Already a boolean?", "if", "isinstance", "(", "value", ",", "bool", ")", ":", "return", "value", "# None", "if", "value", "==", "None", ":", "return", "False", "# Integers", "if", "isinstance", "(", "value", ",", "int", ")", ":", "return", "not", "value", "==", "0", "# Strings", "if", "isinstance", "(", "value", ",", "str", ")", ":", "if", "value", ".", "lower", "(", ")", "in", "{", "'y'", ",", "'yes'", ",", "'t'", ",", "'true'", "}", ":", "return", "True", "elif", "value", ".", "lower", "(", ")", "in", "{", "'n'", ",", "'no'", ",", "'f'", ",", "'false'", "}", ":", "return", "False", "# Nope", "raise", "Error", "(", "\"Not a boolean value.\"", ")", "return", "built" ]
24.342105
[ 0.07142857142857142, 0.2857142857142857, 0.025974025974025976, 0.03773584905660377, 0, 0.07692307692307693, 0, 0.061224489795918366, 0, 0.07547169811320754, 0, 0.12, 0.12, 0.2857142857142857, 0.10526315789473684, 0.09523809523809523, 0.07142857142857142, 0.05714285714285714, 0.08333333333333333, 0, 0.14285714285714285, 0.12, 0.08333333333333333, 0, 0.1111111111111111, 0.058823529411764705, 0.06060606060606061, 0, 0.11764705882352941, 0.058823529411764705, 0.06666666666666667, 0.07407407407407407, 0.06451612903225806, 0.07142857142857142, 0, 0.14285714285714285, 0.046511627906976744, 0.125 ]
def end_point_to_center_parameters(x1, y1, x2, y2, fA, fS, rx, ry, phi=0): ''' See http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes F.6.5 note that we reduce phi to zero outside this routine ''' rx = fabs(rx) ry = fabs(ry) # step 1 if phi: phi_rad = radians(phi) sin_phi = sin(phi_rad) cos_phi = cos(phi_rad) tx = 0.5 * (x1 - x2) ty = 0.5 * (y1 - y2) x1d = cos_phi * tx - sin_phi * ty y1d = sin_phi * tx + cos_phi * ty else: x1d = 0.5 * (x1 - x2) y1d = 0.5 * (y1 - y2) # step 2 # we need to calculate # (rx*rx*ry*ry-rx*rx*y1d*y1d-ry*ry*x1d*x1d) # ----------------------------------------- # (rx*rx*y1d*y1d+ry*ry*x1d*x1d) # # that is equivalent to # # rx*rx*ry*ry # = ----------------------------- - 1 # (rx*rx*y1d*y1d+ry*ry*x1d*x1d) # # 1 # = -------------------------------- - 1 # x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry) # # = 1/r - 1 # # it turns out r is what they recommend checking # for the negative radicand case r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry) if r > 1: rr = sqrt(r) rx *= rr ry *= rr r = x1d * x1d / (rx * rx) + y1d * y1d / (ry * ry) elif r != 0: r = 1 / r - 1 if -1e-10 < r < 0: r = 0 r = sqrt(r) if fA == fS: r = -r cxd = (r * rx * y1d) / ry cyd = -(r * ry * x1d) / rx # step 3 if phi: cx = cos_phi * cxd - sin_phi * cyd + 0.5 * (x1 + x2) cy = sin_phi * cxd + cos_phi * cyd + 0.5 * (y1 + y2) else: cx = cxd + 0.5 * (x1 + x2) cy = cyd + 0.5 * (y1 + y2) # step 4 theta1 = vector_angle((1, 0), ((x1d - cxd) / rx, (y1d - cyd) / ry)) dtheta = vector_angle( ((x1d - cxd) / rx, (y1d - cyd) / ry), ((-x1d - cxd) / rx, (-y1d - cyd) / ry) ) % 360 if fS == 0 and dtheta > 0: dtheta -= 360 elif fS == 1 and dtheta < 0: dtheta += 360 return cx, cy, rx, ry, -theta1, -dtheta
[ "def", "end_point_to_center_parameters", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "fA", ",", "fS", ",", "rx", ",", "ry", ",", "phi", "=", "0", ")", ":", "rx", "=", "fabs", "(", "rx", ")", "ry", "=", "fabs", "(", "ry", ")", "# step 1", "if", "phi", ":", "phi_rad", "=", "radians", "(", "phi", ")", "sin_phi", "=", "sin", "(", "phi_rad", ")", "cos_phi", "=", "cos", "(", "phi_rad", ")", "tx", "=", "0.5", "*", "(", "x1", "-", "x2", ")", "ty", "=", "0.5", "*", "(", "y1", "-", "y2", ")", "x1d", "=", "cos_phi", "*", "tx", "-", "sin_phi", "*", "ty", "y1d", "=", "sin_phi", "*", "tx", "+", "cos_phi", "*", "ty", "else", ":", "x1d", "=", "0.5", "*", "(", "x1", "-", "x2", ")", "y1d", "=", "0.5", "*", "(", "y1", "-", "y2", ")", "# step 2", "# we need to calculate", "# (rx*rx*ry*ry-rx*rx*y1d*y1d-ry*ry*x1d*x1d)", "# -----------------------------------------", "# (rx*rx*y1d*y1d+ry*ry*x1d*x1d)", "#", "# that is equivalent to", "#", "# rx*rx*ry*ry", "# = ----------------------------- - 1", "# (rx*rx*y1d*y1d+ry*ry*x1d*x1d)", "#", "# 1", "# = -------------------------------- - 1", "# x1d*x1d/(rx*rx) + y1d*y1d/(ry*ry)", "#", "# = 1/r - 1", "#", "# it turns out r is what they recommend checking", "# for the negative radicand case", "r", "=", "x1d", "*", "x1d", "/", "(", "rx", "*", "rx", ")", "+", "y1d", "*", "y1d", "/", "(", "ry", "*", "ry", ")", "if", "r", ">", "1", ":", "rr", "=", "sqrt", "(", "r", ")", "rx", "*=", "rr", "ry", "*=", "rr", "r", "=", "x1d", "*", "x1d", "/", "(", "rx", "*", "rx", ")", "+", "y1d", "*", "y1d", "/", "(", "ry", "*", "ry", ")", "elif", "r", "!=", "0", ":", "r", "=", "1", "/", "r", "-", "1", "if", "-", "1e-10", "<", "r", "<", "0", ":", "r", "=", "0", "r", "=", "sqrt", "(", "r", ")", "if", "fA", "==", "fS", ":", "r", "=", "-", "r", "cxd", "=", "(", "r", "*", "rx", "*", "y1d", ")", "/", "ry", "cyd", "=", "-", "(", "r", "*", "ry", "*", "x1d", ")", "/", "rx", "# step 3", "if", "phi", ":", "cx", "=", "cos_phi", "*", "cxd", "-", "sin_phi", "*", "cyd", "+", "0.5", "*", "(", "x1", "+", "x2", ")", "cy", "=", "sin_phi", "*", "cxd", "+", "cos_phi", "*", "cyd", "+", "0.5", "*", "(", "y1", "+", "y2", ")", "else", ":", "cx", "=", "cxd", "+", "0.5", "*", "(", "x1", "+", "x2", ")", "cy", "=", "cyd", "+", "0.5", "*", "(", "y1", "+", "y2", ")", "# step 4", "theta1", "=", "vector_angle", "(", "(", "1", ",", "0", ")", ",", "(", "(", "x1d", "-", "cxd", ")", "/", "rx", ",", "(", "y1d", "-", "cyd", ")", "/", "ry", ")", ")", "dtheta", "=", "vector_angle", "(", "(", "(", "x1d", "-", "cxd", ")", "/", "rx", ",", "(", "y1d", "-", "cyd", ")", "/", "ry", ")", ",", "(", "(", "-", "x1d", "-", "cxd", ")", "/", "rx", ",", "(", "-", "y1d", "-", "cyd", ")", "/", "ry", ")", ")", "%", "360", "if", "fS", "==", "0", "and", "dtheta", ">", "0", ":", "dtheta", "-=", "360", "elif", "fS", "==", "1", "and", "dtheta", "<", "0", ":", "dtheta", "+=", "360", "return", "cx", ",", "cy", ",", "rx", ",", "ry", ",", "-", "theta1", ",", "-", "dtheta" ]
26.828947
[ 0.013513513513513514, 0.2857142857142857, 0.06666666666666667, 0.03571428571428571, 0.2857142857142857, 0.11764705882352941, 0.11764705882352941, 0, 0.16666666666666666, 0.18181818181818182, 0.06666666666666667, 0.06666666666666667, 0.06666666666666667, 0.07142857142857142, 0.07142857142857142, 0.04878048780487805, 0.04878048780487805, 0.2222222222222222, 0.06896551724137931, 0.06896551724137931, 0, 0.16666666666666666, 0.07692307692307693, 0.0425531914893617, 0.0425531914893617, 0.05128205128205128, 0.4, 0.07407407407407407, 0.4, 0.07692307692307693, 0.044444444444444446, 0.05405405405405406, 0.4, 0.1, 0.045454545454545456, 0.04878048780487805, 0.4, 0.13333333333333333, 0.4, 0.038461538461538464, 0.05555555555555555, 0.03773584905660377, 0.15384615384615385, 0.1, 0.125, 0.125, 0.03508771929824561, 0.125, 0.09523809523809523, 0.09090909090909091, 0.15384615384615385, 0.13333333333333333, 0.125, 0.14285714285714285, 0.06896551724137931, 0.06666666666666667, 0, 0.16666666666666666, 0.18181818181818182, 0.03333333333333333, 0.03333333333333333, 0.2222222222222222, 0.058823529411764705, 0.058823529411764705, 0, 0.16666666666666666, 0.028169014084507043, 0.11538461538461539, 0.044444444444444446, 0.043478260869565216, 0.2727272727272727, 0.06666666666666667, 0.09523809523809523, 0.0625, 0.09523809523809523, 0.046511627906976744 ]
def render_markdown(text, context=None): """ Turn markdown into HTML. """ if context is None or not isinstance(context, dict): context = {} markdown_html = _transform_markdown_into_html(text) sanitised_markdown_html = _sanitise_markdown_html(markdown_html) return mark_safe(sanitised_markdown_html)
[ "def", "render_markdown", "(", "text", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", "or", "not", "isinstance", "(", "context", ",", "dict", ")", ":", "context", "=", "{", "}", "markdown_html", "=", "_transform_markdown_into_html", "(", "text", ")", "sanitised_markdown_html", "=", "_sanitise_markdown_html", "(", "markdown_html", ")", "return", "mark_safe", "(", "sanitised_markdown_html", ")" ]
36.222222
[ 0.025, 0.2857142857142857, 0.07142857142857142, 0.2857142857142857, 0.03571428571428571, 0.1, 0.03636363636363636, 0.029411764705882353, 0.044444444444444446 ]
def and_constraint(v=1, sense="minimize"): """ AND constraint """ assert v in [0,1], "v must be 0 or 1 instead of %s" % v.__repr__() model, x, y, z = _init() r = model.addVar("r", "B") model.addConsAnd([x,y,z], r) model.addCons(x==v) model.setObjective(r, sense=sense) _optimize("AND", model)
[ "def", "and_constraint", "(", "v", "=", "1", ",", "sense", "=", "\"minimize\"", ")", ":", "assert", "v", "in", "[", "0", ",", "1", "]", ",", "\"v must be 0 or 1 instead of %s\"", "%", "v", ".", "__repr__", "(", ")", "model", ",", "x", ",", "y", ",", "z", "=", "_init", "(", ")", "r", "=", "model", ".", "addVar", "(", "\"r\"", ",", "\"B\"", ")", "model", ".", "addConsAnd", "(", "[", "x", ",", "y", ",", "z", "]", ",", "r", ")", "model", ".", "addCons", "(", "x", "==", "v", ")", "model", ".", "setObjective", "(", "r", ",", "sense", "=", "sense", ")", "_optimize", "(", "\"AND\"", ",", "model", ")" ]
35.111111
[ 0.023809523809523808, 0.07692307692307693, 0.04285714285714286, 0.07142857142857142, 0.06666666666666667, 0.125, 0.13043478260869565, 0.05263157894736842, 0.07407407407407407 ]
def argsort(indexable, key=None, reverse=False): """ Returns the indices that would sort a indexable object. This is similar to `numpy.argsort`, but it is written in pure python and works on both lists and dictionaries. Args: indexable (Iterable or Mapping): indexable to sort by key (Callable, optional): customizes the ordering of the indexable reverse (bool, optional): if True returns in descending order Returns: list: indices: list of indices such that sorts the indexable Example: >>> import ubelt as ub >>> # argsort works on dicts by returning keys >>> dict_ = {'a': 3, 'b': 2, 'c': 100} >>> indices = ub.argsort(dict_) >>> assert list(ub.take(dict_, indices)) == sorted(dict_.values()) >>> # argsort works on lists by returning indices >>> indexable = [100, 2, 432, 10] >>> indices = ub.argsort(indexable) >>> assert list(ub.take(indexable, indices)) == sorted(indexable) >>> # Can use iterators, but be careful. It exhausts them. >>> indexable = reversed(range(100)) >>> indices = ub.argsort(indexable) >>> assert indices[0] == 99 >>> # Can use key just like sorted >>> indexable = [[0, 1, 2], [3, 4], [5]] >>> indices = ub.argsort(indexable, key=len) >>> assert indices == [2, 1, 0] >>> # Can use reverse just like sorted >>> indexable = [0, 2, 1] >>> indices = ub.argsort(indexable, reverse=True) >>> assert indices == [1, 2, 0] """ # Create an iterator of value/key pairs if isinstance(indexable, collections_abc.Mapping): vk_iter = ((v, k) for k, v in indexable.items()) else: vk_iter = ((v, k) for k, v in enumerate(indexable)) # Sort by values and extract the indices if key is None: indices = [k for v, k in sorted(vk_iter, reverse=reverse)] else: # If key is provided, call it using the value as input indices = [k for v, k in sorted(vk_iter, key=lambda vk: key(vk[0]), reverse=reverse)] return indices
[ "def", "argsort", "(", "indexable", ",", "key", "=", "None", ",", "reverse", "=", "False", ")", ":", "# Create an iterator of value/key pairs", "if", "isinstance", "(", "indexable", ",", "collections_abc", ".", "Mapping", ")", ":", "vk_iter", "=", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "indexable", ".", "items", "(", ")", ")", "else", ":", "vk_iter", "=", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "enumerate", "(", "indexable", ")", ")", "# Sort by values and extract the indices", "if", "key", "is", "None", ":", "indices", "=", "[", "k", "for", "v", ",", "k", "in", "sorted", "(", "vk_iter", ",", "reverse", "=", "reverse", ")", "]", "else", ":", "# If key is provided, call it using the value as input", "indices", "=", "[", "k", "for", "v", ",", "k", "in", "sorted", "(", "vk_iter", ",", "key", "=", "lambda", "vk", ":", "key", "(", "vk", "[", "0", "]", ")", ",", "reverse", "=", "reverse", ")", "]", "return", "indices" ]
39.90566
[ 0.020833333333333332, 0.2857142857142857, 0.03389830508474576, 0, 0.039473684210526314, 0.04878048780487805, 0, 0.2222222222222222, 0.04918032786885246, 0, 0.04054054054054054, 0, 0.043478260869565216, 0, 0.16666666666666666, 0.029411764705882353, 0, 0.16666666666666666, 0.1, 0.07407407407407407, 0.06521739130434782, 0.07692307692307693, 0.04054054054054054, 0.07017543859649122, 0.07317073170731707, 0.06976744186046512, 0.0410958904109589, 0.06060606060606061, 0.06818181818181818, 0.06976744186046512, 0.08571428571428572, 0.09523809523809523, 0.0625, 0.057692307692307696, 0.07692307692307693, 0.08695652173913043, 0.09090909090909091, 0.05263157894736842, 0.07692307692307693, 0.2857142857142857, 0.046511627906976744, 0.037037037037037035, 0.03571428571428571, 0.2222222222222222, 0.03389830508474576, 0.045454545454545456, 0.10526315789473684, 0.030303030303030304, 0.2222222222222222, 0.03225806451612903, 0.04, 0.07017543859649122, 0.1111111111111111 ]
def index2qindexb(self, index): """ from a buffer index, get the QIndex (row/column coordinate system) of the byte pane """ r = index // 0x10 c = index % 0x10 return self.index(r, c)
[ "def", "index2qindexb", "(", "self", ",", "index", ")", ":", "r", "=", "index", "//", "0x10", "c", "=", "index", "%", "0x10", "return", "self", ".", "index", "(", "r", ",", "c", ")" ]
42
[ 0.03225806451612903, 0.030303030303030304, 0.08, 0.08333333333333333, 0.06451612903225806 ]
def make_fetch_func(base_url, async, **kwargs): """ make a fetch function based on conditions of 1) async 2) ssl """ if async: client = AsyncHTTPClient(force_instance=True, defaults=kwargs) return partial(async_fetch, httpclient=client) else: client = HTTPClient(force_instance=True, defaults=kwargs) return partial(sync_fetch, httpclient=client)
[ "def", "make_fetch_func", "(", "base_url", ",", "async", ",", "*", "*", "kwargs", ")", ":", "if", "async", ":", "client", "=", "AsyncHTTPClient", "(", "force_instance", "=", "True", ",", "defaults", "=", "kwargs", ")", "return", "partial", "(", "async_fetch", ",", "httpclient", "=", "client", ")", "else", ":", "client", "=", "HTTPClient", "(", "force_instance", "=", "True", ",", "defaults", "=", "kwargs", ")", "return", "partial", "(", "sync_fetch", ",", "httpclient", "=", "client", ")" ]
32.916667
[ 0.0425531914893617, 0.2857142857142857, 0.041666666666666664, 0.3333333333333333, 0.3, 0.2857142857142857, 0.23076923076923078, 0.02857142857142857, 0.037037037037037035, 0.2222222222222222, 0.03076923076923077, 0.03773584905660377 ]
def t(root, children=None, debug=False, root_id=None): "Create (DGParented)Tree from a root (str) and a list of (str, list) tuples." if isinstance(root, Tree): if children is None: return root return root.__class__(root, children, root_id) elif isinstance(root, basestring): root = debug_root_label(root, debug, root_id) # Beware: (DGParented)Tree is a subclass of list! if isinstance(children, Tree): child_trees = [children] elif isinstance(children, list): child_trees = [] for child in children: if isinstance(child, Tree): child_trees.append(child) elif isinstance(child, list): child_trees.extend(child) elif isinstance(child, tuple): child_trees.append(t(*child)) elif isinstance(child, basestring): child_trees.append(child) else: raise NotImplementedError elif isinstance(children, basestring): # this tree does only have one child, a leaf node # TODO: this is a workaround for the following problem: # Tree('foo', [Tree('bar', [])]) != Tree('foo', ['bar']) child_trees = [Tree(children, [])] else: # this tree only consists of one leaf node assert children is None child_trees = [] return DGParentedTree(root, child_trees, root_id) else: raise NotImplementedError
[ "def", "t", "(", "root", ",", "children", "=", "None", ",", "debug", "=", "False", ",", "root_id", "=", "None", ")", ":", "if", "isinstance", "(", "root", ",", "Tree", ")", ":", "if", "children", "is", "None", ":", "return", "root", "return", "root", ".", "__class__", "(", "root", ",", "children", ",", "root_id", ")", "elif", "isinstance", "(", "root", ",", "basestring", ")", ":", "root", "=", "debug_root_label", "(", "root", ",", "debug", ",", "root_id", ")", "# Beware: (DGParented)Tree is a subclass of list!", "if", "isinstance", "(", "children", ",", "Tree", ")", ":", "child_trees", "=", "[", "children", "]", "elif", "isinstance", "(", "children", ",", "list", ")", ":", "child_trees", "=", "[", "]", "for", "child", "in", "children", ":", "if", "isinstance", "(", "child", ",", "Tree", ")", ":", "child_trees", ".", "append", "(", "child", ")", "elif", "isinstance", "(", "child", ",", "list", ")", ":", "child_trees", ".", "extend", "(", "child", ")", "elif", "isinstance", "(", "child", ",", "tuple", ")", ":", "child_trees", ".", "append", "(", "t", "(", "*", "child", ")", ")", "elif", "isinstance", "(", "child", ",", "basestring", ")", ":", "child_trees", ".", "append", "(", "child", ")", "else", ":", "raise", "NotImplementedError", "elif", "isinstance", "(", "children", ",", "basestring", ")", ":", "# this tree does only have one child, a leaf node", "# TODO: this is a workaround for the following problem:", "# Tree('foo', [Tree('bar', [])]) != Tree('foo', ['bar'])", "child_trees", "=", "[", "Tree", "(", "children", ",", "[", "]", ")", "]", "else", ":", "# this tree only consists of one leaf node", "assert", "children", "is", "None", "child_trees", "=", "[", "]", "return", "DGParentedTree", "(", "root", ",", "child_trees", ",", "root_id", ")", "else", ":", "raise", "NotImplementedError" ]
35.953488
[ 0.018518518518518517, 0.037037037037037035, 0.06666666666666667, 0.07142857142857142, 0.08695652173913043, 0.037037037037037035, 0, 0.05263157894736842, 0.03773584905660377, 0, 0.03508771929824561, 0.05263157894736842, 0.05555555555555555, 0, 0.05, 0.07142857142857142, 0.058823529411764705, 0.046511627906976744, 0.044444444444444446, 0.044444444444444446, 0.044444444444444446, 0.043478260869565216, 0.04081632653061224, 0.0392156862745098, 0.044444444444444446, 0.09523809523809523, 0.044444444444444446, 0, 0.043478260869565216, 0.03278688524590164, 0.029850746268656716, 0.029411764705882353, 0.043478260869565216, 0, 0.15384615384615385, 0.037037037037037035, 0.05714285714285714, 0.07142857142857142, 0, 0.03508771929824561, 0, 0.2222222222222222, 0.06060606060606061 ]
def fsplit(file_to_split): """ Split the file and return the list of filenames. """ dirname = file_to_split + '_splitted' if not os.path.exists(dirname): os.mkdir(dirname) part_file_size = os.path.getsize(file_to_split) / number_of_files + 1 splitted_files = [] with open(file_to_split, "r") as f: number = 0 actual = 0 while 1: prec = actual # Jump of "size" from the current place in the file f.seek(part_file_size, os.SEEK_CUR) # find the next separator or EOF s = f.readline() if len(s) == 0: s = f.readline() while len(s) != 0 and s != separator: s = f.readline() # Get the current place actual = f.tell() new_file = os.path.join(dirname, str(number)) # Create the new file with open(file_to_split, "r") as temp: temp.seek(prec) # Get the text we want to put in the new file copy = temp.read(actual - prec) # Write the new file open(new_file, 'w').write(copy) splitted_files.append(new_file) number += 1 # End of file if len(s) == 0: break return splitted_files
[ "def", "fsplit", "(", "file_to_split", ")", ":", "dirname", "=", "file_to_split", "+", "'_splitted'", "if", "not", "os", ".", "path", ".", "exists", "(", "dirname", ")", ":", "os", ".", "mkdir", "(", "dirname", ")", "part_file_size", "=", "os", ".", "path", ".", "getsize", "(", "file_to_split", ")", "/", "number_of_files", "+", "1", "splitted_files", "=", "[", "]", "with", "open", "(", "file_to_split", ",", "\"r\"", ")", "as", "f", ":", "number", "=", "0", "actual", "=", "0", "while", "1", ":", "prec", "=", "actual", "# Jump of \"size\" from the current place in the file", "f", ".", "seek", "(", "part_file_size", ",", "os", ".", "SEEK_CUR", ")", "# find the next separator or EOF", "s", "=", "f", ".", "readline", "(", ")", "if", "len", "(", "s", ")", "==", "0", ":", "s", "=", "f", ".", "readline", "(", ")", "while", "len", "(", "s", ")", "!=", "0", "and", "s", "!=", "separator", ":", "s", "=", "f", ".", "readline", "(", ")", "# Get the current place", "actual", "=", "f", ".", "tell", "(", ")", "new_file", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "str", "(", "number", ")", ")", "# Create the new file", "with", "open", "(", "file_to_split", ",", "\"r\"", ")", "as", "temp", ":", "temp", ".", "seek", "(", "prec", ")", "# Get the text we want to put in the new file", "copy", "=", "temp", ".", "read", "(", "actual", "-", "prec", ")", "# Write the new file", "open", "(", "new_file", ",", "'w'", ")", ".", "write", "(", "copy", ")", "splitted_files", ".", "append", "(", "new_file", ")", "number", "+=", "1", "# End of file", "if", "len", "(", "s", ")", "==", "0", ":", "break", "return", "splitted_files" ]
31.452381
[ 0.038461538461538464, 0.2857142857142857, 0.03571428571428571, 0.2857142857142857, 0.04878048780487805, 0.05714285714285714, 0.08, 0.0273972602739726, 0.08695652173913043, 0.05128205128205128, 0.1111111111111111, 0.1111111111111111, 0.125, 0.08, 0.031746031746031744, 0.0425531914893617, 0, 0.045454545454545456, 0.07142857142857142, 0.07407407407407407, 0.0625, 0.04081632653061224, 0.0625, 0, 0.05714285714285714, 0.06896551724137931, 0.03508771929824561, 0, 0.06060606060606061, 0.04, 0.06451612903225806, 0.03278688524590164, 0.0425531914893617, 0.05555555555555555, 0.0425531914893617, 0.046511627906976744, 0.08695652173913043, 0, 0.08, 0.07407407407407407, 0.09523809523809523, 0.08 ]
def render_field(self, field, render_kw): """ Returns the rendered field after adding auto–attributes. Calls the field`s widget with the following kwargs: 1. the *render_kw* set on the field are used as based 2. and are updated with the *render_kw* arguments from the render call 3. this is used as an argument for a call to `get_html5_kwargs` 4. the return value of the call is used as final *render_kw* """ field_kw = getattr(field, 'render_kw', None) if field_kw is not None: render_kw = dict(field_kw, **render_kw) render_kw = get_html5_kwargs(field, render_kw) return field.widget(field, **render_kw)
[ "def", "render_field", "(", "self", ",", "field", ",", "render_kw", ")", ":", "field_kw", "=", "getattr", "(", "field", ",", "'render_kw'", ",", "None", ")", "if", "field_kw", "is", "not", "None", ":", "render_kw", "=", "dict", "(", "field_kw", ",", "*", "*", "render_kw", ")", "render_kw", "=", "get_html5_kwargs", "(", "field", ",", "render_kw", ")", "return", "field", ".", "widget", "(", "field", ",", "*", "*", "render_kw", ")" ]
41.176471
[ 0.024390243902439025, 0.18181818181818182, 0.03125, 0, 0.05084745762711865, 0, 0.06557377049180328, 0.05128205128205128, 0.04225352112676056, 0.04411764705882353, 0, 0.18181818181818182, 0.038461538461538464, 0.0625, 0.0392156862745098, 0.037037037037037035, 0.0425531914893617 ]
def RX(angle, qubit): """Produces the RX gate:: RX(phi) = [[cos(phi / 2), -1j * sin(phi / 2)], [-1j * sin(phi / 2), cos(phi / 2)]] This gate is a single qubit X-rotation. :param angle: The angle to rotate around the x-axis on the bloch sphere. :param qubit: The qubit apply the gate to. :returns: A Gate object. """ return Gate(name="RX", params=[angle], qubits=[unpack_qubit(qubit)])
[ "def", "RX", "(", "angle", ",", "qubit", ")", ":", "return", "Gate", "(", "name", "=", "\"RX\"", ",", "params", "=", "[", "angle", "]", ",", "qubits", "=", "[", "unpack_qubit", "(", "qubit", ")", "]", ")" ]
33.076923
[ 0.047619047619047616, 0.06896551724137931, 0, 0.05555555555555555, 0.07407407407407407, 0, 0.046511627906976744, 0, 0.039473684210526314, 0.06521739130434782, 0.10714285714285714, 0.2857142857142857, 0.027777777777777776 ]
def getaddrlist(self, name): """Get a list of addresses from a header. Retrieves a list of addresses from a header, where each address is a tuple as returned by getaddr(). Scans all named headers, so it works properly with multiple To: or Cc: headers for example. """ raw = [] for h in self.getallmatchingheaders(name): if h[0] in ' \t': raw.append(h) else: if raw: raw.append(', ') i = h.find(':') if i > 0: addr = h[i+1:] raw.append(addr) alladdrs = ''.join(raw) a = AddressList(alladdrs) return a.addresslist
[ "def", "getaddrlist", "(", "self", ",", "name", ")", ":", "raw", "=", "[", "]", "for", "h", "in", "self", ".", "getallmatchingheaders", "(", "name", ")", ":", "if", "h", "[", "0", "]", "in", "' \\t'", ":", "raw", ".", "append", "(", "h", ")", "else", ":", "if", "raw", ":", "raw", ".", "append", "(", "', '", ")", "i", "=", "h", ".", "find", "(", "':'", ")", "if", "i", ">", "0", ":", "addr", "=", "h", "[", "i", "+", "1", ":", "]", "raw", ".", "append", "(", "addr", ")", "alladdrs", "=", "''", ".", "join", "(", "raw", ")", "a", "=", "AddressList", "(", "alladdrs", ")", "return", "a", ".", "addresslist" ]
34.142857
[ 0.03571428571428571, 0.04081632653061224, 0, 0.02631578947368421, 0.025974025974025976, 0.03225806451612903, 0.18181818181818182, 0.125, 0.04, 0.06896551724137931, 0.06896551724137931, 0.11764705882352941, 0.08695652173913043, 0.05555555555555555, 0.06451612903225806, 0.08, 0.058823529411764705, 0.0625, 0.06451612903225806, 0.06060606060606061, 0.07142857142857142 ]
def _calc_avg_and_last_val(self, has_no_column, sum_existing_columns): """ Calculate the average of all columns and return a rounded down number. Store the remainder and add it to the last row. Could be implemented better. If the enduser wants more control, he can also just add the amount of columns. Will work fine with small number (<4) of items in a row. :param has_no_column: :param sum_existing_columns: :return: average, columns_for_last_element """ sum_no_columns = len(has_no_column) columns_left = self.ALLOWED_COLUMNS - sum_existing_columns if sum_no_columns == 0: columns_avg = columns_left else: columns_avg = int(columns_left / sum_no_columns) remainder = columns_left - (columns_avg * sum_no_columns) columns_for_last_element = columns_avg + remainder return columns_avg, columns_for_last_element
[ "def", "_calc_avg_and_last_val", "(", "self", ",", "has_no_column", ",", "sum_existing_columns", ")", ":", "sum_no_columns", "=", "len", "(", "has_no_column", ")", "columns_left", "=", "self", ".", "ALLOWED_COLUMNS", "-", "sum_existing_columns", "if", "sum_no_columns", "==", "0", ":", "columns_avg", "=", "columns_left", "else", ":", "columns_avg", "=", "int", "(", "columns_left", "/", "sum_no_columns", ")", "remainder", "=", "columns_left", "-", "(", "columns_avg", "*", "sum_no_columns", ")", "columns_for_last_element", "=", "columns_avg", "+", "remainder", "return", "columns_avg", ",", "columns_for_last_element" ]
41.391304
[ 0.014285714285714285, 0.18181818181818182, 0.02564102564102564, 0.02631578947368421, 0.02666666666666667, 0.05128205128205128, 0.16666666666666666, 0, 0.10344827586206896, 0.08333333333333333, 0.06, 0.18181818181818182, 0.046511627906976744, 0.030303030303030304, 0, 0.06451612903225806, 0.05263157894736842, 0.15384615384615385, 0.03333333333333333, 0, 0.03076923076923077, 0.034482758620689655, 0.038461538461538464 ]
def _find(self, url): """Return properties document for path.""" # Query the permanent view to find a url vr = self.db.view("properties/by_url", key=url, include_docs=True) _logger.debug("find(%r) returned %s" % (url, len(vr))) assert len(vr) <= 1, "Found multiple matches for %r" % url for row in vr: assert row.doc return row.doc return None
[ "def", "_find", "(", "self", ",", "url", ")", ":", "# Query the permanent view to find a url", "vr", "=", "self", ".", "db", ".", "view", "(", "\"properties/by_url\"", ",", "key", "=", "url", ",", "include_docs", "=", "True", ")", "_logger", ".", "debug", "(", "\"find(%r) returned %s\"", "%", "(", "url", ",", "len", "(", "vr", ")", ")", ")", "assert", "len", "(", "vr", ")", "<=", "1", ",", "\"Found multiple matches for %r\"", "%", "url", "for", "row", "in", "vr", ":", "assert", "row", ".", "doc", "return", "row", ".", "doc", "return", "None" ]
41.4
[ 0.047619047619047616, 0.04, 0.041666666666666664, 0.02702702702702703, 0.03225806451612903, 0.030303030303030304, 0.09090909090909091, 0.07692307692307693, 0.07692307692307693, 0.10526315789473684 ]
def get_build_log_zip(self, project, build_id, log_id, start_line=None, end_line=None, **kwargs): """GetBuildLogZip. Gets an individual log file for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param int log_id: The ID of the log file. :param long start_line: The start line. :param long end_line: The end line. :rtype: object """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if build_id is not None: route_values['buildId'] = self._serialize.url('build_id', build_id, 'int') if log_id is not None: route_values['logId'] = self._serialize.url('log_id', log_id, 'int') query_parameters = {} if start_line is not None: query_parameters['startLine'] = self._serialize.query('start_line', start_line, 'long') if end_line is not None: query_parameters['endLine'] = self._serialize.query('end_line', end_line, 'long') response = self._send(http_method='GET', location_id='35a80daf-7f30-45fc-86e8-6b813d9c90df', version='5.0', route_values=route_values, query_parameters=query_parameters, accept_media_type='application/zip') if "callback" in kwargs: callback = kwargs["callback"] else: callback = None return self._client.stream_download(response, callback=callback)
[ "def", "get_build_log_zip", "(", "self", ",", "project", ",", "build_id", ",", "log_id", ",", "start_line", "=", "None", ",", "end_line", "=", "None", ",", "*", "*", "kwargs", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'project'", ",", "project", ",", "'str'", ")", "if", "build_id", "is", "not", "None", ":", "route_values", "[", "'buildId'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'build_id'", ",", "build_id", ",", "'int'", ")", "if", "log_id", "is", "not", "None", ":", "route_values", "[", "'logId'", "]", "=", "self", ".", "_serialize", ".", "url", "(", "'log_id'", ",", "log_id", ",", "'int'", ")", "query_parameters", "=", "{", "}", "if", "start_line", "is", "not", "None", ":", "query_parameters", "[", "'startLine'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "'start_line'", ",", "start_line", ",", "'long'", ")", "if", "end_line", "is", "not", "None", ":", "query_parameters", "[", "'endLine'", "]", "=", "self", ".", "_serialize", ".", "query", "(", "'end_line'", ",", "end_line", ",", "'long'", ")", "response", "=", "self", ".", "_send", "(", "http_method", "=", "'GET'", ",", "location_id", "=", "'35a80daf-7f30-45fc-86e8-6b813d9c90df'", ",", "version", "=", "'5.0'", ",", "route_values", "=", "route_values", ",", "query_parameters", "=", "query_parameters", ",", "accept_media_type", "=", "'application/zip'", ")", "if", "\"callback\"", "in", "kwargs", ":", "callback", "=", "kwargs", "[", "\"callback\"", "]", "else", ":", "callback", "=", "None", "return", "self", ".", "_client", ".", "stream_download", "(", "response", ",", "callback", "=", "callback", ")" ]
49.878788
[ 0.020618556701030927, 0.07692307692307693, 0.041666666666666664, 0.05555555555555555, 0.061224489795918366, 0.06, 0.06382978723404255, 0.06976744186046512, 0.13636363636363635, 0.18181818181818182, 0.08, 0.06451612903225806, 0.03571428571428571, 0.0625, 0.03488372093023256, 0.06666666666666667, 0.0375, 0.06896551724137931, 0.058823529411764705, 0.030303030303030304, 0.0625, 0.03225806451612903, 0.0625, 0.06172839506172839, 0.09090909090909091, 0.07142857142857142, 0.0625, 0.07575757575757576, 0.0625, 0.04878048780487805, 0.15384615384615385, 0.07407407407407407, 0.027777777777777776 ]
def commitreturn(self, cursor, qstring, vals=()): "careful: don't pass cursor (it's from decorator)" cursor.execute(qstring, vals) return cursor.fetchall()[0]
[ "def", "commitreturn", "(", "self", ",", "cursor", ",", "qstring", ",", "vals", "=", "(", ")", ")", ":", "cursor", ".", "execute", "(", "qstring", ",", "vals", ")", "return", "cursor", ".", "fetchall", "(", ")", "[", "0", "]" ]
41.75
[ 0.02040816326530612, 0.037037037037037035, 0.06060606060606061, 0.06451612903225806 ]
def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: """Generator for streaming request body data. """ chunk_size = chunk_size or CONTENT_CHUNK_SIZE async def async_gen(resp): while True: chunk = await resp.content.read(chunk_size) if not chunk: break callback(chunk, resp) return async_gen(self.internal_response)
[ "def", "stream_download", "(", "self", ",", "chunk_size", ":", "Optional", "[", "int", "]", "=", "None", ",", "callback", ":", "Optional", "[", "Callable", "]", "=", "None", ")", "->", "AsyncIterator", "[", "bytes", "]", ":", "chunk_size", "=", "chunk_size", "or", "CONTENT_CHUNK_SIZE", "async", "def", "async_gen", "(", "resp", ")", ":", "while", "True", ":", "chunk", "=", "await", "resp", ".", "content", ".", "read", "(", "chunk_size", ")", "if", "not", "chunk", ":", "break", "callback", "(", "chunk", ",", "resp", ")", "return", "async_gen", "(", "self", ".", "internal_response", ")" ]
44.818182
[ 0.01652892561983471, 0.03773584905660377, 0.18181818181818182, 0.03773584905660377, 0.058823529411764705, 0.08695652173913043, 0.03389830508474576, 0.06896551724137931, 0.08, 0.05405405405405406, 0.041666666666666664 ]
def stop(self): """ Stops monitoring the predefined directory. """ with self._status_lock: if self._running: assert self._observer is not None self._observer.stop() self._running = False self._origin_mapped_data = dict()
[ "def", "stop", "(", "self", ")", ":", "with", "self", ".", "_status_lock", ":", "if", "self", ".", "_running", ":", "assert", "self", ".", "_observer", "is", "not", "None", "self", ".", "_observer", ".", "stop", "(", ")", "self", ".", "_running", "=", "False", "self", ".", "_origin_mapped_data", "=", "dict", "(", ")" ]
31.9
[ 0.06666666666666667, 0.18181818181818182, 0.04, 0.18181818181818182, 0.06451612903225806, 0.06896551724137931, 0.04081632653061224, 0.05405405405405406, 0.05405405405405406, 0.04081632653061224 ]
def cartesian_args(args, listargs, dictargs): """ Compute a list of inputs and outputs for a function with kw arguments. args: dict fixed arguments, e.g. {'x': 3}, then x=3 for all inputs listargs: dict arguments specified as a list; then the inputs should be the Cartesian products of these lists dictargs: dict same as above, except the key will be used in the output (see module doc for more explanation) """ ils = {k: [v, ] for k, v in args.items()} ils.update(listargs) ils.update({k: v.values() for k, v in dictargs.items()}) ols = listargs.copy() ols.update({k: v.keys() for k, v in dictargs.items()}) return cartesian_lists(ils), cartesian_lists(ols)
[ "def", "cartesian_args", "(", "args", ",", "listargs", ",", "dictargs", ")", ":", "ils", "=", "{", "k", ":", "[", "v", ",", "]", "for", "k", ",", "v", "in", "args", ".", "items", "(", ")", "}", "ils", ".", "update", "(", "listargs", ")", "ils", ".", "update", "(", "{", "k", ":", "v", ".", "values", "(", ")", "for", "k", ",", "v", "in", "dictargs", ".", "items", "(", ")", "}", ")", "ols", "=", "listargs", ".", "copy", "(", ")", "ols", ".", "update", "(", "{", "k", ":", "v", ".", "keys", "(", ")", "for", "k", ",", "v", "in", "dictargs", ".", "items", "(", ")", "}", ")", "return", "cartesian_lists", "(", "ils", ")", ",", "cartesian_lists", "(", "ols", ")" ]
36.35
[ 0.022222222222222223, 0.03389830508474576, 0.09090909090909091, 0, 0.14285714285714285, 0.06557377049180328, 0.1111111111111111, 0.05555555555555555, 0.03636363636363636, 0.1111111111111111, 0.03125, 0.044444444444444446, 0, 0.2857142857142857, 0.044444444444444446, 0.08333333333333333, 0.03333333333333333, 0.08, 0.034482758620689655, 0.03773584905660377 ]
def monthly_wind_conditions(self): """A list of 12 monthly wind conditions that are used on the design days.""" return [WindCondition(x, y) for x, y in zip( self._monthly_wind, self.monthly_wind_dirs)]
[ "def", "monthly_wind_conditions", "(", "self", ")", ":", "return", "[", "WindCondition", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "self", ".", "_monthly_wind", ",", "self", ".", "monthly_wind_dirs", ")", "]" ]
56.5
[ 0.029411764705882353, 0.03571428571428571, 0.057692307692307696, 0.05357142857142857 ]
def analog_latch_callback(self, data): """ This method handles analog_latch data received from pymata_core :param data: analog latch callback message :returns:{"method": "analog_latch_data_reply", "params": [ANALOG_PIN, VALUE_AT_TRIGGER, TIME_STAMP_STRING]} """ ts = data[2] st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S') reply = json.dumps({"method": "analog_latch_data_reply", "params": [data[0], data[1], st]}) asyncio.ensure_future(self.websocket.send(reply))
[ "def", "analog_latch_callback", "(", "self", ",", "data", ")", ":", "ts", "=", "data", "[", "2", "]", "st", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "ts", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "reply", "=", "json", ".", "dumps", "(", "{", "\"method\"", ":", "\"analog_latch_data_reply\"", ",", "\"params\"", ":", "[", "data", "[", "0", "]", ",", "data", "[", "1", "]", ",", "st", "]", "}", ")", "asyncio", ".", "ensure_future", "(", "self", ".", "websocket", ".", "send", "(", "reply", ")", ")" ]
55
[ 0.02631578947368421, 0.18181818181818182, 0.028169014084507043, 0.06, 0.043478260869565216, 0.18181818181818182, 0.1, 0.02564102564102564, 0.030303030303030304, 0.03508771929824561 ]
def sendPygletEvent(self,event_type,args,window=None): """ Handles a pyglet event. This method is called by :py:meth:`PengWindow.dispatch_event()` and handles all events. See :py:meth:`registerEventHandler()` for how to listen to these events. This method should be used to send pyglet events. For new code, it is recommended to use :py:meth:`sendEvent()` instead. For "tunneling" pyglet events, use event names of the format ``pyglet:<event>`` and for the data use ``{"args":<args as list>,"window":<window object or none>,"src":<event source>,"event_type":<event type>}`` Note that you should send pyglet events only via this method, the above event will be sent automatically. Do not use this method to send custom events, use :py:meth:`sendEvent` instead. """ args = list(args) self.sendEvent("pyglet:%s"%event_type,{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type}) self.sendEvent("peng3d:pyglet",{"peng":self,"args":args,"window":window,"src":self,"event_type":event_type}) if event_type not in ["on_draw","on_mouse_motion"] and self.cfg["debug.events.dump"]: print("Event %s with args %s"%(event_type,args)) if event_type in self.pygletEventHandlers: for whandler in self.pygletEventHandlers[event_type]: # This allows for proper collection of deleted handler methods by using weak references handler = whandler() if handler is None: del self.pygletEventHandlers[event_type][self.pygletEventHandlers[event_type].index(whandler)] handler(*args)
[ "def", "sendPygletEvent", "(", "self", ",", "event_type", ",", "args", ",", "window", "=", "None", ")", ":", "args", "=", "list", "(", "args", ")", "self", ".", "sendEvent", "(", "\"pyglet:%s\"", "%", "event_type", ",", "{", "\"peng\"", ":", "self", ",", "\"args\"", ":", "args", ",", "\"window\"", ":", "window", ",", "\"src\"", ":", "self", ",", "\"event_type\"", ":", "event_type", "}", ")", "self", ".", "sendEvent", "(", "\"peng3d:pyglet\"", ",", "{", "\"peng\"", ":", "self", ",", "\"args\"", ":", "args", ",", "\"window\"", ":", "window", ",", "\"src\"", ":", "self", ",", "\"event_type\"", ":", "event_type", "}", ")", "if", "event_type", "not", "in", "[", "\"on_draw\"", ",", "\"on_mouse_motion\"", "]", "and", "self", ".", "cfg", "[", "\"debug.events.dump\"", "]", ":", "print", "(", "\"Event %s with args %s\"", "%", "(", "event_type", ",", "args", ")", ")", "if", "event_type", "in", "self", ".", "pygletEventHandlers", ":", "for", "whandler", "in", "self", ".", "pygletEventHandlers", "[", "event_type", "]", ":", "# This allows for proper collection of deleted handler methods by using weak references", "handler", "=", "whandler", "(", ")", "if", "handler", "is", "None", ":", "del", "self", ".", "pygletEventHandlers", "[", "event_type", "]", "[", "self", ".", "pygletEventHandlers", "[", "event_type", "]", ".", "index", "(", "whandler", ")", "]", "handler", "(", "*", "args", ")" ]
56.322581
[ 0.07407407407407407, 0.18181818181818182, 0.06451612903225806, 0.25, 0.08421052631578947, 0.25, 0.1, 0.25, 0.03508771929824561, 0.08974358974358974, 0.08045977011494253, 0.13970588235294118, 0.25, 0.02654867256637168, 0.25, 0.09195402298850575, 0.18181818181818182, 0.08, 0.25, 0.11382113821138211, 0.11206896551724138, 0.25, 0.043010752688172046, 0.06666666666666667, 0.04, 0.03076923076923077, 0.02912621359223301, 0.05555555555555555, 0.05714285714285714, 0.02631578947368421, 0.06666666666666667 ]
def setup_pins(self, pins, values={}, write=True): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin mode (IN or OUT). Optional starting values of pins can be provided in the values dict (with pin name to pin value). """ # General implementation that can be improved by subclasses. for pin, mode in iter(pins.items()): self._setup_pin(pin, mode) for pin, value in iter(values.items()): self._output_pin(pin, value) if write: self.mpsse_write_gpio()
[ "def", "setup_pins", "(", "self", ",", "pins", ",", "values", "=", "{", "}", ",", "write", "=", "True", ")", ":", "# General implementation that can be improved by subclasses.", "for", "pin", ",", "mode", "in", "iter", "(", "pins", ".", "items", "(", ")", ")", ":", "self", ".", "_setup_pin", "(", "pin", ",", "mode", ")", "for", "pin", ",", "value", "in", "iter", "(", "values", ".", "items", "(", ")", ")", ":", "self", ".", "_output_pin", "(", "pin", ",", "value", ")", "if", "write", ":", "self", ".", "mpsse_write_gpio", "(", ")" ]
48.583333
[ 0.02, 0.02564102564102564, 0.038461538461538464, 0.03896103896103896, 0.18181818181818182, 0.029411764705882353, 0.045454545454545456, 0.05263157894736842, 0.0425531914893617, 0.05, 0.11764705882352941, 0.05714285714285714 ]
def batch_message(cls, batch, request_ids): '''Convert a request Batch to a message.''' assert isinstance(batch, Batch) if not cls.allow_batches: raise ProtocolError.invalid_request( 'protocol does not permit batches') id_iter = iter(request_ids) rm = cls.request_message nm = cls.notification_message parts = (rm(request, next(id_iter)) if isinstance(request, Request) else nm(request) for request in batch) return cls.batch_message_from_parts(parts)
[ "def", "batch_message", "(", "cls", ",", "batch", ",", "request_ids", ")", ":", "assert", "isinstance", "(", "batch", ",", "Batch", ")", "if", "not", "cls", ".", "allow_batches", ":", "raise", "ProtocolError", ".", "invalid_request", "(", "'protocol does not permit batches'", ")", "id_iter", "=", "iter", "(", "request_ids", ")", "rm", "=", "cls", ".", "request_message", "nm", "=", "cls", ".", "notification_message", "parts", "=", "(", "rm", "(", "request", ",", "next", "(", "id_iter", ")", ")", "if", "isinstance", "(", "request", ",", "Request", ")", "else", "nm", "(", "request", ")", "for", "request", "in", "batch", ")", "return", "cls", ".", "batch_message_from_parts", "(", "parts", ")" ]
45.75
[ 0.023255813953488372, 0.0392156862745098, 0.05128205128205128, 0.06060606060606061, 0.0625, 0.058823529411764705, 0.05714285714285714, 0.0625, 0.05405405405405406, 0.04, 0.07272727272727272, 0.04 ]
def yaml_squote(text): ''' Make text into a single-quoted YAML string with correct escaping for special characters. Includes the opening and closing single quote characters. ''' with io.StringIO() as ostream: yemitter = yaml.emitter.Emitter(ostream, width=six.MAXSIZE) yemitter.write_single_quoted(six.text_type(text)) return ostream.getvalue()
[ "def", "yaml_squote", "(", "text", ")", ":", "with", "io", ".", "StringIO", "(", ")", "as", "ostream", ":", "yemitter", "=", "yaml", ".", "emitter", ".", "Emitter", "(", "ostream", ",", "width", "=", "six", ".", "MAXSIZE", ")", "yemitter", ".", "write_single_quoted", "(", "six", ".", "text_type", "(", "text", ")", ")", "return", "ostream", ".", "getvalue", "(", ")" ]
38.4
[ 0.045454545454545456, 0.2857142857142857, 0.029411764705882353, 0.029411764705882353, 0.09523809523809523, 0.2857142857142857, 0.058823529411764705, 0.029850746268656716, 0.03508771929824561, 0.06060606060606061 ]
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest # null else: lexer.unpop_token(tok) return tuple()
[ "def", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", ":", "tok", "=", "next", "(", "lexer", ")", "toktype", "=", "type", "(", "tok", ")", "if", "toktype", "is", "OP_not", "or", "toktype", "is", "IntegerToken", ":", "lexer", ".", "unpop_token", "(", "tok", ")", "first", "=", "_clause", "(", "lexer", ",", "varname", ",", "nvars", ")", "rest", "=", "_clauses", "(", "lexer", ",", "varname", ",", "nvars", ")", "return", "(", "first", ",", ")", "+", "rest", "# null", "else", ":", "lexer", ".", "unpop_token", "(", "tok", ")", "return", "tuple", "(", ")" ]
31
[ 0.027777777777777776, 0.0425531914893617, 0.09523809523809523, 0.08695652173913043, 0.038461538461538464, 0.06666666666666667, 0.043478260869565216, 0.043478260869565216, 0.06451612903225806, 0.2, 0.2222222222222222, 0.06666666666666667, 0.09090909090909091 ]
def newKernel(self, nb): """ generate a new kernel """ manager, kernel = utils.start_new_kernel( kernel_name=nb.metadata.kernelspec.name ) return kernel
[ "def", "newKernel", "(", "self", ",", "nb", ")", ":", "manager", ",", "kernel", "=", "utils", ".", "start_new_kernel", "(", "kernel_name", "=", "nb", ".", "metadata", ".", "kernelspec", ".", "name", ")", "return", "kernel" ]
25.625
[ 0.041666666666666664, 0.18181818181818182, 0.06896551724137931, 0.18181818181818182, 0.061224489795918366, 0.058823529411764705, 0.3333333333333333, 0.09523809523809523 ]
def load_default_run_plugins(self): """ Load default run level plugins from icetea_lib.Plugin.plugins.default_plugins. :return: Nothing """ for plugin_name, plugin_class in default_plugins.items(): if issubclass(plugin_class, RunPluginBase): try: self.register_run_plugins(plugin_name, plugin_class()) except PluginException as error: self.logger.debug(error) continue
[ "def", "load_default_run_plugins", "(", "self", ")", ":", "for", "plugin_name", ",", "plugin_class", "in", "default_plugins", ".", "items", "(", ")", ":", "if", "issubclass", "(", "plugin_class", ",", "RunPluginBase", ")", ":", "try", ":", "self", ".", "register_run_plugins", "(", "plugin_name", ",", "plugin_class", "(", ")", ")", "except", "PluginException", "as", "error", ":", "self", ".", "logger", ".", "debug", "(", "error", ")", "continue" ]
38.538462
[ 0.02857142857142857, 0.18181818181818182, 0.03488372093023256, 0, 0.125, 0.18181818181818182, 0.03076923076923077, 0.03636363636363636, 0.1, 0.02702702702702703, 0.041666666666666664, 0.045454545454545456, 0.07142857142857142 ]
def set_cpu_property(self, property_p, value): """Sets the virtual CPU boolean value of the specified property. in property_p of type :class:`CPUPropertyType` Property type to query. in value of type bool Property value. raises :class:`OleErrorInvalidarg` Invalid property. """ if not isinstance(property_p, CPUPropertyType): raise TypeError("property_p can only be an instance of type CPUPropertyType") if not isinstance(value, bool): raise TypeError("value can only be an instance of type bool") self._call("setCPUProperty", in_p=[property_p, value])
[ "def", "set_cpu_property", "(", "self", ",", "property_p", ",", "value", ")", ":", "if", "not", "isinstance", "(", "property_p", ",", "CPUPropertyType", ")", ":", "raise", "TypeError", "(", "\"property_p can only be an instance of type CPUPropertyType\"", ")", "if", "not", "isinstance", "(", "value", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"value can only be an instance of type bool\"", ")", "self", ".", "_call", "(", "\"setCPUProperty\"", ",", "in_p", "=", "[", "property_p", ",", "value", "]", ")" ]
36.368421
[ 0.021739130434782608, 0.027777777777777776, 0, 0.1111111111111111, 0.05714285714285714, 0, 0.06896551724137931, 0.07407407407407407, 0, 0.14285714285714285, 0.06896551724137931, 0.25, 0.18181818181818182, 0.03636363636363636, 0.033707865168539325, 0.05128205128205128, 0.0273972602739726, 0.08333333333333333, 0.10869565217391304 ]
def match_length(self): """ Find the total length of all words that match between the two sequences.""" length = 0 for match in self.get_matching_blocks(): a, b, size = match length += self._text_length(self.a[a:a+size]) return length
[ "def", "match_length", "(", "self", ")", ":", "length", "=", "0", "for", "match", "in", "self", ".", "get_matching_blocks", "(", ")", ":", "a", ",", "b", ",", "size", "=", "match", "length", "+=", "self", ".", "_text_length", "(", "self", ".", "a", "[", "a", ":", "a", "+", "size", "]", ")", "return", "length" ]
40.571429
[ 0.043478260869565216, 0.034482758620689655, 0.1111111111111111, 0.041666666666666664, 0.06666666666666667, 0.03508771929824561, 0.09523809523809523 ]
def parallel_snr_func(num, binary_args, phenomdwave, signal_type, noise_interpolants, prefactor, verbose): """SNR calulation with PhenomDWaveforms Generate PhenomDWaveforms and calculate their SNR against sensitivity curves. Args: num (int): Process number. If only a single process, num=0. binary_args (tuple): Binary arguments for :meth:`gwsnrcalc.utils.waveforms.EccentricBinaries.__call__`. phenomdwave (obj): Initialized class of :class:`gwsnrcalc.utils.waveforms.PhenomDWaveforms`. signal_type (list of str): List with types of SNR to calculate. Options are `all` for full wavefrom, `ins` for inspiral, `mrg` for merger, and/or `rd` for ringdown. noise_interpolants (dict): All the noise noise interpolants generated by :mod:`gwsnrcalc.utils.sensitivity`. prefactor (float): Prefactor to multiply SNR by (not SNR^2). verbose (int): Notify each time ``verbose`` processes finish. If -1, then no notification. Returns: (dict): Dictionary with the SNR output from the calculation. """ wave = phenomdwave(*binary_args) out_vals = {} for key in noise_interpolants: hn_vals = noise_interpolants[key](wave.freqs) snr_out = csnr(wave.freqs, wave.hc, hn_vals, wave.fmrg, wave.fpeak, prefactor=prefactor) if len(signal_type) == 1: out_vals[key + '_' + signal_type[0]] = snr_out[signal_type[0]] else: for phase in signal_type: out_vals[key + '_' + phase] = snr_out[phase] if verbose > 0 and (num+1) % verbose == 0: print('Process ', (num+1), 'is finished.') return out_vals
[ "def", "parallel_snr_func", "(", "num", ",", "binary_args", ",", "phenomdwave", ",", "signal_type", ",", "noise_interpolants", ",", "prefactor", ",", "verbose", ")", ":", "wave", "=", "phenomdwave", "(", "*", "binary_args", ")", "out_vals", "=", "{", "}", "for", "key", "in", "noise_interpolants", ":", "hn_vals", "=", "noise_interpolants", "[", "key", "]", "(", "wave", ".", "freqs", ")", "snr_out", "=", "csnr", "(", "wave", ".", "freqs", ",", "wave", ".", "hc", ",", "hn_vals", ",", "wave", ".", "fmrg", ",", "wave", ".", "fpeak", ",", "prefactor", "=", "prefactor", ")", "if", "len", "(", "signal_type", ")", "==", "1", ":", "out_vals", "[", "key", "+", "'_'", "+", "signal_type", "[", "0", "]", "]", "=", "snr_out", "[", "signal_type", "[", "0", "]", "]", "else", ":", "for", "phase", "in", "signal_type", ":", "out_vals", "[", "key", "+", "'_'", "+", "phase", "]", "=", "snr_out", "[", "phase", "]", "if", "verbose", ">", "0", "and", "(", "num", "+", "1", ")", "%", "verbose", "==", "0", ":", "print", "(", "'Process '", ",", "(", "num", "+", "1", ")", ",", "'is finished.'", ")", "return", "out_vals" ]
40.093023
[ 0.03076923076923077, 0.06451612903225806, 0.046511627906976744, 0, 0.037037037037037035, 0, 0.2222222222222222, 0.05970149253731343, 0.061224489795918366, 0.0684931506849315, 0.06382978723404255, 0.078125, 0.04225352112676056, 0.0625, 0.06666666666666667, 0.05, 0.10638297872340426, 0.07352941176470588, 0.061224489795918366, 0, 0.16666666666666666, 0.029411764705882353, 0, 0.2857142857142857, 0, 0.05555555555555555, 0, 0.11764705882352941, 0, 0.058823529411764705, 0.03773584905660377, 0.057692307692307696, 0.07575757575757576, 0, 0.06060606060606061, 0.02702702702702703, 0.15384615384615385, 0.05405405405405406, 0.03333333333333333, 0.043478260869565216, 0.04, 0, 0.10526315789473684 ]
def extract(self, point_x, point_y, radius=0): ''' geo.extract(x, y, radius=r) Return subraster of raster geo around location (x,y) with radius r where (x,y) and r are in the same coordinate system as geo ''' row, col = map_pixel(point_x, point_y, self.x_cell_size, self.y_cell_size, self.xmin, self.ymax) col2 = np.abs(radius/self.x_cell_size).astype(int) row2 = np.abs(radius/self.y_cell_size).astype(int) return GeoRaster(self.raster[max(row-row2, 0):min(row+row2+1, self.shape[0]), \ max(col-col2, 0):min(col+col2+1, self.shape[1])], self.geot, nodata_value=self.nodata_value,\ projection=self.projection, datatype=self.datatype)
[ "def", "extract", "(", "self", ",", "point_x", ",", "point_y", ",", "radius", "=", "0", ")", ":", "row", ",", "col", "=", "map_pixel", "(", "point_x", ",", "point_y", ",", "self", ".", "x_cell_size", ",", "self", ".", "y_cell_size", ",", "self", ".", "xmin", ",", "self", ".", "ymax", ")", "col2", "=", "np", ".", "abs", "(", "radius", "/", "self", ".", "x_cell_size", ")", ".", "astype", "(", "int", ")", "row2", "=", "np", ".", "abs", "(", "radius", "/", "self", ".", "y_cell_size", ")", ".", "astype", "(", "int", ")", "return", "GeoRaster", "(", "self", ".", "raster", "[", "max", "(", "row", "-", "row2", ",", "0", ")", ":", "min", "(", "row", "+", "row2", "+", "1", ",", "self", ".", "shape", "[", "0", "]", ")", ",", "max", "(", "col", "-", "col2", ",", "0", ")", ":", "min", "(", "col", "+", "col2", "+", "1", ",", "self", ".", "shape", "[", "1", "]", ")", "]", ",", "self", ".", "geot", ",", "nodata_value", "=", "self", ".", "nodata_value", ",", "projection", "=", "self", ".", "projection", ",", "datatype", "=", "self", ".", "datatype", ")" ]
52.866667
[ 0.021739130434782608, 0.18181818181818182, 0.05714285714285714, 0, 0.05405405405405406, 0.06060606060606061, 0.18181818181818182, 0.04878048780487805, 0.08, 0.034482758620689655, 0.034482758620689655, 0.04597701149425287, 0.05952380952380952, 0.07142857142857142, 0.06666666666666667 ]
def find(self, instance_id): """ find an instance Create a new instance and populate it with data stored if it exists. Args: instance_id (str): UUID of the instance Returns: AtlasServiceInstance.Instance: An instance """ instance = AtlasServiceInstance.Instance(instance_id, self.backend) self.backend.storage.populate(instance) return instance
[ "def", "find", "(", "self", ",", "instance_id", ")", ":", "instance", "=", "AtlasServiceInstance", ".", "Instance", "(", "instance_id", ",", "self", ".", "backend", ")", "self", ".", "backend", ".", "storage", ".", "populate", "(", "instance", ")", "return", "instance" ]
31.857143
[ 0.03571428571428571, 0.07142857142857142, 0.25, 0.02631578947368421, 0.25, 0.15384615384615385, 0.058823529411764705, 0.25, 0.125, 0.037037037037037035, 0.18181818181818182, 0.02666666666666667, 0.0425531914893617, 0.08695652173913043 ]
def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track information across calls to the method. :returns: Bytes that may be transmitted on the stream. """ # Generate and return the frame return (self.begin + self.nop.join(six.binary_type(frame).split(self.prefix)) + self.end)
[ "def", "to_bytes", "(", "self", ",", "frame", ",", "state", ")", ":", "# Generate and return the frame", "return", "(", "self", ".", "begin", "+", "self", ".", "nop", ".", "join", "(", "six", ".", "binary_type", "(", "frame", ")", ".", "split", "(", "self", ".", "prefix", ")", ")", "+", "self", ".", "end", ")" ]
37
[ 0.030303030303030304, 0.18181818181818182, 0.029411764705882353, 0.10526315789473684, 0, 0.04411764705882353, 0.06779661016949153, 0.05714285714285714, 0.04285714285714286, 0.10344827586206896, 0, 0.04838709677419355, 0.18181818181818182, 0, 0.05128205128205128, 0.10714285714285714, 0.02702702702702703, 0.12 ]
def update_positions(self, time, xs, ys, zs, vxs, vys, vzs, ethetas, elongans, eincls, ds=None, Fs=None, ignore_effects=False): """ TODO: add documentation all arrays should be for the current time, but iterable over all bodies """ self.xs = np.array(_value(xs)) self.ys = np.array(_value(ys)) self.zs = np.array(_value(zs)) for starref,body in self.items(): body.update_position(time, xs, ys, zs, vxs, vys, vzs, ethetas, elongans, eincls, ds=ds, Fs=Fs, ignore_effects=ignore_effects)
[ "def", "update_positions", "(", "self", ",", "time", ",", "xs", ",", "ys", ",", "zs", ",", "vxs", ",", "vys", ",", "vzs", ",", "ethetas", ",", "elongans", ",", "eincls", ",", "ds", "=", "None", ",", "Fs", "=", "None", ",", "ignore_effects", "=", "False", ")", ":", "self", ".", "xs", "=", "np", ".", "array", "(", "_value", "(", "xs", ")", ")", "self", ".", "ys", "=", "np", ".", "array", "(", "_value", "(", "ys", ")", ")", "self", ".", "zs", "=", "np", ".", "array", "(", "_value", "(", "zs", ")", ")", "for", "starref", ",", "body", "in", "self", ".", "items", "(", ")", ":", "body", ".", "update_position", "(", "time", ",", "xs", ",", "ys", ",", "zs", ",", "vxs", ",", "vys", ",", "vzs", ",", "ethetas", ",", "elongans", ",", "eincls", ",", "ds", "=", "ds", ",", "Fs", "=", "Fs", ",", "ignore_effects", "=", "ignore_effects", ")" ]
41.4375
[ 0.03389830508474576, 0.058823529411764705, 0.1076923076923077, 0.18181818181818182, 0.06451612903225806, 0, 0.02531645569620253, 0.18181818181818182, 0.05263157894736842, 0.05263157894736842, 0.05263157894736842, 0, 0.07317073170731707, 0.046153846153846156, 0.05084745762711865, 0.09090909090909091 ]
def set_power(self, controller, zone, power): """ Switch power on/off to a zone :param controller: Russound Controller ID. For systems with one controller this should be a value of 1. :param zone: The zone to be controlled. Expect a 1 based number. :param power: 0 = off, 1 = on """ _LOGGER.debug("Begin - controller= %s, zone= %s, change power to %s",controller, zone, power) send_msg = self.create_send_message("F0 @cc 00 7F 00 00 @kk 05 02 02 00 00 F1 23 00 @pr 00 @zz 00 01", controller, zone, power) try: self.lock.acquire() _LOGGER.debug('Zone %s - acquired lock for ', zone) self.send_data(send_msg) _LOGGER.debug("Zone %s - sent message %s", zone, send_msg) self.get_response_message() # Clear response buffer finally: self.lock.release() _LOGGER.debug("Zone %s - released lock for ", zone) _LOGGER.debug("End - controller %s, zone %s, power set to %s.\n", controller, zone, power)
[ "def", "set_power", "(", "self", ",", "controller", ",", "zone", ",", "power", ")", ":", "_LOGGER", ".", "debug", "(", "\"Begin - controller= %s, zone= %s, change power to %s\"", ",", "controller", ",", "zone", ",", "power", ")", "send_msg", "=", "self", ".", "create_send_message", "(", "\"F0 @cc 00 7F 00 00 @kk 05 02 02 00 00 F1 23 00 @pr 00 @zz 00 01\"", ",", "controller", ",", "zone", ",", "power", ")", "try", ":", "self", ".", "lock", ".", "acquire", "(", ")", "_LOGGER", ".", "debug", "(", "'Zone %s - acquired lock for '", ",", "zone", ")", "self", ".", "send_data", "(", "send_msg", ")", "_LOGGER", ".", "debug", "(", "\"Zone %s - sent message %s\"", ",", "zone", ",", "send_msg", ")", "self", ".", "get_response_message", "(", ")", "# Clear response buffer", "finally", ":", "self", ".", "lock", ".", "release", "(", ")", "_LOGGER", ".", "debug", "(", "\"Zone %s - released lock for \"", ",", "zone", ")", "_LOGGER", ".", "debug", "(", "\"End - controller %s, zone %s, power set to %s.\\n\"", ",", "controller", ",", "zone", ",", "power", ")" ]
54.2
[ 0.022222222222222223, 0.04878048780487805, 0.036036036036036036, 0.041666666666666664, 0.08108108108108109, 0.18181818181818182, 0, 0.039603960396039604, 0.03636363636363636, 0.04411764705882353, 0.16666666666666666, 0.06451612903225806, 0.031746031746031744, 0.05555555555555555, 0.02857142857142857, 0.03125, 0.125, 0.06451612903225806, 0.031746031746031744, 0.029411764705882353 ]
def f_extend_old(map, s): """Extend map of function to cover sphere "twice" up to theta=2pi This introduces new points when Nphi is odd, and duplicates values when Nphi is even, making it easier to perform certain transformation operations. This is mostly an internal function, included here for backwards compatibility. See map2salm and salm2map for more useful functions. """ import numpy as np map = np.ascontiguousarray(map, dtype=np.complex128) extended_map = np.empty((2*(map.shape[0]-1), map.shape[1],), dtype=np.complex128) _f_extend_old(map, extended_map, s) return extended_map
[ "def", "f_extend_old", "(", "map", ",", "s", ")", ":", "import", "numpy", "as", "np", "map", "=", "np", ".", "ascontiguousarray", "(", "map", ",", "dtype", "=", "np", ".", "complex128", ")", "extended_map", "=", "np", ".", "empty", "(", "(", "2", "*", "(", "map", ".", "shape", "[", "0", "]", "-", "1", ")", ",", "map", ".", "shape", "[", "1", "]", ",", ")", ",", "dtype", "=", "np", ".", "complex128", ")", "_f_extend_old", "(", "map", ",", "extended_map", ",", "s", ")", "return", "extended_map" ]
41.4
[ 0.04, 0.028985507246376812, 0, 0.030303030303030304, 0.03571428571428571, 0, 0.030927835051546393, 0.046511627906976744, 0, 0.2857142857142857, 0.09090909090909091, 0.03571428571428571, 0.03529411764705882, 0.05128205128205128, 0.08695652173913043 ]
def get_auth(host, app_name, database_name): """ Authentication hook to allow plugging in custom authentication credential providers """ from .hooks import _get_auth_hook return _get_auth_hook(host, app_name, database_name)
[ "def", "get_auth", "(", "host", ",", "app_name", ",", "database_name", ")", ":", "from", ".", "hooks", "import", "_get_auth_hook", "return", "_get_auth_hook", "(", "host", ",", "app_name", ",", "database_name", ")" ]
39.666667
[ 0.022727272727272728, 0.2857142857142857, 0.034482758620689655, 0.2857142857142857, 0.05405405405405406, 0.03571428571428571 ]
def selectisinstance(table, field, value, complement=False): """Select rows where the given field is an instance of the given type.""" return selectop(table, field, value, isinstance, complement=complement)
[ "def", "selectisinstance", "(", "table", ",", "field", ",", "value", ",", "complement", "=", "False", ")", ":", "return", "selectop", "(", "table", ",", "field", ",", "value", ",", "isinstance", ",", "complement", "=", "complement", ")" ]
53
[ 0.016666666666666666, 0.025974025974025976, 0, 0.02666666666666667 ]
def insert(self, item, priority): """Adds item to DEPQ with given priority by performing a binary search on the concurrently rotating deque. Amount rotated R of DEPQ of length n would be n <= R <= 3n/2. Performance: O(n)""" with self.lock: self_data = self.data rotate = self_data.rotate self_items = self.items maxlen = self._maxlen try: if priority <= self_data[-1][1]: self_data.append((item, priority)) elif priority > self_data[0][1]: self_data.appendleft((item, priority)) else: length = len(self_data) + 1 mid = length // 2 shift = 0 while True: if priority <= self_data[0][1]: rotate(-mid) shift += mid mid //= 2 if mid == 0: mid += 1 else: rotate(mid) shift -= mid mid //= 2 if mid == 0: mid += 1 if self_data[-1][1] >= priority > self_data[0][1]: self_data.appendleft((item, priority)) # When returning to original position, never shift # more than half length of DEPQ i.e. if length is # 100 and we rotated -75, rotate -25, not 75 if shift > length // 2: shift = length % shift rotate(-shift) else: rotate(shift) break try: self_items[item] += 1 except TypeError: self_items[repr(item)] += 1 except IndexError: self_data.append((item, priority)) try: self_items[item] = 1 except TypeError: self_items[repr(item)] = 1 if maxlen is not None and maxlen < len(self_data): self._poplast()
[ "def", "insert", "(", "self", ",", "item", ",", "priority", ")", ":", "with", "self", ".", "lock", ":", "self_data", "=", "self", ".", "data", "rotate", "=", "self_data", ".", "rotate", "self_items", "=", "self", ".", "items", "maxlen", "=", "self", ".", "_maxlen", "try", ":", "if", "priority", "<=", "self_data", "[", "-", "1", "]", "[", "1", "]", ":", "self_data", ".", "append", "(", "(", "item", ",", "priority", ")", ")", "elif", "priority", ">", "self_data", "[", "0", "]", "[", "1", "]", ":", "self_data", ".", "appendleft", "(", "(", "item", ",", "priority", ")", ")", "else", ":", "length", "=", "len", "(", "self_data", ")", "+", "1", "mid", "=", "length", "//", "2", "shift", "=", "0", "while", "True", ":", "if", "priority", "<=", "self_data", "[", "0", "]", "[", "1", "]", ":", "rotate", "(", "-", "mid", ")", "shift", "+=", "mid", "mid", "//=", "2", "if", "mid", "==", "0", ":", "mid", "+=", "1", "else", ":", "rotate", "(", "mid", ")", "shift", "-=", "mid", "mid", "//=", "2", "if", "mid", "==", "0", ":", "mid", "+=", "1", "if", "self_data", "[", "-", "1", "]", "[", "1", "]", ">=", "priority", ">", "self_data", "[", "0", "]", "[", "1", "]", ":", "self_data", ".", "appendleft", "(", "(", "item", ",", "priority", ")", ")", "# When returning to original position, never shift", "# more than half length of DEPQ i.e. if length is", "# 100 and we rotated -75, rotate -25, not 75", "if", "shift", ">", "length", "//", "2", ":", "shift", "=", "length", "%", "shift", "rotate", "(", "-", "shift", ")", "else", ":", "rotate", "(", "shift", ")", "break", "try", ":", "self_items", "[", "item", "]", "+=", "1", "except", "TypeError", ":", "self_items", "[", "repr", "(", "item", ")", "]", "+=", "1", "except", "IndexError", ":", "self_data", ".", "append", "(", "(", "item", ",", "priority", ")", ")", "try", ":", "self_items", "[", "item", "]", "=", "1", "except", "TypeError", ":", "self_items", "[", "repr", "(", "item", ")", "]", "=", "1", "if", "maxlen", "is", "not", "None", "and", "maxlen", "<", "len", "(", "self_data", ")", ":", "self", ".", "_poplast", "(", ")" ]
34.602941
[ 0.030303030303030304, 0.028169014084507043, 0.02857142857142857, 0.04285714285714286, 0, 0.08695652173913043, 0, 0.06060606060606061, 0.05405405405405406, 0.05714285714285714, 0.06060606060606061, 0, 0.125, 0, 0.041666666666666664, 0.037037037037037035, 0.041666666666666664, 0.034482758620689655, 0.09523809523809523, 0, 0.0425531914893617, 0.05405405405405406, 0.06896551724137931, 0, 0.06451612903225806, 0, 0.03636363636363636, 0.05, 0.05, 0.05405405405405406, 0.05, 0.05, 0, 0.06896551724137931, 0.05128205128205128, 0.05, 0.05405405405405406, 0.05, 0.05, 0, 0.02702702702702703, 0.030303030303030304, 0, 0.02564102564102564, 0.025974025974025976, 0.027777777777777776, 0.0392156862745098, 0.037037037037037035, 0.043478260869565216, 0.06060606060606061, 0.044444444444444446, 0, 0.06060606060606061, 0, 0.1, 0.04878048780487805, 0.06060606060606061, 0.0425531914893617, 0, 0.06666666666666667, 0.04, 0.1, 0.05, 0.06060606060606061, 0.043478260869565216, 0, 0.03225806451612903, 0.06451612903225806 ]
def add_note(self, body): """ Create a Note to current object :param body: the body of the note :type body: str :return: newly created Note :rtype: Tag """ from highton.models.note import Note created_id = self._post_request( endpoint=self.ENDPOINT + '/' + str(self.id) + '/' + Note.ENDPOINT, data=self.element_to_string( Note(body=body).encode() ) ).headers.get('Location').replace('.xml', '').split('/')[-1] return Note.get(created_id)
[ "def", "add_note", "(", "self", ",", "body", ")", ":", "from", "highton", ".", "models", ".", "note", "import", "Note", "created_id", "=", "self", ".", "_post_request", "(", "endpoint", "=", "self", ".", "ENDPOINT", "+", "'/'", "+", "str", "(", "self", ".", "id", ")", "+", "'/'", "+", "Note", ".", "ENDPOINT", ",", "data", "=", "self", ".", "element_to_string", "(", "Note", "(", "body", "=", "body", ")", ".", "encode", "(", ")", ")", ")", ".", "headers", ".", "get", "(", "'Location'", ")", ".", "replace", "(", "'.xml'", ",", "''", ")", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "return", "Note", ".", "get", "(", "created_id", ")" ]
33.058824
[ 0.04, 0.18181818181818182, 0.05128205128205128, 0, 0.07317073170731707, 0.13043478260869565, 0.08571428571428572, 0.15789473684210525, 0.18181818181818182, 0.045454545454545456, 0.075, 0.038461538461538464, 0.1, 0.05, 0.23076923076923078, 0.04411764705882353, 0.05714285714285714 ]
def fcoe_fcoe_fabric_map_fcoe_fabric_map_virtual_fabric(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe") fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric-map") fcoe_fabric_map_name_key = ET.SubElement(fcoe_fabric_map, "fcoe-fabric-map-name") fcoe_fabric_map_name_key.text = kwargs.pop('fcoe_fabric_map_name') fcoe_fabric_map_virtual_fabric = ET.SubElement(fcoe_fabric_map, "fcoe-fabric-map-virtual-fabric") fcoe_fabric_map_virtual_fabric.text = kwargs.pop('fcoe_fabric_map_virtual_fabric') callback = kwargs.pop('callback', self._callback) return callback(config)
[ "def", "fcoe_fcoe_fabric_map_fcoe_fabric_map_virtual_fabric", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcoe", "=", "ET", ".", "SubElement", "(", "config", ",", "\"fcoe\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-fcoe\"", ")", "fcoe_fabric_map", "=", "ET", ".", "SubElement", "(", "fcoe", ",", "\"fcoe-fabric-map\"", ")", "fcoe_fabric_map_name_key", "=", "ET", ".", "SubElement", "(", "fcoe_fabric_map", ",", "\"fcoe-fabric-map-name\"", ")", "fcoe_fabric_map_name_key", ".", "text", "=", "kwargs", ".", "pop", "(", "'fcoe_fabric_map_name'", ")", "fcoe_fabric_map_virtual_fabric", "=", "ET", ".", "SubElement", "(", "fcoe_fabric_map", ",", "\"fcoe-fabric-map-virtual-fabric\"", ")", "fcoe_fabric_map_virtual_fabric", ".", "text", "=", "kwargs", ".", "pop", "(", "'fcoe_fabric_map_virtual_fabric'", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "return", "callback", "(", "config", ")" ]
57.461538
[ 0.013888888888888888, 0.06666666666666667, 0.18181818181818182, 0.05405405405405406, 0.034482758620689655, 0.03125, 0.033707865168539325, 0.02702702702702703, 0.02857142857142857, 0.03333333333333333, 0, 0.03508771929824561, 0.06451612903225806 ]
def signup(self, client_id, email, password, connection, username=None, user_metadata=None): """Signup using email and password. Args: client_id (str): ID of the application to use. email (str): The user's email address. password (str): The user's desired password. connection (str): The name of the database connection where this user should be created. username (str, optional): The user's username, if required by the database connection. user_metadata (dict, optional): Additional key-value information to store for the user. Some limitations apply, see: https://auth0.com/docs/metadata#metadata-restrictions See: https://auth0.com/docs/api/authentication#signup """ body = { 'client_id': client_id, 'email': email, 'password': password, 'connection': connection, 'username': username, 'user_metadata': user_metadata } return self.post( 'https://{}/dbconnections/signup'.format(self.domain), data=body, headers={'Content-Type': 'application/json'} )
[ "def", "signup", "(", "self", ",", "client_id", ",", "email", ",", "password", ",", "connection", ",", "username", "=", "None", ",", "user_metadata", "=", "None", ")", ":", "body", "=", "{", "'client_id'", ":", "client_id", ",", "'email'", ":", "email", ",", "'password'", ":", "password", ",", "'connection'", ":", "connection", ",", "'username'", ":", "username", ",", "'user_metadata'", ":", "user_metadata", "}", "return", "self", ".", "post", "(", "'https://{}/dbconnections/signup'", ".", "format", "(", "self", ".", "domain", ")", ",", "data", "=", "body", ",", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", ")" ]
35.5
[ 0.028169014084507043, 0.15151515151515152, 0.046511627906976744, 0.25, 0.15384615384615385, 0.07017543859649122, 0, 0.08163265306122448, 0, 0.07272727272727272, 0, 0.050505050505050504, 0, 0.05154639175257732, 0, 0.05102040816326531, 0.058823529411764705, 0, 0.08196721311475409, 0.18181818181818182, 0.1875, 0.05714285714285714, 0.07407407407407407, 0.06060606060606061, 0.05405405405405406, 0.06060606060606061, 0.047619047619047616, 0.3333333333333333, 0, 0.12, 0.030303030303030304, 0.13636363636363635, 0.05357142857142857, 0.3333333333333333 ]
def set_frequency(self, pin, frequency_hz): """Set frequency (in Hz) of PWM output on specified pin.""" if pin not in self.pwm: raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin)) self.pwm[pin].ChangeFrequency(frequency_hz)
[ "def", "set_frequency", "(", "self", ",", "pin", ",", "frequency_hz", ")", ":", "if", "pin", "not", "in", "self", ".", "pwm", ":", "raise", "ValueError", "(", "'Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'", ".", "format", "(", "pin", ")", ")", "self", ".", "pwm", "[", "pin", "]", ".", "ChangeFrequency", "(", "frequency_hz", ")" ]
63
[ 0.023255813953488372, 0.029850746268656716, 0.06451612903225806, 0.024390243902439025, 0.0392156862745098 ]
def add_path_object(self, *args): """ Add custom path objects :type: path_object: static_bundle.paths.AbstractPath """ for obj in args: obj.bundle = self self.files.append(obj)
[ "def", "add_path_object", "(", "self", ",", "*", "args", ")", ":", "for", "obj", "in", "args", ":", "obj", ".", "bundle", "=", "self", "self", ".", "files", ".", "append", "(", "obj", ")" ]
25.888889
[ 0.030303030303030304, 0.18181818181818182, 0.06451612903225806, 0, 0.05, 0.18181818181818182, 0.08333333333333333, 0.06896551724137931, 0.058823529411764705 ]
def fit(self, X, y): """Build a survival support vector machine model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) if self.alpha <= 0: raise ValueError("alpha must be positive") if not 0 <= self.rank_ratio <= 1: raise ValueError("rank_ratio must be in [0; 1]") if self.fit_intercept and self.rank_ratio == 1.0: raise ValueError("fit_intercept=True is only meaningful if rank_ratio < 1.0") if self.rank_ratio < 1.0: if self.optimizer in {'simple', 'PRSVM'}: raise ValueError("optimizer '%s' does not implement regression objective" % self.optimizer) if (time <= 0).any(): raise ValueError("observed time contains values smaller or equal to zero") # log-transform time time = numpy.log(time) assert numpy.isfinite(time).all() random_state = check_random_state(self.random_state) samples_order = BaseSurvivalSVM._argsort_and_resolve_ties(time, random_state) opt_result = self._fit(X, time, event, samples_order) coef = opt_result.x if self.fit_intercept: self.coef_ = coef[1:] self.intercept_ = coef[0] else: self.coef_ = coef if not opt_result.success: warnings.warn(('Optimization did not converge: ' + opt_result.message), category=ConvergenceWarning, stacklevel=2) self.optimizer_result_ = opt_result return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "event", ",", "time", "=", "check_arrays_survival", "(", "X", ",", "y", ")", "if", "self", ".", "alpha", "<=", "0", ":", "raise", "ValueError", "(", "\"alpha must be positive\"", ")", "if", "not", "0", "<=", "self", ".", "rank_ratio", "<=", "1", ":", "raise", "ValueError", "(", "\"rank_ratio must be in [0; 1]\"", ")", "if", "self", ".", "fit_intercept", "and", "self", ".", "rank_ratio", "==", "1.0", ":", "raise", "ValueError", "(", "\"fit_intercept=True is only meaningful if rank_ratio < 1.0\"", ")", "if", "self", ".", "rank_ratio", "<", "1.0", ":", "if", "self", ".", "optimizer", "in", "{", "'simple'", ",", "'PRSVM'", "}", ":", "raise", "ValueError", "(", "\"optimizer '%s' does not implement regression objective\"", "%", "self", ".", "optimizer", ")", "if", "(", "time", "<=", "0", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "\"observed time contains values smaller or equal to zero\"", ")", "# log-transform time", "time", "=", "numpy", ".", "log", "(", "time", ")", "assert", "numpy", ".", "isfinite", "(", "time", ")", ".", "all", "(", ")", "random_state", "=", "check_random_state", "(", "self", ".", "random_state", ")", "samples_order", "=", "BaseSurvivalSVM", ".", "_argsort_and_resolve_ties", "(", "time", ",", "random_state", ")", "opt_result", "=", "self", ".", "_fit", "(", "X", ",", "time", ",", "event", ",", "samples_order", ")", "coef", "=", "opt_result", ".", "x", "if", "self", ".", "fit_intercept", ":", "self", ".", "coef_", "=", "coef", "[", "1", ":", "]", "self", ".", "intercept_", "=", "coef", "[", "0", "]", "else", ":", "self", ".", "coef_", "=", "coef", "if", "not", "opt_result", ".", "success", ":", "warnings", ".", "warn", "(", "(", "'Optimization did not converge: '", "+", "opt_result", ".", "message", ")", ",", "category", "=", "ConvergenceWarning", ",", "stacklevel", "=", "2", ")", "self", ".", "optimizer_result_", "=", "opt_result", "return", "self" ]
33.859649
[ 0.05, 0.02631578947368421, 0, 0.1111111111111111, 0.1111111111111111, 0.05454545454545454, 0.08333333333333333, 0, 0.06, 0.029411764705882353, 0.028985507246376812, 0.08, 0, 0.13333333333333333, 0.13333333333333333, 0.16666666666666666, 0.18181818181818182, 0.038461538461538464, 0, 0.07407407407407407, 0.037037037037037035, 0, 0.04878048780487805, 0.03333333333333333, 0, 0.03508771929824561, 0.033707865168539325, 0, 0.06060606060606061, 0.03773584905660377, 0.028037383177570093, 0, 0.06060606060606061, 0.03333333333333333, 0, 0.0625, 0.058823529411764705, 0.044444444444444446, 0, 0.03333333333333333, 0.03529411764705882, 0, 0.03278688524590164, 0.07407407407407407, 0.06666666666666667, 0.06060606060606061, 0.05405405405405406, 0.15384615384615385, 0.06896551724137931, 0, 0.058823529411764705, 0.04819277108433735, 0.07407407407407407, 0.1282051282051282, 0.046511627906976744, 0, 0.10526315789473684 ]
def wr_txt_grouping_gos(self): """Write one file per GO group.""" prt_goids = self.grprobj.gosubdag.prt_goids for hdrgo, usrgos in self.grprobj.hdrgo2usrgos.items(): keygos = usrgos.union([hdrgo]) fout_txt = "{BASE}.txt".format(BASE=self.grprobj.get_fout_base(hdrgo)) with open(fout_txt, 'w') as prt: prt_goids(keygos, prt=prt) sys.stdout.write(" {N:5,} GO IDs WROTE: {TXT}\n".format( N=len(keygos), TXT=fout_txt))
[ "def", "wr_txt_grouping_gos", "(", "self", ")", ":", "prt_goids", "=", "self", ".", "grprobj", ".", "gosubdag", ".", "prt_goids", "for", "hdrgo", ",", "usrgos", "in", "self", ".", "grprobj", ".", "hdrgo2usrgos", ".", "items", "(", ")", ":", "keygos", "=", "usrgos", ".", "union", "(", "[", "hdrgo", "]", ")", "fout_txt", "=", "\"{BASE}.txt\"", ".", "format", "(", "BASE", "=", "self", ".", "grprobj", ".", "get_fout_base", "(", "hdrgo", ")", ")", "with", "open", "(", "fout_txt", ",", "'w'", ")", "as", "prt", ":", "prt_goids", "(", "keygos", ",", "prt", "=", "prt", ")", "sys", ".", "stdout", ".", "write", "(", "\" {N:5,} GO IDs WROTE: {TXT}\\n\"", ".", "format", "(", "N", "=", "len", "(", "keygos", ")", ",", "TXT", "=", "fout_txt", ")", ")" ]
51.8
[ 0.03333333333333333, 0.047619047619047616, 0.0392156862745098, 0.031746031746031744, 0.047619047619047616, 0.036585365853658534, 0.045454545454545456, 0.047619047619047616, 0.0410958904109589, 0.10204081632653061 ]
def update(self): """ Update Monit deamon and services status. """ url = self.baseurl + '/_status?format=xml' response = self.s.get(url) response.raise_for_status() from xml.etree.ElementTree import XML root = XML(response.text) for serv_el in root.iter('service'): serv = Monit.Service(self, serv_el) self[serv.name] = serv # Pendingaction occurs when a service is stopping if self[serv.name].pendingaction: time.sleep(1) return Monit.update(self) # Monitor == 2 when service in startup if self[serv.name].monitorState == 2: time.sleep(1) return Monit.update(self)
[ "def", "update", "(", "self", ")", ":", "url", "=", "self", ".", "baseurl", "+", "'/_status?format=xml'", "response", "=", "self", ".", "s", ".", "get", "(", "url", ")", "response", ".", "raise_for_status", "(", ")", "from", "xml", ".", "etree", ".", "ElementTree", "import", "XML", "root", "=", "XML", "(", "response", ".", "text", ")", "for", "serv_el", "in", "root", ".", "iter", "(", "'service'", ")", ":", "serv", "=", "Monit", ".", "Service", "(", "self", ",", "serv_el", ")", "self", "[", "serv", ".", "name", "]", "=", "serv", "# Pendingaction occurs when a service is stopping", "if", "self", "[", "serv", ".", "name", "]", ".", "pendingaction", ":", "time", ".", "sleep", "(", "1", ")", "return", "Monit", ".", "update", "(", "self", ")", "# Monitor == 2 when service in startup", "if", "self", "[", "serv", ".", "name", "]", ".", "monitorState", "==", "2", ":", "time", ".", "sleep", "(", "1", ")", "return", "Monit", ".", "update", "(", "self", ")" ]
37.7
[ 0.058823529411764705, 0.18181818181818182, 0.041666666666666664, 0.18181818181818182, 0.04, 0.058823529411764705, 0.05714285714285714, 0.044444444444444446, 0.06060606060606061, 0.045454545454545456, 0.0425531914893617, 0.058823529411764705, 0.03278688524590164, 0.044444444444444446, 0.06896551724137931, 0.04878048780487805, 0.04, 0.04081632653061224, 0.06896551724137931, 0.04878048780487805 ]
def com_google_fonts_check_ftxvalidator(font): """Checking with ftxvalidator.""" import plistlib try: import subprocess ftx_cmd = [ "ftxvalidator", "-t", "all", # execute all checks font ] ftx_output = subprocess.check_output(ftx_cmd, stderr=subprocess.STDOUT) ftx_data = plistlib.loads(ftx_output) # we accept kATSFontTestSeverityInformation # and kATSFontTestSeverityMinorError if 'kATSFontTestSeverityFatalError' \ not in ftx_data['kATSFontTestResultKey']: yield PASS, "ftxvalidator passed this file" else: ftx_cmd = [ "ftxvalidator", "-T", # Human-readable output "-r", # Generate a full report "-t", "all", # execute all checks font ] ftx_output = subprocess.check_output(ftx_cmd, stderr=subprocess.STDOUT) yield FAIL, f"ftxvalidator output follows:\n\n{ftx_output}\n" except subprocess.CalledProcessError as e: yield ERROR, ("ftxvalidator returned an error code. Output follows:" "\n\n{}\n").format(e.output.decode('utf-8')) except OSError: yield ERROR, "ftxvalidator is not available!"
[ "def", "com_google_fonts_check_ftxvalidator", "(", "font", ")", ":", "import", "plistlib", "try", ":", "import", "subprocess", "ftx_cmd", "=", "[", "\"ftxvalidator\"", ",", "\"-t\"", ",", "\"all\"", ",", "# execute all checks", "font", "]", "ftx_output", "=", "subprocess", ".", "check_output", "(", "ftx_cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "ftx_data", "=", "plistlib", ".", "loads", "(", "ftx_output", ")", "# we accept kATSFontTestSeverityInformation", "# and kATSFontTestSeverityMinorError", "if", "'kATSFontTestSeverityFatalError'", "not", "in", "ftx_data", "[", "'kATSFontTestResultKey'", "]", ":", "yield", "PASS", ",", "\"ftxvalidator passed this file\"", "else", ":", "ftx_cmd", "=", "[", "\"ftxvalidator\"", ",", "\"-T\"", ",", "# Human-readable output", "\"-r\"", ",", "# Generate a full report", "\"-t\"", ",", "\"all\"", ",", "# execute all checks", "font", "]", "ftx_output", "=", "subprocess", ".", "check_output", "(", "ftx_cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "yield", "FAIL", ",", "f\"ftxvalidator output follows:\\n\\n{ftx_output}\\n\"", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "yield", "ERROR", ",", "(", "\"ftxvalidator returned an error code. Output follows:\"", "\"\\n\\n{}\\n\"", ")", ".", "format", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "except", "OSError", ":", "yield", "ERROR", ",", "\"ftxvalidator is not available!\"" ]
33.228571
[ 0.021739130434782608, 0.08571428571428572, 0.17647058823529413, 0.5, 0.09523809523809523, 0.2, 0.08695652173913043, 0.15384615384615385, 0.05555555555555555, 0.16666666666666666, 0.6, 0.02666666666666667, 0.04878048780487805, 0.0425531914893617, 0.05, 0.04878048780487805, 0.0625, 0.061224489795918366, 0.2222222222222222, 0.23529411764705882, 0.12, 0.075, 0.07317073170731707, 0.2, 0.07894736842105263, 0.21428571428571427, 0.5714285714285714, 0.03896103896103896, 0.04477611940298507, 0, 0.06818181818181818, 0.041666666666666664, 0.06557377049180328, 0.17647058823529413, 0.04081632653061224 ]
def statuses_destroy(self, id, trim_user=None): """ Destroys the status specified by the ID parameter. https://dev.twitter.com/docs/api/1.1/post/statuses/destroy/%3Aid :param str id: (*required*) The numerical ID of the desired tweet. :param bool trim_user: When set to ``True``, the return value's user object includes only the status author's numerical ID. :returns: A tweet dict containing the destroyed tweet. """ params = {'id': id} set_bool_param(params, 'trim_user', trim_user) return self._post_api('statuses/destroy.json', params)
[ "def", "statuses_destroy", "(", "self", ",", "id", ",", "trim_user", "=", "None", ")", ":", "params", "=", "{", "'id'", ":", "id", "}", "set_bool_param", "(", "params", ",", "'trim_user'", ",", "trim_user", ")", "return", "self", ".", "_post_api", "(", "'statuses/destroy.json'", ",", "params", ")" ]
34.368421
[ 0.02127659574468085, 0.18181818181818182, 0.034482758620689655, 0, 0.041666666666666664, 0, 0.13636363636363635, 0.031746031746031744, 0, 0.1, 0.038461538461538464, 0.044444444444444446, 0, 0.17647058823529413, 0.03571428571428571, 0.18181818181818182, 0.07407407407407407, 0.037037037037037035, 0.03225806451612903 ]
def differential_pressure_meter_beta(D, D2, meter_type): r'''Calculates the beta ratio of a differential pressure meter. Parameters ---------- D : float Upstream internal pipe diameter, [m] D2 : float Diameter of orifice, or venturi meter orifice, or flow tube orifice, or cone meter end diameter, or wedge meter fluid flow height, [m] meter_type : str One of ('ISO 5167 orifice', 'long radius nozzle', 'ISA 1932 nozzle', 'venuri nozzle', 'as cast convergent venturi tube', 'machined convergent venturi tube', 'rough welded convergent venturi tube', 'cone meter', 'wedge meter'), [-] Returns ------- beta : float Differential pressure meter diameter ratio, [-] Notes ----- Examples -------- >>> differential_pressure_meter_beta(D=0.2575, D2=0.184, ... meter_type='cone meter') 0.6995709873957624 ''' if meter_type in beta_simple_meters: beta = D2/D elif meter_type == CONE_METER: beta = diameter_ratio_cone_meter(D=D, Dc=D2) elif meter_type == WEDGE_METER: beta = diameter_ratio_wedge_meter(D=D, H=D2) return beta
[ "def", "differential_pressure_meter_beta", "(", "D", ",", "D2", ",", "meter_type", ")", ":", "if", "meter_type", "in", "beta_simple_meters", ":", "beta", "=", "D2", "/", "D", "elif", "meter_type", "==", "CONE_METER", ":", "beta", "=", "diameter_ratio_cone_meter", "(", "D", "=", "D", ",", "Dc", "=", "D2", ")", "elif", "meter_type", "==", "WEDGE_METER", ":", "beta", "=", "diameter_ratio_wedge_meter", "(", "D", "=", "D", ",", "H", "=", "D2", ")", "return", "beta" ]
31.105263
[ 0.017857142857142856, 0.029850746268656716, 0.25, 0.14285714285714285, 0.14285714285714285, 0.23076923076923078, 0.045454545454545456, 0.21428571428571427, 0.02631578947368421, 0.0273972602739726, 0.15, 0.06493506493506493, 0.05, 0.06818181818181818, 0.03278688524590164, 0.1111111111111111, 0, 0.18181818181818182, 0.18181818181818182, 0.1875, 0.03636363636363636, 0, 0.2222222222222222, 0.2222222222222222, 0.5, 0.16666666666666666, 0.16666666666666666, 0.08196721311475409, 0.125, 0.09090909090909091, 0.2857142857142857, 0.05, 0.12, 0.058823529411764705, 0.038461538461538464, 0.05714285714285714, 0.038461538461538464, 0.13333333333333333 ]
def _normalize(self): "Normalize basis function. From THO eq. 2.2" l,m,n = self.powers self.norm = np.sqrt(pow(2,2*(l+m+n)+1.5)* pow(self.exponent,l+m+n+1.5)/ fact2(2*l-1)/fact2(2*m-1)/ fact2(2*n-1)/pow(np.pi,1.5)) return
[ "def", "_normalize", "(", "self", ")", ":", "l", ",", "m", ",", "n", "=", "self", ".", "powers", "self", ".", "norm", "=", "np", ".", "sqrt", "(", "pow", "(", "2", ",", "2", "*", "(", "l", "+", "m", "+", "n", ")", "+", "1.5", ")", "*", "pow", "(", "self", ".", "exponent", ",", "l", "+", "m", "+", "n", "+", "1.5", ")", "/", "fact2", "(", "2", "*", "l", "-", "1", ")", "/", "fact2", "(", "2", "*", "m", "-", "1", ")", "/", "fact2", "(", "2", "*", "n", "-", "1", ")", "/", "pow", "(", "np", ".", "pi", ",", "1.5", ")", ")", "return" ]
41.25
[ 0.047619047619047616, 0.038461538461538464, 0.14814814814814814, 0.08163265306122448, 0.05263157894736842, 0.037037037037037035, 0.07142857142857142, 0.14285714285714285 ]
def p_function_expr_1(self, p): """ function_expr \ : FUNCTION LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION LPAREN formal_parameter_list RPAREN \ LBRACE function_body RBRACE """ if len(p) == 7: p[0] = ast.FuncExpr( identifier=None, parameters=None, elements=p[5]) else: p[0] = ast.FuncExpr( identifier=None, parameters=p[3], elements=p[6])
[ "def", "p_function_expr_1", "(", "self", ",", "p", ")", ":", "if", "len", "(", "p", ")", "==", "7", ":", "p", "[", "0", "]", "=", "ast", ".", "FuncExpr", "(", "identifier", "=", "None", ",", "parameters", "=", "None", ",", "elements", "=", "p", "[", "5", "]", ")", "else", ":", "p", "[", "0", "]", "=", "ast", ".", "FuncExpr", "(", "identifier", "=", "None", ",", "parameters", "=", "p", "[", "3", "]", ",", "elements", "=", "p", "[", "6", "]", ")" ]
36.230769
[ 0.03225806451612903, 0.18181818181818182, 0.08695652173913043, 0.03125, 0.03333333333333333, 0.046511627906976744, 0.18181818181818182, 0.08695652173913043, 0.09375, 0.09375, 0.15384615384615385, 0.09375, 0.09375 ]
def parse_field(text, name=None, version=None, encoding_chars=None, validation_level=None, reference=None, force_varies=False): """ Parse the given ER7-encoded field and return an instance of :class:`Field <hl7apy.core.Field>`. :type text: ``str`` :param text: the ER7-encoded string containing the fields to be parsed :type name: ``str`` :param name: the field name (e.g. MSH_7) :type version: ``str`` :param version: the HL7 version (e.g. "2.5"), or ``None`` to use the default (see :func:`set_default_version <hl7apy.set_default_version>`) :type encoding_chars: ``dict`` :param encoding_chars: a dictionary containing the encoding chars or None to use the default (see :func:`set_default_encoding_chars <hl7apy.set_default_encoding_chars>`) :type validation_level: ``int`` :param validation_level: the validation level. Possible values are those defined in :class:`VALIDATION_LEVEL <hl7apy.consts.VALIDATION_LEVEL>` class or ``None`` to use the default validation level (see :func:`set_default_validation_level <hl7apy.set_default_validation_level>`) :type reference: ``dict`` :param reference: a dictionary containing the element structure returned by :func:`load_reference <hl7apy.load_reference>` or :func:`find_reference <hl7apy.find_reference>` or belonging to a message profile :type force_varies: ``boolean`` :param force_varies: flag that force the fields to use a varies structure when no reference is found. It is used when a segment ends with a field of type varies that thus support infinite children :return: an instance of :class:`Field <hl7apy.core.Field>` >>> field = "NUCLEAR^NELDA^W" >>> nk1_2 = parse_field(field, name="NK1_2") >>> print(nk1_2) <Field NK1_2 (NAME) of type XPN> >>> print(nk1_2.to_er7()) NUCLEAR^NELDA^W >>> unknown = parse_field(field) >>> print(unknown) <Field of type None> >>> print(unknown.to_er7()) NUCLEAR^NELDA^W """ version = _get_version(version) encoding_chars = _get_encoding_chars(encoding_chars, version) validation_level = _get_validation_level(validation_level) try: field = Field(name, version=version, validation_level=validation_level, reference=reference) except InvalidName: if force_varies: reference = ('leaf', None, 'varies', None, None, -1) field = Field(name, version=version, validation_level=validation_level, reference=reference) else: field = Field(version=version, validation_level=validation_level, reference=reference) if name in ('MSH_1', 'MSH_2'): s = SubComponent(datatype='ST', value=text, validation_level=validation_level, version=version) c = Component(datatype='ST', validation_level=validation_level, version=version) c.add(s) field.add(c) else: children = parse_components(text, field.datatype, version, encoding_chars, validation_level, field.structure_by_name) if Validator.is_tolerant(validation_level) and is_base_datatype(field.datatype, version) and \ len(children) > 1: field.datatype = None field.children = children return field
[ "def", "parse_field", "(", "text", ",", "name", "=", "None", ",", "version", "=", "None", ",", "encoding_chars", "=", "None", ",", "validation_level", "=", "None", ",", "reference", "=", "None", ",", "force_varies", "=", "False", ")", ":", "version", "=", "_get_version", "(", "version", ")", "encoding_chars", "=", "_get_encoding_chars", "(", "encoding_chars", ",", "version", ")", "validation_level", "=", "_get_validation_level", "(", "validation_level", ")", "try", ":", "field", "=", "Field", "(", "name", ",", "version", "=", "version", ",", "validation_level", "=", "validation_level", ",", "reference", "=", "reference", ")", "except", "InvalidName", ":", "if", "force_varies", ":", "reference", "=", "(", "'leaf'", ",", "None", ",", "'varies'", ",", "None", ",", "None", ",", "-", "1", ")", "field", "=", "Field", "(", "name", ",", "version", "=", "version", ",", "validation_level", "=", "validation_level", ",", "reference", "=", "reference", ")", "else", ":", "field", "=", "Field", "(", "version", "=", "version", ",", "validation_level", "=", "validation_level", ",", "reference", "=", "reference", ")", "if", "name", "in", "(", "'MSH_1'", ",", "'MSH_2'", ")", ":", "s", "=", "SubComponent", "(", "datatype", "=", "'ST'", ",", "value", "=", "text", ",", "validation_level", "=", "validation_level", ",", "version", "=", "version", ")", "c", "=", "Component", "(", "datatype", "=", "'ST'", ",", "validation_level", "=", "validation_level", ",", "version", "=", "version", ")", "c", ".", "add", "(", "s", ")", "field", ".", "add", "(", "c", ")", "else", ":", "children", "=", "parse_components", "(", "text", ",", "field", ".", "datatype", ",", "version", ",", "encoding_chars", ",", "validation_level", ",", "field", ".", "structure_by_name", ")", "if", "Validator", ".", "is_tolerant", "(", "validation_level", ")", "and", "is_base_datatype", "(", "field", ".", "datatype", ",", "version", ")", "and", "len", "(", "children", ")", ">", "1", ":", "field", ".", "datatype", "=", "None", "field", ".", "children", "=", "children", "return", "field" ]
44.616438
[ 0.03333333333333333, 0.09615384615384616, 0.2857142857142857, 0.09090909090909091, 0, 0.17391304347826086, 0.04054054054054054, 0, 0.17391304347826086, 0.09090909090909091, 0, 0.15384615384615385, 0.075, 0.11428571428571428, 0, 0.11764705882352941, 0.041666666666666664, 0.10714285714285714, 0, 0.11428571428571428, 0.04597701149425287, 0.07766990291262135, 0.09523809523809523, 0, 0.13793103448275862, 0.0379746835443038, 0.125, 0.04878048780487805, 0, 0.11428571428571428, 0.0380952380952381, 0.029411764705882353, 0, 0.14516129032258066, 0, 0.09090909090909091, 0.0625, 0.15, 0.1111111111111111, 0.10344827586206896, 0.21052631578947367, 0.08333333333333333, 0.13636363636363635, 0.125, 0.0967741935483871, 0.21052631578947367, 0.2857142857142857, 0.05714285714285714, 0.03076923076923077, 0.03225806451612903, 0, 0.25, 0.03, 0.08695652173913043, 0.08333333333333333, 0.03125, 0.028846153846153848, 0.15384615384615385, 0.030612244897959183, 0, 0.058823529411764705, 0.02912621359223301, 0.03409090909090909, 0.125, 0.1, 0.2222222222222222, 0.04, 0.05, 0.029411764705882353, 0.058823529411764705, 0.06060606060606061, 0.06060606060606061, 0.125 ]
def set_volume(self, pct, channel=None): """ Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses the ``Playback`` channel, as that is the only channel on the EV3. """ if channel is None: channel = self._get_channel() cmd_line = '/usr/bin/amixer -q set {0} {1:d}%'.format(channel, pct) Popen(shlex.split(cmd_line)).wait()
[ "def", "set_volume", "(", "self", ",", "pct", ",", "channel", "=", "None", ")", ":", "if", "channel", "is", "None", ":", "channel", "=", "self", ".", "_get_channel", "(", ")", "cmd_line", "=", "'/usr/bin/amixer -q set {0} {1:d}%'", ".", "format", "(", "channel", ",", "pct", ")", "Popen", "(", "shlex", ".", "split", "(", "cmd_line", ")", ")", ".", "wait", "(", ")" ]
41.785714
[ 0.025, 0.18181818181818182, 0.041666666666666664, 0.20930232558139536, 0.02564102564102564, 0.04, 0.043478260869565216, 0.18181818181818182, 0, 0.07407407407407407, 0.04878048780487805, 0, 0.02666666666666667, 0.046511627906976744 ]
def sample(self, x0, nsteps, nskip=1): r"""generate nsteps sample points""" x = np.zeros(shape=(nsteps + 1,)) x[0] = x0 for t in range(nsteps): q = x[t] for s in range(nskip): q = self.step(q) x[t + 1] = q return x
[ "def", "sample", "(", "self", ",", "x0", ",", "nsteps", ",", "nskip", "=", "1", ")", ":", "x", "=", "np", ".", "zeros", "(", "shape", "=", "(", "nsteps", "+", "1", ",", ")", ")", "x", "[", "0", "]", "=", "x0", "for", "t", "in", "range", "(", "nsteps", ")", ":", "q", "=", "x", "[", "t", "]", "for", "s", "in", "range", "(", "nskip", ")", ":", "q", "=", "self", ".", "step", "(", "q", ")", "x", "[", "t", "+", "1", "]", "=", "q", "return", "x" ]
29.7
[ 0.02631578947368421, 0.045454545454545456, 0.04878048780487805, 0.11764705882352941, 0.06451612903225806, 0.1, 0.058823529411764705, 0.0625, 0.08333333333333333, 0.125 ]
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel subclass. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(self(input)) otherwise compose in reverse order self(other(input)) [default: False] Returns: Stinespring: The composition channel as a Stinespring object. Raises: QiskitError: if other cannot be converted to a channel or has incompatible dimensions. """ if qargs is not None: return Stinespring( SuperOp(self).compose(other, qargs=qargs, front=front)) # Convert other to Kraus if not isinstance(other, Kraus): other = Kraus(other) # Check dimensions match up if front and self._input_dim != other._output_dim: raise QiskitError( 'input_dim of self must match output_dim of other') if not front and self._output_dim != other._input_dim: raise QiskitError( 'input_dim of other must match output_dim of self') # Since we cannot directly compose two channels in Stinespring # representation we convert to the Kraus representation return Stinespring(Kraus(self).compose(other, front=front))
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "if", "qargs", "is", "not", "None", ":", "return", "Stinespring", "(", "SuperOp", "(", "self", ")", ".", "compose", "(", "other", ",", "qargs", "=", "qargs", ",", "front", "=", "front", ")", ")", "# Convert other to Kraus", "if", "not", "isinstance", "(", "other", ",", "Kraus", ")", ":", "other", "=", "Kraus", "(", "other", ")", "# Check dimensions match up", "if", "front", "and", "self", ".", "_input_dim", "!=", "other", ".", "_output_dim", ":", "raise", "QiskitError", "(", "'input_dim of self must match output_dim of other'", ")", "if", "not", "front", "and", "self", ".", "_output_dim", "!=", "other", ".", "_input_dim", ":", "raise", "QiskitError", "(", "'input_dim of other must match output_dim of self'", ")", "# Since we cannot directly compose two channels in Stinespring", "# representation we convert to the Kraus representation", "return", "Stinespring", "(", "Kraus", "(", "self", ")", ".", "compose", "(", "other", ",", "front", "=", "front", ")", ")" ]
43.029412
[ 0.02, 0.03773584905660377, 0, 0.15384615384615385, 0.047619047619047616, 0.039473684210526314, 0.0379746835443038, 0.0379746835443038, 0.07142857142857142, 0, 0.125, 0.0273972602739726, 0, 0.13333333333333333, 0.028985507246376812, 0.05, 0.18181818181818182, 0.06896551724137931, 0.0967741935483871, 0.04225352112676056, 0, 0.0625, 0.05, 0.0625, 0.05714285714285714, 0.034482758620689655, 0.1, 0.04477611940298507, 0.03225806451612903, 0.1, 0.04477611940298507, 0.02857142857142857, 0.031746031746031744, 0.029850746268656716 ]
def generate_argument_parser(cls, tree, actions={}): """Generates argument parser for given assistant tree and actions. Args: tree: assistant tree as returned by devassistant.assistant_base.AssistantBase.get_subassistant_tree actions: dict mapping actions (devassistant.actions.Action subclasses) to their subaction dicts Returns: instance of devassistant_argparse.ArgumentParser (subclass of argparse.ArgumentParser) """ cur_as, cur_subas = tree parser = devassistant_argparse.ArgumentParser(argument_default=argparse.SUPPRESS, usage=argparse.SUPPRESS, add_help=False) cls.add_default_arguments_to(parser) # add any arguments of the top assistant for arg in cur_as.args: arg.add_argument_to(parser) if cur_subas or actions: # then add the subassistants as arguments subparsers = cls._add_subparsers_required(parser, dest=settings.SUBASSISTANT_N_STRING.format('0')) for subas in sorted(cur_subas, key=lambda x: x[0].name): for alias in [subas[0].name] + getattr(subas[0], 'aliases', []): cls.add_subassistants_to(subparsers, subas, level=1, alias=alias) for action, subactions in sorted(actions.items(), key=lambda x: x[0].name): cls.add_action_to(subparsers, action, subactions, level=1) return parser
[ "def", "generate_argument_parser", "(", "cls", ",", "tree", ",", "actions", "=", "{", "}", ")", ":", "cur_as", ",", "cur_subas", "=", "tree", "parser", "=", "devassistant_argparse", ".", "ArgumentParser", "(", "argument_default", "=", "argparse", ".", "SUPPRESS", ",", "usage", "=", "argparse", ".", "SUPPRESS", ",", "add_help", "=", "False", ")", "cls", ".", "add_default_arguments_to", "(", "parser", ")", "# add any arguments of the top assistant", "for", "arg", "in", "cur_as", ".", "args", ":", "arg", ".", "add_argument_to", "(", "parser", ")", "if", "cur_subas", "or", "actions", ":", "# then add the subassistants as arguments", "subparsers", "=", "cls", ".", "_add_subparsers_required", "(", "parser", ",", "dest", "=", "settings", ".", "SUBASSISTANT_N_STRING", ".", "format", "(", "'0'", ")", ")", "for", "subas", "in", "sorted", "(", "cur_subas", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "for", "alias", "in", "[", "subas", "[", "0", "]", ".", "name", "]", "+", "getattr", "(", "subas", "[", "0", "]", ",", "'aliases'", ",", "[", "]", ")", ":", "cls", ".", "add_subassistants_to", "(", "subparsers", ",", "subas", ",", "level", "=", "1", ",", "alias", "=", "alias", ")", "for", "action", ",", "subactions", "in", "sorted", "(", "actions", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ".", "name", ")", ":", "cls", ".", "add_action_to", "(", "subparsers", ",", "action", ",", "subactions", ",", "level", "=", "1", ")", "return", "parser" ]
46.294118
[ 0.019230769230769232, 0.02702702702702703, 0, 0.15384615384615385, 0.0425531914893617, 0.04938271604938271, 0.04395604395604396, 0.08333333333333333, 0.125, 0.04081632653061224, 0.18181818181818182, 0.0625, 0.0449438202247191, 0.05128205128205128, 0.07246376811594203, 0, 0.045454545454545456, 0, 0.041666666666666664, 0.06451612903225806, 0.05128205128205128, 0, 0.0625, 0.03773584905660377, 0.04918032786885246, 0.0625, 0.029411764705882353, 0.0375, 0.03529411764705882, 0, 0.034482758620689655, 0.02702702702702703, 0, 0.09523809523809523 ]
def add_param(self, name, **kwargs): '''Add a parameter to this group. Parameters ---------- name : str Name of the parameter to add to this group. The name will automatically be case-normalized. Additional keyword arguments will be passed to the `Param` constructor. ''' self.params[name.upper()] = Param(name.upper(), **kwargs)
[ "def", "add_param", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "self", ".", "params", "[", "name", ".", "upper", "(", ")", "]", "=", "Param", "(", "name", ".", "upper", "(", ")", ",", "*", "*", "kwargs", ")" ]
33.333333
[ 0.027777777777777776, 0.04878048780487805, 0, 0.1111111111111111, 0.1111111111111111, 0.16666666666666666, 0.028985507246376812, 0.044444444444444446, 0, 0.0379746835443038, 0.18181818181818182, 0.03076923076923077 ]
def reset( self ): """ Resets the ui information to the default data for the widget. """ if not self.plugin(): return False self.plugin().reset() self.refreshUi() return True
[ "def", "reset", "(", "self", ")", ":", "if", "not", "self", ".", "plugin", "(", ")", ":", "return", "False", "self", ".", "plugin", "(", ")", ".", "reset", "(", ")", "self", ".", "refreshUi", "(", ")", "return", "True" ]
22.727273
[ 0.16666666666666666, 0.18181818181818182, 0.028985507246376812, 0.18181818181818182, 0.06896551724137931, 0.08333333333333333, 0.25, 0.06896551724137931, 0.08333333333333333, 0.25, 0.10526315789473684 ]
def add_listener(self, func, name=None): """The non decorator alternative to :meth:`.listen`. Parameters ----------- func: :ref:`coroutine <coroutine>` The function to call. name: Optional[:class:`str`] The name of the event to listen for. Defaults to ``func.__name__``. Example -------- .. code-block:: python3 async def on_ready(): pass async def my_message(message): pass bot.add_listener(on_ready) bot.add_listener(my_message, 'on_message') """ name = func.__name__ if name is None else name if not asyncio.iscoroutinefunction(func): raise TypeError('Listeners must be coroutines') if name in self.extra_events: self.extra_events[name].append(func) else: self.extra_events[name] = [func]
[ "def", "add_listener", "(", "self", ",", "func", ",", "name", "=", "None", ")", ":", "name", "=", "func", ".", "__name__", "if", "name", "is", "None", "else", "name", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "raise", "TypeError", "(", "'Listeners must be coroutines'", ")", "if", "name", "in", "self", ".", "extra_events", ":", "self", ".", "extra_events", "[", "name", "]", ".", "append", "(", "func", ")", "else", ":", "self", ".", "extra_events", "[", "name", "]", "=", "[", "func", "]" ]
28.419355
[ 0.025, 0.03333333333333333, 0, 0.1111111111111111, 0.10526315789473684, 0.19047619047619047, 0.06060606060606061, 0.08333333333333333, 0.0379746835443038, 0, 0.13333333333333333, 0.125, 0, 0.0967741935483871, 0, 0.05263157894736842, 0.0425531914893617, 0, 0.05263157894736842, 0.037037037037037035, 0, 0.18181818181818182, 0.037037037037037035, 0, 0.04081632653061224, 0.03389830508474576, 0, 0.05405405405405406, 0.041666666666666664, 0.15384615384615385, 0.045454545454545456 ]
def set_exec_area(self, exec_area): """ Sets the exec area value. The exec area is a pool of host memory used to store pages translated by the JIT (they contain the native code corresponding to MIPS code pages). :param exec_area: exec area value (integer) """ yield from self._hypervisor.send('vm set_exec_area "{name}" {exec_area}'.format(name=self._name, exec_area=exec_area)) log.info('Router "{name}" [{id}]: exec area updated from {old_exec}MB to {new_exec}MB'.format(name=self._name, id=self._id, old_exec=self._exec_area, new_exec=exec_area)) self._exec_area = exec_area
[ "def", "set_exec_area", "(", "self", ",", "exec_area", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'vm set_exec_area \"{name}\" {exec_area}'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "exec_area", "=", "exec_area", ")", ")", "log", ".", "info", "(", "'Router \"{name}\" [{id}]: exec area updated from {old_exec}MB to {new_exec}MB'", ".", "format", "(", "name", "=", "self", ".", "_name", ",", "id", "=", "self", ".", "_id", ",", "old_exec", "=", "self", ".", "_exec_area", ",", "new_exec", "=", "exec_area", ")", ")", "self", ".", "_exec_area", "=", "exec_area" ]
57.611111
[ 0.02857142857142857, 0.18181818181818182, 0.06060606060606061, 0.030303030303030304, 0.06779661016949153, 0.07142857142857142, 0, 0.0784313725490196, 0.18181818181818182, 0, 0.038461538461538464, 0.045871559633027525, 0, 0.03389830508474576, 0.043859649122807015, 0.03937007874015748, 0.04918032786885246, 0.05714285714285714 ]
def complete_upload(self, upload_id, hash_value, hash_alg): """ Mark the upload we created in create_upload complete. :param upload_id: str uuid of the upload to complete. :param hash_value: str hash value of chunk :param hash_alg: str algorithm used to create hash :return: requests.Response containing the successful result """ data = { "hash[value]": hash_value, "hash[algorithm]": hash_alg } return self._put("/uploads/" + upload_id + "/complete", data, content_type=ContentType.form)
[ "def", "complete_upload", "(", "self", ",", "upload_id", ",", "hash_value", ",", "hash_alg", ")", ":", "data", "=", "{", "\"hash[value]\"", ":", "hash_value", ",", "\"hash[algorithm]\"", ":", "hash_alg", "}", "return", "self", ".", "_put", "(", "\"/uploads/\"", "+", "upload_id", "+", "\"/complete\"", ",", "data", ",", "content_type", "=", "ContentType", ".", "form", ")" ]
44.615385
[ 0.01694915254237288, 0.18181818181818182, 0.03278688524590164, 0.04918032786885246, 0.06, 0.05172413793103448, 0.04477611940298507, 0.18181818181818182, 0.1875, 0.05263157894736842, 0.05128205128205128, 0.3333333333333333, 0.03 ]
def prep_message(msg): """ Add the size header """ if six.PY3: msg_out = msg.as_string().encode("utf-8") else: msg_out = msg.as_string() our_len = len(msg_out) + 4 size = struct.pack('>L', our_len) # why the hell is this "bytes" on python3? return size + msg_out
[ "def", "prep_message", "(", "msg", ")", ":", "if", "six", ".", "PY3", ":", "msg_out", "=", "msg", ".", "as_string", "(", ")", ".", "encode", "(", "\"utf-8\"", ")", "else", ":", "msg_out", "=", "msg", ".", "as_string", "(", ")", "our_len", "=", "len", "(", "msg_out", ")", "+", "4", "size", "=", "struct", ".", "pack", "(", "'>L'", ",", "our_len", ")", "# why the hell is this \"bytes\" on python3?", "return", "size", "+", "msg_out" ]
21.642857
[ 0.045454545454545456, 0.2857142857142857, 0.08695652173913043, 0.2857142857142857, 0.13333333333333333, 0.04081632653061224, 0.2222222222222222, 0.06060606060606061, 0, 0.06666666666666667, 0.05405405405405406, 0.043478260869565216, 0, 0.08 ]
def _check_generic_pos(self, *tokens): """Check if the different tokens were logged in one record, any level.""" for record in self.records: if all(token in record.message for token in tokens): return # didn't exit, all tokens are not present in the same record msgs = ["Tokens {} not found, all was logged is...".format(tokens)] for record in self.records: msgs.append(" {:9s} {!r}".format(record.levelname, record.message)) self.test_instance.fail("\n".join(msgs))
[ "def", "_check_generic_pos", "(", "self", ",", "*", "tokens", ")", ":", "for", "record", "in", "self", ".", "records", ":", "if", "all", "(", "token", "in", "record", ".", "message", "for", "token", "in", "tokens", ")", ":", "return", "# didn't exit, all tokens are not present in the same record", "msgs", "=", "[", "\"Tokens {} not found, all was logged is...\"", ".", "format", "(", "tokens", ")", "]", "for", "record", "in", "self", ".", "records", ":", "msgs", ".", "append", "(", "\" {:9s} {!r}\"", ".", "format", "(", "record", ".", "levelname", ",", "record", ".", "message", ")", ")", "self", ".", "test_instance", ".", "fail", "(", "\"\\n\"", ".", "join", "(", "msgs", ")", ")" ]
49.818182
[ 0.02631578947368421, 0.037037037037037035, 0.05714285714285714, 0.03125, 0.09090909090909091, 0, 0.029411764705882353, 0.02666666666666667, 0.05714285714285714, 0.036585365853658534, 0.041666666666666664 ]
def getNextEyeLocation(self, currentEyeLoc): """ Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) Coordinate of the next eye location. eyeDiff (numpy.array) Vector describing change from currentEyeLoc to nextEyeLoc. """ possibleEyeLocs = [] for loc in self.spatialConfig: shift = abs(max(loc - currentEyeLoc)) if self.minDisplacement <= shift <= self.maxDisplacement: possibleEyeLocs.append(loc) nextEyeLoc = self.nupicRandomChoice(possibleEyeLocs) eyeDiff = nextEyeLoc - currentEyeLoc return nextEyeLoc, eyeDiff
[ "def", "getNextEyeLocation", "(", "self", ",", "currentEyeLoc", ")", ":", "possibleEyeLocs", "=", "[", "]", "for", "loc", "in", "self", ".", "spatialConfig", ":", "shift", "=", "abs", "(", "max", "(", "loc", "-", "currentEyeLoc", ")", ")", "if", "self", ".", "minDisplacement", "<=", "shift", "<=", "self", ".", "maxDisplacement", ":", "possibleEyeLocs", ".", "append", "(", "loc", ")", "nextEyeLoc", "=", "self", ".", "nupicRandomChoice", "(", "possibleEyeLocs", ")", "eyeDiff", "=", "nextEyeLoc", "-", "currentEyeLoc", "return", "nextEyeLoc", ",", "eyeDiff" ]
31.2
[ 0.022727272727272728, 0.2857142857142857, 0.03278688524590164, 0, 0.07894736842105263, 0.029411764705882353, 0, 0.06896551724137931, 0.08108108108108109, 0.038461538461538464, 0, 0.08108108108108109, 0.02702702702702703, 0.2857142857142857, 0.08333333333333333, 0.058823529411764705, 0.06976744186046512, 0.047619047619047616, 0.05714285714285714, 0, 0.03571428571428571, 0, 0.07317073170731707, 0, 0.06666666666666667 ]
def upload_to_s3(context, file_obj): '''Upload a file to s3. Args: info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource. Returns: (str, str): The bucket and key to which the file was uploaded. ''' bucket = context.solid_config['bucket'] key = context.solid_config['key'] context.resources.s3.put_object( Bucket=bucket, Body=file_obj.read(), Key=key, **(context.solid_config.get('kwargs') or {}) ) yield Result(bucket, 'bucket') yield Result(key, 'key')
[ "def", "upload_to_s3", "(", "context", ",", "file_obj", ")", ":", "bucket", "=", "context", ".", "solid_config", "[", "'bucket'", "]", "key", "=", "context", ".", "solid_config", "[", "'key'", "]", "context", ".", "resources", ".", "s3", ".", "put_object", "(", "Bucket", "=", "bucket", ",", "Body", "=", "file_obj", ".", "read", "(", ")", ",", "Key", "=", "key", ",", "*", "*", "(", "context", ".", "solid_config", ".", "get", "(", "'kwargs'", ")", "or", "{", "}", ")", ")", "yield", "Result", "(", "bucket", ",", "'bucket'", ")", "yield", "Result", "(", "key", ",", "'key'", ")" ]
30.277778
[ 0.027777777777777776, 0.07407407407407407, 0, 0.2222222222222222, 0.05434782608695652, 0, 0.16666666666666666, 0.10526315789473684, 0.03225806451612903, 0.2857142857142857, 0.046511627906976744, 0.05405405405405406, 0, 0.08333333333333333, 0.061224489795918366, 0.6, 0.058823529411764705, 0.07142857142857142 ]
def within(resnum, angstroms, chain_id, model, use_ca=False, custom_coord=None): """See: https://www.biostars.org/p/1816/ https://www.biostars.org/p/269579/ Args: resnum (int): angstroms (float): chain_id (str): model (Model): use_ca (bool): If the alpha-carbon atom should be used for the search, otherwise use the last atom of the residue custom_coord (list): Custom XYZ coordinate to get within Returns: list: List of Bio.PDB.Residue.Residue objects """ # XTODO: documentation # TODO: should have separate method for within a normal residue (can use "resnum" with a int) or a custom coord, # where you don't need to specify resnum atom_list = Selection.unfold_entities(model, 'A') ns = NeighborSearch(atom_list) if custom_coord: # a list of XYZ coord target_atom_coord = np.array(custom_coord, 'f') else: target_residue = model[chain_id][resnum] if use_ca: target_atom = target_residue['CA'] else: target_atom = target_residue.child_list[-1] target_atom_coord = np.array(target_atom.get_coord(), 'f') neighbors = ns.search(target_atom_coord, angstroms) residue_list = Selection.unfold_entities(neighbors, 'R') return residue_list
[ "def", "within", "(", "resnum", ",", "angstroms", ",", "chain_id", ",", "model", ",", "use_ca", "=", "False", ",", "custom_coord", "=", "None", ")", ":", "# XTODO: documentation", "# TODO: should have separate method for within a normal residue (can use \"resnum\" with a int) or a custom coord,", "# where you don't need to specify resnum", "atom_list", "=", "Selection", ".", "unfold_entities", "(", "model", ",", "'A'", ")", "ns", "=", "NeighborSearch", "(", "atom_list", ")", "if", "custom_coord", ":", "# a list of XYZ coord", "target_atom_coord", "=", "np", ".", "array", "(", "custom_coord", ",", "'f'", ")", "else", ":", "target_residue", "=", "model", "[", "chain_id", "]", "[", "resnum", "]", "if", "use_ca", ":", "target_atom", "=", "target_residue", "[", "'CA'", "]", "else", ":", "target_atom", "=", "target_residue", ".", "child_list", "[", "-", "1", "]", "target_atom_coord", "=", "np", ".", "array", "(", "target_atom", ".", "get_coord", "(", ")", ",", "'f'", ")", "neighbors", "=", "ns", ".", "search", "(", "target_atom_coord", ",", "angstroms", ")", "residue_list", "=", "Selection", ".", "unfold_entities", "(", "neighbors", ",", "'R'", ")", "return", "residue_list" ]
37.676471
[ 0.025, 0.02531645569620253, 0, 0.2222222222222222, 0.14285714285714285, 0.11538461538461539, 0.13043478260869565, 0.13636363636363635, 0.03305785123966942, 0.046875, 0, 0.16666666666666666, 0.03773584905660377, 0, 0.2857142857142857, 0.07692307692307693, 0.02586206896551724, 0.045454545454545456, 0.03773584905660377, 0.058823529411764705, 0, 0.046511627906976744, 0.03636363636363636, 0.2222222222222222, 0.041666666666666664, 0.1111111111111111, 0.043478260869565216, 0.15384615384615385, 0.03636363636363636, 0.030303030303030304, 0.03636363636363636, 0.03333333333333333, 0, 0.08695652173913043 ]
def reffs(self): """ Get all valid reffs for every part of the CtsText :rtype: MyCapytain.resources.texts.tei.XmlCtsCitation """ if not self.citation.is_set(): self.getLabel() return [ reff for reffs in [self.getValidReff(level=i) for i in range(1, len(self.citation) + 1)] for reff in reffs ]
[ "def", "reffs", "(", "self", ")", ":", "if", "not", "self", ".", "citation", ".", "is_set", "(", ")", ":", "self", ".", "getLabel", "(", ")", "return", "[", "reff", "for", "reffs", "in", "[", "self", ".", "getValidReff", "(", "level", "=", "i", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "self", ".", "citation", ")", "+", "1", ")", "]", "for", "reff", "in", "reffs", "]" ]
35.7
[ 0.0625, 0.03278688524590164, 0, 0.04918032786885246, 0.18181818181818182, 0.05263157894736842, 0.07407407407407407, 0.1875, 0.025423728813559324, 0.3333333333333333 ]
def clean_description(string): """Clean strings returned from API resources and endpoints: - remove newlines and leading whitespace - replace colons with &#58; to avoid problems with RAML validation - remove things like: <pale.fields.string.StringField object at 0x106edbed0> - replace double spaces with single spaces - if there is not a period, comma, question mark or exclamation point at the end of a string, add a period """ leading_whitespace = re.compile(r"(\A\s+)") multiple_spaces = re.compile(r"(\s+\s+)") newlines = re.compile(r"\n") colons = re.compile(r":(?!//)") machine_code = re.compile(r"(<.+>)") trailing_whitespace = re.compile(r"(\s+\Z)") punctuation = re.compile(r"([\.!?,])\s*\Z") result = leading_whitespace.sub("", string, 0) result = newlines.sub(" ", result, 0) result = colons.sub('=', result, 0) result = machine_code.sub("", result, 0) result = multiple_spaces.sub(" ", result, 0) result = trailing_whitespace.sub("", result, 0) has_punctuation = punctuation.search(result) != None if not has_punctuation and result != "": result = result + "." else: result = result return result
[ "def", "clean_description", "(", "string", ")", ":", "leading_whitespace", "=", "re", ".", "compile", "(", "r\"(\\A\\s+)\"", ")", "multiple_spaces", "=", "re", ".", "compile", "(", "r\"(\\s+\\s+)\"", ")", "newlines", "=", "re", ".", "compile", "(", "r\"\\n\"", ")", "colons", "=", "re", ".", "compile", "(", "r\":(?!//)\"", ")", "machine_code", "=", "re", ".", "compile", "(", "r\"(<.+>)\"", ")", "trailing_whitespace", "=", "re", ".", "compile", "(", "r\"(\\s+\\Z)\"", ")", "punctuation", "=", "re", ".", "compile", "(", "r\"([\\.!?,])\\s*\\Z\"", ")", "result", "=", "leading_whitespace", ".", "sub", "(", "\"\"", ",", "string", ",", "0", ")", "result", "=", "newlines", ".", "sub", "(", "\" \"", ",", "result", ",", "0", ")", "result", "=", "colons", ".", "sub", "(", "'='", ",", "result", ",", "0", ")", "result", "=", "machine_code", ".", "sub", "(", "\"\"", ",", "result", ",", "0", ")", "result", "=", "multiple_spaces", ".", "sub", "(", "\" \"", ",", "result", ",", "0", ")", "result", "=", "trailing_whitespace", ".", "sub", "(", "\"\"", ",", "result", ",", "0", ")", "has_punctuation", "=", "punctuation", ".", "search", "(", "result", ")", "!=", "None", "if", "not", "has_punctuation", "and", "result", "!=", "\"\"", ":", "result", "=", "result", "+", "\".\"", "else", ":", "result", "=", "result", "return", "result" ]
38.25
[ 0.03333333333333333, 0.031746031746031744, 0.041666666666666664, 0.05405405405405406, 0.05952380952380952, 0.04, 0.0297029702970297, 0.13636363636363635, 0.2857142857142857, 0, 0.0425531914893617, 0.044444444444444446, 0.0625, 0.05714285714285714, 0.05, 0.041666666666666664, 0.0425531914893617, 0, 0.04, 0.04878048780487805, 0.05128205128205128, 0.045454545454545456, 0.041666666666666664, 0.0392156862745098, 0.05357142857142857, 0, 0.045454545454545456, 0.06896551724137931, 0.2222222222222222, 0.08695652173913043, 0, 0.11764705882352941 ]
def file_contents(self, filename, binary=False): """Return the file for a given filename. If you want binary content use ``mode='rb'``. """ if binary: mode = 'rb' else: mode = 'r' try: with open(filename, mode) as f: return f.read() except (OSError, IOError) as e: raise FileReadError(str(e))
[ "def", "file_contents", "(", "self", ",", "filename", ",", "binary", "=", "False", ")", ":", "if", "binary", ":", "mode", "=", "'rb'", "else", ":", "mode", "=", "'r'", "try", ":", "with", "open", "(", "filename", ",", "mode", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "raise", "FileReadError", "(", "str", "(", "e", ")", ")" ]
26.666667
[ 0.020833333333333332, 0.041666666666666664, 0, 0.07547169811320754, 0, 0.18181818181818182, 0.1111111111111111, 0.08695652173913043, 0.15384615384615385, 0.09090909090909091, 0.16666666666666666, 0.046511627906976744, 0.06451612903225806, 0.05128205128205128, 0.05128205128205128 ]
def request_quotes(tickers_list, selected_columns=['*']): """Request Yahoo Finance recent quotes. Returns quotes information from YQL. The columns to be requested are listed at selected_columns. Check `here <http://goo.gl/8AROUD>`_ for more information on YQL. >>> request_quotes(['AAPL'], ['Name', 'PreviousClose']) { 'PreviousClose': '95.60', 'Name': 'Apple Inc.' } :param table: Table name. :type table: string :param tickers_list: List of tickers that will be returned. :type tickers_list: list of strings :param selected_columns: List of columns to be returned, defaults to ['*'] :type selected_columns: list of strings, optional :returns: Requested quotes. :rtype: json :raises: TypeError, TypeError """ __validate_list(tickers_list) __validate_list(selected_columns) query = 'select {cols} from yahoo.finance.quotes where symbol in ({vals})' query = query.format( cols=', '.join(selected_columns), vals=', '.join('"{0}"'.format(s) for s in tickers_list) ) response = __yahoo_request(query) if not response: raise RequestError('Unable to process the request. Check if the ' + 'columns selected are valid.') if not type(response['quote']) is list: return [response['quote']] return response['quote']
[ "def", "request_quotes", "(", "tickers_list", ",", "selected_columns", "=", "[", "'*'", "]", ")", ":", "__validate_list", "(", "tickers_list", ")", "__validate_list", "(", "selected_columns", ")", "query", "=", "'select {cols} from yahoo.finance.quotes where symbol in ({vals})'", "query", "=", "query", ".", "format", "(", "cols", "=", "', '", ".", "join", "(", "selected_columns", ")", ",", "vals", "=", "', '", ".", "join", "(", "'\"{0}\"'", ".", "format", "(", "s", ")", "for", "s", "in", "tickers_list", ")", ")", "response", "=", "__yahoo_request", "(", "query", ")", "if", "not", "response", ":", "raise", "RequestError", "(", "'Unable to process the request. Check if the '", "+", "'columns selected are valid.'", ")", "if", "not", "type", "(", "response", "[", "'quote'", "]", ")", "is", "list", ":", "return", "[", "response", "[", "'quote'", "]", "]", "return", "response", "[", "'quote'", "]" ]
33.75
[ 0.017543859649122806, 0.046511627906976744, 0, 0.027777777777777776, 0.07792207792207792, 0.08695652173913043, 0, 0.05084745762711865, 0.6, 0.06060606060606061, 0.07142857142857142, 0.6, 0, 0.10344827586206896, 0.13043478260869565, 0.047619047619047616, 0.07692307692307693, 0.05128205128205128, 0.05660377358490566, 0.0967741935483871, 0.1875, 0.09090909090909091, 0.2857142857142857, 0.06060606060606061, 0.05405405405405406, 0.02564102564102564, 0.12, 0.07317073170731707, 0.047619047619047616, 0.6, 0, 0.05405405405405406, 0, 0.1, 0.04, 0.07017543859649122, 0, 0.046511627906976744, 0.058823529411764705, 0.07142857142857142 ]
def add_class(self, ioclass): """Add one VNXIOClass instance to policy. .. note: due to the limitation of VNX, need to stop the policy first. """ current_ioclasses = self.ioclasses if ioclass.name in current_ioclasses.name: return current_ioclasses.append(ioclass) self.modify(new_ioclasses=current_ioclasses)
[ "def", "add_class", "(", "self", ",", "ioclass", ")", ":", "current_ioclasses", "=", "self", ".", "ioclasses", "if", "ioclass", ".", "name", "in", "current_ioclasses", ".", "name", ":", "return", "current_ioclasses", ".", "append", "(", "ioclass", ")", "self", ".", "modify", "(", "new_ioclasses", "=", "current_ioclasses", ")" ]
36.9
[ 0.034482758620689655, 0.04081632653061224, 0, 0.025974025974025976, 0.18181818181818182, 0.047619047619047616, 0.04, 0.1111111111111111, 0.04878048780487805, 0.038461538461538464 ]
def main(argv): """Entry point for command line script to perform OAuth 2.0.""" p = argparse.ArgumentParser() p.add_argument('-s', '--scope', nargs='+') p.add_argument('-o', '--oauth-service', default='google') p.add_argument('-i', '--client-id') p.add_argument('-x', '--client-secret') p.add_argument('-r', '--redirect-uri') p.add_argument('-f', '--client-secrets') args = p.parse_args(argv) client_args = (args.client_id, args.client_secret, args.client_id) if any(client_args) and not all(client_args): print('Must provide none of client-id, client-secret and redirect-uri;' ' or all of them.') p.print_usage() return 1 print args.scope if not args.scope: print('Scope must be provided.') p.print_usage() return 1 config = WizardClientConfig() config.scope = ' '.join(args.scope) print(run_local(UserOAuth2(config))['access_token']) return 0
[ "def", "main", "(", "argv", ")", ":", "p", "=", "argparse", ".", "ArgumentParser", "(", ")", "p", ".", "add_argument", "(", "'-s'", ",", "'--scope'", ",", "nargs", "=", "'+'", ")", "p", ".", "add_argument", "(", "'-o'", ",", "'--oauth-service'", ",", "default", "=", "'google'", ")", "p", ".", "add_argument", "(", "'-i'", ",", "'--client-id'", ")", "p", ".", "add_argument", "(", "'-x'", ",", "'--client-secret'", ")", "p", ".", "add_argument", "(", "'-r'", ",", "'--redirect-uri'", ")", "p", ".", "add_argument", "(", "'-f'", ",", "'--client-secrets'", ")", "args", "=", "p", ".", "parse_args", "(", "argv", ")", "client_args", "=", "(", "args", ".", "client_id", ",", "args", ".", "client_secret", ",", "args", ".", "client_id", ")", "if", "any", "(", "client_args", ")", "and", "not", "all", "(", "client_args", ")", ":", "print", "(", "'Must provide none of client-id, client-secret and redirect-uri;'", "' or all of them.'", ")", "p", ".", "print_usage", "(", ")", "return", "1", "print", "args", ".", "scope", "if", "not", "args", ".", "scope", ":", "print", "(", "'Scope must be provided.'", ")", "p", ".", "print_usage", "(", ")", "return", "1", "config", "=", "WizardClientConfig", "(", ")", "config", ".", "scope", "=", "' '", ".", "join", "(", "args", ".", "scope", ")", "print", "(", "run_local", "(", "UserOAuth2", "(", "config", ")", ")", "[", "'access_token'", "]", ")", "return", "0" ]
35.52
[ 0.06666666666666667, 0.046153846153846156, 0.0967741935483871, 0.06818181818181818, 0.05084745762711865, 0.08108108108108109, 0.07317073170731707, 0.075, 0.07142857142857142, 0.1111111111111111, 0.04411764705882353, 0.06382978723404255, 0.04, 0.13793103448275862, 0.10526315789473684, 0.16666666666666666, 0.16666666666666666, 0.15, 0.05555555555555555, 0.10526315789473684, 0.16666666666666666, 0.0967741935483871, 0.08108108108108109, 0.05555555555555555, 0.3 ]
def session(self): """ Get session object to benefit from connection pooling. http://docs.python-requests.org/en/master/user/advanced/#session-objects :rtype: requests.Session """ if self._session is None: self._session = requests.Session() self._session.headers.update(self._headers) return self._session
[ "def", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "requests", ".", "Session", "(", ")", "self", ".", "_session", ".", "headers", ".", "update", "(", "self", ".", "_headers", ")", "return", "self", ".", "_session" ]
31.333333
[ 0.05555555555555555, 0.18181818181818182, 0.03225806451612903, 0, 0.075, 0, 0.09375, 0.18181818181818182, 0.06060606060606061, 0.043478260869565216, 0.03636363636363636, 0.07142857142857142 ]
def edit(self, resource): """Edit a device. :param resource: :class:`devices.Device <devices.Device>` object :return: :class:`devices.Device <devices.Device>` object :rtype: devices.Device """ schema = DeviceSchema(exclude=('id', 'created', 'updated', 'result_id', 'attachments_dir')) json = self.service.encode(schema, resource) schema = DeviceSchema() resp = self.service.edit(self.base, resource.id, json) return self.service.decode(schema, resp)
[ "def", "edit", "(", "self", ",", "resource", ")", ":", "schema", "=", "DeviceSchema", "(", "exclude", "=", "(", "'id'", ",", "'created'", ",", "'updated'", ",", "'result_id'", ",", "'attachments_dir'", ")", ")", "json", "=", "self", ".", "service", ".", "encode", "(", "schema", ",", "resource", ")", "schema", "=", "DeviceSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "edit", "(", "self", ".", "base", ",", "resource", ".", "id", ",", "json", ")", "return", "self", ".", "service", ".", "decode", "(", "schema", ",", "resp", ")" ]
39.923077
[ 0.04, 0.08, 0, 0.125, 0.140625, 0.1, 0.18181818181818182, 0.030303030303030304, 0.038461538461538464, 0, 0.06451612903225806, 0.03225806451612903, 0.041666666666666664 ]
def checkname(self, elt, ps): '''See if the name and type of the "elt" element is what we're looking for. Return the element's type. Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. ''' parselist,errorlist = self.get_parse_and_errorlist() ns, name = _get_element_nsuri_name(elt) if ns == SOAP.ENC: # Element is in SOAP namespace, so the name is a type. if parselist and \ (None, name) not in parselist and (ns, name) not in parselist: raise EvaluateException( 'Element mismatch (got %s wanted %s) (SOAP encoding namespace)' % \ (name, errorlist), ps.Backtrace(elt)) return (ns, name) # Not a type, check name matches. if self.nspname and ns != self.nspname: raise EvaluateException('Element NS mismatch (got %s wanted %s)' % \ (ns, self.nspname), ps.Backtrace(elt)) if self.pname and name != self.pname: raise EvaluateException('Element Name mismatch (got %s wanted %s)' % \ (name, self.pname), ps.Backtrace(elt)) return self.checktype(elt, ps)
[ "def", "checkname", "(", "self", ",", "elt", ",", "ps", ")", ":", "parselist", ",", "errorlist", "=", "self", ".", "get_parse_and_errorlist", "(", ")", "ns", ",", "name", "=", "_get_element_nsuri_name", "(", "elt", ")", "if", "ns", "==", "SOAP", ".", "ENC", ":", "# Element is in SOAP namespace, so the name is a type.", "if", "parselist", "and", "(", "None", ",", "name", ")", "not", "in", "parselist", "and", "(", "ns", ",", "name", ")", "not", "in", "parselist", ":", "raise", "EvaluateException", "(", "'Element mismatch (got %s wanted %s) (SOAP encoding namespace)'", "%", "(", "name", ",", "errorlist", ")", ",", "ps", ".", "Backtrace", "(", "elt", ")", ")", "return", "(", "ns", ",", "name", ")", "# Not a type, check name matches.", "if", "self", ".", "nspname", "and", "ns", "!=", "self", ".", "nspname", ":", "raise", "EvaluateException", "(", "'Element NS mismatch (got %s wanted %s)'", "%", "(", "ns", ",", "self", ".", "nspname", ")", ",", "ps", ".", "Backtrace", "(", "elt", ")", ")", "if", "self", ".", "pname", "and", "name", "!=", "self", ".", "pname", ":", "raise", "EvaluateException", "(", "'Element Name mismatch (got %s wanted %s)'", "%", "(", "name", ",", "self", ".", "pname", ")", ",", "ps", ".", "Backtrace", "(", "elt", ")", ")", "return", "self", ".", "checktype", "(", "elt", ",", "ps", ")" ]
43.642857
[ 0.034482758620689655, 0.02857142857142857, 0.04081632653061224, 0.10526315789473684, 0.06382978723404255, 0.075, 0.18181818181818182, 0, 0.05, 0.0425531914893617, 0.07692307692307693, 0.030303030303030304, 0.06666666666666667, 0.02702702702702703, 0.075, 0.03614457831325301, 0.04918032786885246, 0.06896551724137931, 0, 0.04878048780487805, 0.0425531914893617, 0.05, 0.05555555555555555, 0, 0.044444444444444446, 0.04878048780487805, 0.05555555555555555, 0.05263157894736842 ]
def encrypt_python_item(item, crypto_config): # type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM """Encrypt a dictionary for DynamoDB. >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item >>> plaintext_item = { ... 'some': 'data', ... 'more': 5 ... } >>> encrypted_item = encrypt_python_item( ... item=plaintext_item, ... crypto_config=my_crypto_config ... ) .. note:: This handles human-friendly dictionaries and is for use with the boto3 DynamoDB service or table resource. :param dict item: Plaintext dictionary :param CryptoConfig crypto_config: Cryptographic configuration :returns: Encrypted and signed dictionary :rtype: dict """ ddb_item = dict_to_ddb(item) encrypted_ddb_item = encrypt_dynamodb_item(ddb_item, crypto_config) return ddb_to_dict(encrypted_ddb_item)
[ "def", "encrypt_python_item", "(", "item", ",", "crypto_config", ")", ":", "# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM", "ddb_item", "=", "dict_to_ddb", "(", "item", ")", "encrypted_ddb_item", "=", "encrypt_dynamodb_item", "(", "ddb_item", ",", "crypto_config", ")", "return", "ddb_to_dict", "(", "encrypted_ddb_item", ")" ]
34.346154
[ 0.022222222222222223, 0.02857142857142857, 0.04878048780487805, 0, 0.038461538461538464, 0.15384615384615385, 0.07407407407407407, 0.09523809523809523, 0.4444444444444444, 0.08888888888888889, 0.09375, 0.07142857142857142, 0.4444444444444444, 0, 0.23076923076923078, 0, 0.02631578947368421, 0, 0.07142857142857142, 0.045454545454545456, 0.06666666666666667, 0.1875, 0.2857142857142857, 0.0625, 0.028169014084507043, 0.047619047619047616 ]
def remove_outliers(lodol, actually_keep=True): bad_indexes = set() bad_keys = set() DEVIATIONS = 3 MAX_LENGTH = 10000 for data in lodol: #print(data['name']) #print([e for e in data['data'] if isinstance(e, (str, unicode))]) if isinstance(data['data'][0], (int, float)): print(data['name']) mean = statistics.mean(data['data']) std = statistics.stdev(data['data']) evils = 0 for index, value in enumerate(data['data']): if mean - DEVIATIONS*std > value or value > mean + DEVIATIONS*std: bad_keys.add(data['name']) bad_indexes.add(index) evils += 1 #print(data['name'], mean-4*std, mean+4*std, evils) total_indexes = len(lodol[0]['data']) reduced_indexes = total_indexes - len(bad_indexes) print("Bad indexes:", len(bad_indexes), "/", total_indexes) ''' I have a list of numbers Z from 0 to N I have a list of J numbers (where J < N) randomly distributed throughout Z I wish to remove K numbers from Z, without drawing from any number in J ''' if reduced_indexes > MAX_LENGTH: stride = total_indexes / MAX_LENGTH for an_index in xrange(0, total_indexes, stride): keep_index = random.randint(0, stride-1) for offset in xrange(0, stride): if keep_index != offset: bad_indexes.add(min(total_indexes, an_index+offset)) if actually_keep: bad_indexes = set() bad_keys = set() print("Trimmed indexes:", len(bad_indexes), "/", total_indexes) #print("Contributing keys:", ', '.join(bad_keys)) key_names = [row['name'] for row in lodol] short_key_names = shortest_unique_strings(key_names) key_name_map = dict(zip(key_names, short_key_names)) for data in lodol: data['data'] = [v for i, v in enumerate(data['data']) if i not in bad_indexes] #inter = data['name'].split('.', 2)[2] #if '.' in inter: # category, name = inter.rsplit('.', 1) #else: # category, name = inter, inter #category = category.replace('.', ' ') #data['pretty'] = category.title() + ": "+name.title() data['pretty'] = key_name_map[data['name']] print(data['pretty']) if isinstance(data['data'][0], (float, int)): data['type'] = 'number' else: data['type'] = 'text' lodol.sort(key= lambda e: e['pretty']) return key_name_map
[ "def", "remove_outliers", "(", "lodol", ",", "actually_keep", "=", "True", ")", ":", "bad_indexes", "=", "set", "(", ")", "bad_keys", "=", "set", "(", ")", "DEVIATIONS", "=", "3", "MAX_LENGTH", "=", "10000", "for", "data", "in", "lodol", ":", "#print(data['name'])", "#print([e for e in data['data'] if isinstance(e, (str, unicode))])", "if", "isinstance", "(", "data", "[", "'data'", "]", "[", "0", "]", ",", "(", "int", ",", "float", ")", ")", ":", "print", "(", "data", "[", "'name'", "]", ")", "mean", "=", "statistics", ".", "mean", "(", "data", "[", "'data'", "]", ")", "std", "=", "statistics", ".", "stdev", "(", "data", "[", "'data'", "]", ")", "evils", "=", "0", "for", "index", ",", "value", "in", "enumerate", "(", "data", "[", "'data'", "]", ")", ":", "if", "mean", "-", "DEVIATIONS", "*", "std", ">", "value", "or", "value", ">", "mean", "+", "DEVIATIONS", "*", "std", ":", "bad_keys", ".", "add", "(", "data", "[", "'name'", "]", ")", "bad_indexes", ".", "add", "(", "index", ")", "evils", "+=", "1", "#print(data['name'], mean-4*std, mean+4*std, evils)", "total_indexes", "=", "len", "(", "lodol", "[", "0", "]", "[", "'data'", "]", ")", "reduced_indexes", "=", "total_indexes", "-", "len", "(", "bad_indexes", ")", "print", "(", "\"Bad indexes:\"", ",", "len", "(", "bad_indexes", ")", ",", "\"/\"", ",", "total_indexes", ")", "if", "reduced_indexes", ">", "MAX_LENGTH", ":", "stride", "=", "total_indexes", "/", "MAX_LENGTH", "for", "an_index", "in", "xrange", "(", "0", ",", "total_indexes", ",", "stride", ")", ":", "keep_index", "=", "random", ".", "randint", "(", "0", ",", "stride", "-", "1", ")", "for", "offset", "in", "xrange", "(", "0", ",", "stride", ")", ":", "if", "keep_index", "!=", "offset", ":", "bad_indexes", ".", "add", "(", "min", "(", "total_indexes", ",", "an_index", "+", "offset", ")", ")", "if", "actually_keep", ":", "bad_indexes", "=", "set", "(", ")", "bad_keys", "=", "set", "(", ")", "print", "(", "\"Trimmed indexes:\"", ",", "len", "(", "bad_indexes", ")", ",", "\"/\"", ",", "total_indexes", ")", "#print(\"Contributing keys:\", ', '.join(bad_keys))", "key_names", "=", "[", "row", "[", "'name'", "]", "for", "row", "in", "lodol", "]", "short_key_names", "=", "shortest_unique_strings", "(", "key_names", ")", "key_name_map", "=", "dict", "(", "zip", "(", "key_names", ",", "short_key_names", ")", ")", "for", "data", "in", "lodol", ":", "data", "[", "'data'", "]", "=", "[", "v", "for", "i", ",", "v", "in", "enumerate", "(", "data", "[", "'data'", "]", ")", "if", "i", "not", "in", "bad_indexes", "]", "#inter = data['name'].split('.', 2)[2]", "#if '.' in inter:", "# category, name = inter.rsplit('.', 1)", "#else:", "# category, name = inter, inter", "#category = category.replace('.', ' ')", "#data['pretty'] = category.title() + \": \"+name.title()", "data", "[", "'pretty'", "]", "=", "key_name_map", "[", "data", "[", "'name'", "]", "]", "print", "(", "data", "[", "'pretty'", "]", ")", "if", "isinstance", "(", "data", "[", "'data'", "]", "[", "0", "]", ",", "(", "float", ",", "int", ")", ")", ":", "data", "[", "'type'", "]", "=", "'number'", "else", ":", "data", "[", "'type'", "]", "=", "'text'", "lodol", ".", "sort", "(", "key", "=", "lambda", "e", ":", "e", "[", "'pretty'", "]", ")", "return", "key_name_map" ]
41.57377
[ 0.02127659574468085, 0.08695652173913043, 0.1, 0.1111111111111111, 0.09090909090909091, 0.5, 0.09090909090909091, 0.10714285714285714, 0.04054054054054054, 0.03773584905660377, 0.06451612903225806, 0.041666666666666664, 0.041666666666666664, 0.09523809523809523, 0.03571428571428571, 0.036585365853658534, 0.043478260869565216, 0.047619047619047616, 0.06666666666666667, 0.047619047619047616, 0.1, 0.04878048780487805, 0.037037037037037035, 0.031746031746031744, 0.2857142857142857, 0.047619047619047616, 0.038461538461538464, 0.02666666666666667, 0.2857142857142857, 0.05555555555555555, 0.046511627906976744, 0.03508771929824561, 0.038461538461538464, 0.045454545454545456, 0.05, 0.027777777777777776, 0.09523809523809523, 0.07407407407407407, 0.08333333333333333, 0.04225352112676056, 0.05660377358490566, 0.043478260869565216, 0.03571428571428571, 0.03571428571428571, 0.09090909090909091, 0.03488372093023256, 0.06521739130434782, 0.12, 0.04, 0.21428571428571427, 0.047619047619047616, 0.06521739130434782, 0.04838709677419355, 0.057692307692307696, 0.06896551724137931, 0.03773584905660377, 0.05714285714285714, 0.15384615384615385, 0.06060606060606061, 0.07142857142857142, 0.08695652173913043 ]
def GameTypeEnum(ctx): """Game Type Enumeration.""" return Enum( ctx, RM=0, Regicide=1, DM=2, Scenario=3, Campaign=4, KingOfTheHill=5, WonderRace=6, DefendTheWonder=7, TurboRandom=8 )
[ "def", "GameTypeEnum", "(", "ctx", ")", ":", "return", "Enum", "(", "ctx", ",", "RM", "=", "0", ",", "Regicide", "=", "1", ",", "DM", "=", "2", ",", "Scenario", "=", "3", ",", "Campaign", "=", "4", ",", "KingOfTheHill", "=", "5", ",", "WonderRace", "=", "6", ",", "DefendTheWonder", "=", "7", ",", "TurboRandom", "=", "8", ")" ]
18.714286
[ 0.045454545454545456, 0.0625, 0.1875, 0.16666666666666666, 0.23076923076923078, 0.15789473684210525, 0.23076923076923078, 0.15789473684210525, 0.15789473684210525, 0.125, 0.14285714285714285, 0.11538461538461539, 0.14285714285714285, 0.6 ]
def _initial_placement(movable_vertices, vertices_resources, machine, random): """For internal use. Produces a random, sequential initial placement, updating the resource availabilities of every core in the supplied machine. Parameters ---------- movable_vertices : {vertex, ...} A set of the vertices to be given a random initial placement. vertices_resources : {vertex: {resource: value, ...}, ...} machine : :py:class:`rig.place_and_route.Machine` A machine object describing the machine into which the vertices should be placed. All chips hosting fixed vertices should have a chip_resource_exceptions entry which accounts for the allocated resources. When this function returns, the machine.chip_resource_exceptions will be updated to account for the resources consumed by the initial placement of movable vertices. random : :py:class`random.Random` The random number generator to use Returns ------- {vertex: (x, y), ...} For all movable_vertices. Raises ------ InsufficientResourceError InvalidConstraintError """ # Initially fill chips in the system in a random order locations = list(machine) random.shuffle(locations) location_iter = iter(locations) # Greedily place the vertices in a random order movable_vertices = list(v for v in vertices_resources if v in movable_vertices) random.shuffle(movable_vertices) vertex_iter = iter(movable_vertices) placement = {} try: location = next(location_iter) except StopIteration: raise InsufficientResourceError("No working chips in system.") while True: # Get a vertex to place try: vertex = next(vertex_iter) except StopIteration: # All vertices have been placed break # Advance through the set of available locations until we find a chip # where the vertex fits while True: resources_if_placed = subtract_resources( machine[location], vertices_resources[vertex]) if overallocated(resources_if_placed): # The vertex won't fit on this chip, move onto the next chip try: location = next(location_iter) continue except StopIteration: raise InsufficientResourceError( "Ran out of chips while attempting to place vertex " "{}".format(vertex)) else: # The vertex fits: record the resources consumed and move on to # the next vertex. placement[vertex] = location machine[location] = resources_if_placed break return placement
[ "def", "_initial_placement", "(", "movable_vertices", ",", "vertices_resources", ",", "machine", ",", "random", ")", ":", "# Initially fill chips in the system in a random order", "locations", "=", "list", "(", "machine", ")", "random", ".", "shuffle", "(", "locations", ")", "location_iter", "=", "iter", "(", "locations", ")", "# Greedily place the vertices in a random order", "movable_vertices", "=", "list", "(", "v", "for", "v", "in", "vertices_resources", "if", "v", "in", "movable_vertices", ")", "random", ".", "shuffle", "(", "movable_vertices", ")", "vertex_iter", "=", "iter", "(", "movable_vertices", ")", "placement", "=", "{", "}", "try", ":", "location", "=", "next", "(", "location_iter", ")", "except", "StopIteration", ":", "raise", "InsufficientResourceError", "(", "\"No working chips in system.\"", ")", "while", "True", ":", "# Get a vertex to place", "try", ":", "vertex", "=", "next", "(", "vertex_iter", ")", "except", "StopIteration", ":", "# All vertices have been placed", "break", "# Advance through the set of available locations until we find a chip", "# where the vertex fits", "while", "True", ":", "resources_if_placed", "=", "subtract_resources", "(", "machine", "[", "location", "]", ",", "vertices_resources", "[", "vertex", "]", ")", "if", "overallocated", "(", "resources_if_placed", ")", ":", "# The vertex won't fit on this chip, move onto the next chip", "try", ":", "location", "=", "next", "(", "location_iter", ")", "continue", "except", "StopIteration", ":", "raise", "InsufficientResourceError", "(", "\"Ran out of chips while attempting to place vertex \"", "\"{}\"", ".", "format", "(", "vertex", ")", ")", "else", ":", "# The vertex fits: record the resources consumed and move on to", "# the next vertex.", "placement", "[", "vertex", "]", "=", "location", "machine", "[", "location", "]", "=", "resources_if_placed", "break", "return", "placement" ]
35.620253
[ 0.01282051282051282, 0.0273972602739726, 0.02531645569620253, 0, 0.14285714285714285, 0.14285714285714285, 0.08333333333333333, 0.028985507246376812, 0.04838709677419355, 0.1509433962264151, 0.02564102564102564, 0.1111111111111111, 0, 0.02531645569620253, 0.03508771929824561, 0, 0.025974025974025976, 0.028169014084507043, 0.05263157894736842, 0.1891891891891892, 0.047619047619047616, 0, 0.18181818181818182, 0.18181818181818182, 0.08, 0.06060606060606061, 0, 0.2, 0.2, 0.06896551724137931, 0.07692307692307693, 0.2857142857142857, 0.034482758620689655, 0.06896551724137931, 0.06896551724137931, 0.05714285714285714, 0, 0.0392156862745098, 0.05263157894736842, 0.05660377358490566, 0.05555555555555555, 0.05, 0, 0.1111111111111111, 0.25, 0.05263157894736842, 0.08, 0.02857142857142857, 0.13333333333333333, 0.06451612903225806, 0.16666666666666666, 0.05263157894736842, 0.06896551724137931, 0.046511627906976744, 0.11764705882352941, 0, 0.025974025974025976, 0.06451612903225806, 0.10526315789473684, 0.05660377358490566, 0.04838709677419355, 0, 0.04, 0.02631578947368421, 0.1, 0.04, 0.07142857142857142, 0.05405405405405406, 0.057692307692307696, 0.02631578947368421, 0.06818181818181818, 0.11764705882352941, 0.02531645569620253, 0.058823529411764705, 0.045454545454545456, 0.03636363636363636, 0.09523809523809523, 0, 0.1 ]
def sed(self, photon_energy, distance=1 * u.kpc): """Spectral energy distribution at a given distance from the source. Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` float or array Photon energy array. distance : :class:`~astropy.units.Quantity` float, optional Distance to the source. If set to 0, the intrinsic luminosity will be returned. Default is 1 kpc. """ if distance != 0: out_unit = "erg/(cm2 s)" else: out_unit = "erg/s" photon_energy = _validate_ene(photon_energy) sed = (self.flux(photon_energy, distance) * photon_energy ** 2.0).to( out_unit ) return sed
[ "def", "sed", "(", "self", ",", "photon_energy", ",", "distance", "=", "1", "*", "u", ".", "kpc", ")", ":", "if", "distance", "!=", "0", ":", "out_unit", "=", "\"erg/(cm2 s)\"", "else", ":", "out_unit", "=", "\"erg/s\"", "photon_energy", "=", "_validate_ene", "(", "photon_energy", ")", "sed", "=", "(", "self", ".", "flux", "(", "photon_energy", ",", "distance", ")", "*", "photon_energy", "**", "2.0", ")", ".", "to", "(", "out_unit", ")", "return", "sed" ]
30.916667
[ 0.02040816326530612, 0.02631578947368421, 0, 0.1111111111111111, 0.1111111111111111, 0.09859154929577464, 0.0625, 0, 0.1044776119402985, 0.02564102564102564, 0.047619047619047616, 0.18181818181818182, 0.08, 0.05555555555555555, 0.15384615384615385, 0.06666666666666667, 0, 0.038461538461538464, 0, 0.03896103896103896, 0.1, 0.3333333333333333, 0, 0.1111111111111111 ]