code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_empty_json_serialization_deserialization_fails(self): <NEW_LINE> <INDENT> json_string = EMPTY_JSON <NEW_LINE> with self.assertRaises(TypeError, msg="Person should not be instantiable with empty JSON!"): <NEW_LINE> <INDENT> JsonHelper.to_instance(json_string, Person)
It is an error to try deserializing an empty JSON back to an object that needs construction-time parameters
625941c3a17c0f6771cbe013
def format_data(self, box_ids): <NEW_LINE> <INDENT> boxes = [Box.get(face_id) for face_id in box_ids] <NEW_LINE> videos = defaultdict(dict) <NEW_LINE> for box in boxes: <NEW_LINE> <INDENT> video_id = int(box.video_id) <NEW_LINE> box_id = int(box.id) <NEW_LINE> videos[box_id]['video_id'] = video_id <NEW_LINE> videos[box...
ideal number of box ids is 18, but the template will not break if there are more or less
625941c3cc0a2c11143dce51
def set_grey_lower(self, val): <NEW_LINE> <INDENT> self.grey_lb = val
Use sliders to set GREY lower bound.
625941c3baa26c4b54cb10e2
def get_ranksum(self, log): <NEW_LINE> <INDENT> values_per_group = {col_name: col for col_name, col in self.stratified_ilash.groupby('Population_x')['sum']} <NEW_LINE> populations = list(values_per_group.keys()) <NEW_LINE> populations_list = list(set([tuple(sorted([i, j])) for i in populations for j in populations])) <...
Args: self object(:obj:`self`): self object with attributes Returns: For each population a paired Wilcoxen-rank sum tests: a test statistic a two-sided p-value of the test
625941c3be7bc26dc91cd5c4
def add_like(obj, user): <NEW_LINE> <INDENT> obj_type = get_obj_type_for_model(obj) <NEW_LINE> with atomic(): <NEW_LINE> <INDENT> like, created = Like.objects.get_or_create(content_type=obj_type, object_id=obj.id, user=user) <NEW_LINE> if not created: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> likes, _ = Likes.obje...
Add a like to an object. If the user has already liked the object nothing happends, so this function can be considered idempotent. :param obj: Any Django model instance. :param user: User adding the like. :class:`~hashup.users.models.User` instance.
625941c35f7d997b87174a57
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 2 <NEW_LINE> (self.requestedID,) = _struct_h.unpack(str[start:end]) <NEW_LINE> return self <NEW_LINE> <DEDENT> except struct.error as e: <NEW_LINE> <INDENT> raise genpy.DeserializationE...
unpack serialized message in str into this message instance using numpy for array types :param str: byte array of serialized message, ``str`` :param numpy: numpy python module
625941c3f548e778e58cd53e
def test_checkForExistingReaction_keeps_identical_reactions_with_duplicate_flag(self): <NEW_LINE> <INDENT> cerm = CoreEdgeReactionModel() <NEW_LINE> spcA = Species().fromSMILES('[H]') <NEW_LINE> spcB = Species().fromSMILES('C=C[CH2]C') <NEW_LINE> spcC = Species().fromSMILES('C=C=CC') <NEW_LINE> spcD = Species().fromSMI...
Test that checkForExistingReaction keeps reactions with different templates and duplicate=True.
625941c3e1aae11d1e749c77
def response_cb(response): <NEW_LINE> <INDENT> if response == stock.ACCEPT: <NEW_LINE> <INDENT> use_http = c_use_http.get_active() <NEW_LINE> use_ipv6 = c_use_ipv6.get_active() <NEW_LINE> use_proxy = c_use_proxy.get_active() <NEW_LINE> use_auth = c_use_auth.get_active() <NEW_LINE> proxy_host = t_proxy_host.get_text() <...
called on any response (close, accept, cancel) if accept get the new values and call callback with those values
625941c36fb2d068a760f05d
def grouper(iterable, n, fillvalue=None): <NEW_LINE> <INDENT> args = [iter(iterable)] * n <NEW_LINE> return itertools.zip_longest(*args, fillvalue=fillvalue)
Collect data into fixed-length chunks or blocks Example: grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
625941c3442bda511e8be3dc
def register_window(): <NEW_LINE> <INDENT> global register_screen <NEW_LINE> global username <NEW_LINE> global password <NEW_LINE> global erase_username <NEW_LINE> global erase_pass <NEW_LINE> username = tk.StringVar() <NEW_LINE> password = tk.StringVar() <NEW_LINE> register_screen = tk.Toplevel(origin_screen) <NEW_LIN...
Design of Registration Window - allows a user with no account to create one
625941c3dd821e528d63b16c
def block(nest=Nesting.POST, sub=None, opts=''): <NEW_LINE> <INDENT> def block_fn(parser:Callable) -> Block: <NEW_LINE> <INDENT> return Block(parser, nest, sub or ['all'], opts) <NEW_LINE> <DEDENT> return block_fn
Decorator for block style elements, to be used on a parser function. eg: ```python @block(...) def BlockName(text): """ docs for BlockName element go here """ return ['div', text] ``` The name of the function becomes the name of the block. There is automatic sanitization/converstion that happens in the process. S...
625941c307d97122c4178849
def remove(self, obj): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> if obj not in self._objects: <NEW_LINE> <INDENT> return self.remove_blacklist(obj) <NEW_LINE> <DEDENT> self._objects.remove(obj) <NEW_LINE> return True
Remove an object from the list. :param obj: vmmLibvirtObject to remove :returns: True if object removed, False if object was not found
625941c399fddb7c1c9de353
def build_cfg(self): <NEW_LINE> <INDENT> pass
Called during the objects instantiation. Override to set the requests `cfg` property.
625941c34428ac0f6e5ba7b3
def get_sentiment(service, sentence): <NEW_LINE> <INDENT> body = get_request_body( sentence, syntax=False, entities=True, sentiment=True) <NEW_LINE> docs = service.documents() <NEW_LINE> request = docs.annotateText(body=body) <NEW_LINE> response = request.execute(num_retries=3) <NEW_LINE> sentiment = response.get('docu...
Get the sentence-level sentiment.
625941c3a17c0f6771cbe014
def login_user(client, user_id, password): <NEW_LINE> <INDENT> return client.post( '/api/auth/login', content_type='application/json', data=json.dumps( { 'user_id': user_id, 'password': password } ) )
Helper function for user login
625941c3bde94217f3682db4
def removeItem(self, p_int): <NEW_LINE> <INDENT> pass
QComboBox.removeItem(int)
625941c31d351010ab855ade
def get_h_all_text(doc): <NEW_LINE> <INDENT> start = [] <NEW_LINE> names = [] <NEW_LINE> regex = re.compile(r"<h[1-6].+\n.*") <NEW_LINE> for match in regex.finditer(doc): <NEW_LINE> <INDENT> h_name = re.findall(r">\n.*", match.group())[0][2:].strip() <NEW_LINE> names.append(h_name) <NEW_LINE> start.append(match.start()...
get text between h tags, except: practice', 'questions', 'review', 'explore more', 'references
625941c34e4d5625662d439c
def high_kick(self, game): <NEW_LINE> <INDENT> ball_pos = game.get_ball_position() <NEW_LINE> if game.is_team_side(game.get_ball_position(), self.my_team) and game.get_player_at(game.get_ball_position()) is None: <NEW_LINE> <INDENT> for player in game.get_players_on_pitch(self.my_team, up=True): <NEW_LIN...
Select player to move under the ball.
625941c310dbd63aa1bd2b66
def _worker_container(task_q, result_q, func): <NEW_LINE> <INDENT> _th_name = threading.current_thread().name <NEW_LINE> logger.debug('[W++] mpms worker %s starting'% _th_name) <NEW_LINE> while True: <NEW_LINE> <INDENT> taskid, args, kwargs = task_q.get() <NEW_LINE> if taskid is StopIteration: <NEW_LINE> <INDENT> logge...
Args: result_q (Queue|None)
625941c32c8b7c6e89b35783
def __init__(self, url, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.url = url <NEW_LINE> self.id = kwargs.pop("id", "") <NEW_LINE> self.title = kwargs.pop("title", "") <NEW_LINE> self.text = kwargs.pop("text", "") <NEW_LINE> self.language = kwargs.pop("language", "") <NEW_LINE> self.author = kwarg...
An item in a list of results returned by SearchEngine.search(). All dictionary keys are available as Unicode string attributes. - id : unique identifier, - url : the URL of the referred web content, - title : the title of the content at the URL, - text : the content text, - language : the content lan...
625941c3be7bc26dc91cd5c5
def set_gradient_error_factor(self, value): <NEW_LINE> <INDENT> self._data['gradient_error'] = value <NEW_LINE> return
Set the error factor for steepness changes. :param value: :type value:
625941c3091ae35668666f23
def extract_from_headers(mail): <NEW_LINE> <INDENT> extracted = {} <NEW_LINE> log.debug("Extracting values from custom headers") <NEW_LINE> branch = mail[X_GIT_BRANCH_HEADER] or None <NEW_LINE> version = mail[X_KERNEL_VERSION_HEADER] or None <NEW_LINE> tree = mail[X_TREE_HEADER] or None <NEW_LINE> patches = mail[X_PATC...
Extract the kerormations from mail headers. :param mail: The email to parse. :return dict A dictionary with tree, branch, version and patches.
625941c391f36d47f21ac4b2
def extractROIsFromPCAICA(spcomps, numSTD=4, gaussiansigmax=2 , gaussiansigmay=2,thresh=None): <NEW_LINE> <INDENT> numcomps, width, height=spcomps.shape <NEW_LINE> rowcols=int(np.ceil(np.sqrt(numcomps))); <NEW_LINE> allMasks=[]; <NEW_LINE> maskgrouped=[]; <NEW_LINE> for k in xrange(0,numcomps): <NEW_LINE> <INDENT> comp...
Given the spatial components output of the IPCA_stICA function extract possible regions of interest The algorithm estimates the significance of a components by thresholding the components after gaussian smoothing Parameters ----------- spcompomps, 3d array containing the spatial components numSTD: number of standard de...
625941c321bff66bcd684916
def check(file, text=""): <NEW_LINE> <INDENT> return __check(file, text)
Private function to check one Python source file for whitespace related problems. @param file source filename (string) @param text source text (string) @return A tuple indicating status (True = an error was found), the filename, the linenumber and the error message (boolean, string, string, string). The values...
625941c363d6d428bbe444b1
def _sorteditems(d, orderby): <NEW_LINE> <INDENT> s = sorted([(i[orderby], k) for k, i in d.items()]) <NEW_LINE> return [(k, d[k]) for i, k in s]
return items from a dict of dict, sorted by the orderby item of the dict
625941c323e79379d52ee527
def report(request): <NEW_LINE> <INDENT> if request.method != 'POST': <NEW_LINE> <INDENT> return render_to_response('assassins/report.html', context_instance=RequestContext(request)) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> reporting_player = Player.objects.get(name=request.POST['playername'], key=request.POST['pla...
provides a form for logging kills
625941c3283ffb24f3c558c5
def slicenames_prefixes(): <NEW_LINE> <INDENT> prefixes = ''.join([string.digits, string.ascii_uppercase, string.ascii_lowercase]) <NEW_LINE> for l in prefixes: <NEW_LINE> <INDENT> yield l + '_'
Prefixes for video slices names in sort order for builtin sorted() function
625941c3d99f1b3c44c67553
def addForeignKeySql(self, c_name, o_pkg, o_tbl, o_fld, m_pkg, m_tbl, m_fld, on_up, on_del, init_deferred): <NEW_LINE> <INDENT> return ''
Sqlite cannot add foreign keys, only define them in CREATE TABLE. However they are not enforced.
625941c39f2886367277a850
@permission_required(add_user_perm) <NEW_LINE> def create(request): <NEW_LINE> <INDENT> is_admin = False <NEW_LINE> is_superuser = request.user.is_superuser <NEW_LINE> if 'wagtailadmin.union_admin' in request.user.get_all_permissions(): <NEW_LINE> <INDENT> is_admin = True <NEW_LINE> <DEDENT> for fn in hooks.get_hooks('...
Return context to create.html
625941c301c39578d7e74dfd
def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None): <NEW_LINE> <INDENT> x = np.asarray(x, order='C', dtype=np.float64) <NEW_LINE> if x.ndim != 1: <NEW_LINE> <INDENT> raise ValueError('`x` must have exactly one dimension') <NEW_LINE> <DEDENT> peaks = np.asarray(peaks) <NEW_LINE> if peaks.size == ...
Calculate the width of each peak in a signal. .. versionadded:: 1.1.0
625941c3711fe17d82542331
def pickling_func2(folder, engine, delta_seq): <NEW_LINE> <INDENT> engine = create_engine('postgresql+psycopg2://ganlan:88a002d51c1@localhost/dataAUV_117', echo=False) <NEW_LINE> """ Creation of a rosbag to postgresql instance """ <NEW_LINE> rtp = rosbag_to_postgresql(pathfile=folder, engine=engine, init_db=True) <NEW_...
Connection parameters to the database
625941c338b623060ff0adb0
def within_bounds(self, item: Item) -> bool: <NEW_LINE> <INDENT> for header, header_range in self.ranges.items(): <NEW_LINE> <INDENT> if not header_range.within_bounds(item[header]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True
Checks whether a tuple is within all the ranges of the this cluster, eg. would cause no information loss on being entered. Args: item: The tuple to perform bounds checking on Returns: Whether or not the tuple is within the bounds of the cluster
625941c330c21e258bdfa45e
def load_pdfreader(self, reader): <NEW_LINE> <INDENT> outlines=reader.getOutlines() <NEW_LINE> self.add_children_from_pdfreader_outlines(outlines)
read outlines from from PyPDF2 reader
625941c39b70327d1c4e0d96
def add_deleted_file(self, path): <NEW_LINE> <INDENT> self.DeletedFiles += 1 <NEW_LINE> self.DeltaEntries += 1 <NEW_LINE> self.add_delta_entries_file(path, b'deleted')
Add stats of file no longer in source directory
625941c30a366e3fb873e7db
def test_is_1_prime(): <NEW_LINE> <INDENT> assert not is_prime(1), "1 is not prime!"
Is 1 prime?
625941c38e71fb1e9831d76c
def sensor2float(int_sensor): <NEW_LINE> <INDENT> float_time = float(int_sensor / 1000000) <NEW_LINE> return float_time
Convert sensor data from int to float.
625941c35fc7496912cc3940
def qryAccount(self): <NEW_LINE> <INDENT> self.qryApi.qryAccount()
查询账户资金
625941c331939e2706e4ce2e
def get_value(self, default=None): <NEW_LINE> <INDENT> ret = self.get("value", default) <NEW_LINE> if ret is None: <NEW_LINE> <INDENT> return self.get_default(default) <NEW_LINE> <DEDENT> return ret
Get field value @param default: @return:
625941c36aa9bd52df036d65
def delete_element_in_dictlist(dic, key): <NEW_LINE> <INDENT> for i in dic: <NEW_LINE> <INDENT> if key in i: <NEW_LINE> <INDENT> del i[key]
Удалить ключ из списка словарей
625941c38a349b6b435e8135
def container_exec(self, name, detach, args): <NEW_LINE> <INDENT> d = util.Decompose(name) <NEW_LINE> if d.registry != "" or ':' in name: <NEW_LINE> <INDENT> repo = self._get_ostree_repo() <NEW_LINE> if not repo: <NEW_LINE> <INDENT> raise ValueError("Cannot find a configured OSTree repo") <NEW_LINE> <DEDENT> name = sel...
Run exec on a container. :param name: The name of the container. :type name: str :param detach: If detach should be used. :type detatch: bool :param args: Arguments to pass to exec :type args: list :returns: The call result :rtype: int :raises: ValueError, OSError, subprocess.CalledProcessError
625941c3b830903b967e98cf
def next_state(present, picum, tmean, kA, opamp): <NEW_LINE> <INDENT> possible = np.nonzero(picum[present] >= random.random())[0] <NEW_LINE> next = np.delete(possible, np.where(possible == present))[0] <NEW_LINE> t = random.expovariate(1 / tmean[next]) <NEW_LINE> a = opamp if next < kA else 0 <NEW_LINE> return next, t,...
Get next state, its lifetime and amplitude.
625941c3a934411ee3751655
def qinclude(context, path, start_at=None, end_at=None): <NEW_LINE> <INDENT> truncate_count = 0 <NEW_LINE> truncate_char = '' <NEW_LINE> fp = StringIO() <NEW_LINE> is_content = start_at is None <NEW_LINE> with open(path) as source: <NEW_LINE> <INDENT> for ii, line in enumerate(source): <NEW_LINE> <INDENT> if not is_con...
start_at: None -> ファイルの先頭から start_at: 'TAG' -> TAGの次の行から end_at: None -> ファイルの最後まで end_at: 'TAG' -> TAGの手前の行まで
625941c373bcbd0ca4b2c039
def check_grad_file_status(grad_file: str) -> dwipy.constants.GRADSTATUS: <NEW_LINE> <INDENT> if os.path.exists(grad_file): <NEW_LINE> <INDENT> return check_grads_status(dwipy.IO.gradient_table.load_mrtrix_grads(grad_file)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dwipy.constants.GRADSTATUS.GRADS_NOT_FOUND
Check the status of the gradients from a gradient file. Args: grad_file (str): Path to gradient file Returns: dwipy.constants.GRADSTATUS: The gradient status
625941c3e76e3b2f99f3a7d1
def compute_novelty(sentences, corpus_file, opt, idx_to_word): <NEW_LINE> <INDENT> ref = sentences[0].split("\n") <NEW_LINE> sentences = [s.split(" ") for s in sentences[1].split("\n")] <NEW_LINE> with open(corpus_file, 'r') as f: <NEW_LINE> <INDENT> corpus = [s.rstrip().split(" ") for s in f.readlines()] <NEW_LINE> <D...
Computes the novelty of a batch of sentences given a corpus.
625941c34a966d76dd550fd0
def pers_ref_lst(self, media_handle): <NEW_LINE> <INDENT> lst = list() <NEW_LINE> backrefs = self._db.find_backlink_handles(media_handle) <NEW_LINE> for (reftype, ref) in backrefs: <NEW_LINE> <INDENT> if reftype == "Person": <NEW_LINE> <INDENT> person = self._db.get_person_from_handle(ref) <NEW_LINE> gallery = person.g...
Get a person reference list with image rectangle information. :param media_handle: handle of the media file :type media_handle: string :return lst: list of reference tuples :rtype lst: list :example lst: (:class Person: object, (0, 0, 100, 100))
625941c3fb3f5b602dac3654
def load(fo): <NEW_LINE> <INDENT> return json.load(fo, object_hook=object_hook)
Load from `fo`, convert date/datetime from string representation to values.
625941c37b180e01f3dc47c3
def __add__(self, other): <NEW_LINE> <INDENT> return DimensionAddition(self, other)
Return the sum of this dimension and `other`.
625941c321bff66bcd684917
def form_post(self, form): <NEW_LINE> <INDENT> pass
Override this method to implement your form processing
625941c39f2886367277a851
def run(self, edit): <NEW_LINE> <INDENT> g = gislacks(self, edit) <NEW_LINE> res = g.Get({ "command": "slack", "options": { "filelistasjson": True, "cfgdirectory": g.settings.get("gislack_cfgpath") } }) <NEW_LINE> if str.strip(res) == "No files.": <NEW_LINE> <INDENT> sublime.message_dialog("No files.") <NEW_LINE> retur...
Function to get file list of Slack @param edit sublime.Edit
625941c3f548e778e58cd53f
def groups(request): <NEW_LINE> <INDENT> if request.user.is_staff: <NEW_LINE> <INDENT> context = {'userGroup': Group.objects.all()} <NEW_LINE> return TemplateResponse(request, 'teacher/groups.html', context) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Http404('<h1>Page not found</h1>')
Учительская админка. Выдает список групп. :param request: :return: 404 :return: шаблон teacher/students.html
625941c329b78933be1e5671
def write_menu(Dish_list: list, s : str): <NEW_LINE> <INDENT> infile1 = open(s,'w') <NEW_LINE> for Dish in Dish_list: <NEW_LINE> <INDENT> infile1.write(str(Dish) + '\n')
Writes a txt document of dishes in list
625941c3a4f1c619b28b0000
def add_sg_pt_tab_detail(self,file_path): <NEW_LINE> <INDENT> sg_pt_tab_detail = list() <NEW_LINE> with open(file_path, 'r') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> line = line.split('\t') <NEW_LINE> if str(line[1]) == "chr3" and str(line[2]) == '18370866': <NEW_LINE>...
导入样本的tab文件 :param file_path:tab文件 :return:
625941c356b00c62f0f1461b
def argvu(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [s.decode(self.encoding) for s in self.argv] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return [s for s in self.argv]
Return the decoded arguments from argv.
625941c3ec188e330fd5a765
def get_scaled_cutout2(self, p1, p2, scales, method='basic', logger=None): <NEW_LINE> <INDENT> if logger is None: <NEW_LINE> <INDENT> logger = self.logger <NEW_LINE> <DEDENT> data = self._get_data() <NEW_LINE> newdata, oscales = trcalc.get_scaled_cutout_basic2(data, p1, p2, scales, interpolation=method, logger=logger) ...
Extract a region of the image defined by points `p1` and `p2` and scale it by scale factors `scales`. `method` describes the method of interpolation used, where the default "basic" is nearest neighbor.
625941c330bbd722463cbd87
def maxAncestorDiff(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.maxdiff=0 <NEW_LINE> self.dfs(root,root.val,root.val) <NEW_LINE> return self.maxdiff
:type root: TreeNode :rtype: int
625941c3236d856c2ad4479a
def run(self): <NEW_LINE> <INDENT> self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> self.sock.connect((self.network, self.port)) <NEW_LINE> self.sock.settimeout(0.3) <NEW_LINE> self.recv() <NEW_LINE> self.send_message('NICK', params=[self.nick]) <NEW_LINE> self.send_message('USER', params=[self....
Connect, execute commands, and then disconnect.
625941c3442bda511e8be3dd
def lonlatradius_2_cartesian(positionVectorLonLatRad): <NEW_LINE> <INDENT> [radius, theta, phi] = lonlatradius_2_sphericalPolar(positionVectorLonLatRad) <NEW_LINE> [x, y, z] = sphericalPolar_2_cartesian([radius, theta, phi]) <NEW_LINE> return [x, y, z]
Convert longitude-latitude-radial coordinates to Cartesian coordinates. Longitude and latitude must be in degrees. The origin of the Cartesian frame of reference is located at the centre of the sphere, the positive half of x-axis goes through 0 deg E, 0 deg N, the positive half of y-axis goes through 90 deg E, 0 deg N...
625941c3091ae35668666f24
def test_postgres_initialise(self): <NEW_LINE> <INDENT> if self.postgres is None: <NEW_LINE> <INDENT> self.skipTest("Postgres is not available. Test is skipping") <NEW_LINE> <DEDENT> data_store_postgres = DataStore( db_username="postgres", db_password="", db_host="localhost", db_port=55527, db_name="test", ) <NEW_LINE>...
Test whether schemas created successfully on PostgresSQL
625941c31f5feb6acb0c4b15
def handle_metadata_verify_json(self, environ, start_response, qs): <NEW_LINE> <INDENT> ok = False <NEW_LINE> services = "[]" <NEW_LINE> try: <NEW_LINE> <INDENT> if CONST_BODY in qs: <NEW_LINE> <INDENT> json_message = json.loads(qs[CONST_BODY]) <NEW_LINE> if "xml" in json_message: <NEW_LINE> <INDENT> xml = json_message...
Handles JSON metadata verifications. The post body must contains a JSON message like { 'xml' : 'a metadata file'} :param environ: wsgi enviroment :param start_response: wsgi start respons :param qs: Query parameters in a dictionary. :return: wsgi response contaning a JSON response. The JSON message will contain th...
625941c37b180e01f3dc47c4
def get_root(self): <NEW_LINE> <INDENT> ancestors = self.get_ancestors() <NEW_LINE> if ancestors: <NEW_LINE> <INDENT> return ancestors[0] <NEW_LINE> <DEDENT> return self
:returns: the root node for the current node object.
625941c399cbb53fe6792ba9
def __init__(self, model_field_name=None, dump=True, dump_key=None, dump_type=None): <NEW_LINE> <INDENT> self._model_field_name = model_field_name <NEW_LINE> self.dump = dump <NEW_LINE> self._dump_key = dump_key <NEW_LINE> self._dump_type = dump_type
Initialize the field. :param model_field_name: Name of field on the database model. :param dump: Set to false to not dump the field. :param dump_key: The dictionary key to use in dumps. :param dump_type: The data type used to determine how to serialize the model field.
625941c350485f2cf553cd5b
def coerce(cls, value): <NEW_LINE> <INDENT> if cls.check(value): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> if isinstance(value, unicode): <NEW_LINE> <INDENT> value = value.encode() <NEW_LINE> <DEDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return DateTimeFrom(value) <NEW_LINE> <DEDENT> elif isinstanc...
Coerce value to the appropriate data type Will accept: DateTimeType string or Unicode representations (DateTimeFrom) float (DateTimeFromTicks) time.struct_time (mktime)
625941c3d10714528d5ffca4
def calculate_bmi(weight, height, system='metric'): <NEW_LINE> <INDENT> if system == 'metric': <NEW_LINE> <INDENT> bmi = (weight / (height ** 2)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bmi = 703 * (weight / (height ** 2)) <NEW_LINE> <DEDENT> return bmi
Return the Body Mass Idex (BMI) for the given weight, height, and measurment system
625941c355399d3f05588676
def update_model(model_spec, **actions): <NEW_LINE> <INDENT> def todo(model): <NEW_LINE> <INDENT> for k, v in actions.items(): <NEW_LINE> <INDENT> if not hasattr(model, k): <NEW_LINE> <INDENT> raise Exception( "%s has no attribute %s to update." % (model, k)) <NEW_LINE> <DEDENT> setattr(model, k, v) <NEW_LINE> <DEDENT>...
Replace the specified attributes in the specified model.q
625941c3e1aae11d1e749c78
def read_csv(filepath): <NEW_LINE> <INDENT> events = pd.read_csv(filepath + 'events.csv') <NEW_LINE> mortality = pd.read_csv(filepath + 'mortality_events.csv') <NEW_LINE> return events, mortality
TODO : This function needs to be completed. Read the events.csv and mortality_events.csv files. Variables returned from this function are passed as input to the metric functions.
625941c37d847024c06be27c
def _convert_remove_append(options): <NEW_LINE> <INDENT> converted = [] <NEW_LINE> for key in options: <NEW_LINE> <INDENT> v = options[key] <NEW_LINE> if isinstance(v, list): <NEW_LINE> <INDENT> v = ','.join(v) <NEW_LINE> <DEDENT> converted.append(key + "=" + v) <NEW_LINE> <DEDENT> return converted
Convert append and remove dicts read from .yaml file. :param options: {'section.key': 'value1,value2', ...} :type options: dict :return: ['section.key=value1,value2', ...] :rtype: list
625941c33317a56b86939c1f
@app.errorhandler(HTTP_BAD_REQUEST) <NEW_LINE> def invalid_request(error): <NEW_LINE> <INDENT> return make_response(jsonify(INVALID_REQUEST), HTTP_BAD_REQUEST)
Return a 400 with the INVALID_REQUEST message.
625941c37d847024c06be27d
def search(self, nums, target): <NEW_LINE> <INDENT> def BS (nums, first, last): <NEW_LINE> <INDENT> if first ==last: <NEW_LINE> <INDENT> if nums[first] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> if nums[(first+last)/2] < target: <NE...
:type nums: List[int] :type target: int :rtype: int
625941c3a219f33f3462892f
def square(n): <NEW_LINE> <INDENT> return n * n
Returns the square of n, which is n * n.
625941c3d6c5a1020814400c
def change_user_password(user: User, password: str) -> None: <NEW_LINE> <INDENT> user.set_password(password) <NEW_LINE> user.save()
Change password field in user object
625941c38da39b475bd64f34
def _add_hidden_group(self) -> None: <NEW_LINE> <INDENT> self[0] = Group('0', self.url, **self._get("/groups/0"))
Add the hidden "all known lights" Group ID 0 since its not returned. Group #0 contains all known lights to the bridge. It can be pretty helpful to have for making "entire home" changes. I am leaving it here so it is explicitly known to exist.
625941c3236d856c2ad4479b
@pytest.mark.parametrize( "constructor_name, container_type", [ ("list", list), ("tuple", tuple), ("array", np.ndarray), ("sparse", sparse.csr_matrix), ("sparse_csr", sparse.csr_matrix), ("sparse_csc", sparse.csc_matrix), ("dataframe", lambda: pytest.importorskip("pandas").DataFrame), ("series", lambda: pytest.importor...
Check that we convert the container to the right type of array with the right data type.
625941c382261d6c526ab45f
def pretty_print_info(text): <NEW_LINE> <INDENT> pretty_print(text, Fore.CYAN)
Print info
625941c3aad79263cf390a01
def test_get_context_with_invalid_choice(self): <NEW_LINE> <INDENT> class MyOperator1(BaseConditionOperator): <NEW_LINE> <INDENT> operator_id = 'my-op-1' <NEW_LINE> name = 'My Op 1' <NEW_LINE> value_field = ConditionValueIntegerField() <NEW_LINE> <DEDENT> class MyOperator2(BaseConditionOperator): <NEW_LINE> <INDENT> op...
Testing ConditionsWidget.get_context with invalid choice
625941c3ad47b63b2c509f42
def forward(self, kernel): <NEW_LINE> <INDENT> kernel_center = torch.sum(kernel.squeeze() * self.locs) <NEW_LINE> loss = F.mse_loss(kernel_center, self.center) <NEW_LINE> return loss
Calculates the loss for this kernel.
625941c316aa5153ce36243b
def calc_sharpe_ratio(returns, periods=250): <NEW_LINE> <INDENT> return np.sqrt(periods) * (np.mean(returns)) / np.std(returns)
计算夏普比率
625941c3b545ff76a8913dd9
def test_read_selection(): <NEW_LINE> <INDENT> ch_names = ['MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043', 'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031'] <NEW_LINE> sel_names = ['Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal', 'Right-parietal', 'Left-occipital', 'Right-occipital', 'Left-fronta...
Test reading of selections
625941c3498bea3a759b9a73
def get_drive(self, drive_id): <NEW_LINE> <INDENT> return self.client.drives[drive_id].get()
Get metadata for a drive :param drive_id: :return:
625941c3d268445f265b4e31
def str_to_key(value, key_table = wx, accel_format = 'ACCEL_%s', key_format = 'WXK_%s', key_transpositions = {}): <NEW_LINE> <INDENT> logger.debug('Converting "%s" to integers.', value) <NEW_LINE> modifiers = 0 <NEW_LINE> key = 0 <NEW_LINE> split = value.split('+') <NEW_LINE> for v in split: <NEW_LINE> <INDENT> v = v.u...
Turns a string like "CTRL_ALT+K" into (3, 75). To get a global hotkey, try passing: key_table = win32con, accel_format = 'MOD_%s', key_format = 'VK_%s', key_transpositions = {'CTRL': 'CONTROL'}
625941c376d4e153a657eaf3
def testNotOffline(self): <NEW_LINE> <INDENT> def fetcher(title, db='database'): <NEW_LINE> <INDENT> return SeqRecord(None) <NEW_LINE> <DEDENT> featureList = FeatureList('title', 'database', set(), sequenceFetcher=fetcher) <NEW_LINE> self.assertEqual(False, featureList.offline)
If the sequence fetcher does not return C{None} we must be marked as being online.
625941c3f8510a7c17cf96be
def _osx_gpudata(): <NEW_LINE> <INDENT> gpus = [] <NEW_LINE> try: <NEW_LINE> <INDENT> pcictl_out = __salt__['cmd.run']('system_profiler SPDisplaysDataType') <NEW_LINE> for line in pcictl_out.splitlines(): <NEW_LINE> <INDENT> fieldname, _, fieldval = line.partition(': ') <NEW_LINE> if fieldname.strip() == "Chipset Model...
num_gpus: int gpus: - vendor: nvidia|amd|ati|... model: string
625941c3be383301e01b544c
def redo(self) -> None: <NEW_LINE> <INDENT> self.__logger.debug("Redo") <NEW_LINE> if self.canRedo: <NEW_LINE> <INDENT> self._currentStep += 1 <NEW_LINE> self.restore() <NEW_LINE> self.scene.isModified = True
Perform the redo operation
625941c350812a4eaa59c2e6
def unset_session_cookie(self, resp): <NEW_LINE> <INDENT> resp.set_cookie( name=self.session_cookie_name, value='', domain=self.session_cookie_domain, path=self.session_cookie_path, secure=self.session_cookie_secure, http_only=self.session_cookie_http_only, expires=datetime.utcnow() - timedelta(1), max_age=-1 )
Disables session cookies.
625941c3ad47b63b2c509f43
def GetDirectedHausdorffDistance(self): <NEW_LINE> <INDENT> return _itkDirectedHausdorffDistanceImageFilterPython.itkDirectedHausdorffDistanceImageFilterIUC3IUC3_GetDirectedHausdorffDistance(self)
GetDirectedHausdorffDistance(self) -> double
625941c35e10d32532c5eeea
def test_delete_alias_creator(self): <NEW_LINE> <INDENT> self._create_alias(self.test_user) <NEW_LINE> result = self.get_success( self.handler.delete_association( create_requester(self.test_user), self.room_alias ) ) <NEW_LINE> self.assertEqual(self.room_id, result) <NEW_LINE> self.get_failure( self.handler.get_associa...
An alias creator can delete their own alias.
625941c3090684286d50eca7
def render_border(xmin: int = 0, xmax: int = 0, ymin: int = 0, ymax: int = 0): <NEW_LINE> <INDENT> pass
Set the boundaries of the border render and enable border render :param xmin: X Min :type xmin: int :param xmax: X Max :type xmax: int :param ymin: Y Min :type ymin: int :param ymax: Y Max :type ymax: int
625941c38c3a87329515837c
def get_webhook_logs(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_webhook_logs_with_http_info(**kwargs)
List Webhook Log Entries # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_webhook_logs(async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param int page_size: The n...
625941c34e4d5625662d439d
def _get_defined_exports(exports_file): <NEW_LINE> <INDENT> with io.open(exports_file, 'rt') as exports_file: <NEW_LINE> <INDENT> exports = ExportTable.deserialize(exports_file) <NEW_LINE> <DEDENT> return exports
Retrieve all defined exports from the nfs exports config file. :param exports_file: path to nfs exports file :type exports_file: string (unicode) :returns: py:class:`scality_manila_utils.exports.ExportTable` with the exports read from file
625941c38e7ae83300e4af8f
def query(self, query): <NEW_LINE> <INDENT> assert isinstance(query, str) <NEW_LINE> self.query = query
@param query: Set the search query @param type: str
625941c3d164cc6175782d11
def R4g(): <NEW_LINE> <INDENT> A = Ugde(b,t1+t2+t3)*Uedg(b,t1+t2)*Ugde(a,t1) <NEW_LINE> return evaluate_cumulant(A, positive_times=(t1, t2, t3), leading_index=a, arrays=["gg"])
625941c3de87d2750b85fd54
def test_blank_logoUrl(self): <NEW_LINE> <INDENT> super().create_user(admin_user) <NEW_LINE> login = super().login_user(admin_user_login) <NEW_LINE> login_content = json.loads(login.data.decode('utf-8')) <NEW_LINE> token = [d['token'] for d in login_content['data']][0] <NEW_LINE> response = super().create_party(party_b...
Test that endpoint cannot accept a logoUrl
625941c3d58c6744b4257c23
@users_route.route('/api/users/count', methods=['GET']) <NEW_LINE> def getUserCount(): <NEW_LINE> <INDENT> if request.method == 'GET': <NEW_LINE> <INDENT> return UsersHandler().count() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return jsonify(Error="Method not allowed. "), 405
Returns the ammount of users
625941c38e05c05ec3eea336
def run(self): <NEW_LINE> <INDENT> for stream in self.audio_streams: <NEW_LINE> <INDENT> self.channels.set_text( get_value_from_model(audio_channels, stream.get_channels())) <NEW_LINE> self.sample_rate.set_text( get_value_from_model(audio_rates, stream.get_sample_rate())) <NEW_LINE> self.has_audio = True <NEW_LINE> bre...
Set up widgets and run the dialog
625941c3283ffb24f3c558c6
def state(self): <NEW_LINE> <INDENT> if self._tty_fd: <NEW_LINE> <INDENT> fcntl.ioctl(self._tty_fd, KDGETLED, self._buf, True) <NEW_LINE> return ord(self._buf.tolist()[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
returns keyboard LED state
625941c3baa26c4b54cb10e4
def filter(self, pred: ty.Callable[[T], bool]) -> IndexedNullableField: <NEW_LINE> <INDENT> ...
unindex each element for which `pred` is False (in new Series)
625941c338b623060ff0adb1
def get_jobID(cmd_args): <NEW_LINE> <INDENT> if os.path.isfile(cmd_args.psub_cmd_or_PBS_JOBID): <NEW_LINE> <INDENT> m = re.match(r'.*run-p.(\d+).balza.\d+/psub_cmd', cmd_args.psub_cmd_or_PBS_JOBID) <NEW_LINE> if not m: <NEW_LINE> <INDENT> fatal_error("Error with regular expression {}".format(cmd_args.psub_cmd_or_PBS_JO...
Get the job id from the psub_cmd's directory path or PBS_JOBID provided by the user on the command line.
625941c3e1aae11d1e749c79
@task(venv) <NEW_LINE> def unused(c): <NEW_LINE> <INDENT> c.run("venv/bin/vulture --sort-by-size {}".format(META["name"]))
Format the source code of the project.
625941c3cb5e8a47e48b7a70
def estimate_omega(q1, q2): <NEW_LINE> <INDENT> return np.mean(((q1-q2)**2)/(q2*(1-q2)))
:param q1: array of alt allele freq in pop1 :param q2: array of alt allele freq in pop2 :return:
625941c37c178a314d6ef420
def __init__(self, label, ipmi_host, ipmi_user, ipmi_pass): <NEW_LINE> <INDENT> self.label = label <NEW_LINE> self.ipmi_host = ipmi_host <NEW_LINE> self.ipmi_user = ipmi_user <NEW_LINE> self.ipmi_pass = ipmi_pass
Register the given node. ipmi_* must be supplied to allow the HaaS to do things like reboot the node. The node is initially registered with no nics; see the Nic class.
625941c3b830903b967e98d0
def _add_readout_trig(self): <NEW_LINE> <INDENT> trig = np.zeros_like(self.readout_iq) <NEW_LINE> start = (np.abs(self.readout_iq) > 0.0).nonzero()[0][0] <NEW_LINE> end = int( np.min((start + self.readout_trig_duration * self.sample_rate, self.n_pts_readout))) <NEW_LINE> trig[start:end] = self.readout_trig_amplitude <N...
Create waveform for readout trigger.
625941c3f548e778e58cd540