code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def wallsAndGates(self, rooms: List[List[int]]) -> None: <NEW_LINE> <INDENT> q = collections.deque([(i, j, 0) for i, row in enumerate(rooms) for j, col in enumerate(row) if not col]) <NEW_LINE> print(q) <NEW_LINE> visited = set() <NEW_LINE> while q: <NEW_LINE> <INDENT> x,y,val = q.popleft() <NEW_LINE> for i,j in [(x+1,...
Do not return anything, modify rooms in-place instead.
625941f431939e2706e4d483
def findRoot(x,power,epsilon): <NEW_LINE> <INDENT> if(x < 0 and power % 2 == 0): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> low = min(-1,x) <NEW_LINE> high = max(1,x) <NEW_LINE> ans = (low + high)/2 <NEW_LINE> while(abs(ans**power - x)>epsilon): <NEW_LINE> <INDENT> if(ans**power<x): <NEW_LINE> <INDENT> low = a...
Assume x and epsilon int or float, power an int, epsilon > 0, power > 0 Returns float y such that y**power is within epsilon of x. If such a float does not exit, it returns None
625941f4dc8b845886cb5b59
def _set_network_id(self, v, load=False): <NEW_LINE> <INDENT> parent = getattr(self, "_parent", None) <NEW_LINE> if parent is not None and load is False: <NEW_LINE> <INDENT> raise AttributeError("Cannot set keys directly when" + " within an instantiated list") <NEW_LINE> <DEDENT> if hasattr(v, "_utype"): <NEW_LINE> <IN...
Setter method for network_id, mapped from YANG variable /networks/network/network_id (nw:network-id) If this variable is read-only (config: false) in the source YANG file, then _set_network_id is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_network_id(...
625941f4fb3f5b602dac3cbd
def wait_for_execution(self): <NEW_LINE> <INDENT> self.send_message(None,sync=True)
Synchronize with the thread (wait until the current iteration is executed).
625941f47b180e01f3dc4e12
def get_factors(p): <NEW_LINE> <INDENT> num_counts = {} <NEW_LINE> if p % 2 == 0: <NEW_LINE> <INDENT> num_counts[2] = 0 <NEW_LINE> <DEDENT> while p % 2 == 0: <NEW_LINE> <INDENT> num_counts[2] += 1 <NEW_LINE> p = p / 2 <NEW_LINE> <DEDENT> current_quotient = 3 <NEW_LINE> while current_quotient <= p ** 0.5: <NEW_LINE> <I...
input is a number. output is a dict showing the primes and their powers
625941f4377c676e912727c9
@pytest.fixture <NEW_LINE> def new_deque(): <NEW_LINE> <INDENT> return Deque()
Return empty deque.
625941f4c4546d3d9de7305d
def get_queryset(self): <NEW_LINE> <INDENT> return Trip_Commitment.objects.filter().order_by('student_grade','last_name','first_name')
Return the current trip.
625941f48a349b6b435e8795
def getStartOffsetBefore(self, offset): <NEW_LINE> <INDENT> def recurse(node, offset): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> result = None <NEW_LINE> if node.startOffset < offset: <NEW_LINE> <INDENT> result = recurse(node.rightChild, offset) or node <NEW_LINE> <DEDENT>...
Gets the start offset immediately preceding `offset` in this offset-tree. :: >>> score = corpus.parse('bwv66.6') >>> tree = score.asTimespans() >>> tree.getStartOffsetBefore(100) 35.0 :: >>> tree.getStartOffsetBefore(0) is None True Return None if no preceding offset exists.
625941f4851cf427c661ab2c
def findMinArrowShots(self, A): <NEW_LINE> <INDENT> if not A: return 0 <NEW_LINE> A.sort(key=lambda I: I[0]) <NEW_LINE> curr, res = A[0], 1 <NEW_LINE> for I in A[1:]: <NEW_LINE> <INDENT> if curr[0] <= I[0] and I[0] <= curr[1]: <NEW_LINE> <INDENT> curr = [max(curr[0], I[0]), min(curr[1], I[1])] <NEW_LINE> <DEDENT> else:...
:type points: List[List[int]] :rtype: int
625941f4cc40096d61595f70
def post(self, request, format=None): <NEW_LINE> <INDENT> response = self.serializer(request.user, data=request.data) <NEW_LINE> if response.is_valid(): <NEW_LINE> <INDENT> user = response.save() <NEW_LINE> serializer_user = UserHeavySerializer(user) <NEW_LINE> return Response(serializer_user.data, status=status.HTTP_2...
user modifies his current photo
625941f47cff6e4e81117fa8
def check_overwrite_file(file_path, content, log_handler=log.debug): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> log_handler(" *** OVERWRITING file: %s", file_path) <NEW_LINE> persisted = read_file(file_path) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> log_handler(" *** CREATING file: %s", file_path) <NEW_...
Write content to file_path if necessary (that is if there are changes), creating it if does not exist. Log a "diff" to preceding content.
625941f463f4b57ef0001729
def _find_adjacency(self, sampler): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return sampler.adjacency <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._pairs_to_dict(sampler.properties["couplers"]) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_...
Perform a depth-first search for an adjacency attribute.
625941f4656771135c3ebe99
def GenLexerMenu(): <NEW_LINE> <INDENT> lex_menu = wx.Menu() <NEW_LINE> f_types = dict() <NEW_LINE> for key in synglob.LANG_MAP: <NEW_LINE> <INDENT> f_types[key] = synglob.LANG_MAP[key][LANG_ID] <NEW_LINE> <DEDENT> f_order = list(f_types) <NEW_LINE> f_order.sort() <NEW_LINE> for lang in f_order: <NEW_LINE> <INDENT> lex...
Generates a menu of available syntax configurations @return: alphabetically ordered menu of of all lexer settings @rtype: wx.Menu
625941f42c8b7c6e89b35dde
def __init__(self, resource_name): <NEW_LINE> <INDENT> self._resource_name = resource_name <NEW_LINE> self._destination = None
When constructed each backupable item needs to provide name of the resource, which is being backed up. The resource name could be used later for pretty printing the name. :param resource_name: :return:
625941f4d53ae8145f87a885
def _generate_start_command(self) -> str: <NEW_LINE> <INDENT> command = f'bash -c "sleep {Node.SLEEP_BEFORE_LAUNCH}; ' '/usr/local/bin/redbackup-node' <NEW_LINE> for node in self._known_nodes: <NEW_LINE> <INDENT> command += f' -k {node.name}' <NEW_LINE> <DEDENT> command = command + '"' <NEW_LINE> LOG.debug(f...
This method generates the actual CLI-Call. It also adds a short timeout because we would run in network problems otherwise (trying to resolve hosts that are not yet up).
625941f4f548e778e58cdba3
def load_latest_checkpoint_student(self): <NEW_LINE> <INDENT> latest_step = self.get_latest_checkpoint_step() <NEW_LINE> if latest_step is not None: <NEW_LINE> <INDENT> self.load_checkpoint(latest_step)
Load the most recent checkpoint and update the model's current step.
625941f48e7ae83300e4b5f2
def get_patent_details(): <NEW_LINE> <INDENT> with open('links_to_recent_patents.txt', 'r') as infile: <NEW_LINE> <INDENT> links = infile.readlines() <NEW_LINE> <DEDENT> ls = [] <NEW_LINE> for link in links: <NEW_LINE> <INDENT> r = requests.get(link) <NEW_LINE> d = {} <NEW_LINE> patent = PatentAward(link, r.text) <NEW_...
Follow links to URLs and scrape data from detail pages. Creates: ./recent-patents.json
625941f4adb09d7d5db6cdae
def run_as_subprocess_command_return_stdout_stderr_exitstatus(cmd, command_execution_directory=None): <NEW_LINE> <INDENT> exit_status = 0 <NEW_LINE> if command_execution_directory: <NEW_LINE> <INDENT> my_command = "cd {dir}; {command}".format(dir=command_execution_directory, command=cmd) <NEW_LINE> <DEDENT> else: <NEW_...
Runs the command in the string cmd by subprocess. :param cmd: A string containing the command to run :type cmd: string :param command_execution_directory: The directory where the command is executed. :type command_execution_directory: string
625941f4b830903b967e9f27
def _get_jobs(self): <NEW_LINE> <INDENT> for job_path in self.ls_dirs(self.jobs_dir): <NEW_LINE> <INDENT> yield os.path.basename(os.path.dirname(job_path))
Generates all jobs in the bucket.
625941f43539df3088e2e96e
def _fetch_html_url(self, url): <NEW_LINE> <INDENT> LOGGER.info('Fetch from url %s ...', url) <NEW_LINE> try: <NEW_LINE> <INDENT> html = request.urlopen(url).read().decode() <NEW_LINE> return html <NEW_LINE> <DEDENT> except client.BadStatusLine as err: <NEW_LINE> <INDENT> LOGGER.warning('Failed fetching: %s', err) <NEW...
Fetch HTML from live URL. :param url: url to load from :type url: str :return: fetched HTML :rtype: str
625941f44f88993c3716c683
def add_child(self, img: "ImageFSM"): <NEW_LINE> <INDENT> self.children.add(img)
Declare another image as child of the current one
625941f47d847024c06be8e4
def find_radial_separation(self, pos_array): <NEW_LINE> <INDENT> N = int(pos_array.size / 2) <NEW_LINE> x = pos_array[0:N] <NEW_LINE> y = pos_array[N:] <NEW_LINE> r = np.sqrt(x ** 2 + y ** 2) <NEW_LINE> sort_ind = np.argsort(r) <NEW_LINE> r = r[sort_ind] <NEW_LINE> x = x[sort_ind] <NEW_LINE> y = y[sort_ind] <NEW_LINE> ...
When given the position array of a crystal, returns 4 arrays: N radii, N^2 x separations, N^2 y separations, and N^2 radial separations. :param pos_array: position array of a crystal. :return: radius, x separations, y separations, radial separations
625941f4dc8b845886cb5b5a
def readAlignmentParagraph(self, ods_element=None): <NEW_LINE> <INDENT> data = {'name': 'Alignment', 'children': []} <NEW_LINE> text_align = ods_element.getAttribute('textalign') <NEW_LINE> vert_align = ods_element.getAttribute('verticalalign') <NEW_LINE> if text_align == 'start': <NEW_LINE> <INDENT> data['Horizontal']...
Прочитать из ODS файла данные о выравнивании текста. :param ods_element: ODS элемент соответствующий ствойствам параграфа.
625941f499fddb7c1c9de9b0
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(FilterLogMsg, self).__init__(*args, **kwargs) <NEW_LINE> regextag = self.thistag.find('LogMsgRegex') <NEW_LINE> if regextag == None: <NEW_LINE> <INDENT> raise ValueError('Required tag missing: LogMsgRegex') <NEW_LINE> <DEDENT> self.regex = RegexTag(regextag...
Read parameters from filter configuration.
625941f4435de62698dfe270
def test_start(self, stdout, script, manager): <NEW_LINE> <INDENT> script(["start", "profile1", "--", "--syslog"]) <NEW_LINE> manager.start_profile.assert_called_once_with( "profile1", extra_args=["--syslog"] ) <NEW_LINE> assert stdout.getvalue() == "Profile started\n"
A profile can be started.
625941f4be8e80087fb2125a
def _get_module(dotted_path): <NEW_LINE> <INDENT> package, module = dotted_path.rsplit('.', 1) <NEW_LINE> return getattr(import_module(package), module)
Returns the entity that is imported from dotted path.
625941f4236d856c2ad44e07
def test_get_studentview_acknowledged_proctored_exam_with_grace_period(self): <NEW_LINE> <INDENT> due_date = datetime.now(pytz.UTC) - timedelta(days=1) <NEW_LINE> context = { 'is_proctored': True, 'display_name': self.exam_name, 'default_time_limit_mins': 10, 'due_date': due_date, 'grace_period': timedelta(days=0) } <N...
Verify the student view for an acknowledge proctored exam with an active grace period. Given a proctored exam with a past due date and an inactive grace period And a verified user submission exists for that exam When user navigates to the exam Then the wait deadline part is not shown If the attempt is acknowledged to ...
625941f4442bda511e8bea32
def setAutocommit(self): <NEW_LINE> <INDENT> warnings.warn( "setAutocommit was moved from BaseDatabaseCreation to " "BaseDatabaseWrapper.", RemovedInTheory20Warning, stacklevel=2) <NEW_LINE> return self.connection.setAutocommit(True)
Make sure a connection is in autocommit mode. - Deprecated, not used anymore by Theory code. Kept for compatibility with user code that might use it.
625941f426068e7796caf30c
def diabetes(display=False): <NEW_LINE> <INDENT> d = sklearn.datasets.load_diabetes() <NEW_LINE> df = pd.DataFrame(data=d.data, columns=d.feature_names) <NEW_LINE> return df, d.target
Return the diabetes data in a nice package.
625941f49b70327d1c4e13fb
def test_fetch(self): <NEW_LINE> <INDENT> (result, out, err) = self.runsubcmd("gpo", "fetch", self.gpo_guid, "-H", "ldap://%s" % os.environ["SERVER"], "--tmpdir", self.tempdir) <NEW_LINE> self.assertCmdSuccess(result, "Ensuring gpo fetched successfully") <NEW_LINE> shutil.rmtree(os.path.join(self.tempdir, "policy"))
Run against a real GPO, and make sure it passes
625941f4d99f1b3c44c67ba6
def test_graph_add_member_existing(session, graph, users, groups): <NEW_LINE> <INDENT> add_member(groups["team-sre"], users["gary@a.co"], role="owner") <NEW_LINE> add_member(groups["tech-ops"], users["gary@a.co"], role="owner") <NEW_LINE> add_member(groups["team-infra"], users["gary@a.co"], role="owner") <NEW_LINE> add...
Test adding members to an existing relationship.
625941f4eab8aa0e5d26e17d
@user_passes_test(user_permission_test) <NEW_LINE> @app_workspace <NEW_LINE> def get_shp_attributes(request, app_workspace): <NEW_LINE> <INDENT> if request.is_ajax() and request.method == 'POST': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> shapefile = request.FILES.getlist('shapefile') <NEW_LINE> attributes = get_shap...
Ajax controller to get attributes of uploaded aquifer file. Can be shapefile, csv, or geojson.
625941f4f8510a7c17cf9d24
def create_interface(self): <NEW_LINE> <INDENT> required_keys = set(['role', 'home_port']) <NEW_LINE> data_protocols_obj = None <NEW_LINE> if self.parameters.get('subnet_name') is None: <NEW_LINE> <INDENT> required_keys.add('address') <NEW_LINE> required_keys.add('netmask') <NEW_LINE> <DEDENT> data_protocols_obj = self...
calling zapi to create interface
625941f457b8e32f52483ac2
def _add_variable_with_custom_getter( self, name, shape=None, dtype=dtypes.float32, initializer=None, getter=None, **kwargs_for_getter): <NEW_LINE> <INDENT> self._maybe_initialize_checkpointable() <NEW_LINE> if name in self._dependency_names: <NEW_LINE> <INDENT> raise ValueError( ("A variable named '%s' already exists ...
Restore-on-create for a variable be saved with this `Checkpointable`. If the user has requested that this object or another `Checkpointable` which depends on this object be restored from a checkpoint (deferred loading before variable object creation), `initializer` may be ignored and the value from the checkpoint used...
625941f463d6d428bbe44b14
def construct_digraph(gstr=''): <NEW_LINE> <INDENT> regex = re.compile(r'^([A-Z]+)::Requires\s+=\s([A-Z"]+)$') <NEW_LINE> G = nx.DiGraph() <NEW_LINE> root = None <NEW_LINE> for l in gstr.splitlines(): <NEW_LINE> <INDENT> if len(l): <NEW_LINE> <INDENT> target, prereq = regex.match(l).groups() <NEW_LINE> if prereq == '""...
Constructs a networkx tree graph with a single root
625941f4cb5e8a47e48b80c2
def recurse_scale(factor, element): <NEW_LINE> <INDENT> if element.hasAttribute('ulx'): <NEW_LINE> <INDENT> ulx = element.getAttribute('ulx') <NEW_LINE> ulx.setValue(str(int(int(ulx.getValue()) * factor))) <NEW_LINE> <DEDENT> if element.hasAttribute('uly'): <NEW_LINE> <INDENT> uly = element.getAttribute('uly') <NEW_LIN...
Scale down coordinated atts of element and its descendants
625941f4be383301e01b5a9c
def pinorder(me): <NEW_LINE> <INDENT> nodes = [me] <NEW_LINE> while nodes: <NEW_LINE> <INDENT> cur = nodes.pop() <NEW_LINE> if not isinstance(cur, _exup): <NEW_LINE> <INDENT> yield cur; continue <NEW_LINE> <DEDENT> me.pretty_push(cur.rite, cur.op, nodes) <NEW_LINE> nodes.append(cur.op) <NEW_LINE> if cur.op in ('ps','ng...
pretty inorder traversal for print.
625941f4f7d966606f6aa62f
def or_with(self, other: GrammarElement): <NEW_LINE> <INDENT> self.current_production_index += 1 <NEW_LINE> self.productions.append([other]) <NEW_LINE> return self
ORs the last element in the rule with the provided element :param other: Grammar element to OR with :return: Self, ( a context to allow chaining )
625941f4d268445f265b5493
def __init__(self, master, dico): <NEW_LINE> <INDENT> Frame.__init__(self, master) <NEW_LINE> self.word_list_frame = None <NEW_LINE> self.sort_option = None <NEW_LINE> self.create_frame() <NEW_LINE> self.dico = dico <NEW_LINE> self.on_sort_event()
Contructeur de la classe ManageMyDico
625941f4ac7a0e7691ed46e3
def workflows_id_get_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id', 'filter'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not i...
Find a model instance by {{id}} from the data source. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.workflo...
625941f482261d6c526abacc
def save_current_images(self, save_dir=None, **kwargs): <NEW_LINE> <INDENT> if save_dir is None or not os.path.isdir(save_dir): <NEW_LINE> <INDENT> save_dir = self._logdir <NEW_LINE> <DEDENT> utils.write_images(self._curr_images, self._curr_sample_ids, save_dir, **kwargs)
Saves current images to disk
625941f4009cb60464c639d0
def reset(self): <NEW_LINE> <INDENT> self.configurations = {} <NEW_LINE> self.interfaces = {}
Clears all known information about the given device.
625941f46aa9bd52df0373cb
def randomize(self, **args): <NEW_LINE> <INDENT> self.mask = zeros(self.pcontainer.paramdim, dtype=bool) <NEW_LINE> onbits = [] <NEW_LINE> for i in range(self.pcontainer.paramdim): <NEW_LINE> <INDENT> if random() > self.maskOnProbability: <NEW_LINE> <INDENT> self.mask[i] = True <NEW_LINE> onbits.append(i) <NEW_LINE> <D...
an initial, random mask (with random params) with as many parameters enabled as allowed
625941f42ae34c7f2600d753
def delete(self): <NEW_LINE> <INDENT> sql = self._deletestr % self._table_name <NEW_LINE> sql = sql + self._buildConditionString("_where") <NEW_LINE> return MySQLConnect.execute(sql)
execute delete
625941f43539df3088e2e96f
def do_d(self, line): <NEW_LINE> <INDENT> return self.do_dump(line)
d Synonym for delete
625941f4287bf620b61d4083
def create_generatethemailsendrequest(self, body): <NEW_LINE> <INDENT> _url_path = '/mail/send' <NEW_LINE> _query_builder = Configuration.base_uri <NEW_LINE> _query_builder += _url_path <NEW_LINE> _query_url = APIHelper.clean_url(_query_builder) <NEW_LINE> _headers = { 'content-type': 'application/json; charset=utf-8' ...
Does a POST request to /mail/send. The endpoint send is used to generate the request to pepipost server for sending an email to recipients. Args: body (Send): New mail request will be generated Returns: object: Response from the API. API Response Raises: APIException: When an error occurs while fetching...
625941f4187af65679ca5744
def set_level(self, level): <NEW_LINE> <INDENT> self.end_level() <NEW_LINE> self.is_tutorial_enabled = False <NEW_LINE> self.gcomprisBoard.level = level <NEW_LINE> gcompris.bar_set_level(self.gcomprisBoard); <NEW_LINE> if level == 1: <NEW_LINE> <INDENT> self.nuggets_to_collect = 3 <NEW_LINE> self.is_tutorial_startable ...
Initialize new level and start it.
625941f497e22403b379d5bf
def path_list_from_main(node): <NEW_LINE> <INDENT> pathlist = node.get_alfred_path_list() <NEW_LINE> if pathlist and (pathlist[0] == 'Main'): <NEW_LINE> <INDENT> pathlist = pathlist[1:] <NEW_LINE> <DEDENT> return pathlist
Return Ulysses path as list, not including the inetrnally named Main node
625941f43617ad0b5ed6851a
def resolve_references(self, do_not_fill_defaults=False): <NEW_LINE> <INDENT> self.tree = reference.resolve_references(self._tree, self)
Finds all external "JSON References" in the tree, loads the external content, and places it directly in the tree. Saving a ASDF file after this operation means it will have no external references, and will be completely self-contained.
625941f4ad47b63b2c50a5a3
def covariance_matrix(self, data): <NEW_LINE> <INDENT> return np.dot((data-np.mean(data, 0)).T, (data-np.mean(data, 0))) / ((len(data)-1))
Computes the covariance matrix of `data` Parameters: ----------- data: ndarray. shape=(num_samps, num_vars) `data` is NOT centered coming in, you should do that here. Returns: ----------- ndarray. shape=(num_vars, num_vars) The covariance matrix of centered `data` NOTE: You should do this wihout any loops NO...
625941f48a43f66fc4b54681
def visit_Lambda(self, node: ast.Lambda) -> None: <NEW_LINE> <INDENT> self._check_nested_lambdas(node) <NEW_LINE> self.generic_visit(node)
Used to find nested ``lambda`` functions. Raises: NestedFunctionViolation
625941f455399d3f05588cdc
def get_sentence_lists(text): <NEW_LINE> <INDENT> if(text == ""): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> text = text.replace('\n', ' ') <NEW_LINE> text = text.lower() <NEW_LINE> punctuation = [',', '-', '--', ':', ';', "'", '''"'''] <NEW_LINE> for a_punctuation in punctuation: <NEW_LINE> <INDENT> text = text...
Return a list (of sentences) of lists (words in each sentence) for a given string. Makes a few a assumptions about the properties of the text -- most of which can be modified within the function itself. Input Information: 2 input parameters: ( <body of text file> ) <body of text file> -- String, containing the full t...
625941f47d43ff24873a32c9
def __init__(self, class_name_list: Optional[List[str]] = None, predicted_label_column_spec: Optional[ColumnSpec] = None, predicted_label_id_column_spec: Optional[ColumnSpec] = None): <NEW_LINE> <INDENT> self._class_name_list = class_name_list <NEW_LINE> self._predicted_label_column_spec = predicted_label_column_spec <...
Create an adapter. Args: class_name_list: Optional class name list, for classification problems. The order of the items is used as an index here and elsewhere. predicted_label_column_spec: The spec for a column containing labels for classes scored by a model, if model returns them. predicted_label_id_col...
625941f4dd821e528d63b7c7
def get_heartbeat_with_http_info(self, name, **kwargs): <NEW_LINE> <INDENT> all_params = ['name'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals(...
Get Heartbeat # noqa: E501 Returns heartbeat with given name # 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_heartbeat_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool :par...
625941f4097d151d1a22347a
def zero(X): <NEW_LINE> <INDENT> if len(X) == 0: return True <NEW_LINE> else: <NEW_LINE> <INDENT> for bit in X: <NEW_LINE> <INDENT> if bit == 1: return False <NEW_LINE> <DEDENT> <DEDENT> return True
Test if a binary array is 0. Both [] and [0, 0, ..., 0] represent 0. Args: X: (list) binary array Returns: (bool) >>> zero([0]) True >>> zero([0,0,0]) True
625941f471ff763f4b549cbb
def tearDown(self): <NEW_LINE> <INDENT> api_key = models.ApiKey.objects.get( name="TestApiKey0", url="TestApiKeyURL0" ) <NEW_LINE> api_key.delete() <NEW_LINE> api_key = models.ApiKey.objects.get( name="TestApiKey1", url="TestApiKeyURL1" ) <NEW_LINE> api_key.delete() <NEW_LINE> user = models.AlphaUser.objects.get( usern...
Set up all the models needed for this test.
625941f4462c4b4f79d1dcf3
def get_primary_maildomain(self): <NEW_LINE> <INDENT> dom = EmailDomain(self._db) <NEW_LINE> if has_default_domains(): <NEW_LINE> <INDENT> dom.find_by_domain(get_primary_default_email_domain()) <NEW_LINE> <DEDENT> entdom = EntityEmailDomain(self._db) <NEW_LINE> for row in self.get_account_types(): <NEW_LINE> <INDENT> o...
Return correct `domain_id' for account's primary address.
625941f40383005118ecfc04
def create_test_env(env_id, n_envs=1, is_atari=False, stats_path=None, seed=0, log_dir='', should_render=True, hyperparams=None): <NEW_LINE> <INDENT> if log_dir is not None: <NEW_LINE> <INDENT> os.environ["OPENAI_LOG_FORMAT"] = 'csv' <NEW_LINE> os.environ["OPENAI_LOGDIR"] = os.path.abspath(log_dir) <NEW_LINE> os.makedi...
Create environment for testing a trained agent :param env_id: (str) :param n_envs: (int) number of processes :param is_atari: (bool) :param stats_path: (str) path to folder containing saved running averaged :param seed: (int) Seed for random number generator :param log_dir: (str) Where to log rewards :param should_ren...
625941f4fff4ab517eb2fa64
def train(model_fn, datasets, logdir, config): <NEW_LINE> <INDENT> if not config: <NEW_LINE> <INDENT> raise KeyError('You must specify a configuration.') <NEW_LINE> <DEDENT> logdir = logdir and os.path.expanduser(logdir) <NEW_LINE> try: <NEW_LINE> <INDENT> config = load_config(logdir) <NEW_LINE> <DEDENT> except IOError...
Train a model on a datasets. The model function receives the following arguments: data batch, trainer phase, whether it should log, and the config. The configuration object should contain the attributes `batch_shape`, `train_steps`, `test_steps`, `max_steps`, in addition to the attributes expected by the model functio...
625941f476e4537e8c351c9c
def optimal_filt(meta_dict, dt): <NEW_LINE> <INDENT> homedir = os.path.expanduser("~") <NEW_LINE> pow_filt_file = homedir+"/Dropbox/Research/power_spectra/out_ps/" "GX339-4HzCQPO/allps_rb_mod_linetied_sigmatied_normfree.xcm" <NEW_LINE> print("WARNING: Hardwired power spectra filter.") <NEW_LINE> print(pow_fi...
Reads in from a mod .xcm file, for fitting multiple power spectra in XSPEC. Expects powerlaw + lorf + lorf + lorf + lorf + lorf .xcm file name is hardcoded. Saves parameters into a ccf_lc.Filter object and makes filters. :param meta_dict: :param dt: :return:
625941f4d486a94d0b98e76b
def data_synchronize(self, start_date, end_date): <NEW_LINE> <INDENT> new_data_frame = pd.DataFrame() <NEW_LINE> for date in range(start_date, end_date): <NEW_LINE> <INDENT> column = ["DATE", "TIME", "PRESSED CHAR", "PRESSED COUNT", "RELEASED CHAR", "RELEASED COUNT", "MOUSE MOVE COUNT", "MOUSE CLICKED COUNT", "MOUSE SC...
For synchronize the missing data with empty string and sorting it accoridng to index. :rtype: object :param start_date: :param end_date:
625941f45fc7496912cc3fa1
def get_scene_numbering_for_show(tvid, prodid): <NEW_LINE> <INDENT> return _get_numbering_for_show('scene_numbering', tvid, prodid)
Returns a dict of (season, episode) : (scene_season, scene_episode) mappings for an entire show. Both the keys and values of the dict are tuples. Will be empty if no scene numbers are set :param tvid: tvid :type tvid: int :param prodid: prodid :type prodid: ing or long :return: :rtype: Dict
625941f4435de62698dfe271
def demo_piechart(request): <NEW_LINE> <INDENT> xdata = ["Apple", "Apricot", "Avocado", "Banana", "Boysenberries", "Blueberries", "Dates", "Grapefruit", "Kiwi", "Lemon"] <NEW_LINE> ydata = [52, 48, 160, 94, 75, 71, 490, 82, 46, 17] <NEW_LINE> chartdata = {'x': xdata, 'y': ydata} <NEW_LINE> charttype = "pieChart" <NEW_L...
pieChart page
625941f491f36d47f21acb1e
def longestCommonPrefix3(self, strs: List[str]) -> str: <NEW_LINE> <INDENT> if not strs: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> min_len = len(min(strs, key=lambda x: len(x))) <NEW_LINE> low = 1 <NEW_LINE> high = min_len <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = (low + high) // 2 <NEW_LINE> if s...
二分法查找 Time O(S*log(n)) S is the sum of all characters in all strings
625941f423e79379d52eeb7f
def single_pass(data: str) -> int: <NEW_LINE> <INDENT> grid = [list(line) for line in data.splitlines()] <NEW_LINE> row_size = len(grid) <NEW_LINE> col_size = len(grid[0]) <NEW_LINE> for step in range(1, 10000): <NEW_LINE> <INDENT> moved = False <NEW_LINE> new_grid = [list(line) for line in grid] <NEW_LINE> for ri in r...
Start at the bottom and work up to avoid having to do a RIGHT pass then a DOWN pass. We can check the previous square and move it RIGHT if it exists, otherwise check the square above and move it DOWN. This is actually slower (just).. ended up being more complicated than I initially thought it could be.
625941f43d592f4c4ed1d680
def thrift_to_python(tobject): <NEW_LINE> <INDENT> if tobject.type == Type.BOOLEAN: <NEW_LINE> <INDENT> py = struct.unpack_from('>?', tobject.data)[0] <NEW_LINE> <DEDENT> elif tobject.type == Type.INTEGER: <NEW_LINE> <INDENT> py = struct.unpack_from(">i", tobject.data)[0] <NEW_LINE> <DEDENT> elif tobject.type == Type.L...
Convert a TObject to the appropriate python representation :return: the pythonic value
625941f4bf627c535bc137f4
def getLatestBuddyNewsTimestamp(self, country): <NEW_LINE> <INDENT> self.send_getLatestBuddyNewsTimestamp(country) <NEW_LINE> return self.recv_getLatestBuddyNewsTimestamp()
Parameters: - country
625941f47b180e01f3dc4e13
def oper(self, nick, password): <NEW_LINE> <INDENT> self.send_raw(b"OPER " + nick + b" " + password)
Send an OPER command.
625941f4b5575c28eb68e62a
def login(self, login_id, password): <NEW_LINE> <INDENT> params = { 'loginID': login_id, 'password': password, 'userKey': self.user_key, } <NEW_LINE> method = 'accounts.login' <NEW_LINE> response = self._call_gigya(method, params) <NEW_LINE> return response
Login into Gigya with the given credentials
625941f4c4546d3d9de7305e
def t380006_x7(): <NEW_LINE> <INDENT> assert t380006_x0() <NEW_LINE> return 0
State 0,1
625941f43eb6a72ae02ecb13
def invoke(self, frame): <NEW_LINE> <INDENT> inf_input = self.preprocess(frame) <NEW_LINE> pred = self.run_inference(inf_input) <NEW_LINE> return pred
Performs inference on an image. This method will preprocess an image and run inference. The preprocessing and inference methods must be defined by child classes. Args: frame (array[int]): An image from 0-255. Returns: Inference prediction
625941f423849d37ff7b36ae
def test_get_user_transitive_permission(self): <NEW_LINE> <INDENT> pass
Test case for get_user_transitive_permission
625941f492d797404e3047b1
def get_energies(self): <NEW_LINE> <INDENT> energy = self.potential_energies() + self.kinetic_energies() <NEW_LINE> self.energies[0].append(self.time) <NEW_LINE> self.energies[1].append(energy) <NEW_LINE> if self.time == 0: <NEW_LINE> <INDENT> mode = "w" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mode = "a" <NEW_LIN...
Calculate the total energy of the system and add it to a text file named 'energies.txt'.
625941f444b2445a339326b6
def __Runoff_Del_Events__(Q, pos1, pos2, minTime = 2.5, minPeak = None, minConcav = None): <NEW_LINE> <INDENT> if minTime is not None: <NEW_LINE> <INDENT> Td = pos2 - pos1 <NEW_LINE> Td = Td.total_seconds()/(3600*24) <NEW_LINE> Td = Td.values <NEW_LINE> p = np.where(Td<minTime)[0] <NEW_LINE> pos1 = pos1.delete(p) <NEW_...
Eliminates events from the selected initial peaks based on different aspects such as min time of the event, min peak and the concativity. Parameters: - Q: pandas series with the observed streamflow. - pos1: Pandas indexes with the start of the events. - pos2: Pandas indexes with the end of the events. ...
625941f44a966d76dd55163b
def __enter__(self): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> return self
Establish a connection with the Chirp server
625941f40a50d4780f6674bc
def show_formulas_menu(shapes): <NEW_LINE> <INDENT> choose = int(input("Choose what shape formulas would you like to see.\n" "(1) Circle\n" "(2) Triangle\n" "(3) Equilateral triangle\n" "(4) Rectangle\n" "(5) Square\n" "(6) Regular pentagon\n" "(0) Go back to Main Menu.\n")) <NEW_LINE> if choose == 1: <NEW_LINE> <INDEN...
Choose which shape's formulas you want to display
625941f492d797404e3047b2
def reverse(x): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> if x < 0: <NEW_LINE> <INDENT> s = '' <NEW_LINE> l = list(str(x)[1:]) <NEW_LINE> l.reverse() <NEW_LINE> n = int('-'+s.join(l)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s = '' <NEW_LINE> l = list(str(x)) <NEW_LINE> l.reverse() <NEW_LINE> n = int(s.join(l)) <NEW_LI...
:type x: int :rtype: int
625941f45fcc89381b1e1ce9
def Connection(person_1, person_2, person_3=None): <NEW_LINE> <INDENT> return ConnectionT(person_1, person_2, person_3)
Returns a ConnectionT namedtuple, allowing for default arguments
625941f47b25080760e39a79
def data_handler(self, addr, data): <NEW_LINE> <INDENT> if data[0] == self.request_state[0]: <NEW_LINE> <INDENT> turn_ip = self.client_handler.find_procedure(data) <NEW_LINE> if not turn_ip: <NEW_LINE> <INDENT> return self.ctller_handler.upper_layer_turn(data) <NEW_LINE> <DEDENT> return turn_ip <NEW_LINE> <DEDENT> elif...
data handler
625941f4956e5f7376d7148f
def raise_error(error_key, *args, **kwargs): <NEW_LINE> <INDENT> raise MarshValidationError(ERROR_MESSAGES[error_key].format(*args), kwargs.get('fields'))
Raises a Marshmallow validation error Args: error_key (str): The key for accessing the correct error message *args: Arguments taken by the serialization error message **kwargs: fields (list): The fields where the error will appear Raises: ValidationError: Marshmallow validation error
625941f415fb5d323cde113e
def __init__(self, solution_size, population_size, problem_data, ini_sol=False): <NEW_LINE> <INDENT> self.len = population_size <NEW_LINE> self.fmed_library = {} <NEW_LINE> self.best_solution = None <NEW_LINE> self.best_fmed = np.inf <NEW_LINE> self.fmed_sum = 0 <NEW_LINE> self.problem_data = problem_data <NEW_LINE> se...
Utilizo una biblioteca de fmeds para no tener que volver a calcularlos de nuevo (que es de lo más costoso)
625941f421a7993f00bc8321
def get_file(self, path, encoding='UTF-8', encoding_errors='strict'): <NEW_LINE> <INDENT> content = self.get_binary_file(path) <NEW_LINE> return unicode(content, encoding, encoding_errors).replace('\r\n', '\n')
Returns the contents of a specified file. This keyword reads the specified file and returns the contents. Line breaks in content are converted to platform independent form. See also `Get Binary File`. ``encoding`` defines the encoding of the file. The default value is UTF-8, which means that UTF-8 and ASCII-encoded f...
625941f499cbb53fe6793209
def test_global_variable_import(self) -> None: <NEW_LINE> <INDENT> assert call_count == 0 <NEW_LINE> mod1.call_count = 1 <NEW_LINE> assert call_count == 0 <NEW_LINE> assert mod1.call_count == 1 <NEW_LINE> Mod1Calculator().add(2, 2) <NEW_LINE> assert call_count == 0 <NEW_LINE> assert mod1.call_count == 2
Because call_count is imported directly into this module, call_count actually points to a *new* variable in this module's namespace. It is *not* the same as the call_count variable in mod1
625941f4fbf16365ca6f67f6
def addFailure(self, test, err=None, details=None): <NEW_LINE> <INDENT> self._log(logging.ERROR, "FAIL: %s" % (test.id())) <NEW_LINE> self._log_details(logging.ERROR, test) <NEW_LINE> return super().addFailure(test, err, details)
Called for a test which failed an assert.
625941f463f4b57ef000172b
@cli.group() <NEW_LINE> @pass_cli_context <NEW_LINE> def monitor(ctx): <NEW_LINE> <INDENT> pass
Monitoring actions
625941f496565a6dacc8fcee
def add_outputs(self, new_outputs, masks={}): <NEW_LINE> <INDENT> new_outputs = self._to_ordered_dict(new_outputs) <NEW_LINE> for (out_port_name, out_port_type) in new_outputs.iteritems(): <NEW_LINE> <INDENT> self._transition_label_def[out_port_name] = out_port_type <NEW_LINE> self.outputs[out_port_name] = ...
Add new outputs. @param new_outputs: ordered pairs of port_name : port_type @type new_outputs: OrderedDict | list, of:: (port_name, port_type) where: - port_name: str - port_type: Iterable | check class @param masks: custom mask functions, for each sublabel based on its current value ...
625941f4b830903b967e9f28
def create_namespaced_deployment_with_http_info(self, namespace, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['namespace', 'body', 'pretty'] <NEW_LINE> all_params.append('async') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_...
create_namespaced_deployment # noqa: E501 create a Deployment # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_namespaced_deployment_with_http_info(namespace, body, async=True) >>> result = thread.get() :param:...
625941f4a17c0f6771cbe673
def order(self, queryset, is_descending): <NEW_LINE> <INDENT> return (queryset, False)
Returns the queryset of the table. This method can be overridden by :ref:`table.order_FOO` methods on the table or by subclassing `.Column`; but only overrides if second element in return tuple is True. returns: Tuple (queryset, boolean)
625941f4d10714528d600310
def test_stream_with_restricted(self): <NEW_LINE> <INDENT> listen_count = self._listen_count() <NEW_LINE> url = _url('{}?restrict=test_event1,test_event3'.format( const.URL_API_STREAM)) <NEW_LINE> with closing(requests.get(url, stream=True, timeout=3, headers=HA_HEADERS)) as req: <NEW_LINE> <INDENT> stream = req.iter_c...
Test the stream with restrictions.
625941f42c8b7c6e89b35de0
def __init__(self, jsondict=None, strict=True): <NEW_LINE> <INDENT> self.classification = None <NEW_LINE> self.comment = None <NEW_LINE> self.gene = None <NEW_LINE> self.geneElement = None <NEW_LINE> self.target = None <NEW_LINE> super(SubstanceReferenceInformation, self).__init__(jsondict=jsondict, strict=strict)
Initialize all valid properties. :raises: FHIRValidationError on validation errors, unless strict is False :param dict jsondict: A JSON dictionary to use for initialization :param bool strict: If True (the default), invalid variables will raise a TypeError
625941f4cad5886f8bd275fc
def setActivate(self,state): <NEW_LINE> <INDENT> pass
Set the activate state to true(1.0) or false(0.0)
625941f4e1aae11d1e74a2e2
def month_navigation(self, nr_up, year, currentsection, add_home): <NEW_LINE> <INDENT> navs = [] <NEW_LINE> if self.home_link: <NEW_LINE> <INDENT> navs.append((self.home_link, _('Home'), add_home)) <NEW_LINE> <DEDENT> navs.extend((date_displayer.long_months[month], date_displayer.short_months[month], True) for month ...
Will create and display the navigation menu bar of = calendar filename being created nr_up = number of directories up to reach root directory year = year being created currentsection = month name being created for proper CSS styling use_home = if creating a link to home -- a link to root directory of website
625941f4460517430c394798
def existsVM(self, vm): <NEW_LINE> <INDENT> instances = self.connection.get_all_instances() <NEW_LINE> for inst in instances: <NEW_LINE> <INDENT> if inst.instances[0].id is vm.ec2_id: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
existsVM - Checks whether a VM exists in the vmms.
625941f4b7558d58953c552b
def test_add(self): <NEW_LINE> <INDENT> for i in range(1, 200 + 1): <NEW_LINE> <INDENT> for j in range(1, 200 + 1): <NEW_LINE> <INDENT> for k in range(1, 200 + 1): <NEW_LINE> <INDENT> value = i + j + k <NEW_LINE> assert value == add(i, j, k)
" Test function that verifies the add() method.
625941f45510c4643540f9f8
def join(self, base, *parts): <NEW_LINE> <INDENT> res = base <NEW_LINE> for part in parts: <NEW_LINE> <INDENT> res = urllib.parse.urljoin(res, part) <NEW_LINE> <DEDENT> return res
Joins multiple url parts with the base. Note: if any part is an absolute url, it will overwrite the parts from before it.
625941f48e7ae83300e4b5f4
def search_subtree(self, attributes=None): <NEW_LINE> <INDENT> self.clear() <NEW_LINE> self._execute_query(SUBTREE, attributes) <NEW_LINE> return self.entries
Perform the LDAP search operation WHOLE_SUBTREE scope :return: Entries found in search
625941f40c0af96317bb880c
def nontrivial(sender, p_threshold=0.75): <NEW_LINE> <INDENT> num_states, num_s1, num_s2 = sender.shape <NEW_LINE> sender /= sender.sum(axis=2, keepdims=True) <NEW_LINE> choices = sender > p_threshold <NEW_LINE> def conditioned_choice(state_choices): <NEW_LINE> <INDENT> some = np.logical_xor.reduce(state_choices) <NEW_...
Whether one of sender's choices depends on the message it received from a previous sender. Args: sender: nparray of shape [states, send1_msgs, send2_msgs] p_threshold: prob when a sender is considered to make a given choice
625941f4b830903b967e9f29
def get_db(): <NEW_LINE> <INDENT> if not hasattr(g, 'sqlite_db'): <NEW_LINE> <INDENT> g.sqlite_db = connect_db() <NEW_LINE> <DEDENT> g.sqlite_db.execute("PRAGMA foreign_keys = ON") <NEW_LINE> return g.sqlite_db
Opens a new database connection if there is none yet for the current application context.
625941f47d847024c06be8e6
def _phase8_step1(self, obj): <NEW_LINE> <INDENT> if self.dbdriver and isinstance(obj, ast.YASDLField) and obj.realized: <NEW_LINE> <INDENT> typ = obj.get_type() <NEW_LINE> try: <NEW_LINE> <INDENT> typeinfo = self.dbdriver.get_typeinfo(typ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.append_error(obj[...
Database driver specific checks.
625941f4187af65679ca5745
def draw_matches(img1, kp1, img2, kp2, matches, color=None): <NEW_LINE> <INDENT> if len(img1.shape) == 3: <NEW_LINE> <INDENT> new_shape = (max(img1.shape[0], img2.shape[0]), img1.shape[1] + img2.shape[1], img1.shape[2]) <NEW_LINE> <DEDENT> elif len(img1.shape) == 2: <NEW_LINE> <INDENT> new_shape = (max(img1.shape[0], i...
Draws lines between matching keypoints of two images. Keypoints not in a matching pair are not drawn. Places the images side by side in a new image and draws circles around each keypoint, with line segments connecting matching pairs. You can tweak the r, thickness, and figsize values as needed. Args: img1: An openC...
625941f4dc8b845886cb5b5c