code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def levelOrder(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> q = [root] <NEW_LINE> res = [] <NEW_LINE> while q: <NEW_LINE> <INDENT> next_q = [] <NEW_LINE> tmp = [] <NEW_LINE> for node in q: <NEW_LINE> <INDENT> tmp.append(node.val) <NEW_LINE> if node.left: <NEW_LINE> <IN...
:type root: TreeNode :rtype: List[List[int]]
625941f7b57a9660fec33ef9
def to_public_png(npy_blob: storage.Blob, public_bucket: storage.Bucket): <NEW_LINE> <INDENT> npy_filepath = f'/tmp/{npy_blob.name.split("/")[-1]}' <NEW_LINE> npy_blob.download_to_filename(npy_filepath) <NEW_LINE> arr = np.load(npy_filepath) <NEW_LINE> png_filepath = npy_filepath.replace('.npy', '.png') <NEW_LINE> plt....
Converts a .npy blob into a png file and uploads it to the public bucket. :param npy_blob: :param public_bucket: :return:
625941f74e696a04525c9aba
def substitute( inFile, outFile, str1, str2 ): <NEW_LINE> <INDENT> logger.debug("Writing " + inFile + " to " + outFile + " while replacing " + str1 + " with " + str2 ) <NEW_LINE> o = open( outFile, "w" ) <NEW_LINE> data = open( inFile ).read() <NEW_LINE> o.write( re.sub( str1, str2, data ) ) <NEW_LINE> o.close()
Write the contents of inFile to outFile with each instance of str1 replaced with str2. :param string inFile: input file :param string outFile: output file :param string str1: string to be replaced :param string str2: replacement string
625941f75fdd1c0f98dc08a2
def process_log_line(ses, bucket, target_directory, temp_directory, message): <NEW_LINE> <INDENT> task_id = message["task_id"] <NEW_LINE> if not task_id: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> stdout_path = os.path.join(temp_directory, task_id + ".txt") <NEW_LINE> if message["type"] == "close": <NEW_LINE> <INDE...
Processes a log line from AMQP.
625941f7a4f1c619b28b0694
def optimize_acktr(trial): <NEW_LINE> <INDENT> return { 'n_steps': trial.suggest_int('n_steps', 3, 100), 'gamma': trial.suggest_loguniform('gamma', 0.8, 0.9999), 'vf_coef': trial.suggest_loguniform('vf_coef', 0.1, 0.6), 'ent_coef': trial.suggest_loguniform('ent_coef', 0.001, 0.07), 'max_grad_norm': trial.suggest_loguni...
Learning hyperparamters we want to optimise
625941f7d268445f265b54db
def process_indirection(self,instr: Instr,ov: Overload,inds: Sequence[int]) -> Tuple[Instr,Overload]: <NEW_LINE> <INDENT> raise NotImplementedError()
Remove instances of IndirectVar. The return value is equivalent to the input parameters, except each argument indexed by "inds" (all of which will be instances of IndirectVar) is replaced with one or more of its component instances of Var, and "instr.op" and "ov" are replaced by equivalent instances of RegAllocatorOve...
625941f76aa9bd52df037414
def __len__(self): <NEW_LINE> <INDENT> return len(self.image_file_paths)
This simple returns the length of the dataset. Essential for iterating the dataset. :return: Length of the dataset.
625941f785dfad0860c3b4c9
def mapToCSC(mat): <NEW_LINE> <INDENT> if 'csc' in mat: <NEW_LINE> <INDENT> row_idx = mat['csc'][IROW] <NEW_LINE> col_p = mat['csc'][ICOL] <NEW_LINE> idx_data = numpy.s_[:] <NEW_LINE> return row_idx, col_p, idx_data <NEW_LINE> <DEDENT> num_rows = mat['shape'][0] <NEW_LINE> num_cols = mat['shape'][1] <NEW_LINE> if 'csr'...
Given a pyoptsparse matrix definition, return a tuple containing a map of the matrix to the CSC format. Parameters ---------- mat : dict A sparse matrix representation. Returns ------- tup : tuple of numpy arrays tup[0] : numpy array (size=nnz) An array that holds the row index of each element in the C...
625941f7167d2b6e31219200
def test_input_var_names(ls_prob): <NEW_LINE> <INDENT> assert sorted(ls_prob.input_var_names) == [ "soil__density", "soil__internal_friction_angle", "soil__maximum_total_cohesion", "soil__minimum_total_cohesion", "soil__mode_total_cohesion", "soil__saturated_hydraulic_conductivity", "soil__thickness", "soil__transmissi...
Testing if the input_var_names outputs the right list.
625941f776d4e153a657f19e
def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False): <NEW_LINE> <INDENT> items = self.get_items(name, label, id, exclude_disabled) <NEW_LINE> return disambiguate(items, nr, name=name, label=label, id=id)
Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of 'name', which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-...
625941f74f6381625f1150a7
def test_check_files(request, compliance_vm, analysis_profile, condition_collection, policy_collection, policy_profile_collection): <NEW_LINE> <INDENT> check_file_name = "/etc/hosts" <NEW_LINE> check_file_contents = "127.0.0.1" <NEW_LINE> condition = condition_collection.create( VMCondition, "Compliance testing conditi...
This test checks presence and contents of a certain file. Due to caching, an existing file is checked.
625941f7d18da76e23532b4b
def __process_usr_action(self, usr_action): <NEW_LINE> <INDENT> user_nlg_sentence = self.nlg_model.convert_diaact_to_nl(usr_action, const.USR_SPEAKER_VAL) <NEW_LINE> usr_action[const.NL_KEY] = user_nlg_sentence <NEW_LINE> if self.simulation_mode == const.NL_SIMULATION_MODE: <NEW_LINE> <INDENT> user_nlu_res = self.nlu_m...
Private helper method for processing the user action. :param usr_action: the user action to be processed :return: processed user action
625941f7099cdd3c635f12c4
def make_client(service_name, tracing_endpoint=None, tracing_queue_name=None, max_span_queue_size=50000, num_span_workers=5, span_batch_interval=0.5, num_conns=100, sample_rate=0.1, log_if_unconfigured=True): <NEW_LINE> <INDENT> if tracing_queue_name: <NEW_LINE> <INDENT> logger.info("Recording spans to queue %s", traci...
Create and return a tracing client based on configuration options. This client can be used by the :py:class:`TraceBaseplateObserver`. :param str service_name: The name for the service this observer is registered to. :param baseplate.config.EndpointConfiguration tracing_endpoint: destination to record span dat...
625941f7a05bb46b383ece87
def mitigate(self): <NEW_LINE> <INDENT> access_key = self.compromised_access_key_id <NEW_LINE> compromised_resource = compromised.CompromisedMetadata( compromised_object_inventory={ 'access_key_id': access_key, 'region': self.region }, case_number=self.case.case_number, type_of_compromise='key_compromise' ).data() <NEW...
Any steps that run as part of key compromises.
625941f763b5f9789fde7752
def run_authenticated(user, command, quiet=False, timeout=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with api.spawn(command, quiet, timeout) as child: <NEW_LINE> <INDENT> match = child.expect([ "Enter passphrase for key", "Password for", pexpect.EOF ]) <NEW_LINE> if match == 0: <NEW_LINE> <INDENT> child.sendli...
Run a command as a authenticated user. Returns command output.
625941f744b2445a339326fd
def players(self) -> Iterable[str]: <NEW_LINE> <INDENT> return [p.stem for p in (self._folder / "playerdata").glob("*.dat")]
Return a list of player's UUIDs.
625941f7566aa707497f4bcb
def get_summary(predict_labels, true_labels): <NEW_LINE> <INDENT> true_labels.index = range(true_labels.shape[0]) <NEW_LINE> result = pd.concat([predict_labels, pd.DataFrame(true_labels)], axis=1) <NEW_LINE> result.columns = ['predict_strain', 'true_strain'] <NEW_LINE> prediction_accurate_count_matrix = pd.crosstab(ind...
Returns a DataFrame of classification result summary, including precision, recall, F1 measure in terms of different strains. Parameters ---------- predict_labels: pandas.DataFrame prediction strain labels true_labels: pandas.Series true strain labels, used to measure the prediction ...
625941f7d6c5a102081446bc
def index_sorted(queryset): <NEW_LINE> <INDENT> score_to_index = dict() <NEW_LINE> i = 1 <NEW_LINE> for L in queryset: <NEW_LINE> <INDENT> score_to_index[L['score_sum']] = i <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> return score_to_index
获取积分与排名的对应关系 :param queryset :return: score_to_index
625941f78e71fb1e9831de12
def is_ready(self) -> bool: <NEW_LINE> <INDENT> self.refresh() <NEW_LINE> status = self.obj.status <NEW_LINE> if status is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> total = status.replicas <NEW_LINE> ready = status.ready_replicas <NEW_LINE> if total is None: <NEW_LINE> <INDENT> return False <NEW_LINE> ...
Check if the StatefulSet is in the ready state. Returns: True if in the ready state; False otherwise.
625941f7e5267d203edce301
def _log(what, args, verbosity, alt=None, stream=sys.stderr): <NEW_LINE> <INDENT> if args.verbose >= verbosity: <NEW_LINE> <INDENT> print(what, file=stream) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if alt is not None: <NEW_LINE> <INDENT> print(alt, file=stream)
Print to stream if args.verbose >= verbosity Args: what: The line to print args: The command line arguments verbosity: Minimum verbosity to display the message alt: What to print if verbosity check fails (default: None) stream: Output stream (default: sys.stderr)
625941f7cc0a2c11143dd4fe
def streamToMidiFile(inputM21): <NEW_LINE> <INDENT> s = inputM21 <NEW_LINE> midiTracks = s._getMidiTracks() <NEW_LINE> for i in range(len(midiTracks)): <NEW_LINE> <INDENT> midiTracks[i].index = i + 1 <NEW_LINE> <DEDENT> mf = midiModule.MidiFile() <NEW_LINE> mf.tracks = midiTracks <NEW_LINE> mf.ticksPerQuarterNote = def...
>>> from music21 import * >>> s = stream.Stream() >>> n = note.Note('g#') >>> n.quarterLength = .5 >>> s.repeatAppend(n, 4) >>> mf = streamToMidiFile(s) >>> len(mf.tracks) 1 >>> len(mf.tracks[0].events) 20
625941f71f037a2d8b946868
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(TransportNNDistanceComputerTestCase, self).__init__(*args, **kwargs) <NEW_LINE> self.non_assignment_penalty = 1 <NEW_LINE> cnn_layer_labels, label_mismatch_penalty = nn_comparators.get_cnn_layer_label_mismatch_penalties(self.non_assignment_penalty) <NE...
Constructor.
625941f7091ae356686675bf
def add_fit_param(self, **argv): <NEW_LINE> <INDENT> if 'name' in argv.keys(): <NEW_LINE> <INDENT> name = argv['name'] <NEW_LINE> <DEDENT> elif 'param' in argv.keys(): <NEW_LINE> <INDENT> name = argv['param'].name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("You must provide either a parameter name o...
Add a fitting parameter to the list. Args: param (:class:`Fit_param`): A Fit_param object to add to the list name (str): name of the parameter, required if param object not passed units (str): units in which parameter is measured (defaults to 'unitless') tolerance (float): smallest difference between t...
625941f723849d37ff7b36f6
def test_HiResFile(self): <NEW_LINE> <INDENT> FIRE_L0_L1.HiResFile(os.path.join('test_data', 'HiResData.csv'), self.tmpfile) <NEW_LINE> self.assertTrue(os.path.isfile(self.tmpfile)) <NEW_LINE> with open(self.tmpfile, 'r') as fp: <NEW_LINE> <INDENT> dat = fp.readlines() <NEW_LINE> self.assertEqual('#{', dat[0][0:2]) <NE...
a hi-res file shold read in and write out
625941f730c21e258bdfab11
def push(self, element): <NEW_LINE> <INDENT> new = self.Node(val=element) <NEW_LINE> new.next = self.head <NEW_LINE> self.head = new
Pushed element to the top of the stack. Time complexity: O(1).
625941f7925a0f43d254a4ea
def convert_Vs30_to_Z10(Vs30): <NEW_LINE> <INDENT> return math.exp(28.5 - Ch_3_82_div_8*math.log(math.pow(Vs30, 8) + Ch_378_7_pow_8))
Convert a Vs30 value to an estimated V1.0 value. This function will handle both scalar and scipy array values of Z10. Formula taken from equation (1) of: Chiou.B.S.-J., Youngs R.R., 2008 An NGA Model for the Average Horizontal Component of Peak Ground Motion and Response Spectra, Earthquake Spectra 24, 173-215.
625941f7d10714528d600358
def on_pvtmsg(self, user, msg): <NEW_LINE> <INDENT> self.console.write('[PM] %s: %s' % (user.nick, msg.text), Color.WHITE)
Received when a user sends the client a private message. :param user: The user sending a private message as User object. :type user: Users.User :param msg: The text message as TextMessage object. :type msg: TextMessage
625941f70fa83653e4657623
def build_tuple_unpack_with_call(self, instr): <NEW_LINE> <INDENT> raise NotImplementedError
This is similar to BUILD_TUPLE_UNPACK, but is used for f(*x, *y, *z) call syntax. The stack item at position count + 1 should be the corresponding callable f.
625941f721bff66bcd684fb9
def begin_list_routes_table_summary( self, resource_group_name, circuit_name, peering_name, device_path, **kwargs ): <NEW_LINE> <INDENT> polling = kwargs.pop('polling', True) <NEW_LINE> cls = kwargs.pop('cls', None) <NEW_LINE> lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) <NEW_LINE> cont_t...
Gets the currently advertised routes table summary associated with the express route circuit in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param circuit_name: The name of the express route circuit. :type circuit_name: str :param peering_name: The name ...
625941f7adb09d7d5db6cdf8
def getAccountPassword(self, multiAccntLabel, accountName, resource=None): <NEW_LINE> <INDENT> if resource: <NEW_LINE> <INDENT> if not isinstance(resource, list): <NEW_LINE> <INDENT> resources = [resource] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> resources = resource <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <...
:param multiAccntLabel: the label associated with the multi account :type multiAccntLabel: str :param accountName: the name of the account who's secrets we want to retrieve :type accountName: str :param resource: the resource in pmp that contains the secrets for the accountName :typ...
625941f7dc8b845886cb5ba3
def fetch_all_topics(self, workers: int) -> None: <NEW_LINE> <INDENT> with ThreadPoolExecutor(max_workers=workers) as executor: <NEW_LINE> <INDENT> list_of_streams = list(self.stream_dict.keys()) <NEW_LINE> thread_objects = { i: executor.submit(self.get_topics_in_stream, list_of_streams[i::workers]) for i in range(work...
Distribute stream ids across threads in order to fetch topics concurrently.
625941f7460517430c3947df
def serialize(func): <NEW_LINE> <INDENT> def wrapped(instance, req, resp, **kwargs): <NEW_LINE> <INDENT> assert not req.get_param("unicode") or req.get_param("unicode") == u"?", "Unicode sanity check failed" <NEW_LINE> resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate"); <NEW_LINE> resp.set_header("...
Falcon response serialization
625941f763b5f9789fde7753
def handle_postback(event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query_payload = Payloads(event["postback"]["payload"].split("?=")[0]) <NEW_LINE> facebook_actions_dict[query_payload](event) <NEW_LINE> <DEDENT> except (KeyError, IndexError, TypeError, ValueError) as e: <NEW_LINE> <INDENT> bot_log("Handling of po...
Handles a postback due to a user interacting with the bot. :param event: JSON containing information about the interaction.
625941f7bde94217f3683457
def checksum(self, cmd, cltrid, **params): <NEW_LINE> <INDENT> password = hashlib.md5(self.password).hexdigest() <NEW_LINE> checksum = [self.client_id, password, cltrid, ONLINENIC_COMMANDS[cmd]['checksum']['name']] <NEW_LINE> if 'extra' in ONLINENIC_COMMANDS[cmd]['checksum']: <NEW_LINE> <INDENT> for k in ONLINENIC_COMM...
Generate the checksum for a command.
625941f74e4d5625662d4a3a
def is_component_equal(component1, component2, omit_features): <NEW_LINE> <INDENT> keys1 = component1.keys() <NEW_LINE> keys2 = component2.keys() <NEW_LINE> for feature in omit_features: <NEW_LINE> <INDENT> if feature in keys1: <NEW_LINE> <INDENT> keys1.remove(feature) <NEW_LINE> <DEDENT> if feature in keys2: <NEW_LINE...
Check if components are the same except features in omit_features.
625941f79f2886367277aef4
def append(self, subpart: str) -> "Path": <NEW_LINE> <INDENT> parts = self._path.split("/") + subpart.split("/") <NEW_LINE> i = 2 <NEW_LINE> while i < len(parts): <NEW_LINE> <INDENT> if parts[i] == "" or parts[i] == ".": <NEW_LINE> <INDENT> parts.pop(i) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <D...
Create a new Path that is the result of appending "subpart" to this Path. This does NOT use "posixpath.normpath" to normalize the resulting path in order to preserve relative paths. For example, normpath would translate "~/../a" to just "a", but we keep it like that to preserve the fact that it's relative, not absolut...
625941f7462c4b4f79d1dd3c
@http <NEW_LINE> @jsonview <NEW_LINE> @only_methods(['POST', ]) <NEW_LINE> def session_logout_v1_view(request): <NEW_LINE> <INDENT> uid, token = request.session['uid'], request.session['login_token'] <NEW_LINE> if uid is None or token is None: <NEW_LINE> <INDENT> return jsonreply(r=0) <NEW_LINE> <DEDENT> tokens.revoke_...
v1 注销接口. :Allow: POST :URL 格式: :wyurl:`api:session-logout-v1` :GET 参数: 无 :POST 参数: 无 :返回: :r: 常量 ``0`` :副作用: * 注销成功时: - 从会话中删去 UID - 刷新会话 ID - 销毁本次使用的登陆 token
625941f7b545ff76a8914482
def ctype_bytearray_from_literal(hexstring): <NEW_LINE> <INDENT> blen = len(hexstring) <NEW_LINE> buf = create_string_buffer(hexstring, blen) <NEW_LINE> cobj = (c_ubyte * blen).from_buffer_copy(buf) <NEW_LINE> return cobj
Load a ctype ubyte array from a string buffer
625941f7656771135c3ebee4
def test_circular_graph(self): <NEW_LINE> <INDENT> graph = MigrationGraph() <NEW_LINE> graph.add_node(("app_a", "0001"), None) <NEW_LINE> graph.add_node(("app_a", "0002"), None) <NEW_LINE> graph.add_node(("app_a", "0003"), None) <NEW_LINE> graph.add_node(("app_b", "0001"), None) <NEW_LINE> graph.add_node(("app_b", "000...
Tests a circular dependency graph.
625941f7de87d2750b860407
def main(): <NEW_LINE> <INDENT> lines = int(input()) <NEW_LINE> for _ in range(lines): <NEW_LINE> <INDENT> text = ''.join(input()) <NEW_LINE> print(tokenize(text))
THE MAIN FUNCTION HERE PASSES THE STRING TO THE FUCNTION
625941f7cc40096d61595fba
def step(self): <NEW_LINE> <INDENT> vectors = self._updateBehaviors() <NEW_LINE> if vectors == "STOP": <NEW_LINE> <INDENT> self.myRobot.stop() <NEW_LINE> transValue = 0 <NEW_LINE> angle = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (magnitude, angle) = self._vectorAdd(vectors) <NEW_LINE> transValue = magnitude <NEW...
one step means figuring out the vectors for each of the behaviors, and performing vector addition to combine them. Then the resulting vector is the action taken.
625941f78e7ae83300e4b63c
def prepare_image_type_choices() -> List[Tuple[str, str]]: <NEW_LINE> <INDENT> return [ ("Distribution only", "distribution"), ("Application only", "application"), ("All available images", "all"), ]
Returns image type choices for the prompt. :return: list of 2-len tuples
625941f726238365f5f0f4e4
def frame_to_nanosecond(frame, framerate): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = frame * Gst.SECOND * framerate.denominator / framerate.numerator <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> t = 0 <NEW_LINE> pass <NEW_LINE> <DEDENT> return t
Frame number to nano second convert
625941f707f4c71912b11af2
def vertex_count(self): <NEW_LINE> <INDENT> return len(self._outgoing)
Return the number of vertices in the graph
625941f791af0d3eaac9c08b
def test_clean(self): <NEW_LINE> <INDENT> self._load_some_fixtures() <NEW_LINE> deleted = self.pers.clean([self.temp1]) <NEW_LINE> removed = self.BASIC_FIXTURES <NEW_LINE> removed.remove(('129a8c30e1c3ad89d2635f8abdfdb50b', self.temp1)) <NEW_LINE> self.assertEquals(deleted, [rem[1] for rem in removed]) <NEW_LINE> curso...
temp1, test3 and test4 were removed so must be cleaned
625941f776e4537e8c351ce6
def has_perms(user, project, perms=[]): <NEW_LINE> <INDENT> if user.is_superuser: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if project.owner == user: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> pur, valid = ProjectUserRole.objects .get(project=project, user=user), T...
Check a group of permissions in a single call. TODO: correct handling public projects.
625941f70a366e3fb873ee8e
def board_remove(self, state, player): <NEW_LINE> <INDENT> board = list() <NEW_LINE> for layer in range(4): <NEW_LINE> <INDENT> for row in range(4 - layer): <NEW_LINE> <INDENT> for column in range(4 - layer): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> state.canMove(layer, row, column) <NEW_LINE> sphere = state.get(la...
travel the board and save all the marbles that can be removed :return: list of removable marbles
625941f77d847024c06be92f
def get_dal_format(self, val): <NEW_LINE> <INDENT> self._validate_pos(val) <NEW_LINE> if len(val) == 3: <NEW_LINE> <INDENT> shape = 'CIRCLE' <NEW_LINE> <DEDENT> elif len(val) == 4: <NEW_LINE> <INDENT> shape = 'RANGE' <NEW_LINE> <DEDENT> elif len(val) > 5 and not len(val) % 2: <NEW_LINE> <INDENT> shape = 'POLYGON' <NEW_...
formats the tuple values into a string to be sent to the service entries in values are either quantities or assumed to be degrees
625941f760cbc95b062c6bb1
def duration_in_mins(datum, city): <NEW_LINE> <INDENT> if city =='NYC': <NEW_LINE> <INDENT> duration = int(datum['tripduration'])/60 <NEW_LINE> <DEDENT> elif city =='Chicago': <NEW_LINE> <INDENT> duration = int(datum['tripduration'])/60 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> duration = int(datum['Duration (ms)']...
Takes as input a dictionary containing info about a single trip (datum) and its origin city (city) and returns the trip duration in units of minutes. Remember that Washington is in terms of milliseconds while Chicago and NYC are in terms of seconds. HINT: The csv module reads in all of the data as strings, including...
625941f755399d3f05588d26
def dismiss_alert_pop_up(): <NEW_LINE> <INDENT> global _driver <NEW_LINE> Alert(_driver).dismiss()
Implementing dismiss alert pop up functionality :return:
625941f763d6d428bbe44b5f
def shutdownVirtualMachine(): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> while(count <= 10): <NEW_LINE> <INDENT> virtualUuidList = os.popen("virsh list --uuid").read().strip().split("\n") <NEW_LINE> if(len(virtualUuidList) != 0): <NEW_LINE> <INDENT> print(len(virtualUuidList)) <NEW_LINE> for i in virtualUuidList: <NEW_LI...
关闭虚拟机,返回关闭状态 return 0 表示关闭成功 return 1 表示关闭失败 :return:
625941f72ae34c7f2600d79d
def __call__(self): <NEW_LINE> <INDENT> if self.available(): <NEW_LINE> <INDENT> if hasattr(self.context, '_v_bumblebee_last_converted'): <NEW_LINE> <INDENT> delattr(self.context, '_v_bumblebee_last_converted') <NEW_LINE> <DEDENT> IBumblebeeDocument(self.context)._handle_update(force=True) <NEW_LINE> api.portal.show_me...
Handles the reviving process.
625941f74f88993c3716c6cd
def _phiforce(self,R,z,phi=0.,t=0.): <NEW_LINE> <INDENT> if self.isNonAxi: <NEW_LINE> <INDENT> Rt2= R**2.*(1.-self._1m1overb2*numpy.sin(phi)**2.) <NEW_LINE> return R**2./(Rt2+(z/self._q)**2.+self._core2) *numpy.sin(2.*phi)*self._1m1overb2/2. <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
NAME: _phiforce PURPOSE: evaluate the azimuthal force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: the azimuthal force HISTORY:
625941f75510c4643540fa40
def add(self, image_id, image_file, image_size, context=None): <NEW_LINE> <INDENT> checksum = hashlib.md5() <NEW_LINE> image_name = str(image_id) <NEW_LINE> with rados.Rados(conffile=self.conf_file, rados_id=self.user) as conn: <NEW_LINE> <INDENT> fsid = None <NEW_LINE> if hasattr(conn, 'get_fsid'): <NEW_LINE> <INDENT>...
Stores an image file with supplied identifier to the backend storage system and returns a tuple containing information about the stored image. :param image_id: The opaque image identifier :param image_file: The image data to write, as a file-like object :param image_size: The size of the image data to write, in bytes ...
625941f74428ac0f6e5bae66
def wait_computations_if_benchmark_mode(func): <NEW_LINE> <INDENT> if BenchmarkMode.get(): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wait(*args, **kwargs): <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> if isinstance(result, tuple): <NEW_LINE> <INDENT> partitions = result[0] <NEW_LINE> <DEDENT> els...
Make sure a `func` finished its computations in benchmark mode. Parameters ---------- func : callable A function that should be performed in syncronous mode. Returns ------- callable Wrapped function that executes eagerly (if benchmark mode) or original `func`. Notes ----- `func` should return NumPy array wi...
625941f70a50d4780f667505
def get_contribs_by_year(category_id=None): <NEW_LINE> <INDENT> category_filter = Event.category_chain_overlaps(category_id) if category_id else True <NEW_LINE> query = (db.session .query(db.cast(db.extract('year', TimetableEntry.start_dt), db.Integer).label('year'), db.func.count()) .join(TimetableEntry.event) .filter...
Get the number of contributions for each year. :param category_id: The category ID to get statistics for. Contributions from subcategories are also included. :return: An `OrderedDict` mapping years to contribution counts.
625941f7bf627c535bc1383d
def _install_bundles(self, bundles): <NEW_LINE> <INDENT> pre_installed = dict((bundle.get_symbolic_name(), Version(bundle.get_version())) for bundle in self._context.get_bundles()) <NEW_LINE> to_install = dict((name, Version(version)) for name, version in bundles) <NEW_LINE> for name, installed_version in pre_installed...
Installs & starts the requested bundles, if necessary :param bundles: A list of (name, version) tuples
625941f7090684286d50f35e
def goto(self, scroll_x, scroll_y): <NEW_LINE> <INDENT> def _update(e, x): <NEW_LINE> <INDENT> if e: <NEW_LINE> <INDENT> e.value = (e.max + e.min) * x <NEW_LINE> <DEDENT> <DEDENT> if not (scroll_x is None): <NEW_LINE> <INDENT> self.scroll_x = scroll_x <NEW_LINE> _update(self.effect_x, scroll_x) <NEW_LINE> <DEDENT> if n...
Update event value along with scroll_*.
625941f701c39578d7e754a9
def climbStairs(self, n: int) -> int: <NEW_LINE> <INDENT> ways = [1, 0] <NEW_LINE> if n == 1: <NEW_LINE> <INDENT> return ways[0] + ways[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in range(2, n + 1): <NEW_LINE> <INDENT> old_1step = ways[0] <NEW_LINE> ways[0] = ways[0] + ways[1] <NEW_LINE> ways[1] = old_1step...
it all depends on the size of the last step achieving (n - 1) climbStairs(n) = climbStairs(n-1, ends with 2 step) + climbStairs(n-1, ends with 1 step) * 2 and: climbStairs(n, ends with 2 step) = climbStairs(n-1, ends with 1 step) climbStairs(n, ends with 1 step) = climbStairs(n-1, ends with 1 step) + climbStairs(n-1, ...
625941f75fc7496912cc3fea
def get_subsidiaries(self, customer_id): <NEW_LINE> <INDENT> endpoint = BackOfficeEndpoint.SUBSIDIARY.value.format(customerID=customer_id) <NEW_LINE> return self._get(url=self._build_url(endpoint))
GET /hq/backOffice/customer/{customerID}/subsidiary :param int customer_id: path parameter :return: Response object :rtype: requests.Response
625941f723e79379d52eebc8
def diet_pest_conc(self, prey_frac, prey_pest_conc, diet_lipid_frac): <NEW_LINE> <INDENT> overall_diet_conc = pd.Series([], dtype = 'float') <NEW_LINE> overall_lipid_norm_conc = pd.Series([], dtype = 'float') <NEW_LINE> overall_diet_conc = len(prey_frac) * [0.0] <NEW_LINE> overall_lipid_norm_conc = len(prey_frac) * [0....
:description Overall concentration of pesticide in aquatic animal/organism diet and lipid normalized overall concentration of pesticide in aquatic animal/organism diet :unit g/(kg wet weight) :expression Kabam Eq. A1 (SUM(Pi * CDi); :param prey_frac: fraction of diet containing prey i (Pi in Eq. A1)) :para...
625941f7a934411ee3751d03
def get_edit_distance(wrong_str, right_str): <NEW_LINE> <INDENT> wrong_str = str(wrong_str) <NEW_LINE> right_str = str(right_str) <NEW_LINE> wrong_len = len(wrong_str) <NEW_LINE> right_len = len(right_str) <NEW_LINE> distance = np.zeros((wrong_len + 1, right_len + 1)) <NEW_LINE> for j in range(right_len + 1): <NEW_LINE...
计算距离 :parawrong_lenwrong_str: :parawrong_lenright_str: :return:
625941f7d99f1b3c44c67bef
def parse_options(): <NEW_LINE> <INDENT> parser = optparse.OptionParser() <NEW_LINE> parser.add_option("-q", "--quiet", action="store_true", default=False, dest="quiet", help="Enable quiet mode") <NEW_LINE> parser.add_option("-l", "--links", action="store_true", default=False, dest="links", help="Get links for specifie...
parse_options() -> opts, args Parse any command-line options given returning both the parsed options and arguments.
625941f7d4950a0f3b08c9b3
def is_general_tensor_shape_op(self) -> bool: <NEW_LINE> <INDENT> return False
Similar to is_general_tensor_value_op, this is a check for ops that works for both floating point and quantized input, that only re-arranges the Tensor values or query some metadata about the Tensor We don't insert observer/fake_quant for the output of these operators Example: reshape, transpose, maxpool2d
625941f7eab8aa0e5d26e1c8
def check_ip( self, perceived_ip ): <NEW_LINE> <INDENT> LEGIT_IPS = json.loads( os.environ['papiweb__LEGIT_IPS'] ) <NEW_LINE> ip_good = False <NEW_LINE> if perceived_ip in LEGIT_IPS: <NEW_LINE> <INDENT> ip_good = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log.debug( 'bad ip, `%s`' % flask.request.remote_addr ) ...
Checks ip; returns boolean. Called by validate_request()
625941f79b70327d1c4e1446
def _write_dataset(name, dataset, indices, num_shards): <NEW_LINE> <INDENT> tf.logging.info("Writing dataset %s", name) <NEW_LINE> borders = np.int32(np.linspace(0, len(indices), num_shards + 1)) <NEW_LINE> for i in range(num_shards): <NEW_LINE> <INDENT> filename = os.path.join(FLAGS.output_dir, "%s-%.5d-of-%.5d" % (na...
Writes a sharded TFRecord dataset. Args: name: Name of the dataset (e.g. "train"). dataset: List of serialized Example protos. indices: List of indices of 'dataset' to be written. num_shards: The number of output shards.
625941f7925a0f43d254a4eb
def limit_signal(signal: int) -> int: <NEW_LINE> <INDENT> return max(0, signal % 65536)
Limit the signal to a value in the possible range.
625941f7c432627299f052b8
def not_aim_at_you(self, role): <NEW_LINE> <INDENT> if not self.passive_skill_has_happened: <NEW_LINE> <INDENT> self.passive_skill_has_happened = True <NEW_LINE> if role.name0 == "Kiana": <NEW_LINE> <INDENT> self.arrow *= 1.25 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if random.randint(1, 10000) < 2500: <NEW_LINE> ...
skill1:not aim at you cause 25% damage more on kiana, and other roles has 25% possibility to enhance basic damage @:param role: my enemy
625941f7fbf16365ca6f6840
def test_decode_attention_request(self): <NEW_LINE> <INDENT> self._decode_attention_request(True, True) <NEW_LINE> self._decode_attention_request(True, False) <NEW_LINE> self._decode_attention_request(False, True) <NEW_LINE> self._decode_attention_request(False, False)
Decode attention requests.
625941f73d592f4c4ed1d6c9
def shutdown(self): <NEW_LINE> <INDENT> self.interrupt() <NEW_LINE> time.sleep(1) <NEW_LINE> self.close()
Stops pending inputs and closes the communication.
625941f745492302aab5e938
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model("sites", "Site") <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "name": "Dialy Menu", }, )
Set site domain and name.
625941f79c8ee82313fbbde5
def k8s_install_k8s(args): <NEW_LINE> <INDENT> print_progress('Kubernetes', 'Creating Kubernetes repo, installing Kubernetes ' 'packages', K8S_FINAL_PROGRESS) <NEW_LINE> run_shell(args, 'sudo -H pip install --upgrade pip') <NEW_LINE> k8s_create_repo(args) <NEW_LINE> demo(args, 'Installing Kubernetes', 'Installing docke...
Necessary repo to install kubernetes and tools This is often broken and may need to be more programatic
625941f74d74a7450ccd4833
def new_batch_list(self): <NEW_LINE> <INDENT> return BatchList(self)
Return a new, empty :class:`boto.dynamodb.batch.BatchList` object.
625941f7b57a9660fec33efb
def _scale(self): <NEW_LINE> <INDENT> Mstar = self._MS/self.M <NEW_LINE> Gstar = self._GS/self.G <NEW_LINE> if (self.scale_radius=='r0'): Rstar = self._RS/self.r0 <NEW_LINE> if (self.scale_radius=='rh'): Rstar = self._RS/self.rh <NEW_LINE> if (self.scale_radius=='rv'): Rstar = self._RS/self.rv <NEW_LINE> if (self.scale...
Scales the model to the units set in the input: GS, MS, RS
625941f7d8ef3951e3243bab
def WriteSignatures(self, signatures, group, subgroup, filename): <NEW_LINE> <INDENT> I_iclass_write_signatures(signatures, group, subgroup, filename)
Writes current signatures to signature file :param signatures: signature (c structure) :param group: imagery group :param filename: signature file name
625941f75fdd1c0f98dc08a4
def remove_section(self, section): <NEW_LINE> <INDENT> if super(SafeConfigCommentParser, self).remove_section(section): <NEW_LINE> <INDENT> if section in self._comments: <NEW_LINE> <INDENT> del self._comments[section] <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> return False
Remove a file section and any comments associated with it. @type section: str @param section: The section to remove. @rtype: bool @return: True of the section existed and was removed. False if the section didn't exist and couldn't be removed.
625941f74e696a04525c9abc
def rtc_runner(rtc): <NEW_LINE> <INDENT> return run_main_gather_fastq(rtc.task.input_files[0], rtc.task.output_files[0], CHUNK_KEY)
:type rtc: pbcommand.models.ResolvedToolContract :return:
625941f7d7e4931a7ee9e58e
def get_param_doc_dict(funcs): <NEW_LINE> <INDENT> def helper(doc, func): <NEW_LINE> <INDENT> first_idx = doc.find(":param") <NEW_LINE> last_idx = doc.find(":return") <NEW_LINE> last_idx = last_idx if last_idx != -1 else len(doc) <NEW_LINE> param_doc = doc[first_idx:last_idx] <NEW_LINE> params_doc = param_doc.split(":p...
Get doc of funcs params. Args: funcs: Target funcs. Returns: Dict of params doc.
625941f7507cdc57c6307359
@app.route("/logout") <NEW_LINE> def logout(): <NEW_LINE> <INDENT> session.pop("curr_user") <NEW_LINE> flash(f"You have been successfully logged out", "success") <NEW_LINE> return redirect("/login")
Handle logout of user.
625941f730dc7b7665901fcc
def list_splice(target, start, delete_count=None, *items): <NEW_LINE> <INDENT> if delete_count == None: <NEW_LINE> <INDENT> delete_count = len(target) - start <NEW_LINE> <DEDENT> total = start + delete_count <NEW_LINE> removed = target[start:total] <NEW_LINE> target[start:total] = items <NEW_LINE> return removed
Remove existing elements and/or add new elements to a list. target the target list (will be changed) start index of starting position delete_count number of items to remove (default: len(target) - start) *items items to insert at start index Returns a new list of removed items (or an empty list...
625941f73617ad0b5ed68564
def get_forces(self, run_ID=None): <NEW_LINE> <INDENT> if run_ID is None: <NEW_LINE> <INDENT> run_ID = self.run_ID - 1 <NEW_LINE> <DEDENT> return self.systems[run_ID]['qmmm_forces']
Function to return qmmm forces Parameters ---------- run_ID : int identifies which step to get forces from Returns ------- dict qmmm forces in au/bohr Examples -------- >>> forces = get_forces()
625941f7d164cc61757833bd
def __init__(self): <NEW_LINE> <INDENT> self.TaskId = None <NEW_LINE> self.Status = None <NEW_LINE> self.Progress = None <NEW_LINE> self.UsedTime = None <NEW_LINE> self.Duration = None <NEW_LINE> self.NoAudio = None <NEW_LINE> self.NoVideo = None <NEW_LINE> self.QualityEvaluationScore = None <NEW_LINE> self.QualityEval...
:param TaskId: 质检任务 ID :type TaskId: str :param Status: 质检任务状态。 1:执行中;2:成功;3:失败 :type Status: int :param Progress: 表示处理进度百分比 :type Progress: int :param UsedTime: 处理时长(s) :type UsedTime: int :param Duration: 计费时长(s) :type Duration: int ...
625941f77d43ff24873a3314
def test_upload(self): <NEW_LINE> <INDENT> filename = "F:\\drive3_1.raw" <NEW_LINE> size = os.stat(filename).st_size <NEW_LINE> file = open(filename, "rb") <NEW_LINE> self.createChannel(size, False) <NEW_LINE> dataplace = 0 <NEW_LINE> while 1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = file.read(self.__channel...
upload
625941f78e7ae83300e4b63d
def match_series(images, affines, params, matches): <NEW_LINE> <INDENT> img_list, aff_list, img_type_list = [], [], [] <NEW_LINE> for match, img_type in matches: <NEW_LINE> <INDENT> for i, series in enumerate(params['_series']): <NEW_LINE> <INDENT> if re.match(match, series): <NEW_LINE> <INDENT> img_list.append(images[...
TODO: finish documentation
625941f7097d151d1a2234c4
def stripLastHaraka(text): <NEW_LINE> <INDENT> if text: <NEW_LINE> <INDENT> return re.sub(LASTHARAKA_pattern,u'',text) <NEW_LINE> <DEDENT> return text
Strip the last Haraka from arabic word except Shadda. The striped marks are : - FATHA, DAMMA, KASRA - SUKUN - FATHATAN, DAMMATAN, KASRATAN, , , . Example: >>> text=u"الْعَرَبِيّةُ" >>> stripTashkeel(text) الْعَرَبِيّة @param text: arabic text. @type text: unicode. @return: return a striped text...
625941f7cdde0d52a9e536a7
def __init__(self, schedule_meeting=None, in_meeting=None, email_notification=None, recording=None, telephony=None): <NEW_LINE> <INDENT> self._schedule_meeting = None <NEW_LINE> self._in_meeting = None <NEW_LINE> self._email_notification = None <NEW_LINE> self._recording = None <NEW_LINE> self._telephony = None <NEW_LI...
Body130 - a model defined in Swagger
625941f74f6381625f1150a9
def getSkip(self): <NEW_LINE> <INDENT> return util.acquireAttribute(self._parents, 'skip', None)
Return the skip reason set on this test, if any is set. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a C{skip} attribute, returns that. Returns L{None} if it cannot find anything. See L{TestCase} docstring for more details.
625941f77cff6e4e81117ff3
@task(name="orders.paper") <NEW_LINE> @entrypoint() <NEW_LINE> def paper(client_id, order_key, user_id ): <NEW_LINE> <INDENT> order = lookup_order_by_key(order_key) <NEW_LINE> user = lookup_user_by_id(user_id) <NEW_LINE> order.checkout(user) <NEW_LINE> order.meta['paper'] = True <NEW_LINE> result = order_to_dict(order,...
Skips the payment provider and finishes the order as a paper ticket
625941f75e10d32532c5f592
def train_step(sess, train_op, global_step, train_step_kwargs): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> trace_run_options = None <NEW_LINE> run_metadata = None <NEW_LINE> if 'should_trace' in train_step_kwargs: <NEW_LINE> <INDENT> if 'logdir' not in train_step_kwargs: <NEW_LINE> <INDENT> raise ValueErro...
Function that takes a gradient step and specifies whether to stop. Args: sess: The current session. train_op: An `Operation` that evaluates the gradients and returns the total loss. global_step: A `Tensor` representing the global training step. train_step_kwargs: A dictionary of keyword arguments. Returns: ...
625941f7b830903b967e9f71
def tupletToMx(tuplet): <NEW_LINE> <INDENT> mxTimeModification = musicxml.TimeModification() <NEW_LINE> mxTimeModification.set('actual-notes', int(tuplet.numberNotesActual)) <NEW_LINE> mxTimeModification.set('normal-notes', int(tuplet.numberNotesNormal)) <NEW_LINE> mxTimeModification.set('normal-type', tuplet.durationN...
return a tuple of mxTimeModification and mxTuplet from a :class:`~music21.duration.Tuplet` object >>> a = duration.Tuplet(6, 4, "16th") >>> a.type = 'start' >>> a.bracket = True >>> b, c = musicxml.toMxObjects.tupletToMx(a) >>> b <time-modification actual-notes=6 normal-notes=4 normal-type=16th> >>> c [<tuplet bracke...
625941f74a966d76dd551685
def points3d_points2d(self, context, points): <NEW_LINE> <INDENT> pts = [] <NEW_LINE> region, rv3d = self.view3d_find(context) <NEW_LINE> if region is not None: <NEW_LINE> <INDENT> pts = [location_3d_to_region_2d(region, rv3d, p) for p in points] <NEW_LINE> <DEDENT> return pts
convert 3d points to 2d region pts and draw
625941f756b00c62f0f14ccc
def __invert__(self): <NEW_LINE> <INDENT> return self.compose()
Get CGR of reaction
625941f7e5267d203edce303
def ax_atom_id(atom): <NEW_LINE> <INDENT> return "AX %s (fpp=%.3f)" % (atom.serial.strip(), atom.occ)
Parameters ---------- atom : iotbx.pdb.hierarchy.atom Returns ------- str
625941f7711fe17d825429ca
@reroute <NEW_LINE> def unlink(destination, source=None): <NEW_LINE> <INDENT> return
This will unlink the connection between two properties. If no source is given all sources to the destination will be removed. :param destination: property to disconnect from :type destination: Host Specific :param source: If given, only links between the source property and the destination property will be unlink...
625941f77b25080760e39ac3
def reinit(self, names, devices, network, monitors): <NEW_LINE> <INDENT> self.devices = devices <NEW_LINE> self.network = network <NEW_LINE> self.monitors = monitors <NEW_LINE> self.names = names <NEW_LINE> self.monitored_list, self.unmonitored_list = self.monitors.get_signal_names() <NEW_LINE> self.total_li...
Re-initialisation when new file is opened
625941f78a349b6b435e87e1
def saverule(self): <NEW_LINE> <INDENT> g = self.combo_group.get() <NEW_LINE> if g not in self.groups or g == '': <NEW_LINE> <INDENT> print("please select group") <NEW_LINE> return <NEW_LINE> <DEDENT> dummy_rules = '' <NEW_LINE> dummy_rules += self.entry_uma1.get().replace(' ', '') <NEW_LINE> dummy_rules += "\n" <NEW_L...
ルールの保存
625941f7009cb60464c63a1a
def __exit__(self, *exc_info): <NEW_LINE> <INDENT> self.close()
Support the context manager protocol
625941f7be7bc26dc91cdc62
def yes_or_no(x): <NEW_LINE> <INDENT> x_input = str(input(x)) <NEW_LINE> while x_input.lower() != "y" and x_input.lower() != "n": <NEW_LINE> <INDENT> print("**Error!**\nPlease only enter 'Y' or 'N'\n") <NEW_LINE> x_input = str(input(x)) <NEW_LINE> <DEDENT> return x_input
Prompts user for 'y' or 'n' if neither, prompts user again for 'y' or 'n'
625941f7d486a94d0b98e7b5
def footnote_anchors(content): <NEW_LINE> <INDENT> h = str(hash(content))[:8] <NEW_LINE> return f"fr-{h}", f"fd-{h}"
Return the id of the reference and the id of the definition.
625941f7c4546d3d9de730a9
def mask_3d(inputs, lengths, mask_value): <NEW_LINE> <INDENT> max_length = tf.shape(inputs)[1] <NEW_LINE> num_units = tf.shape(inputs)[2] <NEW_LINE> mask = tf.sequence_mask(lengths, max_length, name='mask') <NEW_LINE> mask3d = tf.tile(tf.expand_dims(mask, 2), [1, 1, num_units]) <NEW_LINE> masked = tf.where(mask3d, inpu...
Mask the values past sequence length :param inputs: tensor (batch, time_steps, units) :param lengths: tensor (batch) with the real length (non-padding) of each item :param mask_value: mask value :return: masked values
625941f731939e2706e4d4ce