code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_weighted_graph(edge_list): <NEW_LINE> <INDENT> graph = dict() <NEW_LINE> for edge in edge_list: <NEW_LINE> <INDENT> v1, v2, weight = edge.split() <NEW_LINE> weight = int(weight) <NEW_LINE> if v1 not in graph: <NEW_LINE> <INDENT> graph[v1] = dict() <NEW_LINE> <DEDENT> if v2 not in graph: <NEW_LINE> <INDENT> grap... | Converts list of weighted edges to dict of adjacencies
:param edge_list: ['a b 2', 'b c 4', 'b a 3']
:return: {'a': {'b': 3}, 'b': {'a': 3, 'c': 4}, 'c': {'b': 4}} | 625941e4cb5e8a47e48b7e9d |
def seeker(self,db): <NEW_LINE> <INDENT> pass | seeker is a function that returns a list of items to run a certain
// statistic over
// db = database handler from which to extract items | 625941e4566aa707497f495c |
def add(self, obj, offset=None, timeValue=None, idKey=None, classString=None): <NEW_LINE> <INDENT> if offset is not None: <NEW_LINE> <INDENT> raise SitesException("No offsets in sites anymore!") <NEW_LINE> <DEDENT> if idKey is None and obj is not None: <NEW_LINE> <INDENT> idKey = id(obj) <NEW_LINE> <DEDENT> updateNotAd... | Add a reference to the `Sites` collection for this object. Automatically
called on stream.insert(n), etc.
The `timeValue` argument is used to store the time as an int
(in milliseconds after Jan 1, 1970) when this object was added to locations.
If set to `None`, then the current time is used.
`idKey` stores the id() ... | 625941e47d847024c06be6b9 |
def assert_expected(call): <NEW_LINE> <INDENT> args, kwargs = call[1:3] <NEW_LINE> url, = args <NEW_LINE> data = kwargs['data'] <NEW_LINE> assert url == fork_url <NEW_LINE> assert json.loads(data) == expected_call | Extract parameters from the POST call to ensure
the data parameter JSON decodes to the expected
value. String comparison may fail due to
arbitrary ordering of dict keys. See #201. | 625941e4435de62698dfe046 |
def __get__(self, instance, owner): <NEW_LINE> <INDENT> if instance is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> ReferenceField = _import_class("ReferenceField") <NEW_LINE> GenericReferenceField = _import_class("GenericReferenceField") <NEW_LINE> EmbeddedDocumentListField = _import_class("EmbeddedDocume... | Descriptor to automatically dereference references. | 625941e460cbc95b062c693d |
def test_errback(self): <NEW_LINE> <INDENT> a, b, c = [self.multiDeferred.tee() for _ in xrange(3)] <NEW_LINE> self.assertNoResult(a) <NEW_LINE> self.assertNoResult(b) <NEW_LINE> self.assertNoResult(c) <NEW_LINE> error = RuntimeError() <NEW_LINE> self.multiDeferred.errback(error) <NEW_LINE> self.assertIdentical(self.fa... | Any produced L{defer.Deferred}s have their errbacks called when the
L{defer.MultiDeferred} does. | 625941e4287bf620b61d3e5b |
def next_is_op(src): <NEW_LINE> <INDENT> return src.more_on_line and src.current() in ['+','-','*','/'] | Returns whether the next item is an operator
>>> lines = ["+ 2 3"]
>>> src = Buffer(tokenize_lines(lines))
>>> next_is_op(src)
True
>>> lines = ["3"]
>>> src = Buffer(tokenize_lines(lines))
>>> next_is_op(src)
False | 625941e45fcc89381b1e1aba |
def test_realcugan(shape = [1, 3, 200, 200], opset_version=13, fuse=FUSE): <NEW_LINE> <INDENT> from custom_models.upcunet_v3 import RealWaifuUpScaler <NEW_LINE> upscaler2x = RealWaifuUpScaler(2, "custom_models/up2x-latest-denoise3x.pth", half=False, device="cpu") <NEW_LINE> runner = Runner("Real_CUGAN", upscaler2x.mode... | symbolic_opset11.py
def constant_pad_nd(g, input, padding, value=None):
mode = "constant"
value = sym_help._maybe_get_scalar(value)
value = sym_help._if_scalar_type_as(g, value, input)
pad = _prepare_onnx_paddings(g, sym_help._get_tensor_rank(input), padding)
padding = torch.onnx.symbolic_opset9._co... | 625941e4a219f33f34628d5e |
def test_areDemDictsEqual3(self): <NEW_LINE> <INDENT> dict29 = {'dem1': {'1': {'x': np.array([]), 'y': np.array([])}, '2': {'x': np.array([]), 'y': np.array([])}, '3': {'x': np.array([]), 'y': np.array([])}}} <NEW_LINE> dict29b = {'dem1': {'1': {'x': np.array([]), 'y': np.array([])}, '2': {'x': np.array([]), 'y': np.ar... | Testing `areDemDictsEqual` function
Two dicts, both empty arrays | 625941e4ac7a0e7691ed44be |
def tolerance(self): <NEW_LINE> <INDENT> return (self._high-self._low)/2 | The tolerance of SELF.
>>> centered_interval(5, 1).tolerance()
1.0
>>> centered_interval(interval(4, 6)).tolerance()
1.0 | 625941e47d43ff24873a309c |
@receiver(pre_save, sender=Event, dispatch_uid='create_slug_signal') <NEW_LINE> def create_slug(sender, instance, raw, **kwargs): <NEW_LINE> <INDENT> if not instance.slug: <NEW_LINE> <INDENT> instance.slug = slugify(instance.name, instance=instance) <NEW_LINE> <DEDENT> if not instance.planning_pad_url: <NEW_LINE> <INDE... | Auto create unique slug and calculate planning_pad_url. | 625941e4be7bc26dc91cd9f2 |
def check_is_restricted_by_origin_with_match_bug(self, web_socket_url, web_socket_version): <NEW_LINE> <INDENT> origin_domain = web_socket_url.get_domain() <NEW_LINE> origin_domain += '.%s' % self.W3AF_DOMAIN <NEW_LINE> for scheme in {'http', 'https'}: <NEW_LINE> <INDENT> origin = '%s://%s' % (scheme, origin_domain) <N... | Note that this method only makes sense if called in a loop with the
other check_* methods.
:param web_socket_url: The URL of the web socket
:param web_socket_version: The protocol version
:return: True if the web socket checks the origin for connections but
there is a bug in the matching process | 625941e431939e2706e4d25e |
def rad2deg(x): <NEW_LINE> <INDENT> return x / (2 * np.pi) * 360 | convert radians to degrees
args:
x(numeric): angle in degrees
returns:
degreeangle = numeric | 625941e4293b9510aa2c368b |
def progress_bar(total, progress): <NEW_LINE> <INDENT> initial_progress = progress <NEW_LINE> bar_length = 20 <NEW_LINE> progress = progress / total <NEW_LINE> block = int(round(bar_length * progress)) <NEW_LINE> progress_bar_str = '#' * block + '-' * (bar_length - block) <NEW_LINE> text = '\r[{progress_bar}] {percent:... | Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441 | 625941e4498bea3a759b9ea7 |
def deleteLast(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.deq.pop() <NEW_LINE> return True | Deletes an item from the rear of Deque. Return true if the operation is successful.
:rtype: bool | 625941e44c3428357757c71f |
def storages(request, host_id): <NEW_LINE> <INDENT> if not request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect(reverse('login')) <NEW_LINE> <DEDENT> if not request.user.is_staff: <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> errors = [] <NEW_LINE> compute = Compute.objects.... | Storage pool block | 625941e4bde94217f36831e7 |
def filterTopics(topicList,openconnection): <NEW_LINE> <INDENT> cur = openconnection.cursor(cursor_factory=RealDictCursor) <NEW_LINE> query = "select * from topics" <NEW_LINE> for topic in topicList: <NEW_LINE> <INDENT> if query.find("where") > 0 : <NEW_LINE> <INDENT> query = query + " or topicId like '%%%s%%'" %(topic... | :param topicList: List of strings corresponding to substring of desired topics
:param openconnection:
:return: JSON object of {topicid, topicname} ; where each topicid has substring of elements in topicList | 625941e499fddb7c1c9de788 |
def get(self, key): <NEW_LINE> <INDENT> if not isinstance(key, list): <NEW_LINE> <INDENT> log.warning("get() key must be a list. key: {}".format(key)) <NEW_LINE> return None <NEW_LINE> <DEDENT> if not key: <NEW_LINE> <INDENT> log.warning("Cannot get empty key.") <NEW_LINE> return None <NEW_LINE> <DEDENT> obj = self._da... | Get copied value of a given key in data store | 625941e49c8ee82313fbbb6f |
def generate_spin_id_unique(pipe_cont=None, pipe_name=None, mol=None, res=None, spin=None, mol_name=None, res_num=None, res_name=None, spin_num=None, spin_name=None): <NEW_LINE> <INDENT> pipe_cont, mol, res, spin, mol_name, res_num, res_name, spin_num, spin_name = generate_spin_info(pipe_cont=pipe_cont, pipe_name=pipe_... | Generate a list of spin ID variants for the given set of molecule, residue and spin indices.
@keyword pipe_cont: The data pipe object.
@type pipe_cont: PipeContainer instance
@keyword pipe_name: The data pipe name.
@type pipe_name: str
@keyword mol: The molecule container.
@type mol: MoleculeConta... | 625941e4d10714528d6000e1 |
def from_frac(frac: (float, float)) -> Coordinate: <NEW_LINE> <INDENT> return Coordinate(frac, None, None) | Builds a Coordinate given fractional x and y coordinates. | 625941e423849d37ff7b3486 |
def hybridClearCache(self, clearCookies=True, clearCache=True): <NEW_LINE> <INDENT> resultMap = self.execute("hybridClearCache", clearCookies, clearCache) <NEW_LINE> if (self.isThrowExceptionOnFail()): <NEW_LINE> <INDENT> if (resultMap.get("errorMassage")): <NEW_LINE> <INDENT> assert resultMap.get("errorMassage") | Clear browser cookies and/or cache
Args:
clearCookies (boolean, true): If true cookies will be cleared
clearCache (boolean, true): If true cache will be cleared | 625941e49b70327d1c4e11d0 |
def hasAnionic(self, ligand, residue): <NEW_LINE> <INDENT> cation = Chem.MolFromSmarts(self.prm["ionic"]["cation"]) <NEW_LINE> anion = Chem.MolFromSmarts(self.prm["ionic"]["anion"]) <NEW_LINE> lig_matches = ligand.mol.GetSubstructMatches(anion) <NEW_LINE> res_matches = residue.mol.GetSubstructMatches(cation) <NEW_LINE... | Get the presence or absence of an ionic interaction between a residue
as a cation and a ligand as an anion | 625941e421bff66bcd684d48 |
def pause_job( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): <NEW_LINE> <INDENT> if "pause_job" not in self._inner_api_calls: <NEW_LINE> <INDENT> self._inner_api_calls[ "pause_job" ] = google.api_core.gapic_v1.method.wrap_method( self.trans... | Pauses a job.
If a job is paused then the system will stop executing the job until it
is re-enabled via ``ResumeJob``. The state of the job is stored in
``state``; if paused it will be set to ``Job.State.PAUSED``. A job must
be in ``Job.State.ENABLED`` to be paused.
Example:
>>> from google.cloud import scheduler... | 625941e4cad5886f8bd273d3 |
def clear(self, clear_default: bool = False) -> "MutableNumDict": <NEW_LINE> <INDENT> self._dict.clear() <NEW_LINE> if clear_default: <NEW_LINE> <INDENT> self.default = None <NEW_LINE> <DEDENT> return self | Remove all explicit members of self.
Optionally, also clear default. | 625941e4bd1bec0571d90a28 |
def __call__(self, resource_type): <NEW_LINE> <INDENT> return ExportConfigurationContext(self._version, resource_type=resource_type, ) | Constructs a ExportConfigurationContext
:param resource_type: The type of communication – Messages, Calls, Conferences, and Participants
:returns: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportConfigurationContext | 625941e4167d2b6e31218f8f |
def run(self): <NEW_LINE> <INDENT> if self.source_store.isempty(): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> self.convert_store() <NEW_LINE> self.target_store.serialize(self.output_file) <NEW_LINE> return 1 | Run the converter. | 625941e43c8af77a43ae3b9e |
def unregister_worker(self, swarm_uuid, nameservice_uri, worker_uuid): <NEW_LINE> <INDENT> llogger = local_logger.LocalLogger() <NEW_LINE> llogger.log_method_call(self.__class__.__name__, sys._getframe().f_code.co_name) <NEW_LINE> llogger.debug("Try to unregister worker with interface: %s in swarm: %s at host: %s", sel... | Unregister the worker at the nameservice
:param swarm_uuid: UUID of the swarm
:param nameservice_uri: URI of the nameservice
:param worker_uuid: UUID of the worker
:return: boolean, True when unregistered successful | 625941e43617ad0b5ed682f0 |
def get_data() -> dict: <NEW_LINE> <INDENT> with open("inventory.json", "r+") as file: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> existing_items = json.load(file) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> existing_items = {} <NEW_LINE> json.dump(existing_items, file, indent=4) <NEW_LINE> <DEDENT> <DE... | Get Json data from file. | 625941e45fc7496912cc3d77 |
@task <NEW_LINE> def get_story_stats(): <NEW_LINE> <INDENT> for story in Story.select(): <NEW_LINE> <INDENT> logger.info("About to check %s" % (story.name)) <NEW_LINE> team = config.get_team_for_story(story) <NEW_LINE> story_time_bucket = time_bucket(story.date) <NEW_LINE> last_bucket = story.last_bucket <NEW_LINE> if ... | Loop through every story we know about.
If there hasn't been an update recently, fetch stats for that article. | 625941e4d486a94d0b98e540 |
def actual_decorator(controller): <NEW_LINE> <INDENT> @wraps(controller) <NEW_LINE> def wrapped_controller(*args): <NEW_LINE> <INDENT> user = config.session_manager.user <NEW_LINE> if user is None: <NEW_LINE> <INDENT> path = web.ctx.path <NEW_LINE> requested_path_parameter = "?next=%s" % path if path != "/" else "" <NE... | The actual decorator returned by login_required | 625941e4498bea3a759b9ea8 |
def test_calibration_prefit(): <NEW_LINE> <INDENT> n_samples = 50 <NEW_LINE> X, y = make_classification(n_samples=3 * n_samples, n_features=6, random_state=42) <NEW_LINE> sample_weight = np.random.RandomState(seed=42).uniform(size=y.size) <NEW_LINE> X -= X.min() <NEW_LINE> X_train, y_train, sw_train = X[:n_sampl... | Test calibration for prefitted classifiers | 625941e43539df3088e2e745 |
def source_type_weight(self): <NEW_LINE> <INDENT> if self['type'] == 'local': <NEW_LINE> <INDENT> return 3 <NEW_LINE> <DEDENT> sourceobj = self.source() <NEW_LINE> if isinstance(sourceobj, ipaddress.IPv4Network): <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> if isinstance(sourceobj, ipaddress.IPv6Network): <NEW_LINE... | Give a weight on the type of this source.
Basically make sure that IPv6Networks are sorted higher than IPv4Networks.
This is a 'when all else fails' solution in __lt__. | 625941e45510c4643540f7d4 |
def child_nodes(self): <NEW_LINE> <INDENT> return _ChildNodes(self) | Return a child node iter. | 625941e430bbd722463cc1c2 |
def contrast_brightness_cv2(of, fex, vidcap, fps, length, width, height, contrast, brightness): <NEW_LINE> <INDENT> pb = MgProgressbar( total=length, prefix='Adjusting contrast and brightness:') <NEW_LINE> count = 0 <NEW_LINE> if brightness != 0 or contrast != 0: <NEW_LINE> <INDENT> contrast = np.clip(contrast, -100.0,... | Applies contrast and brightness to a video.
Parameters
----------
- of : str
'Only filename' without extension (but with path to the file).
- fex : str
File extension.
- vidcap :
cv2 capture of video file, with all frames ready to be read with `vidcap.read()`.
- fps : int
The FPS (frames per secon... | 625941e48c0ade5d55d3edb8 |
def _get_parent_attribute(self, attr): <NEW_LINE> <INDENT> value = self._attributes[attr] <NEW_LINE> if not value: <NEW_LINE> <INDENT> if self._parent_block: <NEW_LINE> <INDENT> value = getattr(self._block, attr) <NEW_LINE> <DEDENT> elif self._role: <NEW_LINE> <INDENT> value = getattr(self._role, attr) <NEW_LINE> if no... | Generic logic to get the attribute or parent attribute for a block value. | 625941e432920d7e50b285cd |
def test_generate_password_with_length(self): <NEW_LINE> <INDENT> password = generate_password(length=4) <NEW_LINE> assert len(password) == 4 | The password length can be specified. | 625941e4566aa707497f495d |
def warn_long_break(self): <NEW_LINE> <INDENT> self.current_status = 1 <NEW_LINE> self.timer.time_left = self.timer.long_rest_time <NEW_LINE> time_left = seconds_to_minutes(self.timer.time_left) <NEW_LINE> label_str = 'Long Break\nRest for %02d:%02d minutes.' % (time_left) <NEW_LINE> self.dialog.set_markup(l... | The dialog. | 625941e49c8ee82313fbbb70 |
def updateImageData(self): <NEW_LINE> <INDENT> for widget in self.winfo_children(): <NEW_LINE> <INDENT> widget.destroy() <NEW_LINE> <DEDENT> event = self.data.event <NEW_LINE> ttk.Label(self).grid(row=0, columnspan=2, padx=50, pady=13) <NEW_LINE> style = ttk.Style() <NEW_LINE> style.configure("Unverified.TLabel", backg... | Clears the currently displayed table, and draws a new table
displaying the data of currently loaded Event. If there is no Event
currently loaded, raises an IndexError (since the index of current
Event is None). | 625941e429b78933be1e5aa1 |
def EVENT_recaptchaRequired(self, params): <NEW_LINE> <INDENT> self.challenge = params[0] <NEW_LINE> params.append(self.doCaptcha(self.challenge)) <NEW_LINE> self.runCallback(self.recaptchaRequiredCallback, params) | omegle says we need a captcha to connect | 625941e48e71fb1e9831dba2 |
def get_order_status_and_price(self, code, order_id): <NEW_LINE> <INDENT> if self.__ib is None: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> normalized_code = normalize_code(code) <NEW_LINE> for trade in self.__ib.trades(): <NEW_LINE> <INDENT> if trade.contract.symbol != normalized_code: <NEW_LINE> <INDENT... | :return: (order_status, price) (tuple) | 625941e4e76e3b2f99f3abff |
def test_everything_enabled(self): <NEW_LINE> <INDENT> self.root_dc.manage_addRRDTemplate("DockerContainer-Status") <NEW_LINE> self.root_dc.manage_addRRDTemplate("DockerContainer-Stats") <NEW_LINE> self.root_dc.manage_addRRDTemplate("DockerContainer-Size") <NEW_LINE> self.device.setZenProperty("zDockerMonitorContainerS... | Test with all templates and all monitoring enabled. | 625941e4f8510a7c17cf9af9 |
def output(self): <NEW_LINE> <INDENT> end_points = self.line_tool.end_points <NEW_LINE> line_image = np.zeros(self.image_viewer.image.shape[:2], np.uint8) <NEW_LINE> width = self.line_tool.linewidth <NEW_LINE> if width > 1: <NEW_LINE> <INDENT> rp, cp = measure.profile._line_profile_coordinates( *end_points[:, ::-1], li... | Return the drawn line and the resulting scan.
Returns
-------
line_image : (M, N) uint8 array, same shape as image
An array of 0s with the scanned line set to 255.
If the linewidth of the line tool is greater than 1,
sets the values within the profiled polygon to 128.
scan : (P,) or (P, 3) array of int or ... | 625941e476e4537e8c351a6f |
def test_cache_dir_disk_created(self): <NEW_LINE> <INDENT> self.flags(use_linked_clone=True, group='vmware') <NEW_LINE> self._create_vm() <NEW_LINE> cache_file_path = '[%s] vmware_base/fake_image_uuid.vmdk' % self.ds <NEW_LINE> cache_root_path = '[%s] vmware_base/fake_image_uuid.80.vmdk' % self.ds <NEW_LINE> self.asser... | Test image disk is cached when use_linked_clone is True. | 625941e4c4546d3d9de72e31 |
def check_if_number(user_input): <NEW_LINE> <INDENT> while type(user_input) != int: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_input = int(user_input) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> user_input = input("Hm... I guess you have problems with numbers.\n" "Try one more time, remember! This... | Check that user's input is a number | 625941e491f36d47f21ac8f0 |
def load_weights(self, filepath, callback=None): <NEW_LINE> <INDENT> if os.path.exists(filepath): <NEW_LINE> <INDENT> state_dict = torch.load(filepath) <NEW_LINE> if callback: <NEW_LINE> <INDENT> state_dict = callback(state_dict) <NEW_LINE> <DEDENT> self.load_state_dict(state_dict, strict=False) <NEW_LINE> <DEDENT> els... | Modified version of the correspoding Keras function with
the addition of multi-GPU support and the ability to exclude
some layers from loading.
exlude: list of layer names to excluce | 625941e44e4d5625662d47cc |
def write_marker_dataframes(): <NEW_LINE> <INDENT> feature_matrix, mast_feature_list, survival_mat = read_feature_matrix('_raw') <NEW_LINE> subtype_labels = get_subtype_labels(survival_mat) <NEW_LINE> marker_feature_set, test_feature_set = set([]), set([]) <NEW_LINE> for fname in ('cancer_other_info_mr_symp', 'cancer_s... | Writes out the dataframes for each of the cancer subtypes. | 625941e47b180e01f3dc4bef |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> move = key in self.data <NEW_LINE> time = self.timer() if self.ttl is not None else None <NEW_LINE> entry = TTLMappingEntry(time, value) <NEW_LINE> self.data[key] = entry <NEW_LINE> if move: <NEW_LINE> <INDENT> self.data.move_to_end(key) <NEW_LINE> <DEDENT> self.gc... | Wrap an item with a timestamp and if replacing an existing key
move it to the end. | 625941e4fbf16365ca6f65c6 |
def getHost(): <NEW_LINE> <INDENT> pass | Returns an IControlledHost compatible object this software
package lives on. | 625941e4bf627c535bc135ca |
def set_timeout(args): <NEW_LINE> <INDENT> if args.timeout is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if args.timeout: <NEW_LINE> <INDENT> deadline = (datetime.datetime.utcnow() + datetime.timedelta(minutes=args.timeout)).strftime('%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> display.info('Setting a %d minute test time... | :type args: EnvConfig | 625941e426238365f5f0f26e |
def test_vis_optimal_icontour_heuristic(self): <NEW_LINE> <INDENT> g = self._p.batch_generator(batch_sz=3) <NEW_LINE> img_batch, icontour_batch, ocontour_batch = next(g) <NEW_LINE> iheur = np.zeros_like(img_batch) <NEW_LINE> for i in range(iheur.shape[0]): <NEW_LINE> <INDENT> iheur[i][(img_batch[i] > 0.35 * np.amax(img... | Visualize a few examples given the 0.35 threshold icontour heuristic found above (test_icontour_heuristic). | 625941e4f9cc0f698b1409f2 |
def picard_insert_size_metrics( self, in_bam, picard_path='$picard', bg=False, ): <NEW_LINE> <INDENT> metrics = os.path.join( self.tempdir, '{}_insert_size_metrics.txt'.format(self.sample_name)) <NEW_LINE> hist = os.path.join(self.tempdir, '{}_insert_size.pdf'.format(self.sample_name)) <NEW_LINE> lines = (' \\\n\t'.joi... | Collect insert size metrics using Picard. The input bam file is assumed
to be sorted.
Parameters
----------
in_bam : str
Path to input bam file.
picard_path : str
Path to picard jar file. Default assumes the environmental variable
$picard contains the path to the jar file.
bg : boolean
Whether to run... | 625941e415baa723493c4372 |
def get_if_namespace_is_present(self, ns): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> api_res = v1.list_namespace() <NEW_LINE> namespace_names = [i.metadata.name for i in api_res.items] <NEW_LINE> if ns in namespace_names: <NEW_LINE> <INDENT> print (f"{ns} namespace is present") <NEW_LINE> <DEDENT> else: <NEW_LINE> <... | this method checks if a namespace available in the cluster
:param ns
:return: | 625941e4e8904600ed9f232d |
def __call__(self, image, mask): <NEW_LINE> <INDENT> for transform in self.transforms: <NEW_LINE> <INDENT> image, mask = transform(image, mask) <NEW_LINE> <DEDENT> return image, mask | Applies multiple transformations to the image and its mask at the same time.
Args:
image: the image to transform.
mask: the mask to transform.
Returns:
The transformed (image, mask) tuple. | 625941e4baa26c4b54cb1516 |
def __init__(self, channel): <NEW_LINE> <INDENT> self.Create = channel.unary_unary( '/yandex.cloud.datatransfer.v1.TransferService/Create', request_serializer=yandex_dot_cloud_dot_datatransfer_dot_v1_dot_transfer__service__pb2.CreateTransferRequest.SerializeToString, response_deserializer=yandex_dot_cloud_dot_operation... | Constructor.
Args:
channel: A grpc.Channel. | 625941e41f5feb6acb0c4f43 |
def setXform(self, value=None, channelIndex=None): <NEW_LINE> <INDENT> self.xform = Xform(value, channelIndex) | Sets a Transform's values. | 625941e456ac1b37e62645c2 |
def read_results(self, overwrite=False): <NEW_LINE> <INDENT> with open(fn(self, 'rep')) as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> for label, var in STATS.items(): <NEW_LINE> <INDENT> if label in line: <NEW_LINE> <INDENT> name, conv = var <NEW_LINE> setattr(self.stats, name, conv(line.split(':')[1])) ... | Read model estimates from *basename*.rep and *basename*.res. | 625941e4c432627299f05043 |
def choose_loader(arg, path, error_callback): <NEW_LINE> <INDENT> if arg is not None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return LOADERS[arg] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> error_callback("Specified loader doesn't exist") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> res = No... | Decide which loader to use.
The choice depends upon the specified argument and possibly
performing an autodetection.
The autodetection is done by calling detect() on all the known
loaders and returning the only one that returns True. If no one or
more than one return True, then the autodetection is considered
failed ... | 625941e4d6c5a10208144448 |
def fail(self, nodes: NodeSet) -> None: <NEW_LINE> <INDENT> unknown_hosts = nodes - self.hosts <NEW_LINE> if unknown_hosts: <NEW_LINE> <INDENT> ValueError(f'unknown hosts: {unknown_hosts}') <NEW_LINE> <DEDENT> intersection = self.successful.intersection(nodes) <NEW_LINE> if intersection: <NEW_LINE> <INDENT> ValueError(... | Add nodes to the failed list. | 625941e466673b3332b9248c |
def upsert( self, record, pk=DEFAULT, foreign_keys=DEFAULT, column_order=DEFAULT, not_null=DEFAULT, defaults=DEFAULT, hash_id=DEFAULT, hash_id_columns=DEFAULT, alter=DEFAULT, extracts=DEFAULT, conversions=DEFAULT, columns=DEFAULT, ) -> "Table": <NEW_LINE> <INDENT> return self.upsert_all( [record], pk=pk, foreign_keys=f... | Like ``.insert()`` but performs an ``UPSERT``, where records are inserted if they do
not exist and updated if they DO exist, based on matching against their primary key.
See :ref:`python_api_upsert`. | 625941e423e79379d52ee959 |
def add(self, func, args): <NEW_LINE> <INDENT> self.pool.add(func, args) | Add job.
Parameters
----------
func : object
Function to call
args : object
Function arguments | 625941e499cbb53fe6792fe0 |
def component_equation(self, component): <NEW_LINE> <INDENT> coefficients = [] <NEW_LINE> if hasattr(component, "input_type"): <NEW_LINE> <INDENT> if (component.input_type == "current" or (hasattr(component, "is_noise") and component.is_noise)): <NEW_LINE> <INDENT> coefficients.append(ImpedanceCoefficient(component=com... | Equation representing circuit component
The component equation represents the component in the circuit matrix. It maps
input or noise sources to voltages across :class:`nodes <Node>` and currents
through :class:`components <Component>` in terms of their
:class:`impedance <ImpedanceCoefficient>` and
:class:`voltage <Vo... | 625941e45f7d997b87174e95 |
def regexLines(fileHandle): <NEW_LINE> <INDENT> searchForThisText = 'bookmarks' <NEW_LINE> regexExpression = re.compile('.('+searchForThisText+').*') <NEW_LINE> frequencyDict = {} <NEW_LINE> for line in fileHandle: <NEW_LINE> <INDENT> matchObj = regexExpression.search(line) <NEW_LINE> if matchObj: <NEW_LINE> <INDENT> p... | go line by line and get the keys add them and count their frequency in a dict | 625941e48e05c05ec3eea772 |
def name(self): <NEW_LINE> <INDENT> return "" | QMetaEnum.name() -> str | 625941e4d18da76e235328d5 |
def complete_connect(self, text, line, start, end): <NEW_LINE> <INDENT> shortcuts = self.get_settings('motors') <NEW_LINE> prefix = shortcuts.pop('prefix', '') <NEW_LINE> if text in shortcuts: <NEW_LINE> <INDENT> if shortcuts[text] not in line: <NEW_LINE> <INDENT> return [shortcuts[text]] <NEW_LINE> <DEDENT> <DEDENT> r... | Allow completion by the 'motors/prefix' setting or shortcuts defined
in the settings file | 625941e4a4f1c619b28b042a |
def DivideFields(*args): <NEW_LINE> <INDENT> return _ParaMEDMEM.MEDCouplingFieldDouble_DivideFields(*args) | DivideFields(MEDCouplingFieldDouble f1, MEDCouplingFieldDouble f2) -> MEDCouplingFieldDouble
1 | 625941e4442bda511e8be80d |
def test_get_choice(self): <NEW_LINE> <INDENT> author, a_cc, a_values = self._create_author_objects() <NEW_LINE> promotion, p_cc, p_values = self._create_promotion_objects() <NEW_LINE> book, b_cc, b_values = self._create_book_objects( author=author, promotion=promotion) <NEW_LINE> result = Book.objects.get_choices('tit... | Test that a valid list of HTML select option choices are returned
both with and without a header option. | 625941e4b7558d58953c5306 |
def test_claim_resources_success_move_operation_with_shared(self): <NEW_LINE> <INDENT> get_resp_mock = mock.Mock(status_code=200) <NEW_LINE> get_resp_mock.json.return_value = { 'allocations': { uuids.source: { 'resource_provider_generation': 42, 'resources': { 'VCPU': 1, 'MEMORY_MB': 1024, }, }, uuids.shared_storage: {... | Tests that when a move operation is detected (existing allocations
for the same instance UUID) that we end up constructing an appropriate
allocation that contains the original resources on the source host
as well as the resources on the destination host but that when a shared
storage provider is claimed against in both... | 625941e4460517430c394575 |
def predict(self, X, batch_size=None): <NEW_LINE> <INDENT> X = np.array(X) <NEW_LINE> inds = np.arange(len(X)) <NEW_LINE> predictions = [] <NEW_LINE> batch_size = batch_size or len(X) <NEW_LINE> start = time.time() <NEW_LINE> while len(inds) > 0: <NEW_LINE> <INDENT> inds, batch_inds = next_batch(inds, batch_size) <NEW_... | :param X: {array-like, sparse matrix}, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and
n_features is the number of features.
:param batch_size: int, batch size
:return: decoded predicted encodings | 625941e41b99ca400220aeae |
def getAllFallbackFiles(self): <NEW_LINE> <INDENT> listOfFiles = [] <NEW_LINE> for step in self.listSteps(): <NEW_LINE> <INDENT> tmp = self.getFallbackFilesFromStep(stepName=step) <NEW_LINE> if tmp: <NEW_LINE> <INDENT> listOfFiles.extend(tmp) <NEW_LINE> <DEDENT> <DEDENT> return listOfFiles | _getAllFallbackFiles_
Get a list of LFNs for all the input files
listed as fallback attempt on the report | 625941e40fa83653e46573b3 |
def polygon(self, en, curve): <NEW_LINE> <INDENT> self._gen_poly(en, curve) | en: DXF entity of type `POLYGON`
curve: Blender data structure of type `CURVE` | 625941e4d164cc617578314a |
def get_permissions(self, user): <NEW_LINE> <INDENT> if not self.guild_id: <NEW_LINE> <INDENT> return Permissions.ADMINISTRATOR <NEW_LINE> <DEDENT> member = self.guild.get_member(user) <NEW_LINE> base = self.guild.get_permissions(member) <NEW_LINE> ow_everyone = self.overwrites.get(self.guild_id) <NEW_LINE> if ow_every... | Get the permissions a user has in the channel.
Returns
-------
:class:`disco.types.permissions.PermissionValue`
Computed permission value for the user. | 625941e4004d5f362079a72b |
def plug(self, network_id, port_id, device_name, mac_address, bridge=None, namespace=None, prefix=None): <NEW_LINE> <INDENT> if not ip_lib.device_exists(device_name, namespace=namespace): <NEW_LINE> <INDENT> ip = ip_lib.IPWrapper() <NEW_LINE> tap_name = device_name.replace(prefix or self.DEV_NAME_PREFIX, n_const.TAP_DE... | Plugin the interface. | 625941e415baa723493c4373 |
def has_repository_handle(self, handle): <NEW_LINE> <INDENT> raise NotImplementedError | Return True if the handle exists in the current Repository database. | 625941e45166f23b2e1a5554 |
def feed_forward(self): <NEW_LINE> <INDENT> return self.logits | Simply returns logits
More of a sanity preserver than anything else. Allows computation graph
to be "run" in a more natural way in a management environment | 625941e4d10714528d6000e2 |
def _set_interface(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, regi... | Setter method for interface, mapped from YANG variable /inputs/vnfbd/scenario/nodes/connection_points/interface (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface is considered as a private
method. Backends looking to populate this variable should
do ... | 625941e4fb3f5b602dac3a92 |
def test_invalid_section_relaxed(self): <NEW_LINE> <INDENT> self.cp.read_dict({'foo': {'bar': 'baz'}}) <NEW_LINE> self.cfg._from_cp(self.cp, relaxed=True) <NEW_LINE> with self.assertRaises(configexc.NoSectionError): <NEW_LINE> <INDENT> self.cfg.get('foo', 'bar') | Test an invalid section with relaxed=True. | 625941e4ab23a570cc250581 |
def test_import_repo_url(self): <NEW_LINE> <INDENT> common_urls = [ ('./path/to/relative/folder', False), ('../../path/to/relative/folder', False), ('../../path/to/@/folder', False), ('/path/to/local/folder', False), ('/path/to/@/folder', False), ('file:///path/to/local/folder', False), ('file:///path/to/@/folder', Fal... | Validate different type of repository URLs on importing a Project. | 625941e47047854f462a1800 |
def test_get_all_cellphone_senders(self): <NEW_LINE> <INDENT> pass | Test case for get_all_cellphone_senders
Get all cellphone senders # noqa: E501 | 625941e4a4f1c619b28b042b |
def test_failed(self, msg='failed', *args): <NEW_LINE> <INDENT> self.__script.test_failed(msg=msg, *args) <NEW_LINE> raise StopIteration() | Fails the test. | 625941e4de87d2750b860191 |
def __init__(self, element_type=None, element_rect=None, visibility=None, critical_flag=None, area_list=None, reserved2=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_config... | SecurityFeatureResultAllOf - a model defined in OpenAPI | 625941e4d58c6744b4258059 |
def get_data_object_geojson(response_content, table_name, bbox): <NEW_LINE> <INDENT> select_columns = settings.GRACE_TABLE_INFOS_GEOJSON.get(table_name).get('select_col') <NEW_LINE> geom_column = settings.GRACE_TABLE_INFOS_GEOJSON.get(table_name).get('geom_col') <NEW_LINE> resFrom = select_columns.find('FROM') <NEW_LIN... | Perform a SELECT on the DB to retreive infos on associated object, geojson format
Param: table_name : name of the table | 625941e4656771135c3ebc6e |
def print_tags(self): <NEW_LINE> <INDENT> file = str(self.file) <NEW_LINE> with exiftool.ExifTool() as exif: <NEW_LINE> <INDENT> info = exif.get_metadata(file) <NEW_LINE> info = json.dumps(info, sort_keys=True, indent=4) <NEW_LINE> <DEDENT> print(info) | Function to print exif tags | 625941e4a79ad161976cc540 |
def test_cli_parser_unrecognized(capsys: CaptureFixture) -> None: <NEW_LINE> <INDENT> parser = cli.create_parser() <NEW_LINE> with pytest.raises(SystemExit) as exception: <NEW_LINE> <INDENT> cli.parse_args(parser, ['--dummy']) <NEW_LINE> <DEDENT> output = capsys.readouterr() <NEW_LINE> assert exception.type == SystemEx... | Test the CLI parser for unrecognized argument.
:param capsys: System-level capture fixture | 625941e4f548e778e58cd97a |
def upload_single_file(file): <NEW_LINE> <INDENT> http_header = dict() <NEW_LINE> sign,cos_path = get_auth(file) <NEW_LINE> http_header['Authorization'] = sign <NEW_LINE> f = open(file, 'rb') <NEW_LINE> file_content = f.read() <NEW_LINE> http_body = dict() <NEW_LINE> http_body['op'] = 'upload' <NEW_LINE> http_body['fil... | 单文件上传
:param request:
:return: | 625941e4462c4b4f79d1daca |
def get_input_generator(self): <NEW_LINE> <INDENT> if self.prev_cmd is not None: <NEW_LINE> <INDENT> make_input_generator = self.prev_cmd.call() <NEW_LINE> input_generator = make_input_generator() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> input_generator = [] <NEW_LINE> <DEDENT> return input_generator | Gets the input generator from the previous command, if it
exists. If it doesn't exist, we just return an empy list so that
when you iterate over it, it does nothing. | 625941e4cc40096d61595d4a |
@run_async <NEW_LINE> def get_bot_ip(bot: Bot, update: Update): <NEW_LINE> <INDENT> res = requests.get("http://ipinfo.io/ip") <NEW_LINE> update.message.reply_text(res.text) | Sends the bot's IP address, so as to be able to ssh in if necessary.
OWNER ONLY. | 625941e42eb69b55b151ccb0 |
def ConstPointerToConstDecl(dtype, name): <NEW_LINE> <INDENT> return c.Const(c.Pointer(c.Const(c.POD(dtype, name)))) | Returns a cgen variable declaration of a constant pointer to a constant
of type `dtype` | 625941e4b830903b967e9d02 |
def LMemo(matcher): <NEW_LINE> <INDENT> if is_child(matcher, NoMemo, fail=False): <NEW_LINE> <INDENT> return matcher <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return _LMemo(matcher) | Wrap in the _LMemo cache if required. | 625941e4fb3f5b602dac3a93 |
def string_to_ntp_date_time(datestr): <NEW_LINE> <INDENT> if not isinstance(datestr, str): <NEW_LINE> <INDENT> raise IOError('Value %s is not a string.' % str(datestr)) <NEW_LINE> <DEDENT> if not DATE_MATCHER.match(datestr): <NEW_LINE> <INDENT> raise ValueError("date string not in ISO8601 format YYYY-MM-DDTHH:MM:SS.SSS... | Extract an ntp date from a ISO8601 formatted date string.
@param datestr an ISO8601 formatted string containing date information
@retval an ntp date number (seconds since jan 1 1900)
@throws InstrumentParameterException if datestr cannot be formatted to
a date. | 625941e48a349b6b435e856e |
@app.route("/machines-hosts/<int:host_id>", methods=['GET']) <NEW_LINE> @log_user_action <NEW_LINE> @login_required <NEW_LINE> def show_machine_or_host(host_id): <NEW_LINE> <INDENT> data = _get_request_args() <NEW_LINE> return utils.make_json_response( 200, _reformat_host(host_api.get_machine_or_host( current_user, hos... | Get host. | 625941e44e696a04525c9848 |
def is_record_tls(self, record): <NEW_LINE> <INDENT> if 'data' not in record: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 'tls' not in record['data']: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 'server_certificates' not in record['data']['tls']: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDE... | Returns true if contains server_certificates
:param record:
:return: | 625941e4a8370b7717052c98 |
def w_election(self, w_dist, labels): <NEW_LINE> <INDENT> vals = np.unique(labels) <NEW_LINE> best_so_far = (-1, -1) <NEW_LINE> for val in vals: <NEW_LINE> <INDENT> val_idxs = np.where(labels == val) <NEW_LINE> vote = np.sum(w_dist[val_idxs]) <NEW_LINE> if vote > best_so_far[1]: <NEW_LINE> <INDENT> best_so_far = (val, ... | given weighted distances and respective labels
determine election | 625941e44d74a7450ccd45bf |
def make_app(**kwargs): <NEW_LINE> <INDENT> parse_options() <NEW_LINE> URLS = [ U(r"%slogin/" % options.url_prefix, LoginHandler, name="login"), U(r"%slogout/" % options.url_prefix, LogoutHandler, name="logout"), U(r"%sreload_collector/" % options.url_prefix, CollectorReloadHandler, name="reload_collector"), U(r"%sserv... | Parse the config file and instantiate a tornado app. | 625941e4c432627299f05044 |
def generalizeFunction(self, address): <NEW_LINE> <INDENT> bbcount = 1 <NEW_LINE> bbmap = {} <NEW_LINE> cfg = {} <NEW_LINE> bbinfo = {} <NEW_LINE> f = self.imm.getFunction(address) <NEW_LINE> bbs = f.getBasicBlocks() <NEW_LINE> for bb in bbs: <NEW_LINE> <INDENT> if not bbmap.has_key(bb.getStart()): <NEW_LINE> <INDENT> ... | Take an address an return a generalized version of the function, dismissing
address and register dependant information.
@type address: DWORD
@param address: address to the function begin
@rtype: LIST
@return: the 1st value is a DICTIONARY of a Control Flow Graph of the
BB conexions (each BB have an arbitra... | 625941e4bde94217f36831e8 |
def __init__(self, pairs_path, features_path, num_max_minibatches=1000, seed=None, batch_size=8, shuffle_between_epochs=False, align_different_words=False, tcl=0.0): <NEW_LINE> <INDENT> assert 0 <= tcl < 1 <NEW_LINE> self.pairs_path = pairs_path <NEW_LINE> self.features_path = features_path <NEW_LINE> self.statistics_t... | :param string pairs_path: path to dataset where the dev_pairs and
train_pairs folders are
:param features_path: path to feature file
:param int num_max_minibatches: number of batches in each epoch
:param int seed: for randomness
:param bool align_different_words:
If true, different words w... | 625941e4925a0f43d254a276 |
def insertFront(self, value): <NEW_LINE> <INDENT> if len(self.circular_deque) >= self._length: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if isinstance(value, int): <NEW_LINE> <INDENT> self.circular_deque.insert(0, value) <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Adds an item at the front of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool | 625941e4adb09d7d5db6cb88 |
def is_console(self): <NEW_LINE> <INDENT> return self.app.GetRuntimeInfo( Empty()).app_type == App_pb2.ApplicationTypeEnum.Value( 'CONSOLE_APPLICATION') | Returns true if the connected ResInsight instance is a console app | 625941e4dd821e528d63b5a1 |
@task <NEW_LINE> def order_created(order_id): <NEW_LINE> <INDENT> order = Order.objects.get(id=order_id) <NEW_LINE> subject = '订单号. {}'.format(order.id) <NEW_LINE> message = '尊敬的 {},\n\n您已成功下订单。您的订单号是 {}.'.format(order.name, order.id) <NEW_LINE> mail_sent = send_mail(subject, message, '573908896@qq.com', [order.email]... | 当一个订单创建完成后发送邮件通知给用户 | 625941e49c8ee82313fbbb71 |
def load_monrovia_data(): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for file in os.listdir(os.getcwd() + '/data/monrovia'): <NEW_LINE> <INDENT> if file.endswith('.json'): <NEW_LINE> <INDENT> p_data = open('data/monrovia/' + file, 'r').read() <NEW_LINE> p_data = json.loads(p_data) <NEW_LINE> if 'url' in p_data and 'name'... | Get all companion plant references and the plants they correspond to. | 625941e438b623060ff0b1e9 |
def test_turn_off(self): <NEW_LINE> <INDENT> runs = [] <NEW_LINE> self.hass.services.register( 'light', SERVICE_TURN_OFF, lambda x: runs.append(1)) <NEW_LINE> comps.turn_off(self.hass, 'light.Bowl') <NEW_LINE> self.hass.pool.block_till_done() <NEW_LINE> self.assertEqual(1, len(runs)) | Test turn_off method. | 625941e457b8e32f52483899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.