code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def camel_to_snake(text: str) -> str: <NEW_LINE> <INDENT> return sub(r'(?<!^)(?=[A-Z])', '_', text).lower()
Turn a camel-case string to a snake-case string. Args: text (str): The string to convert to snake-case. Returns: (str): Returns the string in snake_case.
625941c77b25080760e394b1
def _spiral_roll(arr: np.ndarray, n: int = None): <NEW_LINE> <INDENT> if n is None: <NEW_LINE> <INDENT> n = arr.shape[1] <NEW_LINE> <DEDENT> for i in range(n): <NEW_LINE> <INDENT> arr[i::n, :] = np.roll( arr[i::n, :], i % n, axis=1 ) <NEW_LINE> <DEDENT> return arr
Cyclically shift arr by n
625941c7d164cc6175782da4
def update(self, i): <NEW_LINE> <INDENT> assert self.progress is not None <NEW_LINE> self.progress.update(i)
Updates the progress bar according to the parameter i. :param i: The progress of the process
625941c7e76e3b2f99f3a864
def __init__(self, expected_override_name, report): <NEW_LINE> <INDENT> super(TestHelper, self).__init__() <NEW_LINE> self._expected_override_name = expected_override_name <NEW_LINE> self.report = report <NEW_LINE> self._data_fns = {self.FN_ADD: {}, self.FN_REMOVE: {}, self.FN_VERIFY: {}} <NEW_LINE> self.data_fn_patter...
Initialize the helper class by creating a number of stub functions that each datastore specific class can chose to override. Basically, the functions are of the form: {FN_TYPE}_{DataType.name}_data For example: add_tiny_data add_small_data remove_small_data verify_large_data and so on. Add and rem...
625941c744b2445a339320ee
def test_basics_4(self): <NEW_LINE> <INDENT> self.pkgsend_bulk(self.rurl, (self.foo10, self.foo11, self.bar10)) <NEW_LINE> api_obj = self.image_create(self.rurl) <NEW_LINE> self.pkg("list -a") <NEW_LINE> api_obj.reset() <NEW_LINE> self.__do_install(api_obj, ["bar@1.0"]) <NEW_LINE> self.pkg("list") <NEW_LINE> self.pkg("...
Add bar@1.0, dependent on foo@1.0, install, uninstall.
625941c7ff9c53063f47c24b
def skip_available(easyconfigs, modtool): <NEW_LINE> <INDENT> module_names = [ec['full_mod_name'] for ec in easyconfigs] <NEW_LINE> modules_exist = modtool.exist(module_names, maybe_partial=False) <NEW_LINE> retained_easyconfigs = [] <NEW_LINE> for ec, mod_name, mod_exists in zip(easyconfigs, module_names, modules_exis...
Skip building easyconfigs for existing modules.
625941c7aad79263cf390a97
def start(self): <NEW_LINE> <INDENT> error, output = None, None <NEW_LINE> try: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> output = self.method(*self.args, **self.kwargs) <NEW_LINE> <DEDENT> except Exception as err: <NEW_LINE> <INDENT> logger.debug(str((self.method.__module__, self.method.__name__, err))) <NEW_LINE...
Start the worker process.
625941c807d97122c41788e1
def bind_floating_ip(floating_ip, device): <NEW_LINE> <INDENT> nova.privsep.linux_net.bind_ip(device, floating_ip) <NEW_LINE> if CONF.send_arp_for_ha and CONF.send_arp_for_ha_count > 0: <NEW_LINE> <INDENT> nova.privsep.linux_net.send_arp_for_ip( floating_ip, device, CONF.send_arp_for_ha_count)
Bind IP to public interface.
625941c73c8af77a43ae37f7
def getRecipeByName(search_query): <NEW_LINE> <INDENT> base_url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/search?query=" + search_query <NEW_LINE> response = requests.get( base_url, headers={ "X-Mashape-Key": "PO4pY9yb8wmshcGIX33au66a9Jvdp1FpU0zjsnwB2BMrEKZ902", "X-Mashape-Host": "spoonacula...
fetches recipes using natural language detection. :param search_query: string :return decoded json
625941c82c8b7c6e89b35819
def constraints_pass_duty_cycle(mod_dev, value): <NEW_LINE> <INDENT> errors = [] <NEW_LINE> all_passed = True <NEW_LINE> if 100 < value < 0: <NEW_LINE> <INDENT> all_passed = False <NEW_LINE> errors.append("Must be a positive value") <NEW_LINE> <DEDENT> return all_passed, errors, mod_dev
Check if the user input is acceptable :param mod_dev: SQL object with user-saved Input options :param value: float or int :return: tuple: (bool, list of strings)
625941c8e1aae11d1e749d0e
def save_images(dir='', figs=None, prefix=None): <NEW_LINE> <INDENT> if figs is None: <NEW_LINE> <INDENT> figs = pylabtools.getfigs() <NEW_LINE> <DEDENT> if dir: <NEW_LINE> <INDENT> mkdir_p(dir) <NEW_LINE> <DEDENT> for i, fig in enumerate(figs, 1): <NEW_LINE> <INDENT> label = _get_title(fig) <NEW_LINE> if label == '': ...
Save all open figures to image files. Parameters: ---------- dir : string Directory to place image files into figs : list of Figures will default to open figures prefix : string prefix all image file names
625941c89b70327d1c4e0e2c
def rgb_maximum(colors_tuple): <NEW_LINE> <INDENT> r_sorted_tuple = sorted(colors_tuple, key=lambda x: x[1][0]) <NEW_LINE> g_sorted_tuple = sorted(colors_tuple, key=lambda x: x[1][1]) <NEW_LINE> b_sorted_tuple = sorted(colors_tuple, key=lambda x: x[1][2]) <NEW_LINE> r_min = r_sorted_tuple[0][1][0] <NEW_LINE> g_min = g_...
:type colors_tuple: list[tuple] :rtype: dict
625941c8fbf16365ca6f621a
def check_active(self, request=None): <NEW_LINE> <INDENT> c = self.get("controller") <NEW_LINE> if c: <NEW_LINE> <INDENT> return current.deployment_settings.has_module(c) <NEW_LINE> <DEDENT> if request is None: <NEW_LINE> <INDENT> request = current.request <NEW_LINE> <DEDENT> parent = self.parent <NEW_LINE> if parent i...
Check whether this item belongs to the requested page (request). If this check returns False, then the item will be deactivated entirely, i.e. no further checks will be run and the renderer will never be called. Args: request: the request object (defaults to current.request)
625941c8187af65679ca5176
def save_thumbnail(self, thumbnail): <NEW_LINE> <INDENT> filename = thumbnail.name <NEW_LINE> try: <NEW_LINE> <INDENT> self.thumbnail_storage.delete(filename) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.thumbnail_storage.save(filename, thumbnail) <NEW_LINE> signals.thumbnail_...
Save a thumbnail to the thumbnail_storage. Also triggers the ``thumbnail_created`` signal and caches the thumbnail values for future lookups.
625941c83346ee7daa2b2dc2
def buildFooter(self): <NEW_LINE> <INDENT> pm.button(l='Choose', c=Callback(self.captureIcon))
Override to build custom footer content for capturing icons
625941c88a43f66fc4b540be
def trait_correlations(feature1, feature2, mapping, tree): <NEW_LINE> <INDENT> f1_contrasts = contrasts(tree, feature1, mapping) <NEW_LINE> f2_contrasts = contrasts(tree, feature2, mapping) <NEW_LINE> slope, intercept, r_value, p_value, std_err = stats.linregress(f1_contrasts, f2_contrasts) <NEW_LINE> return r_value, p...
simple linear regression for correlation testing between two features
625941c8d8ef3951e3243595
def set_membership(self, model, membership_list): <NEW_LINE> <INDENT> if model is Group: <NEW_LINE> <INDENT> m2mfield = self.groups <NEW_LINE> <DEDENT> elif model is Skill: <NEW_LINE> <INDENT> m2mfield = self.skills <NEW_LINE> <DEDENT> m2mfield.remove(*[g for g in m2mfield.all() if g.name not in membership_list and not...
Alters membership to Groups and Skillz
625941c84e696a04525c94a3
def GetEpisodes(self): <NEW_LINE> <INDENT> return(self.data["EpisodesType"],self.data["EpisodesInitTime"],self.data["EpisodesDuration"],self.data["EpisodesVisible"])
Gets all the information of the episodes for time plotting
625941c85f7d997b87174aee
def add_quote(request): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> response = Quotes.objects.add_quote(request.POST, request.session['id']) <NEW_LINE> if len(response) != 0: <NEW_LINE> <INDENT> for message in response: <NEW_LINE> <INDENT> warning(request, message) <NEW_LINE> <DEDENT> <DEDENT> ...
Route for processing a quote to be added to the database
625941c84a966d76dd551066
def set_Format(self, value): <NEW_LINE> <INDENT> super(TextInputSet, self)._set_input('Format', value)
Set the value of the Format input for this Choreo. ((optional, boolean) Specify the retrieved results format. Enter, html, plan, or raw. Default is set to: raw)
625941c8a219f33f346289c3
def exec_sub_rot_arg(self): <NEW_LINE> <INDENT> if self.current_token.matches(DelimiterToken.AT): <NEW_LINE> <INDENT> return ExecuteSubRotSelectorArg(self.selector()) <NEW_LINE> <DEDENT> elif is_coord_token(self.current_token): <NEW_LINE> <INDENT> return ExecuteSubRotVec2Arg(self.vec2()) <NEW_LINE> <DEDENT> self.error(...
exec_sub_rot_arg ::= [selector, vec2] Returns: ExecuteSubRotSelectorArg ExecuteSubRotVec2Arg
625941c83317a56b86939cb2
def peek(target, tokens): <NEW_LINE> <INDENT> return accept(target, tokens, pop=False)
Look at the top of the token stream. Return True if the top token matches {target}. Do not remove the top token from the list.
625941c8ff9c53063f47c24c
def get_random_split_file_list(root, index, Fold = 10): <NEW_LINE> <INDENT> random.seed(0) <NEW_LINE> file_list = os.listdir(root) <NEW_LINE> random.shuffle(file_list) <NEW_LINE> length = len(file_list) <NEW_LINE> length_fold = int(length/Fold) + 1 <NEW_LINE> st = index * length_fold <NEW_LINE> end = min(length, st + l...
random.seed(index) file_list = sorted(os.listdir(root)) train_list = sorted(random.sample(file_list, int(len(file_list) * 0.92))) val_list = sorted(list(set(file_list) - set(train_list))) return train_list, val_list
625941c8d6c5a102081440a2
def read_mobility(self, eh, itemp, component, spin): <NEW_LINE> <INDENT> i,j = abu.s2itup(component) <NEW_LINE> wvals = self.read_variable("vvdos_mesh") <NEW_LINE> mobility = self.read_variable("mobility")[eh,itemp,i,j,spin,:] <NEW_LINE> return wvals, mobility
Read mobility from the TRANSPORT.nc file The mobility is computed separately for electrons and holes.
625941c8956e5f7376d70ec6
def _implement_in_serial(self, project: amicus.Project, **kwargs) -> amicus.Project: <NEW_LINE> <INDENT> for node in self.paths[0]: <NEW_LINE> <INDENT> project = node.execute(project = project, **kwargs) <NEW_LINE> <DEDENT> return project
Applies stored nodes to 'project' in order. Args: project (Project): amicus project to apply changes to and/or gather needed data from. Returns: Project: with possible alterations made.
625941c88e05c05ec3eea3cc
def supports_datasets(self): <NEW_LINE> <INDENT> return False
Whether this preprocessor supports dataset.
625941c823849d37ff7b30e8
def __init__(self): <NEW_LINE> <INDENT> self.connected = 'NULL' <NEW_LINE> self.rh = 'NULL' <NEW_LINE> try: <NEW_LINE> <INDENT> self.rh = redis.Redis(rddbhost) <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> except Exception as err_var: <NEW_LINE> <INDENT> print(err_var) <NEW_LINE> self.connected = False
Constructor
625941c832920d7e50b28227
def follow(self, to_user): <NEW_LINE> <INDENT> if self != to_user: <NEW_LINE> <INDENT> self.following_set.create(to_user=to_user)
self가 to_user를 팔로우 하게 한다
625941c896565a6dacc8f723
def create_anilist_file(output=ANILIST_FILE, directory='data'): <NEW_LINE> <INDENT> data = get_list_data(status="COMPLETED") <NEW_LINE> data["data"]["date"] = time.strftime("%Y-%m-%d") <NEW_LINE> with open(os.path.join(directory, output), 'w') as f: <NEW_LINE> <INDENT> json.dump(data, f) <NEW_LINE> <DEDENT> print("Crea...
Store the users anime list in a JSON file
625941c8377c676e91272201
def build_shift_dict(self, shift): <NEW_LINE> <INDENT> self.translation = {} <NEW_LINE> self.shift = shift <NEW_LINE> self.alphabet = string.ascii_lowercase <NEW_LINE> for letter in self.alphabet: <NEW_LINE> <INDENT> position = self.alphabet.index( letter ) <NEW_LINE> new_position = (position + self.shift) % len( self....
Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amo...
625941c8498bea3a759b9b07
def move(self, x, y): <NEW_LINE> <INDENT> self.x1 += x <NEW_LINE> self.y1 += y <NEW_LINE> self.x2 += x <NEW_LINE> self.y2 += y
Смещение координат :param x: координата х :param y: координата y
625941c81f5feb6acb0c4baa
def my_yield(): <NEW_LINE> <INDENT> print('11') <NEW_LINE> yield 4 <NEW_LINE> yield 5
生成器,本质就是迭代器,区别在于,生成器是自己用python代码构建的数据结构,迭代器是python提供的,或者转化得来的 获取生成器的方法:生成器函数;生成器表达式;python内部提供的 return 函数只存在一个return 结束函数,并且给函数的执行者返回值 yield 只要函数中有yield那么他就是生成器函数,不会返回值,不是函数了,生成器函数中可以存在多个yield,yield不会结束生成器函数,一个yield对应一个next 生成器相当于自己构建的一个数据集 :return:
625941c8eab8aa0e5d26dbb0
def test_LinkReestablishedNotify(self): <NEW_LINE> <INDENT> a,b,c,d,e = self.initComponents(5) <NEW_LINE> L1 = a.link( (a,"outbox"), (b,"outbox"), passthrough=2 ) <NEW_LINE> L2 = b.link( (b,"outbox"), (c,"outbox"), passthrough=2 ) <NEW_LINE> L3 = c.link( (c,"outbox"), (d,"inbox"), ) <NEW_LINE> L4 = d.lin...
If the linkage chain breaks and is then re-established before a message is collected, the owners of outboxes that are no longer in the chain are not notified, but ones that are will be.
625941c8bd1bec0571d90687
def update(self, name, params): <NEW_LINE> <INDENT> if ((self._activation_info['hostname'] != '') and (params['hostname'] != self._activation_info['hostname'])): <NEW_LINE> <INDENT> cmd = ['/opt/ibm/seprovider/bin/unsubscribe', '-h', self._activation_info['hostname']] <NEW_LINE> output, error, rc = run_command(cmd) <NE...
Update/add a subscription machine at IBM SEP tool.
625941c81b99ca400220ab09
@task(pre=[clean], post=[codestats]) <NEW_LINE> def test(ctx): <NEW_LINE> <INDENT> run("nosetests --rednose test/tests.py")
Run Unit tests
625941c891f36d47f21ac549
def spawnSearch(queryevent, **kwargs): <NEW_LINE> <INDENT> if queryevent.dispatched: <NEW_LINE> <INDENT> warnings.warn('QueryEvent {0} has already been dispatched.' .format(queryevent)) <NEW_LINE> return queryevent <NEW_LINE> <DEDENT> logger.debug('QueryEvent {0}, using Engine {1}' .format(queryevent, queryevent.engine...
Executes a series of searches based on the parameters of a :class:`.QueryEvent` and updates it accordingly. Parameters ---------- queryevent : :class:`.QueryEvent` Returns ------- result.id : str UUID for the Celery search task group.
625941c83317a56b86939cb3
def _gp_int(tok): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(tok) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return str(tok)
Gets a int from a token, if it fails, returns the string.
625941c8de87d2750b85fdea
def Decrypt(self, Ciphertext : str): <NEW_LINE> <INDENT> cipher = AES.new(self.Key, AES.MODE_CBC, iv = self.IV) <NEW_LINE> padded_plain_bytes = cipher.decrypt(bytes.fromhex(Ciphertext)) <NEW_LINE> plain_bytes_length = int.from_bytes(padded_plain_bytes[0:4], 'little') <NEW_LINE> plain_bytes = padded_plain_bytes[4:4 + pl...
Decrypt ciphertext and return corresponding plaintext. Args: Ciphertext: A hex string that will be decrypted. Returns: Plaintext string.
625941c8f9cc0f698b140654
def __init__(self, entidade, *, tempos_de_enchimento, tempos_de_despejo, verboso=True): <NEW_LINE> <INDENT> super().__init__(entidade, Estados, verboso) <NEW_LINE> self.tempos_de_enchimento, self.tempos_de_despejo = tempos_de_enchimento, tempos_de_despejo <NEW_LINE> self.vazio, self.cheio = self.ambiente.event().succee...
:param entidade: simulacao.Processo :param tempos_de_enchimento: float :param verboso: bool
625941c829b78933be1e5705
def update_gtfs(self): <NEW_LINE> <INDENT> with(cd(self.ontransit_server_folder)): <NEW_LINE> <INDENT> run('npm run load-gtfs')
Instructs OnTransit server to immediately reload the transit data.
625941c830c21e258bdfa4f4
def login(request): <NEW_LINE> <INDENT> user = None <NEW_LINE> try: <NEW_LINE> <INDENT> username = request.POST['username'] <NEW_LINE> password = request.POST['password'] <NEW_LINE> user = authenticate(request, username=username,password=password) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print("No POST...
Login view authenticate and login user.
625941c8796e427e537b061d
def _get_gisbase(self) -> pathlib.Path: <NEW_LINE> <INDENT> p = delegator.run(f"{self.executable} --config path") <NEW_LINE> return pathlib.Path(p.out.strip()).resolve()
Return the path to the GRASS installation directory.
625941c8cdde0d52a9e5308a
def test_cvox(): <NEW_LINE> <INDENT> P, q, G, h, A, b = load_qp() <NEW_LINE> x = cvxopt_solve_qp(P, q, G, h, A, b) <NEW_LINE> x_expected = np.array([ -1.10833837, 2.71244381, 1.57379586, 1.34409748, -0.98735542, -1.9763331, -0.32983447, -0.11374623, 0.89995774, -2.38376993]) <NEW_LINE> assert_allclose(x, x_expected) <N...
The idea is to setup a QP that we can test in the C++ implementation side. The numbers here come from cvxopt itself, and have been hard-coded in the C++ implementation test suit.
625941c821bff66bcd6849ac
def ConvertTo(self,*__args): <NEW_LINE> <INDENT> pass
ConvertTo(self: ImageKeyConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object Converts the given object to the specified type. context: An System.ComponentModel.ITypeDescriptorContext that provides a format context,which can be used to extract addition...
625941c830c21e258bdfa4f5
def test_document_document_field_categories_id_delete(self): <NEW_LINE> <INDENT> pass
Test case for document_document_field_categories_id_delete
625941c86aa9bd52df036dfc
def get_pad_sen(self, sen): <NEW_LINE> <INDENT> if len(sen) < self.max_len + 2 * self.pad: <NEW_LINE> <INDENT> sen += [self.word2id['BLANK']] * (self.max_len +2 * self.pad - len(sen)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sen = sen[: self.max_len + 2 * self.pad] <NEW_LINE> <DEDENT> return sen
padding the sentences
625941c8283ffb24f3c5595a
def make_history_table(df): <NEW_LINE> <INDENT> cols = ['Rank', 'Team', 'Abbrev', 'Owner', 'REC', 'WPCT', 'AWP', 'PF', 'PA', 'PF/G', 'PA/G', 'DIFF', 'year'] <NEW_LINE> df = df.sort_values(['year', 'rankCalculatedFinal']).reset_index(drop=True) <NEW_LINE> df['Rank'] = df.apply(lambda x: x.get('rankCalculatedFinal'), axi...
Create html table for each year in league history :param df: data frame with scores from every year
625941c8a934411ee37516ec
def update_utilizator(self, ID, nume_nou): <NEW_LINE> <INDENT> for i,utilizator in enumerate(self.lista_utilizatori): <NEW_LINE> <INDENT> if ID == int(utilizator.ID): <NEW_LINE> <INDENT> utilizator.nume = nume_nou <NEW_LINE> return 1 <NEW_LINE> <DEDENT> <DEDENT> return 0
Actualizeaza numele utilizatorului dupa ce il cauta in functie de nume si prenume.
625941c8f7d966606f6aa05b
def get_start_pages(query, num_start_pages=10): <NEW_LINE> <INDENT> res = requests.get('https://www.google.com/search', params={'q': query}) <NEW_LINE> soup = BeautifulSoup(res.content, 'lxml') <NEW_LINE> links = soup.find_all('a') <NEW_LINE> initial_links = [] <NEW_LINE> count = 0 <NEW_LINE> for link in links: <NEW_LI...
get start pages by performing a Google search
625941c891af0d3eaac9ba70
def _load(self, filename=None): <NEW_LINE> <INDENT> if not filename: <NEW_LINE> <INDENT> filename = self.aatsr_path <NEW_LINE> <DEDENT> wb_ = open_workbook(filename) <NEW_LINE> for sheet in wb_.sheets(): <NEW_LINE> <INDENT> ch_name = sheet.name.strip() <NEW_LINE> if ch_name == 'aatsr_' + self.bandname: <NEW_LINE> <INDE...
Read the AATSR rsr data
625941c857b8e32f524834f2
def polygonize(self, lines): <NEW_LINE> <INDENT> source = getattr(lines, "geoms", None) or lines <NEW_LINE> try: <NEW_LINE> <INDENT> source = iter(source) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> source = [source] <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> obs = [self.shapeup(line) for line in so...
Creates polygons from a source of lines The source may be a MultiLineString, a sequence of LineString objects, or a sequence of objects than can be adapted to LineStrings.
625941c8ec188e330fd5a7f9
def is_highpass(self): <NEW_LINE> <INDENT> return self.__is_highpass
Returns if the filter is a highpass filter. :returns: True, if the filter is a highpass filter, False otherwise
625941c8a05bb46b383ec87a
def set_default_binding_overrides(self, default_binding_overrides): <NEW_LINE> <INDENT> self.__default_binding_overrides = default_binding_overrides
Provides a means for setting the default_binding_overrides attribute. This is intentionally not an assignment because it is not intended to be called, but is here in case it is not possible to use the "main()" method.
625941c8e76e3b2f99f3a865
def zip_album_handler(self): <NEW_LINE> <INDENT> for info in self.zip_file.infolist(): <NEW_LINE> <INDENT> track_file = self.zip_file.open(info.filename) <NEW_LINE> track_data = self._get_track_info(info.filename) <NEW_LINE> if track_data.track: <NEW_LINE> <INDENT> self._add_track(track_file, track_data) <NEW_LINE> <DE...
Handler to get Albums and Tracks from zip archive. Track files in root directory have empty album field. Track files in album_folder have album corresponding to album_folder. Files and folders must have following format: 'author - title' or 'title'
625941c8a8ecb033257d3126
def interface_hundredgigabitethernet_vrrp_advertisement_interval(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NEW_LINE> <INDENT> delete_...
Auto Generated Code
625941c8fb3f5b602dac36ea
def delete(self, timestamp=None): <NEW_LINE> <INDENT> query = self.query_filter(models.GraphSnapshot) <NEW_LINE> query = query.filter(models.GraphSnapshot.last_event_timestamp <= timestamp) <NEW_LINE> query.delete()
Delete all graph snapshots taken until timestamp.
625941c8f9cc0f698b140655
def dup(self, g=None, no_mangle=False): <NEW_LINE> <INDENT> set_io = g is None <NEW_LINE> if not g: <NEW_LINE> <INDENT> g = IRGraph(self.parent, self.tag, self.gen) <NEW_LINE> <DEDENT> mapping = {} <NEW_LINE> for node in self.inputs + tuple(self.iternodes()): <NEW_LINE> <INDENT> if no_mangle: <NEW_LINE> <INDENT> mappin...
Duplicate this graph, optionally setting g as the parent of every node in the graph. Return the new graph (or g), a list of inputs, and the output node.
625941c85510c4643540f43f
def list( self, resource_group_name, network_watcher_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2019...
Lists all connection monitors for the specified Network Watcher. :param resource_group_name: The name of the resource group containing Network Watcher. :type resource_group_name: str :param network_watcher_name: The name of the Network Watcher resource. :type network_watcher_name: str :keyword callable cls: A custom t...
625941c8009cb60464c6340b
def wrapper_func(request,*args,**kwargs): <NEW_LINE> <INDENT> if request.user.is_authenticated: <NEW_LINE> <INDENT> return redirect("index") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return view_func(request,*args,**kwargs)
Implementing what has been explained
625941c88e7ae83300e4b025
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> if args and type(args[0]) is dict: <NEW_LINE> <INDENT> BaseModel.__init__(self, args[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> BaseModel.__init__(self)
initializes parent class
625941c8d99f1b3c44c675e8
@nt.raises(ConfigError) <NEW_LINE> def test_get_config_exception(): <NEW_LINE> <INDENT> get_config(__file__, {})
current python file isn't a yaml file
625941c8f7d966606f6aa05c
def show_matrix(validations, predictions, labels): <NEW_LINE> <INDENT> matrix = metrics.confusion_matrix(validations, predictions) <NEW_LINE> plt.figure(figsize=(6, 4)) <NEW_LINE> sns.heatmap(matrix, cmap='coolwarm', linecolor='white', linewidths=1, xticklabels=labels, yticklabels=labels, annot=True, fmt='d') <NEW_LINE...
La matrice di mostra a video la differenza tra predizione e effettiva classificazione dell'immagine. :param validations: validazione (ground) :param predictions: predizioni effettuate :param labels: corrispondenze intero :return:
625941c80c0af96317bb8240
@ app.errorhandler(404) <NEW_LINE> def display_404(error): <NEW_LINE> <INDENT> return render_template('errors/error404.html'), 404
Displays a custom error page when returning a 404 error
625941c81d351010ab855b74
@pytest.fixture <NEW_LINE> def app(): <NEW_LINE> <INDENT> app = create_app(pytest=True) <NEW_LINE> return app
Prepare a app for each testing, using testing db pytest.
625941c84d74a7450ccd421c
@bot.message_handler(func=lambda item: item.text == config.back_button, content_types=['text']) <NEW_LINE> def back(message): <NEW_LINE> <INDENT> print('Пользователь', message.from_user.id, 'вернулся в основное меню') <NEW_LINE> bot.send_message(message.chat.id, config.main_menu, reply_markup=main_menu_keyboard)
Возврат в меню (кнопка "Назад") :param message: Сообщение о нажатой кнопке
625941c8236d856c2ad44832
def ebs_create_snapshot(self, volume_id): <NEW_LINE> <INDENT> name = "MongoBackups-{0}-{1}".format( self.mongo_name, self.instance_id ) <NEW_LINE> description = name <NEW_LINE> self.stats['date_finished'] = dt.now().isoformat() <NEW_LINE> self.snapshot_tags = [ {'Key': 'InstanceId', 'Value': self.instance_id}, {'Key': ...
Perform an EBS snapshot on volume_id.
625941c8e5267d203edcdcf7
def get_unique_local_img_name(image_src_url): <NEW_LINE> <INDENT> source_image_url_parts = urlparse(image_src_url) <NEW_LINE> source_image_basename = os.path.basename(unquote(source_image_url_parts.path)) <NEW_LINE> return '{0}-{1}'.format(hashlib.md5(image_src_url.encode('utf-8')).hexdigest(), source_image_basename)
Uses the 'filename' from the URL + an MD5 hash of the entire URL to create a unique local name to use for the image file. :param image_src_url: :return: str "{MD5 hash of src URL}-{file name of segemnt of src URL}"
625941c80c0af96317bb8241
def Key(name): <NEW_LINE> <INDENT> return type(name, (BaseKey,), {})
Create a new type key. >>> Age = Key('Age') >>> def configure(binder): ... binder.bind(Age, to=90) >>> Injector(configure).get(Age) 90
625941c87c178a314d6ef4b7
def test_invalid_chars_in_name(self): <NEW_LINE> <INDENT> p = self.make_name_packet(dns.DNS_OPCODE_QUERY) <NEW_LINE> questions = [] <NEW_LINE> name = "\x10\x11\x05\xa8.%s" % self.get_dns_domain() <NEW_LINE> q = self.make_name_question(name, dns.DNS_QTYPE_A, dns.DNS_QCLASS_IN) <NEW_LINE> print("asking for %s" % (q.name)...
Check the server refuses invalid characters in the query name
625941c860cbc95b062c659c
def Class(self): <NEW_LINE> <INDENT> return "%s(%r)" % (self.__class__, self.__dict__)
self.Class() -> Class of node. @return: Class of node.
625941c8a4f1c619b28b0094
def _connect_to_project(self, project): <NEW_LINE> <INDENT> project.connect("asset-added", self._asset_added_cb) <NEW_LINE> project.connect("asset-loading-progress", self._asset_loading_progress_cb) <NEW_LINE> project.connect("asset-removed", self._asset_removed_cb) <NEW_LINE> project.connect("error-loading-asset", sel...
Connects signal handlers to the specified project.
625941c8a79ad161976cc19e
def test_csrf_token_in_header(self): <NEW_LINE> <INDENT> req = self._get_POST_csrf_cookie_request(meta_token=self._csrf_id_token) <NEW_LINE> mw = CsrfViewMiddleware(post_form_view) <NEW_LINE> mw.process_request(req) <NEW_LINE> resp = mw.process_view(req, post_form_view, (), {}) <NEW_LINE> self.assertIsNone(resp)
The token may be passed in a header instead of in the form.
625941c8097d151d1a222eb3
def _remove_multiple_choice(self): <NEW_LINE> <INDENT> if _MULTIPLE_FIELD_VALUES == self.itemText(0): <NEW_LINE> <INDENT> self.removeItem(0)
Removes the 'multiple values' choice from the list
625941c8287bf620b61d3abd
def get_tenant_custom_attr(self): <NEW_LINE> <INDENT> url = self._gen_request_url('/open-apis/contact/v2/tenant/custom_attr/get') <NEW_LINE> res = self._get(url, with_tenant_token=True) <NEW_LINE> data = res['data'] <NEW_LINE> is_open = data.get('is_open', False) <NEW_LINE> attrs = [make_datatype(DepartmentUserCustomAt...
获取企业自定义属性信息 :type self: OpenLark :return: is_open, attrs :rtype: (bool, list[DepartmentUserCustomAttr]) https://open.feishu.cn/document/ukTMukTMukTM/ucTN3QjL3UzN04yN1cDN https://bytedance.feishu.cn/docs/doccnOcR1fnxBACchoY9tlg7Amg#
625941c84e696a04525c94a4
def update_action_value(self, state, decided_action, reward, next_state): <NEW_LINE> <INDENT> next_action_values = self.network.forward(next_state, should_save_output=False) <NEW_LINE> next_max_action_value = max(next_action_values) <NEW_LINE> target = list(self.network.output['y_output']) <NEW_LINE> target[decided_act...
Q-Learningアルゴリズムでネットワークを更新する 元のQ-Learningの更新式は Q(St, At) ← (1 - η)Q(St, At) + η(Rt+1 + γ * max_a{Q(St+1, At+1))} または式変形して Q(St, At) ← η( Rt+1 + γ * max_a{Q(St+1, At+1)} - Q(St, At) ) この Rt+1 + γ * max_a{Q(St+1, At+1)} が教師信号targetとなる
625941c89f2886367277a8e7
@main.route('/login', methods=['POST']) <NEW_LINE> def login(): <NEW_LINE> <INDENT> form = request.form <NEW_LINE> u = User.new(form) <NEW_LINE> u = u.validateLogin_user() <NEW_LINE> if u is not None: <NEW_LINE> <INDENT> session['user_id'] = u.id <NEW_LINE> session.permanent = True <NEW_LINE> resp = redirect(url_for('h...
登录页面的路由函数
625941c8e64d504609d74898
def blocks(self): <NEW_LINE> <INDENT> while self.index < len(self.data): <NEW_LINE> <INDENT> yield self.parse_block() <NEW_LINE> self.block_count += 1
yields blocks one at a time
625941c85166f23b2e1a51b2
def support_setdefault(device, key, value, reason=None): <NEW_LINE> <INDENT> supported, unsupported = support_dicts(device) <NEW_LINE> if value is not False and key not in unsupported: <NEW_LINE> <INDENT> supported.setdefault(key, value) <NEW_LINE> <DEDENT> if value is False: <NEW_LINE> <INDENT> if reason is None: <NEW...
Set value only if no other value is set
625941c823e79379d52ee5be
def read_ini(self): <NEW_LINE> <INDENT> self.read_ini_filename(self._fn)
read ini file using default file name :return:
625941c84f88993c3716c0c1
def total_weight(self): <NEW_LINE> <INDENT> return sum(self.weights.values())/2
Return total weight represented by all edges @attention: only 100% correct when no arrows are present @rtype: number @return: Total weight
625941c84527f215b584c4b1
def yaml_file_save(ft_object, filename): <NEW_LINE> <INDENT> lg.debug("saving to %s", filename) <NEW_LINE> with open(filename, 'w') as F: <NEW_LINE> <INDENT> d = yaml.dump(dict(ft_object), encoding=('ascii'), default_flow_style=False) <NEW_LINE> F.write(d.decode('ascii'))
Save a file to yaml
625941c8d486a94d0b98e19e
def new_node(self, lat, lon): <NEW_LINE> <INDENT> self.elements[self.new_node_counter] = Node.Node.create_new_node(self.new_node_counter, lat, lon) <NEW_LINE> self.new_node_counter -= 1
Add new node to the elements list. Args: lat (float): latitude of the new node lon (float): longitude of the new node
625941c8b7558d58953c4f6f
def freeze_base_model(self): <NEW_LINE> <INDENT> for param in self.sew.parameters(): <NEW_LINE> <INDENT> param.requires_grad = False
Calling this function will disable the gradient computation for the base model so that its parameters will not be updated during training. Only the classification head will be updated.
625941c867a9b606de4a7f13
def wavenumber(sigma, h): <NEW_LINE> <INDENT> g = 9.81 <NEW_LINE> a0 = (sigma ** 2 * h) / g <NEW_LINE> b1 = 1.0 / np.tanh(a0 ** (3.0 / 4)) <NEW_LINE> a1 = a0 * (b1 ** (2.0 / 3)) <NEW_LINE> da1 = 1000.0 <NEW_LINE> d1 = np.ones(np.shape(h)) <NEW_LINE> while np.max(d1) == 1: <NEW_LINE> <INDENT> d1 = abs(da1 / a1) > 0.0000...
Compute wavenumber from sigma and h k = wavenumber(sigma, h) k is the matrix of same size as sigma and h containing the calculated wave numbers sigma is the wave frequencies in rad/s h is the water depth sigma and h must be scalars,vectors or matricies of the same dimensions modified from R.Dalrymple's java code D....
625941c8e64d504609d74899
def parse_headers(f): <NEW_LINE> <INDENT> d = {} <NEW_LINE> while 1: <NEW_LINE> <INDENT> line = f.readline() <NEW_LINE> if not line: <NEW_LINE> <INDENT> raise dpkt.NeedData('premature end of headers') <NEW_LINE> <DEDENT> line = line.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> l = line....
Return dict of HTTP headers parsed from a file object.
625941c83cc13d1c6d3c73d3
def create_flagmappings(package_name, options, verbose=0): <NEW_LINE> <INDENT> with open(package_name + '.flagmappings', 'w') as f: <NEW_LINE> <INDENT> for opt in options.get_option_names(): <NEW_LINE> <INDENT> f.write(opt + ' Unknown\n')
Create a flagmappings file. Create a flagmappings file. This will create a new file called $package_name.flagmappings with all the categories set to Unknown.
625941c87047854f462a1464
def getconffiles(user=False): <NEW_LINE> <INDENT> if _testprefix: <NEW_LINE> <INDENT> prefix = _testprefix <NEW_LINE> <DEDENT> elif user: <NEW_LINE> <INDENT> prefix = os.path.expanduser('~/.config') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = '/etc' <NEW_LINE> <DEDENT> files = map(os.path.expanduser, [ prefi...
Return a list of config file names Only those which actualy exist
625941c899cbb53fe6792c3f
def __init__(self): <NEW_LINE> <INDENT> self._descriptions = {} <NEW_LINE> self._active_matchers = []
Constructor
625941c8656771135c3eb8c6
def _make_resub_sh_and_cl(self): <NEW_LINE> <INDENT> self.log.debug('Setting up for calculation resubmission') <NEW_LINE> arg_d = dict(pe=f'omp {self.n_slots}', M='theavey@bu.edu', m='eas', l=f'h_rt={self.h_rt}', N=self._base_name, j='y', o=self.stdout_file, notify='', hold_jid=self.job_id) <NEW_LINE> resub_dir_path = ...
Make command line for a calculation for resuming in another job Requires SGE_STDOUT_PATH and JOB_ID for running `qstat` :return: None
625941c8ec188e330fd5a7fa
def yaml_load(source, loader=None): <NEW_LINE> <INDENT> Loader = loader or get_yaml_loader() <NEW_LINE> result = yaml.load(source, Loader=Loader) <NEW_LINE> if result is not None and 'INHERIT' in result: <NEW_LINE> <INDENT> relpath = result.pop('INHERIT') <NEW_LINE> abspath = os.path.normpath(os.path.join(os.path.dirna...
Return dict of source YAML file using loader, recursively deep merging inherited parent.
625941c87cff6e4e811179df
def add(isamAppliance, label, address, prefixLength, vlanId=None, allowManagement=False, enabled=True, check_mode=False, force=False): <NEW_LINE> <INDENT> add_needed = True <NEW_LINE> ret_obj = {} <NEW_LINE> warnings = [] <NEW_LINE> if force is False: <NEW_LINE> <INDENT> ret_obj, warnings = ibmsecurity.isam.base.networ...
Adding an IPv6 address to an interface
625941c8ab23a570cc2501db
def ftp_profile(publish_settings): <NEW_LINE> <INDENT> soup = BeautifulSoup(publish_settings, 'html.parser') <NEW_LINE> profiles = soup.find_all('publishprofile') <NEW_LINE> ftp_profile = [profile for profile in profiles if profile['publishmethod'] == 'FTP'][0] <NEW_LINE> matches = re.search('ftp://(.+)/site/wwwroot', ...
Takes PublishSettings, extracts ftp user, password, and host
625941c80383005118ecf63c
def propbundle_Confidence(uco_object, value=Missing(), **kwargs): <NEW_LINE> <INDENT> assert not isinstance(value, Missing), "[propbundle_Confidence] value is required." <NEW_LINE> if not isinstance(value, Missing): <NEW_LINE> <INDENT> assert (isinstance(value, case.CoreObject) and (value.type=='ControlledVocabulary...
:param Value: Exactly one occurrence of type ControlledVocabulary. :return: A PropertyBundle object.
625941c8462c4b4f79d1d72a
def copy_folder(self, folder, target_folder): <NEW_LINE> <INDENT> new_folder_name = self.get_unique_folder_name(target_folder, folder.name) <NEW_LINE> new_folder = target_folder.create_folder(new_folder_name) <NEW_LINE> for item_revision in folder.contained_item_revisions: <NEW_LINE> <INDENT> new_folder.add_item_revisi...
Copies a source folder to the target browser item containing a folder. folder -- A acesframework.lws.folder.Folder instance target_folder -- A acesframework.lws.folder.Folder instance
625941c85fc7496912cc39d7
def fire(*contexts, **arguments): <NEW_LINE> <INDENT> pass
Call all handlers associated with this hook. Each positional argument must be a dictionary; each keyword argument is added to any dictionaries to form the event passed into the handlers.
625941c87b180e01f3dc4858
def run_example() -> None: <NEW_LINE> <INDENT> print(markdownify('<a href="http://www.treyhunner.com">Trey</a> has a blog'))
Run an example!
625941c86fece00bbac2d796
def move(self, direction='up'): <NEW_LINE> <INDENT> dx, dy = self._can_move(direction) <NEW_LINE> if None in (dx, dy): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._position = (self._position[0] + dx, self._position[1] + dy) <NEW_LINE> return True
Makes `Walter` move one step towars given `direction`. :return: `True` if `Walter` could move. `False` otherwise. :parameters: direction : str Determines the direction where to move. Posible values are: - ``'up'`` - ``'left'`` - ``'down'`` - ``'right'``
625941c8377c676e91272202
def get_digits_coordinates(despl, text): <NEW_LINE> <INDENT> left = float(text[4 + despl]) <NEW_LINE> top = float(text[5 + despl]) <NEW_LINE> right = float(text[6 + despl]) <NEW_LINE> bottom = float(text[7 + despl]) <NEW_LINE> return bottom, left, right, top
Obtención de las coordenadas de las detecciones en digits :param despl: desplazamiento para la lectura de las etiquetas :param text: archivo a leer :return:
625941c8d164cc6175782da6
def latex(self): <NEW_LINE> <INDENT> gtx = self.gtx <NEW_LINE> db = gtx["beamplan"] <NEW_LINE> grouped = group(db, "beamtime") <NEW_LINE> for bt, plans in grouped.items(): <NEW_LINE> <INDENT> info = self._gather_info(bt, plans) <NEW_LINE> self.render("beamplan.tex", "{}.tex".format(bt), **info) <NEW_LINE> self.render("...
Render latex template.
625941c83cc13d1c6d3c73d4
def get_closest(point, clusters): <NEW_LINE> <INDENT> min_dist = sys.maxsize <NEW_LINE> min_idx = -1 <NEW_LINE> for i, cluster in enumerate(clusters): <NEW_LINE> <INDENT> dist = np.linalg.norm(point - cluster.center) <NEW_LINE> if dist < min_dist: <NEW_LINE> <INDENT> min_idx = i <NEW_LINE> min_dist = dist <NEW_LINE> <D...
Sub function of K-means algorithm: get closest cluster to a point :param point: np array of point coordinates :param clusters: list of all cluster instances :return: index of closest cluster to the point
625941c8aad79263cf390a99