code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def print_node(self): <NEW_LINE> <INDENT> for pre, fill, node in RenderTree(self): <NEW_LINE> <INDENT> print("%s%s" % (pre, node.name))
Print the node
625941f2ac7a0e7691ed4686
def get_arguments(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser(description="DeepLabLFOV Network Inference.") <NEW_LINE> parser.add_argument("img_path", type=str, help="Path to the RGB image file.") <NEW_LINE> parser.add_argument("model_weights", type=str, help="Path to the file with model weights.") <NEW_LIN...
Parse all the arguments provided from the CLI. Returns: A list of parsed arguments.
625941f271ff763f4b549c5c
def standard_deviation(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> for i in xrange(1, 10): <NEW_LINE> <INDENT> yield i
returns the standard deviation. assumptions: we will use std deviation from 1 to 9 for col2 to col10 respectively
625941f250812a4eaa59c8e1
def default_histogram_parameters(): <NEW_LINE> <INDENT> return { 'xd_bin_edges': (-np.inf, -100, -40, -20, -10, -5, 0, 1, 6, 11, 21, 41, 101, np.inf), 'max_d': 200, 'mq_bin_edges': (0, 1, 11, 21, 31, 41, 51, 61), 'v_bin_edges': (-np.inf, -20, 0, 1, 21, np.inf), 'xt_bin_edges': (-np.inf, -100, -40, -20, -10, -5, 0, 1, 6...
Give us reasonable defaults for the full (8D) histogram. :return: A dictionary which we can then modify if we wish This dictionary can then be passed to `initialize_histogram`
625941f28a349b6b435e8738
def p_relational(p): <NEW_LINE> <INDENT> p[0] = p[1]
relational : '=' | NEQ | '<' | LEQ | '>' | GEQ
625941f2a934411ee3751c5b
def outputText(self, item, titleMode, internal=False): <NEW_LINE> <INDENT> if self.useFileInfo: <NEW_LINE> <INDENT> item = globalref.docRef.fileInfoItem <NEW_LINE> <DEDENT> storedText = item.data.get(self.name, '') <NEW_LINE> if storedText: <NEW_LINE> <INDENT> return self.formatOutput(storedText, titleMode, internal) <...
Return formatted text for this field
625941f2d18da76e23532aa3
def FacetNormal(mesh): <NEW_LINE> <INDENT> cell = mesh.ufl_cell() <NEW_LINE> return cell.n
Return facet normal function for given mesh. *Arguments* mesh a :py:class:`Mesh <dolfin.cpp.Mesh>`. *Example of usage* .. code-block:: python mesh = UnitSquare(4,4) n = FacetNormal(mesh)
625941f27d43ff24873a326b
def xlsxify(rows): <NEW_LINE> <INDENT> sfp = StringIO() <NEW_LINE> with xlsxwriter.Workbook(sfp) as workbook: <NEW_LINE> <INDENT> add_worksheet(workbook, 'worksheet', rows) <NEW_LINE> <DEDENT> sfp.seek(0) <NEW_LINE> return send_file(sfp, mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
Expects a list of dictionaries and returns an xlsx response.
625941f28e05c05ec3eea93f
@set_height_metadata(geopt=False, stag=False) <NEW_LINE> @convert_units("height", "m") <NEW_LINE> def get_height(wrfin, timeidx=0, method="cat", squeeze=True, cache=None, meta=True, _key=None, msl=True, units="m"): <NEW_LINE> <INDENT> return _get_geoht(wrfin, timeidx, method, squeeze, cache, meta, _key, True, msl)
Return the geopotential height. If *msl* is True, then geopotential height is returned as Mean Sea Level (MSL). If *msl* is False, then geopotential height is returned as Above Ground Level (AGL) by subtracting the terrain height. This functions extracts the necessary variables from the NetCDF file object in order t...
625941f24f6381625f115001
def shouldPrintMessage(self, timestamp: int, message: str) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value = self.Dict[message] <NEW_LINE> if timestamp - value >= 10 : <NEW_LINE> <INDENT> self.Dict[message] = timestamp <NEW_LINE> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LI...
Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity.
625941f2d58c6744b4258223
@_plot2d <NEW_LINE> def pcolormesh(x, y, z, ax, **kwargs): <NEW_LINE> <INDENT> x = _infer_interval_breaks(x) <NEW_LINE> y = _infer_interval_breaks(y) <NEW_LINE> primitive = ax.pcolormesh(x, y, z, **kwargs) <NEW_LINE> if not hasattr(ax, 'projection') and x.ndim == 1 and y.ndim == 1: <NEW_LINE> <INDENT> ax.set_xlim(x[0],...
Pseudocolor plot of 2d DataArray Wraps matplotlib.pyplot.pcolormesh
625941f2ec188e330fd5ad58
def get_diff(directory, last_commit_hash, files=None): <NEW_LINE> <INDENT> kwargs = {'should_strip_output': False} <NEW_LINE> git_args = [ directory, 'diff', last_commit_hash, 'HEAD', ] <NEW_LINE> if not files: <NEW_LINE> <INDENT> filenames_to_include_in_diff = _filter_filenames_from_diff(directory, last_commit_hash) <...
Returns the git diff between last commit hash, and HEAD.
625941f20a50d4780f66745d
def get_measurements_along_route(self): <NEW_LINE> <INDENT> measurements = [] <NEW_LINE> otp_json = self.get_json() <NEW_LINE> self._raise_exception_if_no_plan(otp_json) <NEW_LINE> time_stamps_seen = set() <NEW_LINE> for i, leg in enumerate(otp_json["plan"]["itineraries"][0]['legs']): <NEW_LINE> <INDENT> if leg['legGeo...
Returns a list of measurements along trip based on OTP data. Measurements inlcude location entries and motion entries. Motion entries are included so the pipeline can determine the mode of transportation for each section of the trip.
625941f2b545ff76a89143db
def __itruediv__(self,value): <NEW_LINE> <INDENT> return self.iscale(1.0/value)
Divide segment durations (in place). Parameters ---------- value : scalar or 1d array Scaling factor.
625941f2ab23a570cc25074d
@bprop_to_grad_transform(P.scalar_cast) <NEW_LINE> def bprop_scalar_cast(x, t, out, dout): <NEW_LINE> <INDENT> return (P.scalar_cast(dout, typeof(x)), t)
Backpropagator for primitive `scalar_cast`.
625941f25fc7496912cc3f43
def visualize(risks, seen, current): <NEW_LINE> <INDENT> for row, line in enumerate(risks): <NEW_LINE> <INDENT> for col, risk in enumerate(line): <NEW_LINE> <INDENT> symbol = ( Fore.RED + "#" if (row, col) == current else Fore.YELLOW + str(risks[row, col]) if (row, col) in seen else Fore.GREEN + str(risks[row, col]) ) ...
Draw risks to terminal
625941f207d97122c4178e60
def __str__(self) -> str: <NEW_LINE> <INDENT> ret = ("""<FileState instance for %s file '%s'""" % (self.virtual and "virtual" or "physical", self.name)) <NEW_LINE> si = self.statinfo <NEW_LINE> if si is None: <NEW_LINE> <INDENT> ret += ", unreadable -> will be selected>" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> re...
Return a stringified version of self, useful for debugging.
625941f2aad79263cf391010
def __init__(self, system_owned=None, display_name=None, description=None, tags=None, create_user=None, protection=None, create_time=None, last_modified_time=None, last_modified_user=None, id=None, resource_type=None, peer_endpoint_id=None, ipsec_vpn_service_id=None, local_endpoint_id=None, tcp_mss_clamping=None, enabl...
IPSecVPNSession - a model defined in Swagger
625941f24e696a04525c9a14
def set_char_length(dictionary, char_length): <NEW_LINE> <INDENT> if isinstance(char_length, (int, float, np.ndarray)): <NEW_LINE> <INDENT> dictionary['char_length'] = char_length <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif isinstance(char_length, str): <NEW_LINE> <INDENT> assert char_length in dictionary, 'Invalid ke...
Set the characteristic length for each coordinate. Use if length is not uniform. :param char_length: Scalar or key for the length scale. :param dictionary: Dictionary of flow data. :return: 1: success.
625941f2d99f1b3c44c67b49
def calc_distance(self, st, ed): <NEW_LINE> <INDENT> if st == None or ed == None: <NEW_LINE> <INDENT> errmsg("Invalid input argument") <NEW_LINE> <DEDENT> st_x, st_y = st <NEW_LINE> ed_x, ed_y = ed <NEW_LINE> x_diff = abs(st_x - ed_x) <NEW_LINE> y_diff = abs(st_y - ed_y) <NEW_LINE> distance = round(math.sqrt((x_diff * ...
Calculate the distance between two points
625941f256b00c62f0f14c23
def release(self, conn): <NEW_LINE> <INDENT> if not self.enabled: <NEW_LINE> <INDENT> conn.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pool = self._get_pool() <NEW_LINE> try: <NEW_LINE> <INDENT> pool.put_nowait(conn) <NEW_LINE> <DEDENT> except Full: <NEW_LINE> <INDENT> conn.close()
Releases the connection back to the pool. If the pool is full, the connection is closed instead. :param conn: The connection to release.
625941f2293b9510aa2c3856
def filter_for_testarg(self, index, filter): <NEW_LINE> <INDENT> self.limits[index] = [v for v in self.test_values_for(index) if filter(v)] <NEW_LINE> return self
Restrict the index-th parameter (starting at 0) to only values that pass the filter
625941f2ff9c53063f47c7b6
def digits_for_range(npo, sigma=None): <NEW_LINE> <INDENT> import numpy <NEW_LINE> machine_epsilon = _machine_epsilon() <NEW_LINE> if npo.dtype.kind in 'ui': <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if numpy.amax( numpy.mod(npo,1) )< machine_epsilon: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if sigma: <N...
sfloat by default scales a number according to the amount of digits in the mnumber itself. When printing a list of numbers from the same data, it can make sense to adjust that to the range of those values Takes a numpy array, python list, or such. TODO: clean up. A lot. Replace? Abandon?
625941f2e5267d203edce25b
def build_phenotype(phenotype_info): <NEW_LINE> <INDENT> phenotype_obj = dict( phenotype_id=phenotype_info["phenotype_id"], disease_models=phenotype_info["disease_models"], ) <NEW_LINE> return phenotype_obj
Build a phenotype term object Args: phenotype(dict) Returns: phenotype_obj(dict)
625941f24d74a7450ccd478c
def testEscape(self): <NEW_LINE> <INDENT> xml=b"""<faq><a href="http://atpic.com">Some</a> good <i>xml</i>: <escape mode="ok">this is <b>important</b></escape></faq>""" <NEW_LINE> taglist=[b"escape"] <NEW_LINE> escaped_ok=b"""<?xml version="1.0" ?><faq><a href="http://atpic.com">Some</a> good <i>xml</i>: <escape mode="...
should escape the tags
625941f2cad5886f8bd2759e
def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights, buckets, num_decoder_symbols, seq2seq, softmax_loss_function=None, name=None): <NEW_LINE> <INDENT> if len(encoder_inputs) < buckets[-1][0]: <NEW_LINE> <INDENT> raise ValueError("Length of encoder_inputs (%d) must be at least that of la" "st bucket...
Create a sequence-to-sequence model with support for bucketing. The seq2seq argument is a function that defines a sequence-to-sequence model, e.g., seq2seq = lambda x, y: basic_rnn_seq2seq(x, y, rnn_cell.GRUCell(24)) Args: encoder_inputs: a list of Tensors to feed the encoder; first seq2seq input. decoder_inputs:...
625941f21f5feb6acb0c510f
def process_map(osm_file, validate): <NEW_LINE> <INDENT> with codecs.open(NODES_FILE_PATH, 'w') as nodes_file, codecs.open(NODE_TAGS_FILE_PATH, 'w') as nodes_tags_file, codecs.open(WAYS_FILE_PATH, 'w') as ways_file, codecs.open(WAY_NODES_FILE_PATH, 'w') as way_nodes_file, cod...
process each XML element and write to respective CSV files :return: Nothing writes the files to the specified location
625941f27047854f462a19c9
def generate(locale=None): <NEW_LINE> <INDENT> if locale is None or locale not in LOCALES: <NEW_LINE> <INDENT> locale = DEFAULT_LOCALE <NEW_LINE> <DEDENT> vowels = globals()['{}_vowels'.format(locale)] <NEW_LINE> consonants = globals()['{}_consonants'.format(locale)] <NEW_LINE> is_vowels_first = bool(randint(0, 1)) <NE...
Generates nickname from nickname import generate print generate('ru') print generate('en')
625941f2596a89723608a07e
def save_kinetics_lib(rxn_list, path, name, lib_long_desc): <NEW_LINE> <INDENT> entries = dict() <NEW_LINE> if rxn_list: <NEW_LINE> <INDENT> for i, rxn in enumerate(rxn_list): <NEW_LINE> <INDENT> if rxn.kinetics is not None: <NEW_LINE> <INDENT> entry = Entry( index=i, item=rxn, data=rxn.kinetics, label=rxn.label) <NEW_...
Save an RMG kinetics library. Args: rxn_list (list): Entries are Reaction object instances for which kinetics will be saved. path (str): The base folder in which the kinetic library will be saved. name (str): The library name. lib_long_desc (str): A multiline string with relevant description.
625941f282261d6c526aba6f
def params(val, name): <NEW_LINE> <INDENT> global x0, y0, x1, y1 <NEW_LINE> val = round(val,1) <NEW_LINE> if name == "x0": <NEW_LINE> <INDENT> x0 = val <NEW_LINE> <DEDENT> elif name == "x1": <NEW_LINE> <INDENT> x1 = val <NEW_LINE> <DEDENT> elif name == "y0": <NEW_LINE> <INDENT> y0 = val <NEW_LINE> <DEDENT> elif name ==...
a handler with two parameters receives value and name.
625941f256b00c62f0f14c24
def update_capacity_commitment( self, request: Union[reservation.UpdateCapacityCommitmentRequest, dict] = None, *, capacity_commitment: reservation.CapacityCommitment = None, update_mask: field_mask_pb2.FieldMask = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str...
Updates an existing capacity commitment. Only ``plan`` and ``renewal_plan`` fields can be updated. Plan can only be changed to a plan of a longer commitment period. Attempting to change to a plan with shorter commitment period will fail with the error code ``google.rpc.Code.FAILED_PRECONDITION``. .. code-block:: py...
625941f28c3a873295158989
def get_common_css(is_archive=False): <NEW_LINE> <INDENT> if not is_archive: <NEW_LINE> <INDENT> css_text = '<link rel="stylesheet" type="text/css" href="' + url_for('static', filename='styles.css') + '">' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> css_path = os.path.join(current_app.static_folder,...
Get text of common_js or script tag with link.
625941f21d351010ab8560e1
def end(self): <NEW_LINE> <INDENT> return _Math.HotspotListF_end(self)
end(self) -> std::vector<(Seiscomp::Math::Geo::NamedCoord<(float)>)>::iterator
625941f24f88993c3716c627
def check_aliens_bottom(ai_settings, screen, stats, sb, ship, aliens, bullets): <NEW_LINE> <INDENT> screen_rect = screen.get_rect() <NEW_LINE> for alien in aliens.sprites(): <NEW_LINE> <INDENT> if alien.rect.bottom >= screen_rect.bottom: <NEW_LINE> <INDENT> ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets...
check if any aliens have reached the bottom of the screen
625941f276e4537e8c351c3e
def print_progress(numPagesRecieved, numPagesSent): <NEW_LINE> <INDENT> percent = (numPagesRecieved/numPagesSent) * 100 <NEW_LINE> print_and_flush(u'\rArticles processed: {:5.2f}% ({}/{})'.format(percent, numPagesRecieved, numPagesSent))
Print progress based on the number of pages recieved and the total number of pages sent.
625941f2eab8aa0e5d26e121
def get_style_target(style, ctx, mod_type="purposeful_optimization"): <NEW_LINE> <INDENT> if mod_type == "original": <NEW_LINE> <INDENT> gram_executor = StyleGramExecutor(style.shape, ctx) <NEW_LINE> style.copyto(gram_executor.data) <NEW_LINE> gram_executor.executor.forward() <NEW_LINE> new_style = gram_executor.execut...
how to modify style target code 1. purposeful_optimization: sum of code along channel axis at a layer Parameters -------- style: ndarray (1xCxHxW), neurons activations at a layer in CNNs ctx: context of devices, mx.gpu(0) or mx.cpu() mod_type: str, how to modify code. Returns new_code: ndarray (C,1), target style ter...
625941f2c4546d3d9de73000
def myProduct(L): <NEW_LINE> <INDENT> current = 1 <NEW_LINE> for i in L: <NEW_LINE> <INDENT> current *= i <NEW_LINE> <DEDENT> return current
Input: -L: a list of numbers Output: -the product of the numbers in L Be sure your procedure works for the empty list. Examples: >>> myProduct([1,3,5]) 15 >>> myProduct([-3,2,4]) -24
625941f271ff763f4b549c5d
def plot_axis(events, eventsclusters, clusters, conf, plotdir): <NEW_LINE> <INDENT> c1, c2, c3 = [2., 1.8], [6., 1.8], [10., 1.8] <NEW_LINE> csize = 1.5 <NEW_LINE> events_with_mt = [] <NEW_LINE> cols = [] <NEW_LINE> for iev, ev in enumerate(events): <NEW_LINE> <INDENT> if ev.moment_tensor is not None: <NEW_LINE> <INDEN...
Plot axis orientations for the seismicity clusters
625941f25f7d997b87175064
def init(config): <NEW_LINE> <INDENT> config['extension_types'].update(EXTENSION_TYPES) <NEW_LINE> config['serializers'].update(SERIALIZERS)
Update serialization info to include atom.
625941f2ac7a0e7691ed4687
def start(self): <NEW_LINE> <INDENT> self.cov = coverage.coverage(source=self.cov_source, config_file=self.cov_config) <NEW_LINE> self.cov.erase() <NEW_LINE> self.cov.start() <NEW_LINE> self.set_env()
Erase any previous coverage data and start coverage.
625941f291f36d47f21acac0
def do_query(archives, config_file=None, logger=None, context=None): <NEW_LINE> <INDENT> with open(config_file, "r") as f: <NEW_LINE> <INDENT> config = yaml.load(f) <NEW_LINE> <DEDENT> preprocess_type = query_utils.extract_preprocess_word_type(config) <NEW_LINE> data_file = query_utils.extract_data_file(config, os.path...
Counts number of articles in which they are occurences of keysentences and groups them by year. Words in articles and keysentences can be normalized, normalized and stemmed, or normalized and lemmatized (default). config_file must be the path to a configuration file of form: preprocess: none|normalize|stem|lemma...
625941f2ec188e330fd5ad59
def computeQValueFromValues(self, state, action): <NEW_LINE> <INDENT> Q_val = 0 <NEW_LINE> for new_state, probabilities in self.mdp.getTransitionStatesAndProbs(state, action): <NEW_LINE> <INDENT> sum_over_rewards = self.mdp.getReward(state,action,new_state) + self.discount * self.getValue(new_state) <NEW_LINE> Q_val +=...
Compute the Q-value of action in state from the value function stored in self.values.
625941f216aa5153ce362a40
def btn_food(self): <NEW_LINE> <INDENT> plt.figure(figsize=[8, 6], dpi=60) <NEW_LINE> map_food = np.sum(self.map.foodmap) <NEW_LINE> wolf_food = np.sum([w.food for w in self.map.wolf_list]) <NEW_LINE> sheep_food = np.sum([s.food for s in self.map.sheep_list]) <NEW_LINE> an_food = wolf_food + sheep_food <NEW_LINE> ttl =...
plot foodmap
625941f21f037a2d8b9467c2
def strand_reverse(strand): <NEW_LINE> <INDENT> opposite = {'+':'-', '-': '+', '.': '.'} <NEW_LINE> try: <NEW_LINE> <INDENT> return opposite[strand] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return '.'
+ maps to -, - maps to +, all others map to '.'
625941f266656f66f7cbc774
def test_recipe_str(self): <NEW_LINE> <INDENT> ingredient = models.Recipe.objects.create( user=sample_user(), title='Chicken Popcorn', time_minutes=40, price=60 ) <NEW_LINE> self.assertEqual(str(ingredient), ingredient.title)
Test the Recipe string representation
625941f2f7d966606f6aa5d2
def put(self, data): <NEW_LINE> <INDENT> if len(data) > MAX_MESSAGE_BYTES: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self.wf = [] <NEW_LINE> self.wf.append(pigpio.pulse(self.txbit, 0, 500)) <NEW_LINE> self.wf.append(pigpio.pulse(0, self.txbit, 100)) <NEW_LINE> self.cancel() <NEW_LINE> for i in _HEADER: <NEW_...
Transmit a message. If the message is more than MAX_MESSAGE_BYTES in size it is discarded. If a message is currently being transmitted it is aborted and replaced with the new message. True is returned if message transmission has successfully started. False indicates an error.
625941f27d847024c06be888
def create_logger(level: int) -> logging.Logger: <NEW_LINE> <INDENT> global logger_count <NEW_LINE> logger_count += 1 <NEW_LINE> logger = logging.getLogger(f'fides_{logger_count}') <NEW_LINE> ch = logging.StreamHandler() <NEW_LINE> formatter = logging.Formatter( fmt='%(asctime)s fides(%(levelname)s) %(message)s', datef...
Creates a logger instance. To avoid unnecessary locks during multithreading, different logger instance should be created for every :param level: logging level :return: logger instance
625941f2cb5e8a47e48b8067
def nextPermutation(a): <NEW_LINE> <INDENT> i = len(a)-1 <NEW_LINE> while(i > 0 and a[i] <= a[i-1]): <NEW_LINE> <INDENT> i -= 1 <NEW_LINE> <DEDENT> print(i) <NEW_LINE> i -= 1 <NEW_LINE> if i < 0: <NEW_LINE> <INDENT> a.reverse() <NEW_LINE> return None <NEW_LINE> <DEDENT> j = len(a)-1 <NEW_LINE> while(j > 0 and a[j] <= a...
Does not return anything, modifies nums in-place instead.
625941f2d7e4931a7ee9e4e6
def _cdrepo(self, cmdp): <NEW_LINE> <INDENT> topdir = cmdp.get("P1") <NEW_LINE> if cmdp.missing_options(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not FileUtil(topdir).isdir(): <NEW_LINE> <INDENT> Msg().out("Warning: localrepo directory is invalid: ", topdir, l=Msg.WAR) <NEW_LINE> return False <NEW_LINE...
Select the top directory of a local repository
625941f276e4537e8c351c3f
def isCompleteTree(self, root): <NEW_LINE> <INDENT> q = [root] <NEW_LINE> while q[0] != None: <NEW_LINE> <INDENT> cur = q.pop(0) <NEW_LINE> q.append(cur.left) <NEW_LINE> q.append(cur.right) <NEW_LINE> <DEDENT> while q != []: <NEW_LINE> <INDENT> if q.pop(0) != None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <...
:type root: TreeNode :rtype: bool
625941f2090684286d50f2b6
def number_of_lines(filename=""): <NEW_LINE> <INDENT> x = 0 <NEW_LINE> with open(filename, 'r', encoding="utf-8") as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> x += 1 <NEW_LINE> <DEDENT> <DEDENT> return x
Read from a file and nmbr of lines Exception: File opened filename: filename
625941f2be8e80087fb211ff
def system_provenance_file_path(): <NEW_LINE> <INDENT> if _simulator is None: <NEW_LINE> <INDENT> if __unittest_mode: <NEW_LINE> <INDENT> return _temp_dir() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise SimulatorNotSetupException( "system_provenance_file_path not supported before sim.setup.") <NEW_LINE> <DEDENT> ...
Returns the path to the directory that holds all provenance files This will be the path used by the last run call or to be used by the next run if it has not yet been called. ..note: In unittest mode this returns a tempdir shared by all path methods :rtpye: str :raises SimulatorNotSetupException: If the simulato...
625941f215fb5d323cde10e0
def test_revert_unchanged(self): <NEW_LINE> <INDENT> with mock_p4() as mock: <NEW_LINE> <INDENT> mock.add_changelist('test_changelist', ('/p4/file_1', 'rev 1'), ('/p4/file_2', 'rev 1')) <NEW_LINE> self._p4.sync() <NEW_LINE> changelist = self._p4.get_or_create_changelist('test changelist') <NEW_LINE> self._p4.edit(chan...
should rever only files in specified changelist that have not changed
625941f29c8ee82313fbbd3e
def restart(self, cmd): <NEW_LINE> <INDENT> self._clear() <NEW_LINE> self.moveRoom('_init')
Restart the game. Starts in the room named _init.
625941f2a05bb46b383ecde3
def divStrip(self,divId): <NEW_LINE> <INDENT> def popUnderScore(inDiv): <NEW_LINE> <INDENT> if inDiv[0] == '_': <NEW_LINE> <INDENT> splitDiv = inDiv.split('_') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return inDiv <NEW_LINE> <DEDENT> toReturn = ''.join(splitDiv[1:]) <NEW_LINE> if toReturn[0]=='_': <NEW_LINE> <INDE...
cleans divId to ensure html complient divId is set
625941f2b57a9660fec33e53
def random_forward(self, xin_dist, compute_loss=True, aggregate_fn=None, S=5, k=5, T=3): <NEW_LINE> <INDENT> if self.L > 1: <NEW_LINE> <INDENT> raise NotImplementedError('Projections not implemented for > 1 layer') <NEW_LINE> <DEDENT> xin = xin_dist.bernoulli() <NEW_LINE> q_samples_T, q_samplers_T, _, _ = self.inferenc...
Performs random projections and provides a loss computed using random projections
625941f238b623060ff0b3b4
def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False): <NEW_LINE> <INDENT> n = n if n is not None else 15 <NEW_LINE> if subs and is_sequence(subs): <NEW_LINE> <INDENT> raise TypeError('subs must be given as a dictionary') <NEW_LINE> <DEDENT> if n == 1 and isinstance(self, C.Numb...
Evaluate the given formula to an accuracy of n digits. Optional keyword arguments: subs=<dict> Substitute numerical values for symbols, e.g. subs={x:3, y:1+pi}. The substitutions must be given as a dictionary. maxn=<integer> Allow a maximum temporary working precision of maxn d...
625941f2293b9510aa2c3857
def plot_link_load_vs_topology( resultset, alpha, cache_size, topology_range, strategies, plotdir ): <NEW_LINE> <INDENT> desc = {} <NEW_LINE> desc["title"] = "Internal link load: A={} C={}".format(alpha, cache_size) <NEW_LINE> desc["ylabel"] = "Internal link load" <NEW_LINE> desc["xparam"] = ("topology", "name") <NEW_L...
Plot bar graphs of link load for specific values of alpha and cache size for various topologies. The objective here is to show that our algorithms works well on all topologies considered
625941f2be383301e01b5a41
def _generate_scenario(self, test_name, **kwargs): <NEW_LINE> <INDENT> if "estimator_class" in kwargs.keys(): <NEW_LINE> <INDENT> obj = kwargs["estimator_class"] <NEW_LINE> <DEDENT> elif "estimator_instance" in kwargs.keys(): <NEW_LINE> <INDENT> obj = kwargs["estimator_instance"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <I...
Return estimator test scenario. Fixtures parameterized ---------------------- scenario: instance of TestScenario ranges over all scenarios returned by retrieve_scenarios
625941f20383005118ecfba7
def remove_duplicates(list1): <NEW_LINE> <INDENT> tample = [float('inf')] <NEW_LINE> for elem in list1: <NEW_LINE> <INDENT> if elem in tample: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> tample.append(elem) <NEW_LINE> <DEDENT> return tample[1:]
Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative.
625941f22c8b7c6e89b35d83
def _get_route_selection_options(self): <NEW_LINE> <INDENT> return self.__route_selection_options
Getter method for route_selection_options, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/route_selection_options (container) YANG Description: Parameters relating to options for route selection
625941f25510c4643540f99c
def clean_reveal_identity(self): <NEW_LINE> <INDENT> value = self.cleaned_data['reveal_identity'] <NEW_LINE> if self.question.is_anonymous: <NEW_LINE> <INDENT> if value == True: <NEW_LINE> <INDENT> if self.user.is_owner_of(self.question): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sel...
cleans the reveal_identity field which determines whether previous anonymous edits must be rewritten as not anonymous this does not necessarily mean that the edit will be anonymous only does real work when question is anonymous based on the following truth table: is_anon can owner checked cleaned data - * ...
625941f2009cb60464c63974
def _connect(self): <NEW_LINE> <INDENT> self.ssh = pxssh.pxssh() <NEW_LINE> try: <NEW_LINE> <INDENT> self.ssh.login( self.host, self.username, password=self.password, port=self.port ) <NEW_LINE> self.connected = True <NEW_LINE> <DEDENT> except exceptions.EOF: <NEW_LINE> <INDENT> _LOGGER.error("Connection refused. SSH e...
Connect to the Unifi AP SSH server.
625941f20c0af96317bb87ae
def parse_conf(file_path): <NEW_LINE> <INDENT> conf_raw = open(file_path, "r").read() <NEW_LINE> return json.loads(conf_raw)
Returns a JSON representation of the configuration file whose path is given as argument
625941f230dc7b7665901f26
def showConstantReactants(self): <NEW_LINE> <INDENT> if len(self._constantReactants) == 0: <NEW_LINE> <INDENT> print('No constant reactants in the model!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for reactant in self._constantReactants: <NEW_LINE> <INDENT> out = self._ratesLaTeX[repr(reactant)] <NEW_LINE> out = u...
Show a sorted LaTeX representation of the model's constant reactants. Displays the LaTeX representation in the Jupyter Notebook if there are constant reactants in the model, otherwise prints an error. Returns ------- `None`
625941f230dc7b7665901f27
def getWkt(self): <NEW_LINE> <INDENT> gssha_pro_card = self.getCard("#PROJECTION_FILE") <NEW_LINE> if gssha_pro_card is None: <NEW_LINE> <INDENT> raise ValueError("#PROJECTION_FILE card not found ...") <NEW_LINE> <DEDENT> with tmp_chdir(self.project_directory): <NEW_LINE> <INDENT> gssha_prj_file = gssha_pro_card.value....
Returns GSSHA projection WKT string
625941f2b7558d58953c54ce
def readable_timedelta(days): <NEW_LINE> <INDENT> weeks = days // 7 <NEW_LINE> remainder = days % 7 <NEW_LINE> return "{} week(s) and {} day(s)".format(weeks, remainder)
Converts days to Weeks + Days :param days: int :return: weeks and remainder days
625941f20fa83653e465757e
def test_invalid_args(self): <NEW_LINE> <INDENT> self.call_cot(['remove-file', self.input_ovf, '-o', self.temp_file, '--file-path', 'input.vmdk', '--file-id', 'file2'], result=2) <NEW_LINE> self.call_cot(['remove-file', self.input_ovf, '-o', self.temp_file, '--file-id', 'file1', '--file-path', 'foo.bar'], result=2) <NE...
Invalid combinations of arguments.
625941f24f88993c3716c628
@app.before_request <NEW_LINE> def before_request(): <NEW_LINE> <INDENT> g.db = models.db <NEW_LINE> g.db.get_conn() <NEW_LINE> g.user = current_user
Connect to the database before each request.
625941f221a7993f00bc82c2
def terminal_can_color(self): <NEW_LINE> <INDENT> term_debug = False <NEW_LINE> if self.verbose > 3: <NEW_LINE> <INDENT> term_debug = True <NEW_LINE> <DEDENT> return terminal_can_colors(debug=term_debug)
Method to detect, whether the current terminal (stdout and stderr) is able to perform ANSI color sequences. @return: both stdout and stderr can perform ANSI color sequences @rtype: bool
625941f2ad47b63b2c50a547
def TOOL_SUBST(env): <NEW_LINE> <INDENT> env.Append(TOOLS = 'SUBST') <NEW_LINE> def do_subst_in_file(targetfile, sourcefile, dict): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(sourcefile, 'rb') <NEW_LINE> contents = f.read() <NEW_LINE> f.close() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise SCons.Erro...
Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT from the source to the target. The values of SUBST_DICT first have any construction variables expanded (its keys are not expanded). If a value of SUBST_DICT is a python callable function, it is called and the result is expanded as the value. If ...
625941f27cff6e4e81117f4d
def API_request(argv): <NEW_LINE> <INDENT> todo = "https://jsonplaceholder.typicode.com/todos/?userId=" + str(argv[1]) <NEW_LINE> users = "https://jsonplaceholder.typicode.com/users/" + str(argv[1]) <NEW_LINE> responset = requests.get(todo) <NEW_LINE> responseu = requests.get(users) <NEW_LINE> json_t = responset.json()...
script to export data in the CSV format
625941f2fb3f5b602dac3c61
def _pick_random_points(self, length, size): <NEW_LINE> <INDENT> r1 = np.empty((size,3), dtype='float64') <NEW_LINE> for dim in range(3): <NEW_LINE> <INDENT> r1[:,dim] = self.mt.uniform(low=self.ds.left_edge[dim], high=self.ds.right_edge[dim], size=size) <NEW_LINE> <DEDENT> if self.constant_phi is None: <NEW_LINE> <IND...
Picks out size random pairs separated by length *length*.
625941f215baa723493c4542
def setup_figure(self): <NEW_LINE> <INDENT> self.log.info("Empty setup_figure called") <NEW_LINE> pass
Override setup_figure to build graphical interfaces. This function is run on ScopeFoundry startup.
625941f2627d3e7fe0d69419
def extended_storkey_update(sample, weights): <NEW_LINE> <INDENT> scale = 1 / int(weights.get_shape()[0]) <NEW_LINE> numerics = 2*tf.cast(sample, weights.dtype) - 1 <NEW_LINE> row_sample = tf.expand_dims(numerics, axis=0) <NEW_LINE> row_h = tf.matmul(row_sample, weights) <NEW_LINE> pos_term = (tf.matmul(tf.transpose(ro...
Create an Op that performs a step of the Extended Storkey Learning Rule. Args: sample: a 1-D sample Tensor of dtype tf.bool. weights: the weight matrix to update. Returns: An Op that updates the weights based on the sample.
625941f250812a4eaa59c8e2
def EquilibriumDenoising(p_former, class_num): <NEW_LINE> <INDENT> p = p_former + r'\\' + r'ICT DataSet\Label_%s.txt' % class_num <NEW_LINE> with open(p, 'r') as file: <NEW_LINE> <INDENT> print('正在处理第%s个模型数据' % class_num) <NEW_LINE> tru_data = np.loadtxt(file, delimiter=',', skiprows=0)[:1000000, :] <NEW_LINE> data_fra...
对数据进行均衡截取、去噪 :param p_former: 数据目录前缀 :param class_num: 需要处理的模式类别 :return: 经过均衡化、去噪后的数据集
625941f297e22403b379d563
def kernelDriverActive(self, interface): <NEW_LINE> <INDENT> result = libusb1.libusb_kernel_driver_active(self.__handle, interface) <NEW_LINE> if result == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif result == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> raiseUSBError(result)
Tell whether a kernel driver is active on given interface number.
625941f23cc13d1c6d3c793e
def __iter__(self): <NEW_LINE> <INDENT> yield ItemList(list(self.subject))
Override this method to provide custom partitioning
625941f23cc13d1c6d3c793f
def __preGetMntGrp(self): <NEW_LINE> <INDENT> self.__selection.resetMntGrp()
update method for mntGrp attribute
625941f2091ae3566866751c
def test_process_ignore_no_data(self): <NEW_LINE> <INDENT> self.mock_out.readline.side_effect = [ '@F 12320 502 321.83 13.11', '@F 12321 501 321.85 13.09', '@F 12322 500 321.88 13.06', '@P 0', "[coreaudio.c:81] warning: Didn't have any audio data in callback" "(buffer underflow)", "[coreaudio.c:81] warning: Didn't have...
processing mpg123 output ignores coreaudio warning about no data
625941f201c39578d7e75403
def tobogganPath(hillMap, xValue, yValue): <NEW_LINE> <INDENT> hillLines = [] <NEW_LINE> trees = 0 <NEW_LINE> xPosition = 0 <NEW_LINE> yPosition = 0 <NEW_LINE> for line in hillMap: <NEW_LINE> <INDENT> hillLines.append(line[:len(line)-1]) <NEW_LINE> <DEDENT> while xPosition != len(hillLines): <NEW_LINE> <INDENT> try: <N...
Tree-checking function of the Day 3 puzzle. :param hillMap: The content of the Day3HillsAndTrees.txt file. :param xValue: Your lateral movement. :param yValue: Your vertical movement.
625941f221a7993f00bc82c3
def urquhart_graph(X, weighted=False): <NEW_LINE> <INDENT> e1, e2 = _delaunay_edges(X) <NEW_LINE> w = paired_distances(X[e1], X[e2]) <NEW_LINE> mask = np.ones_like(w, dtype=bool) <NEW_LINE> bad_inds = w.reshape((-1, 3)).argmax(axis=1) + np.arange(0, len(e1), 3) <NEW_LINE> mask[bad_inds] = False <NEW_LINE> weights = w[m...
Urquhart graph: made from the 2 shortest edges of each Delaunay triangle.
625941f2462c4b4f79d1dc97
def set_expose(self, expose): <NEW_LINE> <INDENT> if expose: <NEW_LINE> <INDENT> self.__pages_manager.update_sort(True) <NEW_LINE> self.__pages_manager.set_filtered(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__window.toolbar.actions.view_button.set_active(False) <NEW_LINE> self.__window.container.pages_ma...
Show current views @param expose as bool
625941f21d351010ab8560e2
def testCommentNextWithQueryStringAndAnchor(self): <NEW_LINE> <INDENT> a = Article.objects.get(pk=1) <NEW_LINE> data = self.getValidData(a) <NEW_LINE> data["next"] = "/somewhere/else/?foo=bar#baz" <NEW_LINE> data["comment"] = "This is another comment" <NEW_LINE> response = self.client.post("/post/", data) <NEW_LINE> lo...
The `next` key needs to handle already having an anchor. Refs #13411.
625941f2d18da76e23532aa5
def test_name_must_be_captalized(self): <NEW_LINE> <INDENT> form = self.make_validated_form(name="MORENO cunha") <NEW_LINE> self.assertEqual('Moreno Cunha', form.cleaned_data['name'])
Name must be capitalized.
625941f2bde94217f36833b3
def tick(): <NEW_LINE> <INDENT> global timer <NEW_LINE> wtime.config(text="Time : %s" % str(timer)) <NEW_LINE> if timer == 0: <NEW_LINE> <INDENT> wrong() <NEW_LINE> <DEDENT> elif isinstance(timer, int): <NEW_LINE> <INDENT> timer -= 1 <NEW_LINE> wtime.after(1000, tick)
Count timer.
625941f2f9cc0f698b140bbe
def test_existance_of_no_single_bucket_list_item(self): <NEW_LINE> <INDENT> user = User(username='Joe', password='12345') <NEW_LINE> db.session.add(user) <NEW_LINE> db.session.commit() <NEW_LINE> response = self.request( 'GET', url_for('list_item', id=1, item_id=1), auth=('Joe', '12345')) <NEW_LINE> self.assertEqual(re...
tests that there exists no single bucket-list-item
625941f2236d856c2ad44dab
def read_obj(self, path): <NEW_LINE> <INDENT> objModels = [] <NEW_LINE> objModel = ObjModel() <NEW_LINE> file = open(path, 'r') <NEW_LINE> for line in file: <NEW_LINE> <INDENT> if line.startswith('o'): <NEW_LINE> <INDENT> data = line.split(' ') <NEW_LINE> if len(data) == 2: <NEW_LINE> <INDENT> self.add_obj_to_list(objM...
Read path obj 3d model into a list of ObjModel objects
625941f2e1aae11d1e74a285
def aStarSearch(problem, heuristic=nullHeuristic): <NEW_LINE> <INDENT> closed = set() <NEW_LINE> fringe = util.PriorityQueue() <NEW_LINE> fringe.push((problem.getStartState(), [], 0), 0) <NEW_LINE> while not fringe.isEmpty(): <NEW_LINE> <INDENT> elem = fringe.pop() <NEW_LINE> if problem.isGoalState(elem[0]): <NEW_LINE>...
Search the node that has the lowest combined cost and heuristic first.
625941f27b180e01f3dc4db8
def create_organization_class_ex(self, request, runtime): <NEW_LINE> <INDENT> UtilClient.validate_model(request) <NEW_LINE> return _ebc_models.CreateOrganizationClassResponse().from_map(self.do_request("baas.ebc.organization.class.create", "HTTPS", "POST", "/gateway.do", request.to_map(), runtime))
Description: 创建班级 Summary: 创建班级
625941f2d58c6744b4258225
def _set_color(self, c): <NEW_LINE> <INDENT> assert c is None or isinstance( c, Color), "The object passed is not a Color object." <NEW_LINE> self._color = c
Sets the color of the GraphicsObject.
625941f2004d5f362079a8f6
def showSettingsMenu(self): <NEW_LINE> <INDENT> menu = studioqt.Menu(self) <NEW_LINE> self.settingsMenuRequested.emit(menu) <NEW_LINE> self.createSettingsMenu(menu) <NEW_LINE> point = QtGui.QCursor.pos() <NEW_LINE> point.setX(point.x() + 3) <NEW_LINE> point.setY(point.y() + 3) <NEW_LINE> action = menu.exec_(point) <NEW...
Create and show a new settings menu instance.
625941f2f7d966606f6aa5d3
def __init__(self, modifier, folder): <NEW_LINE> <INDENT> if folder != '' and not folder.endswith("/"): <NEW_LINE> <INDENT> folder += "/" <NEW_LINE> <DEDENT> if modifier != '' and not modifier.startswith("_"): <NEW_LINE> <INDENT> modifier = "_" + modifier <NEW_LINE> <DEDENT> self.modifier=modifier <NEW_LINE> self.folde...
modifier: the modifier of the data set folder: the folder of this data set
625941f230c21e258bdfaa6c
def list_uk8s_cluster_v2( self, req: typing.Optional[dict] = None, **kwargs ) -> dict: <NEW_LINE> <INDENT> d = { "ProjectId": self.config.project_id, "Region": self.config.region, } <NEW_LINE> req and d.update(req) <NEW_LINE> d = apis.ListUK8SClusterV2RequestSchema().dumps(d) <NEW_LINE> resp = self.invoke("ListUK8SClus...
ListUK8SClusterV2 - 获取UK8S集群列表信息 **Request** - **ProjectId** (str) - (Config) 项目ID。不填写为默认项目,子帐号必须填写。 请参考 `GetProjectList接口 <https://docs.ucloud.cn/api/summary/get_project_list>`_ - **Region** (str) - (Config) 地域。 参见 `地域和可用区列表 <https://docs.ucloud.cn/api/summary/regionlist>`_ - **ClusterId** (str) - UK8S集群ID - **Limi...
625941f2187af65679ca56e8
def climbStairs2(self, n: int) -> int: <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> dp = [1, 1] <NEW_LINE> for i in range(2, n+1): <NEW_LINE> <INDENT> dp.append(dp[i-1] + dp[i-2]) <NEW_LINE> <DEDENT> return dp[-1]
这里的处理更加简洁易懂,相比于上面方法
625941f2dc8b845886cb5aff
def retrievedata(self, source): <NEW_LINE> <INDENT> self._option = ('-j -G1 -struct').split() <NEW_LINE> resultcode = self.run_cmd(source) <NEW_LINE> return resultcode
Retrieving metadata, the data are stored in this class
625941f2d18da76e23532aa6
def start(self) -> Any: <NEW_LINE> <INDENT> raise NotImplementedError(f"Please implement {type(self).__name__}.start")
How the parse should start parsing the query string :return: The parse result
625941f2cc0a2c11143dd45a
def __addKnownUserProxiesInfo(self, retDict): <NEW_LINE> <INDENT> retDict['proxies'] = self.__generateUserProxiesInfo() <NEW_LINE> return retDict
Given a S_OK/S_ERR add a proxies entry with info of all the proxies a user has uploaded
625941f24e696a04525c9a16
def test(self): <NEW_LINE> <INDENT> pair_orig = deepcopy(self.pair) <NEW_LINE> pair_type = filter_read_pair(self.pair, self.ref, match_len_min=3) <NEW_LINE> self.assertEqual(pair_type, 'good') <NEW_LINE> self.assertEqual(self.pair, pair_orig)
Test match only pairs
625941f291f36d47f21acac1
def two_qubit_reduced_operator(self, m, threshold=10**-13): <NEW_LINE> <INDENT> if self._paulis is None or self._paulis == []: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> operator_out = Operator(paulis=[]) <NEW_LINE> par_1 = 1 if m % 2 == 0 else -1 <NEW_LINE> par_2 = 1 if m % 4 == 0 else -1 <NEW_LINE> n = len(s...
Eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped fermionic Hamiltonians when the spin orbitals are ordered in two spin sectors, (block spin order) according to the...
625941f25fdd1c0f98dc07fd