code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def generate_timeline_from(profile: List[dict], output: str, title: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(output, "w") as visualization: <NEW_LINE> <INDENT> visualization.write(TIMELINE.format(title=title, dataset=profile)) <NEW_LINE> <DEDENT> <DEDENT> except RuntimeError as exc: <NEW_LINE> <INDE...
Generate a visjs timeline from the ninja build profile. :param profile: Ninja build information. :param output: File to output the visualization. :param title: Title of the visualization. :return:
625941e538b623060ff0b218
def train(train_dir, model_save_path=None, n_neighbors=None): <NEW_LINE> <INDENT> X = [] <NEW_LINE> y = [] <NEW_LINE> for class_dir in os.listdir(train_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join(train_dir, class_dir)): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for img_path in image_files_in_fold...
Trains a k-nearest neighbors classifier for face recognition. :param train_dir: directory that contains a sub-directory for each known person, with its name. (View in source code to see train_dir example tree structure) Structure: <train_dir>/ ├── <person1>/ │ ├── <somename1>.jpeg │ ├── <somename2...
625941e54e4d5625662d47fd
def get_dict(self, a_list): <NEW_LINE> <INDENT> d = {} <NEW_LINE> for k in a_list: <NEW_LINE> <INDENT> if (isinstance(k, list)): <NEW_LINE> <INDENT> if isinstance(k[1], list) and k[0]: <NEW_LINE> <INDENT> d.update({k[0]: self.get_dict(k[1])}) <NEW_LINE> <DEDENT> elif k[0]: <NEW_LINE> <INDENT> d.update({k[0]: k[1]}) <NE...
A function that return a dictionary from a list of lists, with any depth
625941e566673b3332b924bc
def on_attribute_context_input_accepted(self, node_name, attribute_name): <NEW_LINE> <INDENT> self.graph.attribute_context.close() <NEW_LINE> self.graph.signal_about_attribute_create.emit(node_name, attribute_name)
should be called when the attribute field widgets input_accepted signal was emitted Will close the attribute field widget and emit a different signal that sends the node and chosen attribute name Args: node_name: name of the node attribute_name: name of the node that is selected in the widget Returns:
625941e556ac1b37e62645f2
def print_test_report_summary(name, report): <NEW_LINE> <INDENT> passed = report.get('PASSED', False) <NEW_LINE> if passed: <NEW_LINE> <INDENT> resstr = '\033[42mPASSED\033[0m' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resstr = '\033[41mFAILED\033[0m' <NEW_LINE> <DEDENT> print('%6s %-50s: %s' % (resstr, name, repo...
Print summary for a test run.
625941e58e7ae83300e4b3f9
def set(self, l): <NEW_LINE> <INDENT> self._db.update(l) <NEW_LINE> CMOSRatesNamespace.update_trigger() <NEW_LINE> ChannelRatesNamespace.update_trigger() <NEW_LINE> CMOSRatesTestNamespace.update_trigger() <NEW_LINE> ScreamersNamespace.update_trigger()
Store a list of key/value/timestamp dicts
625941e55166f23b2e1a5584
def desc(self, qrn=None, type_=None): <NEW_LINE> <INDENT> def get_fqrn(key): <NEW_LINE> <INDENT> return ".".join([f'"{elt}"' for elt in key[1:]]) <NEW_LINE> <DEDENT> if not qrn: <NEW_LINE> <INDENT> ret_val = [] <NEW_LINE> entry = self.__metadata[self.__dbname]['byname'] <NEW_LINE> for key in entry: <NEW_LINE> <INDENT> ...
Returns the list of the relations of the model. Each line contains: - the relation type: 'r' relation, 'v' view, 'm' materialized view, - the quoted FQRN (Fully qualified relation name) "<schema name>"."<relation name>" - the list of the FQRN of the inherited relations. If a qualified relation name (<schema name>.<ta...
625941e5796e427e537b09f4
def capacity(self): <NEW_LINE> <INDENT> return _math.FloatVector_capacity(self)
capacity(self) -> std::vector< float >::size_type
625941e5004d5f362079a75b
def textile(text, html_type='xhtml', encoding=None, output=None): <NEW_LINE> <INDENT> return Textile(html_type=html_type).parse(text)
Apply Textile to a block of text. This function takes the following additional parameters: html_type - 'xhtml' or 'html5' style tags (default: 'xhtml')
625941e5a79ad161976cc570
def send_version(self): <NEW_LINE> <INDENT> msg = MsgVersion() <NEW_LINE> try: <NEW_LINE> <INDENT> payload = self.msgfactory.serialize(msg, self.id, self.factory.port) <NEW_LINE> self._send(payload) <NEW_LINE> <DEDENT> except SerializationError as e: <NEW_LINE> <INDENT> logger.error("[ERROR] {}".format(e))
Send a version message
625941e5287bf620b61d3e8c
def validate(client): <NEW_LINE> <INDENT> name = client.recv(buffersize).decode() <NEW_LINE> if name in users: <NEW_LINE> <INDENT> client.send(b'Username already exists!') <NEW_LINE> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> users.append(name) <NEW_LINE> client.send(b'Welcome!') <NEW_LINE> return True
检验用户名 validate username
625941e5a79ad161976cc571
def ch2_writing_IV_A(show=True, *arguments, **keywords): <NEW_LINE> <INDENT> pass
p. 17 Rebeam each of the vocal lines to reflect the meter and beat unit instead.
625941e5be8e80087fb21068
def __init__(self): <NEW_LINE> <INDENT> this = _algorithms.new_SegmentData() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this
__init__(self) -> SegmentData
625941e5b5575c28eb68e42f
def regex_match(necessity, string_to_match): <NEW_LINE> <INDENT> expressions = {'patient image':re.compile(r'^PC-[0-9]{10}.*?.nii$|^aa[a,b]0*[0-9]{2}.*?.nii$|^01\.00[0-9]{2}$'), 'patient directory': re.compile(r'^PC-[0-9]{10}$|^01.[0-9]{4}$|^aa[a,b]0*[0-9]{2}$'), 'axial T2':re.compile(r'(ax.*?t2|t2.*?ax)(?!.*pelvis.*$)...
"Gathering all regex matches used throughout the code to make it applicable to other datasets by modifying. Therefore, if we have to train on a new dataset where sequence description is in a new format, only this function has to be editted and all regex matches used to make the dataset mapping will be up to date. Gener...
625941e563f4b57ef0001538
def makeBuildScript(path): <NEW_LINE> <INDENT> pass
Make a simple python build script in this folder using the build() function.
625941e5a8370b7717052cc8
def editcomponent(self, data): <NEW_LINE> <INDENT> data = data.copy() <NEW_LINE> self._component_data_convert(data, update=True) <NEW_LINE> log.debug("Calling Component.update with: %s", data) <NEW_LINE> return self._proxy.Component.update(data)
A method to edit a component in Bugzilla. Takes a dict, with mandatory elements of product. component, and initialowner. All other elements are optional and use the same names as the addcomponent() method.
625941e55fc7496912cc3da9
def register_models(engine): <NEW_LINE> <INDENT> models = (Image, ImageProperty, ImageMember) <NEW_LINE> for model in models: <NEW_LINE> <INDENT> model.metadata.create_all(engine)
Create database tables for all models with the given engine.
625941e530bbd722463cc1f3
def Build(self, source_helper): <NEW_LINE> <INDENT> source_filename = source_helper.Download() <NEW_LINE> if not source_filename: <NEW_LINE> <INDENT> logging.info(u'Download of: {0:s} failed'.format( source_helper.project_name)) <NEW_LINE> return False <NEW_LINE> <DEDENT> logging.info(u'Building rpm of: {0:s}'.format(s...
Builds the rpms. Args: source_helper: the source helper (instance of SourceHelper). Returns: True if the build was successful, False otherwise.
625941e57c178a314d6ef891
def chainsToBeds(chains): <NEW_LINE> <INDENT> dbBeds = {} <NEW_LINE> for db, chains in chains.iteritems(): <NEW_LINE> <INDENT> logging.debug("Converting %d chains on db %s to bedx" % (len(chains), db)) <NEW_LINE> dbPsls = [] <NEW_LINE> bedxList = [] <NEW_LINE> for pslList in chains: <NEW_LINE> <INDENT> bedx = pslListTo...
convert psl chains to lists of bed features Return None if too many features on any db Return dict db -> tuple (list of chain-beds, list of all psls for beds) otherwise
625941e5236d856c2ad44c0b
def add(self, x): <NEW_LINE> <INDENT> if x in self.vertices: <NEW_LINE> <INDENT> raise ValueError("Already a vertex") <NEW_LINE> <DEDENT> self._vertices = self._vertices.union([x])
Add vertex *x*. Args: x(hashable): new vertex to add. Raises: ValueError: if *x* is already a vertex.
625941e5a4f1c619b28b045b
def incoming_call(self, nickname: str, ip: str) -> bool: <NEW_LINE> <INDENT> accept = self.gui.yesNoBox("Incoming call", f"The user {nickname} is calling from {ip}. Do you want to accept the call?") <NEW_LINE> return accept
This function will be called when there's an incoming call :param nickname: nickname of the user :param ip: the actual IP address of the user :return: true if the call is accepted and false otherwise
625941e5460517430c3945a6
def configure(self): <NEW_LINE> <INDENT> self.linux_dir = os.path.join(self.work_dir, 'linux-%s' % self.version) <NEW_LINE> build.make(self.linux_dir, extra_args='mrproper') <NEW_LINE> dotconfig = os.path.join(self.linux_dir, '.config') <NEW_LINE> shutil.copy(self.config_path, dotconfig)
Configure/prepare kernel source to build.
625941e5baa26c4b54cb1547
def _latex_generic_point(self, v=None): <NEW_LINE> <INDENT> if v is None: <NEW_LINE> <INDENT> v = self.gens() <NEW_LINE> <DEDENT> return '\\left(%s\\right)'%(" : ".join([str(latex(f)) for f in v]))
Return a LaTeX representation of the generic point corresponding to the list of polys on this projective space. If polys is None, the representation of the generic point of the projective space is returned. EXAMPLES:: sage: P.<x, y, z> = ProjectiveSpace(2, ZZ) sage: P._latex_generic_point([z*y-x^2]) '\le...
625941e5c4546d3d9de72e63
def WAYP(self): <NEW_LINE> <INDENT> if hasattr(self.obj, "__mro__"): <NEW_LINE> <INDENT> return inspect.getmro(self.obj)[1:] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "Object without object resolution order"
Who are your parents
625941e53c8af77a43ae3bd0
def _findSwiplLin(): <NEW_LINE> <INDENT> (path, swiHome) = _findSwiplFromExec() <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> return (path, swiHome) <NEW_LINE> <DEDENT> path = _findSwiplPathFromFindLib() <NEW_LINE> if path is not None: <NEW_LINE> <INDENT> return (path, swiHome) <NEW_LINE> <DEDENT> paths = ['/lib'...
This function uses several heuristics to guess where SWI-Prolog is installed in Linuxes. :returns: A tuple of (path to the swipl so, path to the resource file) :returns type: ({str, None}, {str, None})
625941e5d8ef3951e3243969
def __init__(self, *args): <NEW_LINE> <INDENT> _kinova_raw.IntVector_swiginit(self, _kinova_raw.new_IntVector(*args))
__init__(IntVector self) -> IntVector __init__(IntVector self, IntVector other) -> IntVector __init__(IntVector self, std::vector< int >::size_type size) -> IntVector __init__(IntVector self, std::vector< int >::size_type size, std::vector< int >::value_type const & value) -> IntVector
625941e526238365f5f0f2a0
def get_dt(input_file): <NEW_LINE> <INDENT> val1 = None <NEW_LINE> val2 = None <NEW_LINE> file_dt = None <NEW_LINE> ifile = open(input_file) <NEW_LINE> for line in ifile: <NEW_LINE> <INDENT> if line.startswith("#") or line.startswith("%"): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> pieces = line.split() <NEW_LINE...
Read RWG file and return DT
625941e59f2886367277acb5
def oversample(self): <NEW_LINE> <INDENT> print('Current outcome sampling {}'.format(Counter(self.y))) <NEW_LINE> ros = SMOTE() <NEW_LINE> self.X, self.y = ros.fit_sample(self.X, self.y) <NEW_LINE> self.Xview = self.X.view()[:, :self.n_features] <NEW_LINE> print('Resampled dataset shape {}'.format(Counter(self.y)))
Balance class data based on outcome
625941e5d7e4931a7ee9e34a
def func1(): <NEW_LINE> <INDENT> import time <NEW_LINE> from functools import wraps <NEW_LINE> def time_this(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> result = func(*args, **kwargs) <NEW_LINE> end = time.time() <NEW_LINE> print(fu...
给函数添加一个包装 -> 装饰器 装饰器就是一个函数,它可以接受一个函数作为输入并返回一个新的函数作为输出 装饰器内部的代码一般会涉及创建一个新的函数,利用*args和**kwargs来接受任意的参数。在这个函数内部,我们需要调用原来的输入函数(即被包装的那个函数)并返回它的结果。也可以添加任何想要添加的额外代码。这个新创建的函数会作为装饰器的返回,取代了原来的函数 需要重点注意的是,通常情况下,装饰器不会修改调用签名,也不会修改被包装函数返回的结果
625941e5de87d2750b8601c2
def clearDictNone(d): <NEW_LINE> <INDENT> for k, v in list(d.items()): <NEW_LINE> <INDENT> if not v: <NEW_LINE> <INDENT> del d[k] <NEW_LINE> <DEDENT> <DEDENT> return d
in-place
625941e524f1403a92600f8e
def reverse_alternate(self): <NEW_LINE> <INDENT> current = self.head <NEW_LINE> after = self.head.next <NEW_LINE> while after: <NEW_LINE> <INDENT> current.next = after.next <NEW_LINE> after.next = self.head <NEW_LINE> self.head = after <NEW_LINE> after = current.next
Additive reverse. Each node becomes the head, briefly, before following node becomes the head, and so on.
625941e5c432627299f05075
@application.route('/about') <NEW_LINE> def about(): <NEW_LINE> <INDENT> return render_template('about.html')
static page including contact and app information
625941e592d797404e3045b7
def lex(src): <NEW_LINE> <INDENT> return parser.lex(src)
Takes a string containing source code, returns list of token tuples
625941e5d164cc617578317b
def toggleRequestList(self): <NEW_LINE> <INDENT> if self.showRequestList: <NEW_LINE> <INDENT> self.requestList.size_hint_y = None <NEW_LINE> self.requestList.height = '0dp' <NEW_LINE> self.disableRequestListItemButtons() <NEW_LINE> self.showRequestList = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> listItemNumbe...
called by 'History' toggle button to toggle the display of the history request list.
625941e591af0d3eaac9be48
def config(request): <NEW_LINE> <INDENT> context_extras = {'DOJANGO': {}} <NEW_LINE> config = Config() <NEW_LINE> context_extras['DOJANGO'] = config.get_context_dict() <NEW_LINE> return context_extras
Make several dojango constants available in the template, like: {{ DOJANGO.DOJO_BASE_URL }}, {{ DOJANGO.DOJO_URL }}, ... You can also use the templatetag 'set_dojango_context' in your templates. Just set the following at the top of your template to set these context contants: If you want to use the default DOJ...
625941e56fb2d068a760f4cf
def checkedItems(self): <NEW_LINE> <INDENT> return [i for i in self.listItems() if i.checkState()==Qt.Checked]
Returns list of seleected fields names (as strings)
625941e538b623060ff0b219
def __calibrationWaveSolution(self): <NEW_LINE> <INDENT> my_name = '__calibrationWaveSolution' <NEW_LINE> if not (hasattr(self, "_Spectrum__calibration_peaks_x") and hasattr(self, "_Spectrum__calibration_peaks_y") and hasattr(self, "_Spectrum__calibration_peaks_wl")): <NEW_LINE> <INDENT> plt.close() <NEW_LINE> raise Sp...
Compute the wavelength solution METHOD: Spectrum.__calibrationCalPeak TYPE: Private PURPOSE: Add or remove a peak to the be used in the calibration. The peak to be set is stored in the transient member __calibration_peaks, which should be present. ARGUMENTS: NONE RETURNS: NONE RAISES: * SpectrumNameError when one ...
625941e57c178a314d6ef892
def _async_manifest_fetchlist( portdb, repo_config, cp, cpv_list=None, max_jobs=None, max_load=None, loop=None ): <NEW_LINE> <INDENT> loop = asyncio._wrap_loop(loop) <NEW_LINE> result = loop.create_future() <NEW_LINE> cpv_list = ( portdb.cp_list(cp, mytree=repo_config.location) if cpv_list is None else cpv_list ) <NEW_...
Asynchronous form of FetchlistDict, with max_jobs and max_load parameters in order to control async_aux_get concurrency. @param portdb: portdbapi instance @type portdb: portdbapi @param repo_config: repository configuration for a Manifest @type repo_config: RepoConfig @param cp: cp for a Manifest @type cp: str @param ...
625941e52ae34c7f2600d55c
def get_arg_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description='Iorio DB CLI') <NEW_LINE> parser.add_argument('--verbose', '-v', action='count') <NEW_LINE> parser.add_argument('-u', '--username', default='admin', help='username used for authentication') <NEW_LINE> parser.add_argument('-p', '--pa...
build the cli arg parser
625941e54f88993c3716c48f
def create(self): <NEW_LINE> <INDENT> subset = values = None <NEW_LINE> viewconf = self.GetViewConf() <NEW_LINE> title = "" <NEW_LINE> if viewconf and viewconf.get("settings"): <NEW_LINE> <INDENT> subset = viewconf.settings.get("form") <NEW_LINE> title = viewconf.settings.get("title") <NEW_LINE> values = viewconf.setti...
Renders and executes a web form based on the items configuration values. Form form setup requires the `subset` or list of fields to be used. If nothing is given it defaults to `create`. `subset` is the form identifier used in the items configuration as `form`. **Settings** - *form*: (dict) form definition inlcuding f...
625941e59f2886367277acb6
def replacer(tmp): <NEW_LINE> <INDENT> for i in "~.-!$&'()*+,;=/?#@": <NEW_LINE> <INDENT> x = "\\" + i <NEW_LINE> tmp = tmp.replace(i, x) <NEW_LINE> <DEDENT> tmp = tmp.replace("%", "__") <NEW_LINE> tmp = tmp.replace("’", "\_") <NEW_LINE> tmp = tmp.replace("{", "\(") <NEW_LINE> tmp = tmp.replace("}", "\)") <NEW_LINE> t...
This function adds \ to all the signs, which are not accepted by Turtle
625941e530dc7b7665901d8e
def get_area_by_name(self, name): <NEW_LINE> <INDENT> for area in self.areas: <NEW_LINE> <INDENT> if area.name == name: <NEW_LINE> <INDENT> return area <NEW_LINE> <DEDENT> <DEDENT> raise AreaError('Area not found.')
Get an area by name.
625941e571ff763f4b549abe
def apply_shift(self, shift): <NEW_LINE> <INDENT> text = "" <NEW_LINE> for e in self.get_message_text(): <NEW_LINE> <INDENT> if e in self.build_shift_dict(shift): <NEW_LINE> <INDENT> e = self.dict[e] <NEW_LINE> <DEDENT> text += e <NEW_LINE> <DEDENT> return text
Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in w...
625941e5cb5e8a47e48b7ed0
def get_creator_cat(self): <NEW_LINE> <INDENT> mapping = self.glam_info.mappings.get('people') <NEW_LINE> cats = [] <NEW_LINE> for person in self.creator: <NEW_LINE> <INDENT> name = person.get('name') <NEW_LINE> mapped_info = self.glam_info.mapped_and_wikidata(name, mapping) <NEW_LINE> if mapped_info.get('commonscat'):...
Return the commonscat(s) for the creator(s).
625941e5cc40096d61595d7b
def cross_reference(self, model): <NEW_LINE> <INDENT> msg = ', which is required by %s eid=%s' % (self. type, self.eid) <NEW_LINE> self.nodes_ref = model.EmptyNodes(self.nodes, msg=msg) <NEW_LINE> self.pid_ref = model.Property(self.pid, msg=msg)
Cross links the card so referenced cards can be extracted directly Parameters ---------- model : BDF() the BDF object
625941e5bd1bec0571d90a5b
@app.route('/show-song') <NEW_LINE> def show_song(): <NEW_LINE> <INDENT> logging.debug(f"Entering show-song") <NEW_LINE> return render_template('show-songs.html', songs=Song.query.all())
This function displays the show-song template to the screen :param none: :returns: show-song HTML Template to display the songs :raises none
625941e5b545ff76a8914241
def absolute_path(path): <NEW_LINE> <INDENT> return os.path.abspath(os.path.normpath(path))
Returns the absolute path for the given path and normalizes the path. :param path: Path for which the absolute normalized path will be found. :returns: Absolute normalized path.
625941e5d486a94d0b98e573
def findBezoutCoef(a, b): <NEW_LINE> <INDENT> s = 0; <NEW_LINE> old_s = 1 <NEW_LINE> t = 1; <NEW_LINE> old_t = 0 <NEW_LINE> r = b; <NEW_LINE> old_r = a <NEW_LINE> while r != 0: <NEW_LINE> <INDENT> quotient = old_r / r <NEW_LINE> old_r, r = r, old_r - quotient * r <NEW_LINE> old_s, s = s, old_s - quotient * s <NEW_LINE>...
Returns a list `result` of size 3 where: Referring to the equation ax + by = gcd(a, b) result[0] is gcd(a, b) result[1] is x result[2] is y
625941e5d4950a0f3b08c775
def apply_op(op, larg, rarg): <NEW_LINE> <INDENT> if op == PLUS: <NEW_LINE> <INDENT> return larg + rarg <NEW_LINE> <DEDENT> if op == TIMES: <NEW_LINE> <INDENT> return larg * rarg <NEW_LINE> <DEDENT> raise ValueError(f"unrecognized operator '{op}'")
Apply the given binary operator to the two arguments. The result value is returned
625941e523e79379d52ee98a
def format_alias(x): <NEW_LINE> <INDENT> if not isinstance(x, ast.alias): <NEW_LINE> <INDENT> raise TypeError("Can only format an ast.alias; got %s" % type(x)) <NEW_LINE> <DEDENT> if x.asname is not None: <NEW_LINE> <INDENT> return "%s as %s" % (x.name, x.asname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "%s...
Return human-readable description of an ast.alias (used in Import and ImportFrom nodes).
625941e5bde94217f3683219
def G_calc(PPV, TPR): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = math.sqrt(PPV * TPR) <NEW_LINE> return result <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return "None"
This function calculate G-measure :param PPV: precision or positive predictive value :type PPV : float :param TPR: sensitivity, recall, hit rate, or true positive rate :type TPR : float :return: G-measure as float
625941e555399d3f05588ae3
def _insert_options(self, menu): <NEW_LINE> <INDENT> menu.append(Gtk.SeparatorMenuItem()) <NEW_LINE> menu.append(self._menuitem( _('Mount disc image'), self._icons.get_icon('losetup', Gtk.IconSize.MENU), run_bg(lambda _: self._losetup()) )) <NEW_LINE> menu.append(Gtk.SeparatorMenuItem()) <NEW_LINE> menu.append(self._me...
Add configuration options to menu.
625941e5ac7a0e7691ed44f0
def get_remote_socket(self, *args: int, **kwargs: int) -> socket.socket: <NEW_LINE> <INDENT> r_socket = self.connection.modules['socket'] <NEW_LINE> return r_socket.socket(*args, **kwargs)
Allocates a socket on remote machine. Args: args: Positional arguments passed to socket.socket() constructor. kwargs: Keyword arguments passed to socket.socket() constructor.
625941e5ad47b63b2c50a3ab
def load_app(self, app): <NEW_LINE> <INDENT> self.container = app <NEW_LINE> return self
Load the container into the request class. Arguments: app {masonite.app.App} -- Application Container Returns: self
625941e5d8ef3951e324396a
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ServiceLoader.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are yo...
Run administrative tasks.
625941e576d4e153a657ef5e
def get_force_plot_strokestate(self): <NEW_LINE> <INDENT> if 'CSAFE_PM_GET_STROKESTATE' in list(self.__results.keys()): <NEW_LINE> <INDENT> return self.__results['CSAFE_PM_GET_STROKESTATE'][0] <NEW_LINE> <DEDENT> return None
:return:
625941e557b8e32f524838ca
def listModels(self): <NEW_LINE> <INDENT> print("Models available:") <NEW_LINE> print("Index\t Model name") <NEW_LINE> print("========================") <NEW_LINE> for index, model in enumerate(self.models): <NEW_LINE> <INDENT> print("\t".join([str(index), str(model)]))
List the optical models in the environment.
625941e58e71fb1e9831dbd4
def test_noHome(self): <NEW_LINE> <INDENT> path = self.mktemp() <NEW_LINE> os.environ['HOME'] = path <NEW_LINE> process = ConchTestOpenSSHProcess() <NEW_LINE> d = self.execute('echo goodbye', process) <NEW_LINE> def cb(ign): <NEW_LINE> <INDENT> return self.assertFailure(process.deferred, ConchError) <NEW_LINE> <DEDENT>...
When setting the HOME environment variable to a path that doesn't exist, L{connect.connect} should forward the failure, and the created process should fail with a L{ConchError}.
625941e573bcbd0ca4b2c4a1
def idx_ranges(table, chrom, starts, ends, mode): <NEW_LINE> <INDENT> assert mode in ('inner', 'outer') <NEW_LINE> if chrom: <NEW_LINE> <INDENT> assert isinstance(chrom, basestring) <NEW_LINE> try: <NEW_LINE> <INDENT> table = table[table['chromosome'] == chrom] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> r...
Iterate through sub-ranges.
625941e50383005118ecfa0d
def Draw_PreRenderTags(self,g,cnt): <NEW_LINE> <INDENT> pass
Draw_PreRenderTags(self: GH_AbstractGraph,g: Graphics,cnt: GH_GraphContainer) -> GH_GraphDrawInstruction
625941e5d6c5a1020814447a
def test_health_check_unhealthy(): <NEW_LINE> <INDENT> client = marathon.create_client() <NEW_LINE> app_def = python_http_app() <NEW_LINE> health_list = [] <NEW_LINE> health_list.append(health_check('/bad-url', failures=0, timeout=0)) <NEW_LINE> app_def['id'] = 'unhealthy' <NEW_LINE> app_def['healthChecks'] = health_li...
Tests failed health checks of an app launched by marathon. This was a health check that never passed.
625941e576d4e153a657ef5f
def __init__(self, objects, bad, num_to_prefetch=10, locations=None): <NEW_LINE> <INDENT> super(ObjectReview, self).__init__(num_to_prefetch=num_to_prefetch) <NEW_LINE> self.todo = [] <NEW_LINE> for o in objects: <NEW_LINE> <INDENT> if isinstance(o, collections.Iterable): <NEW_LINE> <INDENT> self.todo.append(o) <NEW_LI...
Constructor. Args: objects: iterable of object IDs or iterables of object IDs. In the latter case it is assumed that every iterable forms a group of objects to be agglomerated together. bad: set in which to store objects or groups of objects flagged as bad. num_to_prefetch: number of items from `objects`...
625941e5566aa707497f498f
def get_buckets(self, timeout=None): <NEW_LINE> <INDENT> raise NotImplementedError
Gets the list of buckets as strings.
625941e58a349b6b435e859f
@try_me <NEW_LINE> def get_avg_score(reviews_el, **kwargs): <NEW_LINE> <INDENT> for attr in ('alt', 'title'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> img = reviews_el.find('img', attrs={attr: FLOAT_RE}) <NEW_LINE> text = str(img.attrs[attr]) <NEW_LINE> avg_score_str = FLOAT_RE.match(text).group() <NEW_LINE> return...
Takes a BeautifulSoup Element instance and returns a float of the average score of reviews of the product found in HTML. e.g. <div class='crIFrameNumCustReviews' ...>...</div> -> 4.8
625941e530bbd722463cc1f4
def merge_dict_lists_on_specific_keys_with_priority(l1, l2, duplicates, priority, comparison_keys): <NEW_LINE> <INDENT> dst_list = [] <NEW_LINE> if duplicates: <NEW_LINE> <INDENT> return [x for x in itertools.chain(l1, l2)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if priority != 2 and priority != 1: <NEW_LINE> <IN...
Merge two lists :param l1: the first list :param l2: the second list :param duplicates: allow duplicates if True :param priority: in case duplicates is set to False, indicates which list has the priority in case of duplicate value :param comparison_keys: the keys that have to be compared when merging the two li...
625941e53617ad0b5ed68323
def create_git_log_content(git_log): <NEW_LINE> <INDENT> git_logs = [] <NEW_LINE> single_log = '' <NEW_LINE> for log in git_log: <NEW_LINE> <INDENT> if log.startswith(COMMIT): <NEW_LINE> <INDENT> if single_log: <NEW_LINE> <INDENT> git_logs.append(single_log) <NEW_LINE> single_log = '' <NEW_LINE> <DEDENT> <DEDENT> singl...
Method to generate git log list having each commit as a list item :param git_log: :return: list of git commits
625941e5d6c5a1020814447b
def create_app(): <NEW_LINE> <INDENT> config_name = os.environ['ENV_SETTINGS'] <NEW_LINE> config_object = ".".join(('config.settings',config_name)) <NEW_LINE> app = Flask(__name__) <NEW_LINE> app.config.from_object(config_object) <NEW_LINE> app.register_blueprint(fredApi) <NEW_LINE> return app
This is the application factory which returns the flask app object. The config_name directs a runtime configuration load.
625941e55fdd1c0f98dc0661
def Bitwise(subcon): <NEW_LINE> <INDENT> MAX_BUFFER = 1024 * 8 <NEW_LINE> def resizer(length): <NEW_LINE> <INDENT> if length & 7: <NEW_LINE> <INDENT> raise SizeofError("size must be a multiple of 8", length) <NEW_LINE> <DEDENT> return length >> 3 <NEW_LINE> <DEDENT> if not subcon._is_flag(subcon.FLAG_DYNAMIC) and subco...
converts the stream to bits, and passes the bitstream to subcon * subcon - a bitwise construct (usually BitField)
625941e51b99ca400220aee0
def get(self, identifier="amp", all=False): <NEW_LINE> <INDENT> if not all: <NEW_LINE> <INDENT> return self.__getitem__(identifier)[0]._getStream().getValue() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [obj._getStream().getValue() for obj in self.__getitem__(identifier).getBaseObjects()]
Return the first sample of the current buffer as a float. Can be used to convert audio stream to usable Python data. "tap", "amp" or "dur" must be given to `identifier` to specify which stream to get value from. :Args: identifier : string {"tap", "amp", "dur"} Address string parameter identifying audio ...
625941e523849d37ff7b34b8
def residue_field(self): <NEW_LINE> <INDENT> ret = self.residue_ring() <NEW_LINE> from sage.categories.fields import Fields <NEW_LINE> if ret in Fields(): <NEW_LINE> <INDENT> return ret <NEW_LINE> <DEDENT> from sage.rings.polynomial.polynomial_ring import is_PolynomialRing <NEW_LINE> if is_PolynomialRing(ret): <NEW_LIN...
Return the residue field of this valuation, i.e., the field of fractions of the :meth:`residue_ring`, the elements of non-negative valuation modulo the elements of positive valuation. EXAMPLES:: sage: sys.path.append(os.getcwd()); from mac_lane import * # optional: standalone sage: pAdicValuation(QQ, 2).resid...
625941e5d18da76e23532907
def test_unpickle_gpuarray_as_numpy_ndarray_flag0(): <NEW_LINE> <INDENT> oldflag = config.experimental.unpickle_gpu_on_cpu <NEW_LINE> config.experimental.unpickle_gpu_on_cpu = False <NEW_LINE> try: <NEW_LINE> <INDENT> testfile_dir = os.path.dirname(os.path.realpath(__file__)) <NEW_LINE> fname = 'GpuArray.pkl' <NEW_LINE...
Test when pygpu isn't there for unpickle are in test_pickle.py
625941e55510c4643540f806
def on_done(self, _): <NEW_LINE> <INDENT> self.Close()
Handle event '_' to confirms all colours
625941e50fa83653e46573e5
def _prompt_lookup(self, output_data): <NEW_LINE> <INDENT> prompt = None <NEW_LINE> for line in reversed(output_data.splitlines()[-3:]): <NEW_LINE> <INDENT> if len(line.split()) == 1 and any(x in line for x in standard_prompt_endings): <NEW_LINE> <INDENT> prompt = line.strip().replace('\r\n', '') <NEW_LINE> break <NEW_...
Recursive method that will try and find the prompt in the last 3 lines of config, if not will send a space, get the data and call itself to run again
625941e5283ffb24f3c55d29
def get(prop_name): <NEW_LINE> <INDENT> return get_property_from_list_of_loaders(get_loaders(), prop_name)
Returns the value of a property. :param prop_name: Name of the property to get :return: The property's value :raises KeyError if `prop_name` cannot be loaded
625941e599cbb53fe6793012
def __dir__(self): <NEW_LINE> <INDENT> return self.INTERNAL_ATTRS + [k.lower() for k in self.keys()] + list(self.keys())
Enable auto-complete for code editors
625941e53346ee7daa2b319b
def __iter__(self): <NEW_LINE> <INDENT> return iter(self.images.keys())
:return: Iterator of image keys.
625941e5099cdd3c635f1085
def remove_lines(org_image, lines=None, top_bot_pixel_removal=True, top_bot_pixel_diff=2, thickness_based_removal=True, thickness_tolerance=0): <NEW_LINE> <INDENT> image = org_image.copy() <NEW_LINE> if lines is None: <NEW_LINE> <INDENT> lines = find_lines(org_image)[0] <NEW_LINE> <DEDENT> image_height, image_width = i...
Return an image that represents a copy of the original without the staff lines :param org_image: :param lines: :param top_bot_pixel_removal: :param top_bot_pixel_diff: :param thickness_based_removal: :param thickness_tolerance:
625941e54428ac0f6e5bac22
def close_reuse(self): <NEW_LINE> <INDENT> log.debug(LOG_PROXY, '%s close_reuse', self) <NEW_LINE> super(HttpClient, self).close_reuse() <NEW_LINE> self.reset()
Reset connection state, leave connection alive for pipelining.
625941e53d592f4c4ed1d48e
def report_topic(url, page, topic): <NEW_LINE> <INDENT> references = '' <NEW_LINE> if find_references(page, topic) != '': <NEW_LINE> <INDENT> references = 'Source url:' + url + '\n' <NEW_LINE> references = references + find_references(page, topic) <NEW_LINE> references = references + '\n--------------------------------...
Return source url and references, if any Parameters: url (string) - a url page (string) - HTML page topic (string) - word to find references of Return: references (string) - references to topic
625941e51d351010ab855f47
def send_media(self, media_id, user_ids, text='', thread_id=None): <NEW_LINE> <INDENT> user_ids = _get_user_ids(self, user_ids) <NEW_LINE> if not isinstance(text, str) and not isinstance(user_ids, (list, str)): <NEW_LINE> <INDENT> self.logger.error('Text must be an string, user_ids must be an list or string') <NEW_LINE...
:param media_id: :param self: bot :param text: text of message :param user_ids: list of user_ids for creating group or one user_id for send to one person :param thread_id: thread_id
625941e501c39578d7e75268
def query(self, sql): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = psycopg2.connect(self.config) <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute(sql) <NEW_LINE> res = cur.fetchall() <NEW_LINE> cur.close() <NEW_LINE> conn.close() <NEW_LINE> if not res: <NEW_LINE> <INDENT> res = [] <NEW_LINE> <DEDENT> return...
Args: sql: sql you want to query
625941e567a9b606de4a82e3
def dump(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(self.__data[State.__STATE_FILE_KEY], 'w') as f: <NEW_LINE> <INDENT> json.dump(self.__data, f, sort_keys=True, indent=4, ensure_ascii=False) <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass
Dump state to the current json format state file. The state file name is initialised from a microbit_settings.py file, if one exists. Otherwise the file microbit_state.json is used as the initial state file. Errors and exceptions during dumping are ignored. This method has no effect if the state file is empty, has ...
625941e5187af65679ca554d
def _processImage( self, image: str, name: Optional[str], command: [str], actionPresentTense: str, actionPastTense: str, env: Optional[dict[str, str]] = None, ): <NEW_LINE> <INDENT> if self._willProcess(image) == False: <NEW_LINE> <INDENT> self.logger.info( 'Image "{}" exists and rebuild not requested, skipping {}.'.fo...
Processes the specified image by running the supplied command if it doesn't exist (use rebuild=True to force processing)
625941e576e4537e8c351aa2
def main(): <NEW_LINE> <INDENT> global MAP_SEED, IS_PREVIEW, GAME_MODE <NEW_LINE> utils.con_log("BEE2 VBSP hook initiallised.") <NEW_LINE> args = " ".join(sys.argv) <NEW_LINE> new_args = sys.argv[1:] <NEW_LINE> old_args = sys.argv[1:] <NEW_LINE> path = sys.argv[-1] <NEW_LINE> path_dir, path_file = os.path.split(path) <...
Main program code.
625941e5be7bc26dc91cda25
def cost(self, x): <NEW_LINE> <INDENT> c = np.zeros(x.shape[1:]) <NEW_LINE> c = np.sum([x[i]**2 for i in range(0, self.n)]) <NEW_LINE> return c
Cost function.
625941e5ec188e330fd5abc3
def module_path(): <NEW_LINE> <INDENT> if frozen(): <NEW_LINE> <INDENT> return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding())) <NEW_LINE> <DEDENT> return os.path.dirname(unicode(__file__, sys.getfilesystemencoding()))
Returns path to this executable/script.
625941e58e05c05ec3eea7a5
def set_controller(self, controller: WhiskerController) -> None: <NEW_LINE> <INDENT> self.whisker = controller
Called by :class:`WhiskerOwner`. No need to override.
625941e5cdde0d52a9e53462
def set__id(self, new__id): <NEW_LINE> <INDENT> self._id = new__id
Sets the _id of the note object
625941e5d10714528d600114
def __init__(self, root, transform=None): <NEW_LINE> <INDENT> self.images = None <NEW_LINE> self.labels = None <NEW_LINE> self.filenames = [] <NEW_LINE> self.root = root <NEW_LINE> self.transform = transform <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> filenames = glob.glob(os.path.join(root, str(i), '*.png')) <N...
Intialize the MNIST dataset
625941e55fcc89381b1e1aee
def start_challenge_code007(self, *chall_code_args, **chall_code_kwargs): <NEW_LINE> <INDENT> print("This is start_challenge_code007 from ChallengeDefinition #",self.ID, sep='')
Start Challenge code number 007.
625941e5ff9c53063f47c61e
def is_neighbor(self, player, d=1): <NEW_LINE> <INDENT> manhattan_distance = ( abs(self.position[0] - player.position[0]) + abs(self.position[1] - player.position[1]) ) <NEW_LINE> return (manhattan_distance <= d)
Determine whether other player is adjacent.
625941e54f88993c3716c490
def newman_watts_strogatz_graph(n, k, p, seed=None): <NEW_LINE> <INDENT> if seed is not None: <NEW_LINE> <INDENT> random.seed(seed) <NEW_LINE> <DEDENT> if k>=n // 2: <NEW_LINE> <INDENT> raise nx.NetworkXError("k>=n/2, choose smaller k or larger n") <NEW_LINE> <DEDENT> G=empty_graph(n) <NEW_LINE> G.name="newman_watts_st...
Return a Newman-Watts-Strogatz small world graph. Parameters ---------- n : int The number of nodes k : int Each node is connected to k nearest neighbors in ring topology p : float The probability of adding a new edge for each edge seed : int, optional seed for random number generator (default=...
625941e5e1aae11d1e74a0e8
def longestPalindrome(self, s): <NEW_LINE> <INDENT> dim = len(s) <NEW_LINE> longest = '' <NEW_LINE> max_len = 0 <NEW_LINE> record = [[False] * dim for i in range(dim)] <NEW_LINE> for i in range(dim): <NEW_LINE> <INDENT> j = i <NEW_LINE> while j >= 0: <NEW_LINE> <INDENT> if s[j] == s[i] and (i - j < 2 or record[j + 1][i...
:type s: str :rtype: str
625941e5b7558d58953c5338
def __call__(self, boxlists: List[Tensor]) -> Tensor: <NEW_LINE> <INDENT> s = torch.sqrt(torch.cat([box_area(boxlist) for boxlist in boxlists])) <NEW_LINE> target_lvls = torch.floor(self.lvl0 + torch.log2(s / self.s0) + torch.tensor(self.eps, dtype=s.dtype)) <NEW_LINE> target_lvls = torch.clamp(target_lvls, min=self.k_...
Args: boxlists (list[BoxList])
625941e5d99f1b3c44c679b4
@contract(args='tuple[N],N>0', kwargs='dict(str: (int))', returns=None) <NEW_LINE> def all_the_args(*args: str, **kwargs: str) -> None: <NEW_LINE> <INDENT> print(args) <NEW_LINE> print(kwargs)
2: Return an array. Use * to expand positional args and use ** to expand keyword args >>> all_the_args(1, 2, a=3, b=4) (1, 2) {'a': 3, 'b': 4}
625941e5be8e80087fb21069
def comment_on(*args, dry=False, **kwargs): <NEW_LINE> <INDENT> comment = Comment(*args, **kwargs) <NEW_LINE> return _cast_return(comment, dry)
`Create a Comment` @orm: (:class:ORM) @name: (#str) name of the table @type: (#str) |COLUMN|, |TABLE|, |SCHEMA|, etc... @identifier: (#str) if you're commenting on a cast for instance, the identifier is |(source_type AS target_type)|, and on a column |relation_name.column_name|. See http://www.postgresql.or...
625941e5287bf620b61d3e8e
def test_basic_request(self): <NEW_LINE> <INDENT> test_stream = io.BytesIO() <NEW_LINE> json_rpc_writer = jsonrpc.JsonRpcWriter(test_stream) <NEW_LINE> json_rpc_writer.send_request( method=u'testMethod/DoThis', params={ u'Key': u'Value'}, id=1) <NEW_LINE> test_stream.seek(0) <NEW_LINE> json_rpc_reader = jsonrpc.JsonRpc...
Verify json rpc writer submits a valid request.
625941e54d74a7450ccd45f1
def get_validators(self): <NEW_LINE> <INDENT> DATATYPE_VALIDATORS = { 'text': validate_text, 'float': validate_float, 'int': validate_int, 'date': validate_date, 'bool': validate_bool, 'object': validate_object, 'enum': validate_enum, } <NEW_LINE> validation_function = DATATYPE_VALIDATORS[self.datatype] <NEW_LINE> retu...
Returns the appropriate validator function from :mod:`~eav.validators` as a list (of length one) for the datatype. .. note:: The reason it returns it as a list, is eventually we may want this method to look elsewhere for additional attribute specific validators to return as well as the default, built-in one.
625941e5f548e778e58cd9ac
def test_head_method(self): <NEW_LINE> <INDENT> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> s.connect((self.host, self.port)) <NEW_LINE> s.send(b"HEAD /httptest/dir2/page.html HTTP/1.0\r\n\r\n") <NEW_LINE> data = b"" <NEW_LINE> while 1: <NEW_LINE> <INDENT> buf = s.recv(1024) <NEW_LINE> if not buf: ...
head method support
625941e510dbd63aa1bd2fcf
def reverse(self, x): <NEW_LINE> <INDENT> if x == 0: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> isNegative = 0 <NEW_LINE> if x < 0: <NEW_LINE> <INDENT> isNegative = 1 <NEW_LINE> x = -x <NEW_LINE> <DEDENT> res = 0 <NEW_LINE> while x: <NEW_LINE> <INDENT> res = 10*res + x%10 <NEW_LINE> x=x//10 <NEW_LINE> <DEDENT> if...
:type x: int :rtype: int
625941e57c178a314d6ef893