code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _generate_tag(tid): <NEW_LINE> <INDENT> classname = tid.split(".")[-1] <NEW_LINE> return "{0}#{1}".format(classname, uuid().hex)
Helper method to generate a tag for a component execution context. Will generate a tag containing the classname of the component and a hex representation of a 128-bit UUID value, separated by a hash character. :param component: string containing the component type id :returns: string tag in the format described above
625941cf9c8ee82313fbb8d1
def test_delete_website_logs(self): <NEW_LINE> <INDENT> task = DeleteWebsiteLogsTask() <NEW_LINE> assert task.run() >= 0
Process segment 0.
625941cf31939e2706e4cfc5
def euclidean_dist(dic1, dic2): <NEW_LINE> <INDENT> return sqrt(sum([pow(dic1[elem]-dic2[elem], 2) for elem in dic1 if elem in dic2]))
Compute the sum of squares of the elements common to both dictionaries
625941cf32920d7e50b2832c
def answer_distributions(course_key): <NEW_LINE> <INDENT> state_keys_to_problem_info = {} <NEW_LINE> def url_and_display_name(usage_key): <NEW_LINE> <INDENT> problem_store = modulestore() <NEW_LINE> if usage_key not in state_keys_to_problem_info: <NEW_LINE> <INDENT> problem = problem_store.get_item(usage_key) <NEW_LINE...
Given a course_key, return answer distributions in the form of a dictionary mapping: (problem url_name, problem display_name, problem_id) -> {dict: answer -> count} Answer distributions are found by iterating through all StudentModule entries for a given course with type="problem" and a grade that is not null. This...
625941cf1f037a2d8b946359
def get_index_max_values(self): <NEW_LINE> <INDENT> series_copy = np.copy(self.lsprop.pgram) <NEW_LINE> self.lsprop.index_max_values = [] <NEW_LINE> self.lsprop.index_max_values.append(np.argmax(series_copy)) <NEW_LINE> for n in range(self.lsprop.number_of_freq - 1): <NEW_LINE> <INDENT> series_copy[self.lsprop.index_ma...
Calculate the maximums of the periodgram.
625941cf3d592f4c4ed1d1c8
def map_record(record, mappings): <NEW_LINE> <INDENT> mapped_record = defaultdict(list) <NEW_LINE> for field, value in record.items(): <NEW_LINE> <INDENT> mapped_record[mappings[field]].append(value) <NEW_LINE> <DEDENT> return(mapped_record)
Convert field names of a given record to the standardized form.
625941cf287bf620b61d3bbf
def printFilePaths(directory): <NEW_LINE> <INDENT> for dirpath,_,filenames in os.walk(directory): <NEW_LINE> <INDENT> for f in filenames: <NEW_LINE> <INDENT> print(os.path.abspath(os.path.join(dirpath, f)))
Will print the paths of all files stored in the current working directory :param directory: The name of the current directory
625941cf91f36d47f21ac64f
def pypi(wheel=True, test=False): <NEW_LINE> <INDENT> if wheel: <NEW_LINE> <INDENT> subprocess.run(['python', 'setup.py', 'sdist', 'bdist_wheel'], shell=True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> subprocess.run(['python', 'setup.py', 'sdist'], shell=True) <NEW_LINE> <DEDENT> if test: <NEW_LINE> <INDENT> subpro...
release on pypi
625941cffb3f5b602dac37ef
def test_ae_response_listener_singleton(self): <NEW_LINE> <INDENT> print(self.shortDescription()) <NEW_LINE> f1 = AsyncResponseListenerFactory() <NEW_LINE> i1 = id(f1.get_instance()) <NEW_LINE> f2 = AsyncResponseListenerFactory() <NEW_LINE> i2 = id(f2.get_instance()) <NEW_LINE> self.assertEqual(i1, i2, 'Factory failed ...
AsyncResponseListernerFactory returns singleton instance of AsyncResponseListener.
625941cfad47b63b2c50a0db
def violinPlotMotifMatches(model, data, filename = None): <NEW_LINE> <INDENT> seqs = np.concatenate(list(data.values()), axis=0) <NEW_LINE> labels = [] <NEW_LINE> for k in data: <NEW_LINE> <INDENT> labels += [k] * data[k].shape[0] <NEW_LINE> <DEDENT> hiddenprobs = model.motifHitProbs(seqs) <NEW_LINE> probs = hiddenprob...
Violin plot of motif abundances. This function summarized the relative motif abundances of the :class:`CRBM` motifs in a given set of sequences (e.g. sequences with different functions). Parameters ----------- model : :class:`CRBM` object A cRBM object data : dict Dictionary with keys representing dataset-nam...
625941cf004d5f362079a48e
def initializeGL(self): <NEW_LINE> <INDENT> self.sceneManager.init_gl()
Performs initial OpenGL setup
625941cf63d6d428bbe4464b
def write_config(config, path=None): <NEW_LINE> <INDENT> if path is None: <NEW_LINE> <INDENT> path = DEFAULT_USER_CONFIG_PATH <NEW_LINE> <DEDENT> resolved_path = os.path.expanduser(path) <NEW_LINE> with open(resolved_path, 'w') as handle: <NEW_LINE> <INDENT> json.dump(config, handle, sort_keys=True, indent=2)
Creates a user-configuration file from parsed config. Parameters ---------- config : dict path : str, optional Location to be specied. If not, it uses `DEFAULT_USER_CONFIG_PATH`
625941cf377c676e91272304
def file_len(fname): <NEW_LINE> <INDENT> non_blank_count = 0 <NEW_LINE> with open(fname) as infp: <NEW_LINE> <INDENT> for line in infp: <NEW_LINE> <INDENT> if line.strip() and not line.strip().startswith("#"): <NEW_LINE> <INDENT> non_blank_count += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return non_blank_count
Function that counts the number of non-blank lines in given file
625941cf8e05c05ec3eea4d1
def _verify(leniency, numobj): <NEW_LINE> <INDENT> if leniency == Leniency.POSSIBLE: <NEW_LINE> <INDENT> return phonenumberutil.is_possible_number(numobj) <NEW_LINE> <DEDENT> elif leniency == Leniency.VALID: <NEW_LINE> <INDENT> return phonenumberutil.is_valid_number(numobj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
Returns True if number is a verified number according to the leniency.
625941cf0fa83653e4657116
def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.status != DynamicRNN.AFTER_RNN: <NEW_LINE> <INDENT> raise ValueError(("Output of the dynamic RNN can only be visited " "outside the rnn block.")) <NEW_LINE> <DEDENT> if len(self.outputs) == 1: <NEW_LINE> <INDENT> return self.outputs[0] <NEW_LINE> <DEDENT>...
Get the output of RNN. This API should only be invoked after RNN.block()
625941cfdc8b845886cb5691
def on_radioauto_clicked(self, widget, data=None): <NEW_LINE> <INDENT> self.builder.get_object("acceptaddnetwork").set_sensitive(True) <NEW_LINE> self.builder.get_object("entrymac").set_sensitive(False)
Function called when you selet radio "auto" (mac autogenerated) On add new network window
625941cf8e7ae83300e4b128
def match(self, req, alt=False): <NEW_LINE> <INDENT> for m in self.matches(req, alt): <NEW_LINE> <INDENT> return m
Return the first view that the given request matches.
625941cf66673b3332b921ed
def interact(self): <NEW_LINE> <INDENT> self.log.debug("No command given, running default command: %s", self.default_command) <NEW_LINE> result = self.run_subcommand([self.default_command]) <NEW_LINE> return result
Action taken if no command given
625941cfb5575c28eb68e15c
def assert_busy_time_overlap_doesnt_double(busy_times, numblocks_expected): <NEW_LINE> <INDENT> schedule = Schedule() <NEW_LINE> bitmaps_set = set() <NEW_LINE> for busy_time in busy_times: <NEW_LINE> <INDENT> schedule.add_busy_time(busy_time) <NEW_LINE> bitmaps_set.add(''.join(bin(day_bitmap) for day_bitmap in schedule...
Check that adding the same busy_time more than once to a new Schedule is idempotent
625941cf30bbd722463cbf22
def start_http(app: tornado.web.Application, http_port: int = 80): <NEW_LINE> <INDENT> http_socket = tornado.netutil.bind_sockets(http_port) <NEW_LINE> try: <NEW_LINE> <INDENT> tornado.process.fork_processes(0) <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> tornado.ioloop.IOLoop.current().stop() <NEW...
Create app instance(s) binding a port. :param app: the app to execute in server instances :param http_port: port to bind
625941cf1b99ca400220ac0d
def get_Xc(self, data): <NEW_LINE> <INDENT> patient = [concept for visit in data for concept in visit] <NEW_LINE> patient = [x-1 for x in patient] <NEW_LINE> counts = np.bincount(patient, minlength=self.vocab_size) <NEW_LINE> stops_flag = np.array(list(np.ones([self.lda_vocab_size], dtype=np.int32)) + list(np.zeros([se...
data is a patient...a sequence of visits so a list of lists...the outer list is of size T_patient the inner lists contain the concepts within each visit
625941cf73bcbd0ca4b2c1d2
def pop(self): <NEW_LINE> <INDENT> if self.stack[-1] == self.min_val: <NEW_LINE> <INDENT> self.stack.pop(-1) <NEW_LINE> self.min_val = min(self.stack) if self.stack else None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stack.pop(-1)
:rtype: void
625941cf26238365f5f0efca
def loss_gradient(self, x: "np.ndarray", y: "np.ndarray", **kwargs) -> "np.ndarray": <NEW_LINE> <INDENT> raise NotImplementedError
No gradients to compute for this method; do nothing.
625941cf8da39b475bd650d0
def plot_best_fit(weights): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> data_mat, label_mat = load_data_set() <NEW_LINE> data_arr = np.array(data_mat) <NEW_LINE> n = np.shape(data_mat)[0] <NEW_LINE> x_cord1 = [] <NEW_LINE> y_cord1 = [] <NEW_LINE> x_cord2 = [] <NEW_LINE> y_cord2 = [] <NEW_LINE> for i ...
可视化画出决策边界 :param weights: :return:
625941cfe1aae11d1e749e13
def get_node(token, location): <NEW_LINE> <INDENT> heads = HEADS.copy() <NEW_LINE> heads['X-Auth-Token'] = token <NEW_LINE> heads = do_request('GET', location, heads) <NEW_LINE> return heads
Retrieve a single resource.
625941cfa8370b77170529fb
def download_album(self,album_id): <NEW_LINE> <INDENT> params={'csrf_token':''} <NEW_LINE> result = self.post_request(apis['album']%album_id,params) <NEW_LINE> songs=result['songs'] <NEW_LINE> d = modificate_text(result['album']['name'] + ' - ' + result['album']['artist']['name']) <NEW_LINE> self.dir_ = os.p...
解析专辑 :album_id 专辑id :return 专辑信息
625941cf1f5feb6acb0c4cac
def pip(filename): <NEW_LINE> <INDENT> requirements = [] <NEW_LINE> for line in open(os.path.join('requirements', filename)): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line or '://' in line or line.startswith('#'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> requirements.append(line) <NEW_LINE> <DE...
Parse pip reqs file and transform it to setuptools requirements.
625941cf566aa707497f46c4
@app.route('/') <NEW_LINE> def show_home(): <NEW_LINE> <INDENT> categories = session.query(ItemCategory).all() <NEW_LINE> return render_template('home.htm', categories=categories)
Shows the home page which by default renders the categories in the database. Returns: on GET: home page.
625941cf1d351010ab855c78
def tasso_errata_classificazione(p): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> i = None <NEW_LINE> return i
Tasso di errata classificazione Parameters ---------- p : array, shape (n,) Array delle probabilità. Returns ------- i : array, shape (n,) Tasso di errata classificazione degli elementi di p.
625941cf187af65679ca527b
def mult_backward(dout, cache): <NEW_LINE> <INDENT> x, w = cache <NEW_LINE> dx = np.dot(dout, w.T) <NEW_LINE> dw = np.dot(x.T, dout) <NEW_LINE> return dx, dw
Computes the backward pass for an multiplication layer. Inputs: - dout: Upstream derivative, of shape (d_1, d_3) - cache: Tuple of: - x: Input data, of shape (d_1, d_2) - w: Weights, of shape (d_2, d_3) Returns a tuple of: - dx: Gradient with respect to x, of shape (d_1, d_2) - dw: Gradient with respect to w, of ...
625941cf851cf427c661a66a
def bq_create_table(table_id, schema, partition_column_name=None, cluster_column_name=None, if_exists='ERROR', client=None): <NEW_LINE> <INDENT> if not client: <NEW_LINE> <INDENT> logging.debug( "instantiating bigquery client from defualt environment variable") <NEW_LINE> client = bigquery.Client() <NEW_LINE> <DEDENT> ...
Create bigquery table with paritioned and clustering columns. Arguments: table_id {str} -- fully qualified table_id e.g. project_id.dataset.new_tablename schema {bigquery} -- fully qualified table_id e.g. project_id.dataset.new_tablename Keyword Arguments: partition_column_name {str} -- optional. column m...
625941cf8a349b6b435e82d0
def count_channels(self): <NEW_LINE> <INDENT> merge = self.index['merge'] <NEW_LINE> if len(self.idx_chan.selectedItems()) > 1: <NEW_LINE> <INDENT> if merge.isEnabled(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> merge.setEnabled(True) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT>...
If more than one channel selected, activate merge checkbox.
625941cf6fb2d068a760f1fa
def test_get_tax_amount_basic_rate(self): <NEW_LINE> <INDENT> tax_ctrl = TaxController(self.taxable_income_salary) <NEW_LINE> tax_amount = tax_ctrl.get_tax_amount() <NEW_LINE> self.assertIsNotNone(tax_amount) <NEW_LINE> self.assertEqual(tax_amount, tax_ctrl.basic_rate())
Test get_tax_amount() returns correct value when taxable income fits the basic rate
625941cf7d847024c06be419
def number_of_nodes(self): <NEW_LINE> <INDENT> return self._graph.number_of_nodes()
Return the number of nodes in the graph. Returns ------- int The number of nodes
625941cf23849d37ff7b31ec
def current(self, date=None): <NEW_LINE> <INDENT> if date is None: <NEW_LINE> <INDENT> date = timezone.now() <NEW_LINE> <DEDENT> return self.filter(start__lt=date).order_by('-end').first()
Aktuálny semester na zobrazenie
625941cfcc40096d61595aad
def __repr__(self): <NEW_LINE> <INDENT> if len(self.text) > 10: <NEW_LINE> <INDENT> return self.to_string(self.text[:7]) + "..." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.to_string(self.text)
String representation
625941cf5510c4643540f540
def set_analog_level(self, amplitude=None, offset=None): <NEW_LINE> <INDENT> return {}, {}
Set amplitude and/or offset value of the provided analog channel(s). @param dict amplitude: dictionary, with key being the channel descriptor string (i.e. 'a_ch1', 'a_ch2') and items being the amplitude values (in Volt peak to peak, i.e. the full amp...
625941cf442bda511e8be574
def __init__(self, key=None, value=None): <NEW_LINE> <INDENT> self.key = key <NEW_LINE> self.value = value
:param key: (Optional) 标签键 :param value: (Optional) 标签值
625941cf96565a6dacc8f827
def send_message(self, message): <NEW_LINE> <INDENT> return self.client.api_call( "chat.postMessage", channel=self.channel, text=message, username=self.username, icon_emoji=self.icon_emoji)
Send a signle message
625941cf5fcc89381b1e181c
def addnontripts(tripts_labels, nontripts_labels, ptsdict): <NEW_LINE> <INDENT> tripts = [list(ptsdict[p]) for p in tripts_labels] <NEW_LINE> pairs = [[0, 1], [1, 2], [0, 2]] <NEW_LINE> q = [tripts] <NEW_LINE> num = len(nontripts_labels) <NEW_LINE> gridpts = [[float((tripts[0][0]+tripts[1][0]+tripts[2][0])/3), float(tr...
Return modified ``ptsdict`` with additional keys and values corresponding to ``nontripts``. INPUT: - ``tripts`` -- A list of 3 ground set elements that are to be placed on vertices of the triangle. - ``ptsdict`` -- A dictionary (at least) containing ground set elements in ``tripts`` as keys and their (x,y) positi...
625941cfb7558d58953c5070
def _mbb(self): <NEW_LINE> <INDENT> mins = self.points.min(axis=0) <NEW_LINE> maxs = self.points.max(axis=0) <NEW_LINE> return np.hstack((mins, maxs))
Minimum bounding box
625941cf046cf37aa974cea4
def testCommunityStringWithMaxLengthInV2(self): <NEW_LINE> <INDENT> event_table = EventTable(AGENT_IP, community='private', version=2) <NEW_LINE> community_str='SNMPCommunitystringsareusedonlybydeviceswhichsupportSNMPv1andSNMPv2cprotocolSNMPv3usesusernamepasswordauthenticationalongwithan' <NEW_LINE> result = event_tabl...
Test case that verifies the community string can be set with the maximum allowed characters via Version V2. (=127)
625941cf38b623060ff0af4a
def deploy_test_form(test, guest_vm, params): <NEW_LINE> <INDENT> script = params.get("guest_script") <NEW_LINE> script_path = os.path.join(data_dir.get_deps_dir(), "spice", script) <NEW_LINE> guest_vm.copy_files_to(script_path, "/tmp/%s" % params.get("guest_script"), timeout=60)
Copy wxPython Test form to guest VM. Test form is copied to /tmp directory. :param test :param guest_vm - vm object :param params
625941cfff9c53063f47c350
def flatten(nested): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for sublist in nested: <NEW_LINE> <INDENT> if type(sublist)==type(""): <NEW_LINE> <INDENT> yield sublist <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for element in flatten(sublist): <NEW_LINE> <INDENT> yield element <NEW_LINE> <DEDENT> <DEDENT> <DEDENT...
Flatten a list using iterator and exceptional control.
625941cf009cb60464c6350e
def removeDuplicateLetters(self, s): <NEW_LINE> <INDENT> if not s: return '' <NEW_LINE> pos = defaultdict(list) <NEW_LINE> for i, c in enumerate(s): <NEW_LINE> <INDENT> pos[c].append(i) <NEW_LINE> <DEDENT> avail = [set()] * len(s) <NEW_LINE> for i, c in reversed(list(enumerate(s))): <NEW_LINE> <INDENT> if i == len(s)-1...
:type s: str :rtype: str
625941cf96565a6dacc8f828
def get_dataframe_from_datasource(self, data: DataSourceModel) -> pd.DataFrame: <NEW_LINE> <INDENT> path = data.path <NEW_LINE> try: <NEW_LINE> <INDENT> self.core.check_source(path) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> path = str(self.directory / data.source) <NEW_LINE> self.core.check_sour...
Return the dataframe for a data source. Parameters ---------- data: DataSourceModel Returns ------- pd.DataFrame
625941cf32920d7e50b2832d
def decode(self, identifier): <NEW_LINE> <INDENT> return unquote_plus(identifier)
Decode identifier to put back unsafe chars.
625941cf379a373c97cfaca2
def sentence_position(i, size): <NEW_LINE> <INDENT> normalized = i*1.0 / size <NEW_LINE> if 0 < normalized <= 0.1: <NEW_LINE> <INDENT> return 0.17 <NEW_LINE> <DEDENT> elif 0.1 < normalized <= 0.2: <NEW_LINE> <INDENT> return 0.23 <NEW_LINE> <DEDENT> elif 0.2 < normalized <= 0.3: <NEW_LINE> <INDENT> return 0.14 <NEW_LINE...
different sentence position might indicate variness in importance
625941cfbd1bec0571d9078c
def void_invoices(self, request, queryset): <NEW_LINE> <INDENT> valid_invoices = queryset.filter(status__in=[1, 4]) <NEW_LINE> invalid_invoices = queryset.filter(status__in=[2, 3]) <NEW_LINE> if invalid_invoices: <NEW_LINE> <INDENT> if valid_invoices: <NEW_LINE> <INDENT> for invoice in valid_invoices: <NEW_LINE> <INDEN...
Manually void invoices with a status of 1 (Pending) or 4 (Stale) Checks for invalid invoice selections, refuses to operate on them and flags up a notification. Status codes: 1 - Pending (valid for voiding) 2 - Void (invalid) 3 - Complete (invalid) 4 - Stale (valid)
625941cfbde94217f3682f4d
def add_recent_project(self, filename): <NEW_LINE> <INDENT> self._validate() <NEW_LINE> if filename is None or not osp.exists(filename): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for action in self._recent_project_actions: <NEW_LINE> <INDENT> if osp.samefile(filename, action.data()): <NEW_LINE> <INDENT> action = s...
Add the project corresponding to filename to the list of recent projects. The project is always added at the top of the recent projects list. Parameters ---------- filename : str The absolute path of the project that needs to be added to the list of recent projects.
625941cf4e696a04525c95a8
def parse_code(self): <NEW_LINE> <INDENT> code = open(self.path, encoding="utf-8").read() <NEW_LINE> try: <NEW_LINE> <INDENT> body = ast.parse(code).body <NEW_LINE> <DEDENT> except SyntaxError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> code = code.encode("utf-8") <NEW_LINE> body = ast.parse(code).body <NEW_LINE> <DE...
Read the source code and return all the import statements. Returns: list of dict: the import statements.
625941cf91af0d3eaac9bb76
def _tensor_summary_v2( name, tensor, summary_description=None, collections=None, summary_metadata=None, family=None): <NEW_LINE> <INDENT> del summary_description <NEW_LINE> serialized_summary_metadata = "" <NEW_LINE> if summary_metadata: <NEW_LINE> <INDENT> serialized_summary_metadata = summary_metadata.SerializeToStr...
Outputs a `Summary` protocol buffer with a serialized tensor.proto. NOTE(chizeng): This method is temporary. It should never make it into TensorFlow 1.3, and nothing should depend on it. This method should be deleted before August 2017 (ideally, earlier). This method exists to unblock the TensorBoard plugin refactorin...
625941cf1b99ca400220ac0e
def ipv6_link_eth_mcast(dst_ip): <NEW_LINE> <INDENT> mcast_mac_bytes = ipaddr.Bytes('\x33\x33') + dst_ip.packed[-4:] <NEW_LINE> mcast_mac = ':'.join(['%02X' % ord(x) for x in mcast_mac_bytes]) <NEW_LINE> return mcast_mac
Return an Ethernet multicast address from an IPv6 address. See RFC 2464 section 7. Args: dst_ip (ipaddr.IPv6Address): IPv6 address. Returns: str: Ethernet multicast address.
625941cf0383005118ecf73f
def _is_cuda_available(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert len(paddle.static.cuda_places()) > 0 <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.warning( "You are using GPU version PaddlePaddle, but there is no GPU " "detected on your machine. Maybe CUDA d...
Check whether CUDA is avaiable.
625941cf6fece00bbac2d89c
def nthUglyNumber(self, n): <NEW_LINE> <INDENT> factors = [2, 3, 5] <NEW_LINE> idx = [0, 0, 0] <NEW_LINE> res = [1] <NEW_LINE> for i in range(n-1): <NEW_LINE> <INDENT> for j in range(len(factors)): <NEW_LINE> <INDENT> while res[idx[j]] * factors[j] <= res[-1]: <NEW_LINE> <INDENT> idx[j] += 1 <NEW_LINE> <DEDENT> <DEDENT...
:type n: int :rtype: int
625941cf0a50d4780f666fef
def delenv(): <NEW_LINE> <INDENT> global _env <NEW_LINE> if not _env: <NEW_LINE> <INDENT> raise EnvError("No environment exists") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _env.clear_config_options() <NEW_LINE> log.debug("Cleared existing %r options", _env)
Delete options in the existing environment.
625941cf07d97122c41789e9
def delete(self,request, pk=None): <NEW_LINE> <INDENT> return Response({'method':'delete'})
Deletes the object.
625941cf16aa5153ce3625d5
def validate(val_loader, encoder, decoder, criterion): <NEW_LINE> <INDENT> decoder.eval() <NEW_LINE> if encoder is not None: <NEW_LINE> <INDENT> encoder.eval() <NEW_LINE> <DEDENT> batch_time = AverageMeter() <NEW_LINE> losses = AverageMeter() <NEW_LINE> start = time.time() <NEW_LINE> references = list() <NEW_LINE> hypo...
Performs one epoch's validation val_loader: Data loader for validation set encoder: encoder model decoder: decoder model criterion: loss layer Returns: bleu4: BLEU-4 score
625941cf3617ad0b5ed68054
def polygcd(a, b): <NEW_LINE> <INDENT> a_roots = a.r.tolist() <NEW_LINE> b_roots = b.r.tolist() <NEW_LINE> a_common, b_common = common_roots_ind(a_roots, b_roots) <NEW_LINE> gcd_roots = [] <NEW_LINE> for i in range(len(a_common)): <NEW_LINE> <INDENT> gcd_roots.append((a_roots[a_common[i]]+b_roots[b_common[i]])/2) <NEW_...
Find the approximate Greatest Common Divisor of two polynomials >>> a = numpy.poly1d([1, 1]) * numpy.poly1d([1, 2]) >>> b = numpy.poly1d([1, 1]) * numpy.poly1d([1, 3]) >>> polygcd(a, b) poly1d([ 1., 1.]) >>> polygcd(numpy.poly1d([1, 1]), numpy.poly1d([1])) poly1d([ 1.])
625941cf56b00c62f0f147b6
def getConnections(*args, **kwargs): <NEW_LINE> <INDENT> pass
Returns all the plugs which are connected to attributes of this node.
625941cf26068e7796caee3c
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <IND...
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941cfc4546d3d9de72b92
@pytest.fixture(params=['test_image_nikon.NEF']) <NEW_LINE> def s3_put_event(generic_s3_put_notification, sns_topic_arn, request) -> S3Event: <NEW_LINE> <INDENT> generic_s3_put_notification['Records'][0]["s3"]["bucket"]["name"] = BUCKET_NAME <NEW_LINE> generic_s3_put_notification['Records'][0]["s3"]["bucket"]["arn"] = ...
Return an event referencing a real S3 object
625941cf956e5f7376d70fca
def _intersect3D_lineseg_triangle(self, lineseg, triangle): <NEW_LINE> <INDENT> ray = Ray(lineseg) <NEW_LINE> t = self._intersect3D_ray_triangle(ray, triangle) <NEW_LINE> if t is None or t > 1.0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ray.orig + t*ray.dir
Find intersection of a line segment with a triangle.
625941cf63f4b57ef0001275
def __call__(self, source, language=None, metadata=None, strip_verbatim=False): <NEW_LINE> <INDENT> from pygments.formatters import LatexFormatter <NEW_LINE> if not language: <NEW_LINE> <INDENT> language=self.pygments_lexer <NEW_LINE> <DEDENT> latex = _pygments_highlight(source, LatexFormatter(**self.extra_formatter_op...
Return a syntax-highlighted version of the input source as latex output. Parameters ---------- source : str source of the cell to highlight language : str language to highlight the syntax of metadata : NotebookNode cell metadata metadata of the cell to highlight strip_verbatim : bool remove the Verbati...
625941cf73bcbd0ca4b2c1d3
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Websitenya_TA.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are yo...
Run administrative tasks.
625941cf3539df3088e2e4a8
def __init__(self, data=None): <NEW_LINE> <INDENT> self.start = create_nodes(data)
List constructor. :param data: the initial data of the lists
625941cf4527f215b584c5b3
def fit_apply(fit_result,vec_array): <NEW_LINE> <INDENT> t1, mt2, m = fit_result[:3] <NEW_LINE> return [add(t1, transform(m, add(mt2, x))) for x in vec_array]
fit_apply(fir_result,vec_array) -> vec_array Applies a fit result to an array of vectors
625941cf283ffb24f3c55a5e
def recv(self, client, arg, arg2): <NEW_LINE> <INDENT> return utils.lib.zhttp_response_recv(self._p, client._p, arg._p, arg2._p)
Receive a response from zhttp_client. On success return 0, -1 otherwise. Recv returns the two user arguments which was provided with the request. The reason for two, is to be able to pass around the server connection when forwarding requests or both a callback function and an argument.
625941cf442bda511e8be575
@bprop_to_grad_transform(P.distribute) <NEW_LINE> def bprop_distribute(arr, shp, out, dout): <NEW_LINE> <INDENT> return (array_reduce(scalar_add, dout, shape(arr)), zeros_like(shp))
Backpropagator for primitive `distribute`.
625941cf01c39578d7e74f98
def get_credentials(auth_url, fill_in=True, identity_version='v2', disable_ssl_certificate_validation=None, ca_certs=None, trace_requests=None, **kwargs): <NEW_LINE> <INDENT> if not is_identity_version_supported(identity_version): <NEW_LINE> <INDENT> raise exceptions.InvalidIdentityVersion( identity_version=identity_ve...
Builds a credentials object based on the configured auth_version :param auth_url (string): Full URI of the OpenStack Identity API(Keystone) which is used to fetch the token from Identity service. :param fill_in (boolean): obtain a token and fill in all credential details provided by the identity service....
625941cfbe8e80087fb20d9f
def execute(self, session): <NEW_LINE> <INDENT> ip = cli_type_ip.ipv4_atoi(self.params[0]) <NEW_LINE> c_struct = struct.pack(self.fmt, self.major_type, self.cli_code, socket.AF_INET, ip, '') <NEW_LINE> ret = dcslib.process_cli_data(c_struct) <NEW_LINE> cli_interface.process_error(ret)
@param session: The session context @type session: Class login_context
625941cf30bbd722463cbf23
def name_object(self, obj): <NEW_LINE> <INDENT> return obj._meta.verbose_name
Overridable: describe object being deleted to the user. The result text will be included in a user notice along the lines of "<Object> deleted." :param obj: Object that's been deleted from the database. :return: Description of the object, along the lines of "User <obj.username>".
625941cf7b25080760e395b7
def get(self, name: str) -> list: <NEW_LINE> <INDENT> matches = [x for x in self.array if x.name == name and x.duration > 0] <NEW_LINE> if len(matches) > 0: <NEW_LINE> <INDENT> if name == "shield_bonus": <NEW_LINE> <INDENT> return matches[:5] <NEW_LINE> <DEDENT> elif name == "shield_malus": <NEW_LINE> <INDENT> return m...
Get specific effects by their name Returns None if the character doesn't have that effect
625941cf498bea3a759b9c0c
def get_short_name(self): <NEW_LINE> <INDENT> return self.first_name
Used to ge the short name of the user
625941cfbe7bc26dc91cd75c
def timer(func): <NEW_LINE> <INDENT> def inner_function(*args, **kwargs): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> result = func(*args, **kwargs) <NEW_LINE> duration = time.time() - start_time <NEW_LINE> print("{} ran for {} seconds".format(func.__name__, duration)) <NEW_LINE> return result <NEW_LINE> <D...
time how long a function run
625941cf1d351010ab855c79
def batchnorm_backward(dout, cache): <NEW_LINE> <INDENT> x, xc, var, std, xn, gamma = cache <NEW_LINE> N = x.shape[0] <NEW_LINE> dbeta = np.sum(dout, axis=0) <NEW_LINE> dgamma = np.sum(dout * xn, axis=0) <NEW_LINE> dxn = dout * gamma <NEW_LINE> dxc = dxn / std <NEW_LINE> dstd = np.sum(-(xc * dxn) / (std * std), axis=0)...
Backward pass for batch normalization. Inputs: - dout: Upstream derivatives, of shape (N, D) - cache: Variable of intermediates from batchnorm_forward. Returns: - dx: Gradient with respect to inputs x, of shape (N, D) - dgamma: Gradient with respect to scale parameter gamma, of shape (D,) - dbeta: Gradient with respect...
625941cf01c39578d7e74f99
def next_trial(self): <NEW_LINE> <INDENT> if self.data_obj.data and self.data_obj.proband_id != 'TEST': <NEW_LINE> <INDENT> self.data_obj.update() <NEW_LINE> self.data_obj.to_csv() <NEW_LINE> <DEDENT> if not self.data_obj.control: <NEW_LINE> <INDENT> self.data_obj.test_done = True <NEW_LINE> if self.data_obj.proband_id...
Checks to see if the test should stop, saves the data, then either quits or moves on to the next trial.
625941cf38b623060ff0af4b
def partitionLabels(self, S): <NEW_LINE> <INDENT> maxLen = len(S) <NEW_LINE> calcArr = [[maxLen, 0] for i in range(26)] <NEW_LINE> for i in range(maxLen): <NEW_LINE> <INDENT> currChar = ord(S[i]) - ord('a') <NEW_LINE> if i > calcArr[currChar][1]: <NEW_LINE> <INDENT> calcArr[currChar][1] = i <NEW_LINE> <DEDENT> if i < c...
:type S: str :rtype: List[int]
625941cfb830903b967e9a68
def __init__(self, **kw): <NEW_LINE> <INDENT> super(GradientSimulator,self).__init__(**kw)
Initialize instance. inherited instance attributes .stamp = time stamp .lapse = time lapse between updates of controller .name .store
625941cf5fdd1c0f98dc0391
def post_multiply(self, *args): <NEW_LINE> <INDENT> return _vnl_vectorPython.vnl_vectorUL_post_multiply(self, *args)
post_multiply(self, vnl_matrixUL M) -> vnl_vectorUL
625941cf5e10d32532c5f084
def _build_cuts_from_cumulative_fraction(self, props, weathering): <NEW_LINE> <INDENT> cuts = [] <NEW_LINE> frac_data = props <NEW_LINE> temp_values = range(40, 200, 20) + range(200, 701, 50) <NEW_LINE> for temp_c in temp_values: <NEW_LINE> <INDENT> label = '{}'.format(temp_c) <NEW_LINE> percent = frac_data[label] <NEW...
Build a list of EC distillation cut objects from cumulative weight fraction data. - prop_names: The list of property names - values: A list of Excel cell objects representing the properties. - weathering: The fractional oil weathering amount. Note: The labels have a bit of a problem. Most of them are percent va...
625941cfd486a94d0b98e2a3
def getSegmentList(self): <NEW_LINE> <INDENT> raise NotImplementedError
Return a list of segments.
625941cfbd1bec0571d9078d
def acceptGroupInvitation(self, reqSeq, groupId): <NEW_LINE> <INDENT> pass
Parameters: - reqSeq - groupId
625941cf004d5f362079a490
def lambda_handler(event, context): <NEW_LINE> <INDENT> print(event) <NEW_LINE> if 'body' in event: <NEW_LINE> <INDENT> event = json.loads(event["body"]) <NEW_LINE> <DEDENT> amount = float(event["amount"]) <NEW_LINE> res = [] <NEW_LINE> coins = [1,5,10,25] <NEW_LINE> coin_lookup = {25: "quarters", 10: "dimes", 5: "nick...
Accepts some US dollar input and returns the amount of change needed to make up that value. :param event: a request that has a JSON input with some "amount" value :return: a response with the correct US change to make up the amount, formatted in JSON as the number of quarters/dimes/nickels/pennies.
625941cfcad5886f8bd27137
def receive(self) -> list: <NEW_LINE> <INDENT> self._check_interval() <NEW_LINE> num_rx_vals = int(ljm.eReadName(self._handle, "ASYNCH_NUM_BYTES_RX")) <NEW_LINE> asynch_rx_vals = ljm.eReadNameArray( self._handle, "ASYNCH_DATA_RX", num_rx_vals ) <NEW_LINE> self._last_host_tick = ljm.getHostTick() <NEW_LINE> return async...
Asynchronously receive serial data from device via LabJack RX line. Returns ------- asynch_rx_vals : list Asynch response from device via LabJack RX line.
625941cfb5575c28eb68e15e
def setUp(self): <NEW_LINE> <INDENT> super(OrganizationsHelpersTestCase, self).setUp() <NEW_LINE> self.course = CourseFactory.create() <NEW_LINE> self.organization = { 'name': 'Test Organization', 'short_name': 'Orgx', 'description': 'Testing Organization Helpers Library', }
Test case scaffolding
625941cf21bff66bcd684ab0
def ev_list(self, names, print_output=True, use_cache=None): <NEW_LINE> <INDENT> if not isinstance(names, (list, tuple)): <NEW_LINE> <INDENT> raise ValueError("input should be a list or tuple, not ", type(names)) <NEW_LINE> <DEDENT> if use_cache is None: <NEW_LINE> <INDENT> use_cache = self.use_cache <NEW_LINE> <DEDENT...
Return a dictionary containing values of IDL variables in list names.
625941cf30dc7b7665901ac4
def new_screen(self)-> '2D table, list of lists': <NEW_LINE> <INDENT> result=[] <NEW_LINE> for i in range(self.rows): <NEW_LINE> <INDENT> result.append([0]*self.columns) <NEW_LINE> <DEDENT> if self.B_W=='black': <NEW_LINE> <INDENT> result[int(self.rows/2-1)][int(self.columns/2-1)]=1 <NEW_LINE> result[int(self.rows/2-1)...
Create and return an empty screen: a list of rows, with each row a list of pixels going across that row. All the pixels will be 0 (black).
625941cf7cff6e4e81117ae4
def __str__(self) -> str: <NEW_LINE> <INDENT> return f'type: {self._type}\nprice_per_month_per_gb: ${self._price_per_month_per_gb}'
Prints the volume type :return: volume type string representation :rtype: str
625941cfe64d504609d7499e
def decoding_sentence(morse_sentence): <NEW_LINE> <INDENT> morse_list = morse_sentence.split(' ') <NEW_LINE> letters = [' ' if morse=='' else decoding_character(morse) for morse in morse_list] <NEW_LINE> result = ''.join(letters) <NEW_LINE> return result
Input: - morse_sentence : 문자열 값으로 모스 부호를 표현하는 문자열 Output: - 모스부호를 알파벳으로 변환한 문자열 Examples: >>> import morsecode as mc >>> mc.decoding_sentence("... --- ...") 'SOS' >>> mc.decoding_sentence("--. .- -.-. .... --- -.") 'GACHON' >>> mc.decoding_sentence(".. .-.. --- ...- . -.-- --- ..-") ...
625941cf29b78933be1e5809
def testGetMissingRequires_requiredIdentifier(self): <NEW_LINE> <INDENT> input_lines = [ 'goog.require(\'package.Foo\');', 'package.Foo.methodName();' ] <NEW_LINE> token = self._tokenizer.TokenizeFile(input_lines) <NEW_LINE> namespaces_info = self._GetInitializedNamespacesInfo(token, ['package'], []) <NEW_LINE> self.as...
Tests that required namespaces satisfy identifiers on that namespace.
625941cf57b8e32f524835f9
def passwordDictionary(self): <NEW_LINE> <INDENT> dictionary = open("dictionary.txt", "r") <NEW_LINE> words = dictionary.readlines() <NEW_LINE> dictionary.close() <NEW_LINE> return words[random.randint(0, len(words)-1)].replace("\n","")
Takes as password one word from the dictionary.txt file
625941cfcb5e8a47e48b7c07
def find_elements(self, loc, desc=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> eles = self.driver.find_elements(*loc) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error('查找元素--【{}】--失败'.format(desc)) <NEW_LINE> log.exception(e) <NEW_LINE> self.error_save_screenshot(desc) <NEW_LINE> raise e ...
查找元素 :param loc: 元素定位器 :param desc: 元素描述 :return:
625941cfeab8aa0e5d26dcb6
def insert(self, head, insertVal): <NEW_LINE> <INDENT> temp = Node(insertVal, head) <NEW_LINE> if not head: <NEW_LINE> <INDENT> return temp <NEW_LINE> <DEDENT> node = head <NEW_LINE> while True: <NEW_LINE> <INDENT> if node.val > node.next.val and (insertVal <= node.next.val or insertVal >= node.val): <NEW_LINE> <INDENT...
:type head: Node :type insertVal: int :rtype: Node
625941cf30bbd722463cbf24
def __init__(self, winSize, blockSize, blockStride, cellSize, nbins): <NEW_LINE> <INDENT> self.img = None <NEW_LINE> self._winSize = winSize <NEW_LINE> self._blockSize = blockSize <NEW_LINE> self._cellSize = cellSize <NEW_LINE> self._nbins = nbins <NEW_LINE> self._hog = cv2.HOGDescriptor(winSize, blockSize, blockStride...
Initialize parameters. @param winSize: HoG window size @param blockSize: HoG block size @param blockStride: HoG block stride @param cellSize: HoG cell size @param nbins: HoG number of bins
625941cfd53ae8145f87a3cd
def _is_valid_homomorphism_(self, codomain, im_gens, base_map=None): <NEW_LINE> <INDENT> if base_map is None and not codomain.has_coerce_map_from(self.base_ring()): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> f = self.modulus() <NEW_LINE> try: <NEW_LINE> <INDENT> if base_map is not None: <NEW_LINE> <INDENT> f ...
EXAMPLES:: sage: T.<t> = ZZ[] sage: K.<i> = NumberField(t^2 + 1) sage: R.<x> = K[] sage: S.<a> = R.quotient(x^2 - i) sage: Q8.<z> = CyclotomicField(8) sage: S._is_valid_homomorphism_(Q8, [z]) # no coercion from K to Q8 False sage: S._is_valid_homomorphism_(Q8, [z], K.hom([z^2])) Tru...
625941cf3539df3088e2e4a9
def factor(self): <NEW_LINE> <INDENT> token = self.current_token <NEW_LINE> if token.type == PLUS: <NEW_LINE> <INDENT> self.eat(PLUS) <NEW_LINE> node = UnaryOp(token, self.factor()) <NEW_LINE> return node <NEW_LINE> <DEDENT> elif token.type == MINUS: <NEW_LINE> <INDENT> self.eat(MINUS) <NEW_LINE> node = UnaryOp(token, ...
factor : (PLUS | MINUS) factor | INTEGER | LPAREN expr RPAREN
625941cfd8ef3951e324369b
def _get_activity_index(self,id): <NEW_LINE> <INDENT> self.l_debug("_get_activity_index", str(id)) <NEW_LINE> if not self.config_good(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> cnt = 0 <NEW_LINE> for a in self.harmony_config['info']['activities']: <NEW_LINE> <INDENT> if int(a['id']) == int(id): <NEW_LINE> ...
Convert from activity index from nls, to real activity number
625941cfff9c53063f47c351
def process_text(text): <NEW_LINE> <INDENT> return word_re.sub(lambda match: process_word(match.group()), text)
Main function to be called in this module. Given some plain text return the text with primary-stressed syllables in bold. Bold is handled using HTML tags <b></b>
625941cf4f88993c3716c1c5
@tf_export('fake_quant_with_min_max_vars_gradient') <NEW_LINE> def fake_quant_with_min_max_vars_gradient(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> if num_bits i...
Compute gradients for a FakeQuantWithMinMaxVars operation. Args: gradients: A `Tensor` of type `float32`. Backpropagated gradients above the FakeQuantWithMinMaxVars operation. inputs: A `Tensor` of type `float32`. Values passed as inputs to the FakeQuantWithMinMaxVars operation. min, max: Quantization...
625941cf92d797404e3042e8