code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def get_weight_norm(self): <NEW_LINE> <INDENT> layer_2_w_norm = torch.norm(self.layer_2.weight, 2) <NEW_LINE> return layer_2_w_norm | Return ||W||
:return: float | 625941d99f2886367277ab2a |
def setState(self, number): <NEW_LINE> <INDENT> partials = number.split('.') <NEW_LINE> plen = len(partials) <NEW_LINE> if plen <= 5: <NEW_LINE> <INDENT> self._t0 = partials[0] <NEW_LINE> self._n0 = int(partials[0])+1 <NEW_LINE> if plen >= 2: <NEW_LINE> <INDENT> self._t1 = partials[1] <NEW_LINE> self._n1 = int(partials... | Jump starts the question number into a given state. Useful for merging operations
P.S. I really dont like the way this function works, it limits the level to 4 levels only
and makes us lose time repeating statements. We should use an array for state keeping... | 625941d930bbd722463cc067 |
def generateTrees(self, n): <NEW_LINE> <INDENT> num_list = [i for i in range(1, n + 1)] <NEW_LINE> return list(set(self.generrate(num_list))) | :type n: int
:rtype: List[TreeNode] | 625941d9e5267d203edcdf39 |
def expression_function_qop_arguments(self, t): <NEW_LINE> <INDENT> if len(t) == 2: <NEW_LINE> <INDENT> t[0] = [] <NEW_LINE> t[0].append(t[1].strip()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t[0] = t[1] <NEW_LINE> t[0].append(t[3].strip()) | expression_function_qop_arguments : TEXT
| expression_function_qop_arguments COMMA TEXT | 625941d9d268445f265b510d |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GreaterThreshold): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Return true if both objects are equal. | 625941d98e71fb1e9831da47 |
def __hash__(self): <NEW_LINE> <INDENT> return hash((self.user, self.host, self.resource)) | Calculate hash.
L{JID}s with identical constituent user, host and resource parts have
equal hash values. In combination with the comparison defined on JIDs,
this allows for using L{JID}s in sets and as dictionary keys. | 625941d999cbb53fe6792e85 |
def word_positions(self): <NEW_LINE> <INDENT> return self._get_config_property('word-positions') | Index word positions for faster phrase and near searches
(slower document loads and larger database files).
*word positions* specifies whether index data should
be included in the database files to enable proximity
searches (``cts:near-query``). When this parameter
is true, positional searches are possible, but docume... | 625941d910dbd63aa1bd2e41 |
def constructRectangle(self, area): <NEW_LINE> <INDENT> square = int(area**(1/2.0)) <NEW_LINE> while True: <NEW_LINE> <INDENT> if area % square == 0: <NEW_LINE> <INDENT> return [area / square, square] <NEW_LINE> <DEDENT> square -= 1 | :type area: int
:rtype: List[int] | 625941d94c3428357757c5c5 |
def test_pep8_model(self): <NEW_LINE> <INDENT> p8 = pep8.StyleGuide(quiet=True) <NEW_LINE> p = p8.check_files(['models/base.py']) <NEW_LINE> self.assertEqual(p.total_errors, 0, "fix pep8") | Tests for pep8 model | 625941d95fc7496912cc3c1c |
def __iter__(self): <NEW_LINE> <INDENT> return iter(self.__list[1:]) | Returns an iterator to the working values in this Fenwick Tree. | 625941d915fb5d323cde0db1 |
def compile_html(self, source, dest, is_two_file=True): <NEW_LINE> <INDENT> if not has_docutils: <NEW_LINE> <INDENT> req_missing(['docutils'], 'build this site (compile reStructuredText)') <NEW_LINE> <DEDENT> makedirs(os.path.dirname(dest)) <NEW_LINE> error_level = 100 <NEW_LINE> with codecs.open(dest, "w+", "utf8") as... | Compile reSt into HTML. | 625941d98e7ae83300e4b26c |
def test_repr(self): <NEW_LINE> <INDENT> d = defer.Deferred() <NEW_LINE> address = hex(unsignedID(d)) <NEW_LINE> self.assertEqual( repr(d), '<Deferred at %s>' % (address,)) | The C{repr()} of a L{Deferred} contains the class name and a
representation of the internal Python ID. | 625941d9a8ecb033257d336b |
def c_bool_value(value): <NEW_LINE> <INDENT> return 'true' if value else 'false' | Returns the C representation of a Boolean value. | 625941d9596a897236089d5d |
def bestof(func, *pargs, **kargs): <NEW_LINE> <INDENT> _reps = kargs.pop('_reps', 1000) <NEW_LINE> best = 2 ** 32 <NEW_LINE> for i in range(_reps): <NEW_LINE> <INDENT> start = timer() <NEW_LINE> ret = func(*pargs, **kargs) <NEW_LINE> elapsed = timer() - start <NEW_LINE> if elapsed < best: <NEW_LINE> <INDENT> best = ela... | Quickest func() among reps runs. Returns (best time, last result) | 625941d9ec188e330fd5aa39 |
def __init__(self, fish_socket_id=0): <NEW_LINE> <INDENT> _ItascaSoftwareConnection.__init__(self, fish_socket_id) <NEW_LINE> self.executable_name = "C:\\Program Files\\Itasca\\FLAC3D700\\exe64\\flac3d700_gui.exe" | (fish_socket_id=0: int) -> Instance. Constructor. | 625941d9b5575c28eb68e2a1 |
def pdvgg11_bn(pretrained=False, **kwargs): <NEW_LINE> <INDENT> if pretrained: <NEW_LINE> <INDENT> kwargs['init_weights'] = False <NEW_LINE> <DEDENT> model = PDVGG(make_layers_pd(cfg['A'], batch_norm=True), **kwargs) <NEW_LINE> if pretrained: <NEW_LINE> <INDENT> model.load_state_dict(model_zoo.load_url(model_urls['pdvg... | VGG 11-layer model (configuration "A") with batch normalization
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet | 625941d98e05c05ec3eea615 |
def checkComponent(self, component, component_name, service_name): <NEW_LINE> <INDENT> accept = False <NEW_LINE> if '*' in component.acls.keys(): <NEW_LINE> <INDENT> accept |= service_name in component.acls['*'] <NEW_LINE> <DEDENT> if component_name in component.acls.keys(): <NEW_LINE> <INDENT> accept |= service_name i... | Check that component is allowed to access to component_name.service_name() | 625941d976d4e153a657edd1 |
def either(a, b): <NEW_LINE> <INDENT> return b if a is None else a | :param a: Uncertain value (might be None).
:param b: Default value.
:return: Either the uncertain value if it is not None or the default value. | 625941d9eab8aa0e5d26ddf7 |
def arbitrary_item(S): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return iter(S).next() <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> raise IndexError("No items to select.") | Select an arbitrary item from set or sequence S.
Avoids bugs caused by directly calling iter(S).next() and
mysteriously terminating loops in callers' code when S is empty. | 625941d926238365f5f0f110 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alurareceita.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 you... | Run administrative tasks. | 625941d9090684286d50ef86 |
def dump_param(path, param=None): <NEW_LINE> <INDENT> if param is None: <NEW_LINE> <INDENT> param = default_param() <NEW_LINE> <DEDENT> with open(path + '_mcts.json', 'w') as f: <NEW_LINE> <INDENT> dump = json.dumps(param) <NEW_LINE> f.write(dump) | dump parameter for later use | 625941d9ec188e330fd5aa3a |
def set_seq2(self, b): <NEW_LINE> <INDENT> self.parser.parse(b) <NEW_LINE> super(MovieComparator, self).set_seq2(self.parser.name) <NEW_LINE> self.b_year = self.parser.year <NEW_LINE> self.b_quality = self.parser.quality | Set second string for comparison. | 625941d9d6c5a102081442eb |
def get_full_bounds(self): <NEW_LINE> <INDENT> result = self.bounds <NEW_LINE> for child in self.children: <NEW_LINE> <INDENT> result = result.get_merge(child.get_full_bounds()) <NEW_LINE> <DEDENT> return result | getter: Return full bounds which include morph bounds and all its childrend bounds | 625941d97cff6e4e81117c24 |
def new_transaction(self, productname,buyername, price, quantity,TransactionId): <NEW_LINE> <INDENT> self.current_transactions.append({ 'productname': productname, 'buyername': buyername, 'price': price, 'quantity': quantity, 'TransactionId': TransactionId }) <NEW_LINE> return self.last_block['index'] + 1 | Creates a new transaction to go into the next mined Block
:param name: Address of the name
:param price: Address of the price
:param quantity: quantity
:return: The index of the Block that will hold this transaction | 625941d91d351010ab855dba |
def __setattr__(self, name, value): <NEW_LINE> <INDENT> if name == 'data_folder': <NEW_LINE> <INDENT> self.__data_folder_check(value) <NEW_LINE> <DEDENT> super(CMDOWSObject, self).__setattr__(name, value) | Add check on data_folder when setting it.
Parameters
----------
name : str
Name of the attribute.
value : any
Value to set the attribute to. | 625941d923e79379d52ee800 |
def create_local_file(self, award_type, source, agency_code, generate_since): <NEW_LINE> <INDENT> logger.info("Generating CSV file with creations and modifications") <NEW_LINE> timestamp = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S%f") <NEW_LINE> working_dir = f"{settings.CSV_LOCAL_PATH}_{agency_code}_delta_gen_{t... | Generate complete file from SQL query and S3 bucket deletion files, then zip it locally | 625941d9925a0f43d254a118 |
def _calculate_dc(self, lux): <NEW_LINE> <INDENT> g = self.get_gain() <NEW_LINE> it = self.get_integration_time() <NEW_LINE> return int(round(lux/_lux_coeff[it][g])) | Calculate digital count that corresponds to lux value (based on current gain and integration time)
:param lux:
:type lux: float
:return:
:rtype: int | 625941d93346ee7daa2b300c |
def __init__(self, lig_obj, bs_obj, protcomplex): <NEW_LINE> <INDENT> self.ligand = lig_obj <NEW_LINE> self.name = lig_obj.name <NEW_LINE> self.lig_members = lig_obj.members <NEW_LINE> self.pdbid = protcomplex.pymol_name <NEW_LINE> self.bindingsite = bs_obj <NEW_LINE> self.idx_to_pdb = protcomplex.idx_to_pdb_mapping <N... | Detect all interactions when initializing | 625941d930dc7b7665901c03 |
def firstMissingPositive(self, nums): <NEW_LINE> <INDENT> nums.append(0) <NEW_LINE> L=len(nums) <NEW_LINE> t=0 <NEW_LINE> i=0 <NEW_LINE> for i in xrange(L): <NEW_LINE> <INDENT> if (0<nums[i]<L) and (nums[i]!=nums[nums[i]]): <NEW_LINE> <INDENT> t=nums[nums[i]] <NEW_LINE> nums[nums[i]]=nums[i] <NEW_LINE> <DEDENT> while (... | :type nums: List[int]
:rtype: int | 625941d9435de62698dfdeec |
@_patch.object(Hydrator, 'to_borrow_request', return_value=_s.borrow_request) <NEW_LINE> @_patch.object(Hydrator, '__init__', return_value=None) <NEW_LINE> @_patch.object(DatabaseQuery, 'select', return_value=[_s.record]) <NEW_LINE> @_patch.object(DatabaseQuery, '__init__', return_value=None) <NEW_LINE> def test_find_o... | Test basic functionality | 625941d9f548e778e58cd81e |
def Retrieval_Tournament(self, Seq, G, debug = False): <NEW_LINE> <INDENT> self.active_list = {} <NEW_LINE> cue = self.Project_Message_to_Neuron(Seq)[0 : self.r] <NEW_LINE> for i in range(self.r): <NEW_LINE> <INDENT> self.active_list[i] = cue[i] <NEW_LINE> <DEDENT> for i in range(self.r, self.L): <NEW_LINE> <INDENT> Ac... | This method uses the first r component of a previously learnt sequence,
Seq, together with learnt network G and returns a complete sequence | 625941d9eab8aa0e5d26ddf8 |
def flush(self): <NEW_LINE> <INDENT> self._controller._flush() | Force the flush of the HW FIFOs | 625941d944b2445a33932334 |
def _unpack_varint(self, sock): <NEW_LINE> <INDENT> data = 0 <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> ordinal = sock.recv(1) <NEW_LINE> if len(ordinal) == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> byte = ord(ordinal) <NEW_LINE> data |= (byte & 0x7F) << 7 * i <NEW_LINE> if not byte & 0x80: <NEW_LINE> <IN... | Unpack the varint | 625941d94e4d5625662d4674 |
def __batch_gradient(self, x, indices): <NEW_LINE> <INDENT> from scipy.misc import logsumexp <NEW_LINE> slices = self._project_slices(x) <NEW_LINE> global shared_slices <NEW_LINE> global shared_gradient <NEW_LINE> shared_slices[:] = slices[:] <NEW_LINE> params = [(self._orientations[i], i) for i in indices] <NEW_LINE> ... | Currently not working -> | 625941d92eb69b55b151cb51 |
def most(df: pd.DataFrame, column: str = 'value') -> pd.DataFrame: <NEW_LINE> <INDENT> return df.sort_values(by=column)[-1:] | Sort the DataFrame by a column, and then return the row with the largest value for that column.
:param df: The DataFrame to sort.
:param column: The column to sort upon.
:return: A new DataFrame with a single row. | 625941d966656f66f7cbc44c |
def _get_policy_by_arn_or_raise(arn: str, policies: List[Policy]) -> Policy: <NEW_LINE> <INDENT> for policy in policies: <NEW_LINE> <INDENT> if arn == policy.arn: <NEW_LINE> <INDENT> return policy <NEW_LINE> <DEDENT> <DEDENT> raise ValueError('Could not locate policy {}.'.format(arn)) | Helper function: pull a Policy object with the same ARN from a List, or raise a ValueError | 625941d96fece00bbac2d9e0 |
def get_steam_library_folders_maclinux(self): <NEW_LINE> <INDENT> folders = [] <NEW_LINE> steam_dir = self.get_steam_base_path_maclinux() <NEW_LINE> if not steam_dir: <NEW_LINE> <INDENT> return folders <NEW_LINE> <DEDENT> for steamapps in ['steamapps', 'SteamApps']: <NEW_LINE> <INDENT> base_library = os.path.join(steam... | Given an `steam_dir`, try to find all Steam library folders. | 625941d960cbc95b062c67e3 |
def _send_request(self, method, endpoint, headers=None, data=None): <NEW_LINE> <INDENT> return self._http_client.send_request(method, endpoint, headers, data) | for internal use only;
sends a request to the api server | 625941d921bff66bcd684bef |
def truncate_period(df, truncate_val, truncate_col='quarter'): <NEW_LINE> <INDENT> df.sort_values(truncate_col, inplace=True) <NEW_LINE> last = df.iloc[-1] <NEW_LINE> if last[truncate_col] != truncate_val: <NEW_LINE> <INDENT> df.loc[truncate_val, :] = last <NEW_LINE> df.loc[truncate_val, truncate_col] = truncate_val <N... | set the value of truncate point to the last,(to prepare for further merge) | 625941d9e64d504609d74adf |
def refresh(self, time_to_expiry): <NEW_LINE> <INDENT> request = Message.encode(turn.METHOD_REFRESH, stun.CLASS_REQUEST) <NEW_LINE> if time_to_expiry: <NEW_LINE> <INDENT> request.add_attr(turn.ATTR_LIFETIME, time_to_expiry) | :see: http://tools.ietf.org/html/rfc5766#section-6 | 625941d90a366e3fb873eabb |
def get_goodread_data(ratings_csv, books_csv): <NEW_LINE> <INDENT> df_ratings = pd.read_csv(ratings_csv) <NEW_LINE> df_books = pd.read_csv(books_csv, usecols=['book_id', 'best_book_id']) <NEW_LINE> dict_best_id = df_books.set_index(['book_id'])['best_book_id'].to_dict() <NEW_LINE> df_ratings['book_id'] = df_ratings['bo... | INPUT:
From Kaggle dataset
- ratings_csv - book_id (nothing to do with goodreads), user_id (who knows),
rating
- book_csv - we will use this to get the Kaggle book ID to the goodreads
best book id
OUTPUT:
DataFrame with the following columns:
'user_id','book_id','rating' | 625941d9a8370b7717052b3e |
def intersect(*args): <NEW_LINE> <INDENT> if not all(args): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> intersection = args[0] <NEW_LINE> for l in args[1:]: <NEW_LINE> <INDENT> intersection = [item for item in intersection if item in l] <NEW_LINE> <DEDENT> return intersection | Finds the intersection of several iterables
Args:
*args: Several iterables
Returns:
A list containing the ordered intersection of all given iterables,
where the order is defined by the first iterable | 625941d907f4c71912b11723 |
def _get_err_obj(msg): <NEW_LINE> <INDENT> err = {'errors': msg} <NEW_LINE> if hasattr(g, 'sentry_event_id'): <NEW_LINE> <INDENT> err['error_id'] = str(g.sentry_event_id) <NEW_LINE> <DEDENT> return err | Generate the error entry with a Sentry ID. | 625941d97b25080760e396f8 |
def update_geom_from_feature(self, feat): <NEW_LINE> <INDENT> geom = feat.geom <NEW_LINE> if not geom.srid: <NEW_LINE> <INDENT> raise Aquifer.BadShapefileException("Shapefile contains no projection information") <NEW_LINE> <DEDENT> wkt = wkt_w(dim=2).write(GEOSGeometry(geom.wkt, srid=geom.srid)).decode() <NEW_LINE> geo... | Given a spatial feature with Geometry, update spatial fields of the aquifer.
You must still call aquifer.save() afterwards. | 625941d90c0af96317bb8487 |
def record_current_q_cells(self): <NEW_LINE> <INDENT> store = {} <NEW_LINE> if len(self.cell_data_store) > 0: <NEW_LINE> <INDENT> prev_data_store = self.cell_data_store[self.prev_iteration_num] <NEW_LINE> update = False <NEW_LINE> for c in range(0, len(self.cell_data)): <NEW_LINE> <INDENT> cell = self.cell_data[str(c+1... | Records the data on how Q matrix cells change over time | 625941d996565a6dacc8f96a |
def model_update(t, state, model): <NEW_LINE> <INDENT> q = state[0] <NEW_LINE> p = state[1] <NEW_LINE> x = np.cos(q) <NEW_LINE> y = np.sin(q) <NEW_LINE> state = np.column_stack((x,y,p)) <NEW_LINE> state = state.reshape(-1,3) <NEW_LINE> deriv = np.zeros_like(state, dtype=np.float32) <NEW_LINE> np_x = state <NEW_LINE> x ... | Procedure model_update is for integrating a vector field parameterized by a NN or HNN.
It is used by the DynamicalSystem.get_orbit method to calculate the derivatives via the model. | 625941d91b99ca400220ad52 |
@templatedoc() <NEW_LINE> def sampling_id(x, min=0.0, max=1.0, seed=0, dtype='float32'): <NEW_LINE> <INDENT> helper = LayerHelper('sampling_id', **locals()) <NEW_LINE> out = helper.create_variable_for_type_inference(dtype) <NEW_LINE> helper.append_op( type='sampling_id', inputs={'X': x}, outputs={'Out': out}, attrs={'m... | ${comment}
Args:
x (Variable): ${x_comment}
min (Float): ${min_comment}
max (Float): ${max_comment}
seed (Float): ${seed_comment}
dtype(np.dtype|core.VarDesc.VarType|str): The type of output data : float32, float_16, int etc
Returns:
out (Variable): ${out_comment}
Examples:
.. code-block:... | 625941d9cc0a2c11143dd130 |
def pre_process_nut_config(config): <NEW_LINE> <INDENT> nut_configs = {NUT_CONFIG: collections.OrderedDict(), NUT_UPS_CONFIG: collections.OrderedDict(), NUT_UPSD_CONFIG: collections.OrderedDict(), NUT_USERS_CONFIG: collections.OrderedDict(), NUT_MONITOR_CONFIG: collections.OrderedDict()} <NEW_LINE> config['MODE'] = con... | Populates a dictionary of dictionaries where the top level dict is indexed
by a config file path & name string, each top level entry (config file) is
paired with an OrderedDict of options. This way we have:-
"file -> options_in_order" pairs.
OrderedDict allows for section head sub-section ordering eg:-
[myups]
driver =... | 625941d9d99f1b3c44c6782b |
def login(self): <NEW_LINE> <INDENT> prompt = 'Email:' if (webdriver and self.selenium.get()) or (webview and not self.selenium.get()) else 'Use browser' ' to login.\nPage Not Found will be shown at success.\n\nEmail:' <NEW_LINE> result = askstring('Login', prompt, initialvalue=self.emai... | Display login dialog and start new thread to get vehicle list | 625941d93346ee7daa2b300d |
def unpack_body(self, packet): <NEW_LINE> <INDENT> offset, self.question = utils.str2labels(packet, HEADER_LENGTH) <NEW_LINE> self.qtype, self.qclass = struct.unpack( "!HH", packet[offset:offset+4].export() ) <NEW_LINE> offset += 4 <NEW_LINE> records = [] <NEW_LINE> for _ in range(self.ancount + self.nscount): <NEW_LIN... | Parse the body data of a DNS packet. | 625941d9d268445f265b510e |
def parse_file(self, file_path, currency) -> List[PriceModel]: <NEW_LINE> <INDENT> contents = self.load_file(file_path) <NEW_LINE> prices = [] <NEW_LINE> for line in contents: <NEW_LINE> <INDENT> price = self.parse_line(line) <NEW_LINE> assert isinstance(price, PriceModel) <NEW_LINE> price.currency = currency <NEW_LINE... | Load and parse a .csv file | 625941d96fece00bbac2d9e1 |
def testKnownValuesv4n2p(self): <NEW_LINE> <INDENT> for x in self.known4Values: <NEW_LINE> <INDENT> (question, answer) = x <NEW_LINE> result = IPy._netmaskToPrefixlen(question) <NEW_LINE> self.assertEqual(answer, result, hex(question)) | conversion of known values values should give known results | 625941d98e05c05ec3eea616 |
def remove(self, data): <NEW_LINE> <INDENT> to_remove = self.find(data) <NEW_LINE> if self.head == None: <NEW_LINE> <INDENT> raise ValueError("Can't remove because list is empty") <NEW_LINE> <DEDENT> elif self.head is self.tail: <NEW_LINE> <INDENT> self.head = None <NEW_LINE> self.tail = None <NEW_LINE> self.count = 0 ... | Remove the first node in the list containing 'data'. Return nothing.
Raises:
ValueError: if the list is empty, or does not contain 'data'.
Examples:
>>> print(l1) | >>> print(l2)
[1, 3, 5, 7, 9] | [2, 4, 6, 8]
>>> l1.remove(5) | >>> l2.remove(10)
>>> l1.remove(1) | ValueErr... | 625941d90c0af96317bb8488 |
def __repr__(self): <NEW_LINE> <INDENT> return 'Ladybug Result Mesh ({} values)'.format(len(self)) | ResultMesh representation. | 625941d97047854f462a16a7 |
def __get_last_online_version(): <NEW_LINE> <INDENT> import http <NEW_LINE> conn = http.client.HTTPConnection("xael.org") <NEW_LINE> conn.request("GET", "/pages/python-nmap/python-nmap_CURRENT_VERSION.txt") <NEW_LINE> online_version = bytes.decode(conn.getresponse().read()).strip() <NEW_LINE> return online_version | Gets last python-nmap published version
WARNING : it does an http connection to http://xael.org/pages/python-nmap/python-nmap_CURRENT_VERSION.txt
:returns: a string which indicate last published version (example :'0.4.3') | 625941d901c39578d7e750db |
def process_doc(lines): <NEW_LINE> <INDENT> lines = MultiDict([(line[0], line[1:]) for line in lines]) <NEW_LINE> bill = { 'type': lines['DOCHDR'][1], 'id': lines['RCPID'][1] if 'RCPID' in lines else None, 'salesman': lines['RCPID'][0] if 'RCPID' in lines else None, 'total_price': lines['TTL'][0].replace('.', ',') if '... | processes lines
:returns bill | 625941d93539df3088e2e5eb |
def update_fn(v1, v2): <NEW_LINE> <INDENT> if not v1.trainable: <NEW_LINE> <INDENT> current_tau = tau_non_trainable <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current_tau = tau <NEW_LINE> <DEDENT> if current_tau == 1.0: <NEW_LINE> <INDENT> return v1.assign(v2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return v1.... | Update variables. | 625941d94527f215b584c6f4 |
def symbol_get_enclosure_state_capture_data(self, system_id, body, **kwargs): <NEW_LINE> <INDENT> all_params = ['system_id', 'body', 'controller', 'verbose_error_response'] <NEW_LINE> all_params.append('callback') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> i... | This procedure will retrieve state capture information from controller and expansion enclosures, including DCMs, if any. Send the command to both controllers if the tray is an RBOD.
Documented return codes: ok.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please defin... | 625941d98a349b6b435e8413 |
def make_sample_data(file_path, num_lines=2000): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> f_write = open(file_path+'_'+str(num_lines), 'r', encoding='utf8') <NEW_LINE> with open(file_path, 'r', encoding='utf8') as f: <NEW_LINE> <INDENT> for line in f: <NEW_LINE> <INDENT> f_write.write(line) <NEW_LINE> i+=1 <NEW_LINE> if i=... | How to use: make_sample_data('LM_clean_reviews_1.5M.txt') | 625941d991f36d47f21ac794 |
def __getitem__(self, key): <NEW_LINE> <INDENT> out = self.copy() <NEW_LINE> if type(key)==slice or self.isBool(key): <NEW_LINE> <INDENT> out.fcs_files = out.fcs_files[key] <NEW_LINE> <DEDENT> elif type(key)==int: <NEW_LINE> <INDENT> out.fcs_files = [out.fcs_files[key]] <NEW_LINE> <DEDENT> elif type(key)==str: <NEW_LIN... | Selects subset of files | 625941d90383005118ecf882 |
def setDict(self, name, val): <NEW_LINE> <INDENT> self.__dict__[name] = val <NEW_LINE> return self | setDict(name, val): Assign *val* to the key *name* of __dict__.
:Usage:
>>> bd = BaseDict()
>>> bd.getDict()['height']
Traceback (most recent call last):
...
KeyError: 'height'
>>> bd.setDict('height', 160) # setDict
{}
>>> bd.getDict()['height']
160 | 625941d955399d3f05588955 |
def pc_nproduced(self): <NEW_LINE> <INDENT> return _filter_swig.fractional_interpolator_cc_sptr_pc_nproduced(self) | pc_nproduced(fractional_interpolator_cc_sptr self) -> float | 625941d9a05bb46b383ecac0 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(SampleByAreaDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) | Constructor. | 625941d901c39578d7e750dc |
def error(msg): <NEW_LINE> <INDENT> print(msg) <NEW_LINE> exit(0) | 输出错误信息,退出程序
:param msg: 错误信息
:return: | 625941d9a79ad161976cc3e6 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, MachineTranslateResponse): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941d99b70327d1c4e1076 |
def get_wire_frame(self): <NEW_LINE> <INDENT> self.body_points = self.get_vertices(self.body_corners).dot(self.R) + self.x_sensed[:3] <NEW_LINE> self.head_points = self.get_vertices(self.head_corners).dot(self.R) + self.x_sensed[:3] <NEW_LINE> self.body_faces = self.get_face_tuples(self.body_points) <NEW_LINE> self.hea... | gives the array of the edges in ground frame in the order that allows for
the plotting of a line to connect the appropriate lines | 625941d99c8ee82313fbba15 |
def get_ipconfig(self): <NEW_LINE> <INDENT> if self.__https: <NEW_LINE> <INDENT> uri = 'https://' + self._address + '/rest/device/ipconfig?' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> uri = 'http://' + self._address + '/rest/device/ipconfig?' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> response = requests.get(uri, ... | Return IP config of device and set netmask and gateway properties.
:returns: A string, JSON-formatted.
:raises: ConnectionError: if unable to successfully make GET request to device. | 625941d994891a1f4081bd4a |
def generate_email_certification_code(email): <NEW_LINE> <INDENT> redis_client = current_app.config['REDIS_CLIENT'] <NEW_LINE> while True: <NEW_LINE> <INDENT> code = ''.join(random.choice(ascii_uppercase + digits) for _ in range(12)) <NEW_LINE> if not redis_client.exists(code): <NEW_LINE> <INDENT> redis_client.set(code... | 전달된 email에 12자리의 인증 코드를 매핑하여 반환합니다. 인증 코드는 하루 동안만 유효합니다. | 625941d9dc8b845886cb57d6 |
def mult_mat4(self, m, n): <NEW_LINE> <INDENT> return [ m[0]*n[0] + m[1]*n[4] + m[2]*n[8] + m[3]*n[12], m[0]*n[1] + m[1]*n[5] + m[2]*n[9] + m[3]*n[13], m[0]*n[2] + m[1]*n[6] + m[2]*n[10] + m[3]*n[14], m[0]*n[3] + m[1]*n[7] + m[2]*n[11] + m[3]*n[15], m[4]*n[0] + m[5]*n[4] + m[6]*n[8] + m[7]*n[12], m[4]... | multiply two 4X4 matricies together | 625941d931939e2706e4d107 |
def limit_check(self, context, tenant_id, resources, values): <NEW_LINE> <INDENT> unders = [key for key, val in values.items() if val < 0] <NEW_LINE> if unders: <NEW_LINE> <INDENT> raise exceptions.InvalidQuotaValue(unders=sorted(unders)) <NEW_LINE> <DEDENT> quotas = self._get_quotas(context, resources, values.keys()) ... | Check simple quota limits.
For limits--those quotas for which there is no usage
synchronization function--this method checks that a set of
proposed values are permitted by the limit restriction.
This method will raise a QuotaResourceUnknown exception if a
given resource is unknown or if it is not a simple limit
resou... | 625941d9e8904600ed9f21d0 |
def parse_msg(self, msg): <NEW_LINE> <INDENT> pass | Subclass this class and implement this method | 625941d996565a6dacc8f96b |
def update_counters(counters, chunk_id): <NEW_LINE> <INDENT> start = timer() <NEW_LINE> content = get(INPUT_BUCKET, str(chunk_id)).decode("utf-8") <NEW_LINE> for token in tokenize(content): <NEW_LINE> <INDENT> reducer_id = hash_token(token) % len(counters) <NEW_LINE> counters[reducer_id][token] += 1 <NEW_LINE> <DEDENT>... | kappa:ignore | 625941d9d8ef3951e32437de |
def test_0600_AddtoCart(self): <NEW_LINE> <INDENT> self.sheetLocation('Requisition Creation', 10, 8) <NEW_LINE> driver = self.driver <NEW_LINE> addtoCartXpath = "//button[@class='button green'][@type='submit']" <NEW_LINE> selectCartID = 'cart' <NEW_LINE> cartHeaderID = 'pageHeader' <NEW_LINE> itemNameXpath = "//span[@c... | step "RC21.6": Click "add to Cart" to add this item in your cart | 625941d98c0ade5d55d3ec5d |
def get_DH(self,samples): <NEW_LINE> <INDENT> return self.DH0*np.exp(samples) | Build expansion histories from Gaussian process samples.
Each sample gamma(z) generates a Hubble distance function
DH(z) = DH0(z)*exp(gamma(z)).
Args:
samples(ndarray): 2D array with shape (num_samples,num_steps)
of num_samples samples gamma(z) tabulated at the num_steps
redshifts z given in zvalu... | 625941d9e76e3b2f99f3aaa8 |
@cache('step') <NEW_LINE> def system_flexibility_and_adaptability_counter(): <NEW_LINE> <INDENT> return bioretention_flexibility_and_adaptability_counter( ) + bioswale_flexibility_and_adaptability_counter( ) + green_roof_flexibility_and_adaptability_counter( ) + gws_flexibility_and_adaptability_counter() + lm_flexibili... | Real Name: System Flexibility and Adaptability Counter
Original Eqn: Bioretention Flexibility and Adaptability Counter+Bioswale Flexibility and Adaptability Counter\ +Green Roof Flexibility and Adaptability Counter +GWS Flexibility and Adaptability Counter+LM Flexibility and Adaptability Counter+Porous Pavement Flexibi... | 625941d94f6381625f114cdc |
def form_valid(self, form): <NEW_LINE> <INDENT> self.object = form.save() <NEW_LINE> return self.render_to_response( self.get_context_data( form=form, tips='添加成功!', display_control=' ' ) ) | 重写函数,表单数据合法时,保存表单数据,并将指定参数传递给给模版 | 625941d9f7d966606f6aa2a8 |
def canVisitAllRooms_iter(self, rooms: List[List[int]]) -> bool: <NEW_LINE> <INDENT> dfs = [0] <NEW_LINE> seen = set(dfs) <NEW_LINE> while dfs: <NEW_LINE> <INDENT> cur = dfs.pop() <NEW_LINE> for j in rooms[cur]: <NEW_LINE> <INDENT> if j not in seen: <NEW_LINE> <INDENT> dfs.append(j) <NEW_LINE> seen.add(j) <NEW_LINE> if... | [summary]
https://leetcode.com/problems/keys-and-rooms/discuss/133855/Straight-Forward | 625941d9377c676e91272448 |
def get_from_buffer(self, topic): <NEW_LINE> <INDENT> if not ProxySubscriberCached._topics[topic]['buffered']: <NEW_LINE> <INDENT> Logger.logwarn('Attempted to access buffer of non-buffered topic!') <NEW_LINE> return None <NEW_LINE> <DEDENT> if len(ProxySubscriberCached._topics[topic]['msg_queue']) == 0: <NEW_LINE> <IN... | Pops the oldest buffered message of the given topic.
@type topic: string
@param topic: The topic of interest. | 625941d994891a1f4081bd4b |
def base64encrypt(content): <NEW_LINE> <INDENT> b_content = content.encode("utf-8") <NEW_LINE> b_base64_content = base64.encodebytes(b_content) <NEW_LINE> base64_content = b_base64_content.decode("utf-8") <NEW_LINE> return base64_content | base64加密 | 625941d9004d5f362079a5d3 |
def test_unlock_to_camera_with_passcode(self): <NEW_LINE> <INDENT> lock_screen = LockScreen(self.marionette) <NEW_LINE> camera = lock_screen.unlock_to_camera() <NEW_LINE> self.wait_for_condition(lambda m: self.device.is_locked) <NEW_LINE> camera.switch_to_secure_camera_frame() <NEW_LINE> camera.take_photo() <NEW_LINE> ... | https://moztrap.mozilla.org/manage/case/2460/ | 625941d99f2886367277ab2c |
def process_data(self): <NEW_LINE> <INDENT> self.reset_data_labels() <NEW_LINE> self.symbol_names = os.listdir(self.training_dir) <NEW_LINE> self.num_classes = len(self.symbol_names) <NEW_LINE> self.process_training_data() <NEW_LINE> self.process_testing_data() | Takes training/testing data directories and turns them into tf.datasets | 625941d9ac7a0e7691ed4369 |
def build_feature_set(self,label_section,sectionName): <NEW_LINE> <INDENT> section_dataset = [] <NEW_LINE> for doc in label_section: <NEW_LINE> <INDENT> for sentence in doc: <NEW_LINE> <INDENT> feature_set,sentence = self.feature_freq(sentence) <NEW_LINE> feats_sentence = self.build_sentence_features(feature_set[0]) <N... | * Builds the feature set of each sentence contained in the
* label_section | 625941d999cbb53fe6792e87 |
def update_learning_rate(self): <NEW_LINE> <INDENT> self.train_tb.add_scalar('learning_rate', self.optimizer.param_groups[-1]['lr'], self.clock.epoch) <NEW_LINE> if self.scheduler is not None: <NEW_LINE> <INDENT> self.scheduler.step(self.clock.epoch) | record and update learning rate | 625941d9fb3f5b602dac3936 |
def run_cmd(cmd: str, success_codes: Tuple = (0,), env: str = None) -> Dict: <NEW_LINE> <INDENT> parsed_cmd = json.loads(cmd) <NEW_LINE> parsed_env = (json.loads(env) if env is not None else None) <NEW_LINE> results = subprocess.run( parsed_cmd, capture_output=True, shell=isinstance(parsed_cmd, str), check=False, env=p... | Run CMD and return the CMD's status code and output as a dict | 625941d92ae34c7f2600d3d1 |
def getl(self, wait=False): <NEW_LINE> <INDENT> pose = self.secmon.get_cartesian_info(wait) <NEW_LINE> if pose: <NEW_LINE> <INDENT> pose = [pose["X"], pose["Y"], pose["Z"], pose["Rx"], pose["Ry"], pose["Rz"]] <NEW_LINE> <DEDENT> self.logger.debug("Current pose from robot: " + str(pose)) <NEW_LINE> return pose | get TCP position | 625941d9507cdc57c6306f80 |
def openPicture(self): <NEW_LINE> <INDENT> address = self.currentText() <NEW_LINE> if address: <NEW_LINE> <INDENT> if urltools.isRelative(address): <NEW_LINE> <INDENT> defaultPath = globalref.mainControl.defaultFilePath(True) <NEW_LINE> address = urltools.toAbsolute(address, defaultPath) <NEW_LINE> <DEDENT> openExtUrl(... | Open the link in a web browser.
| 625941d98c3a87329515865d |
@atexit.register <NEW_LINE> def quit(): <NEW_LINE> <INDENT> config.g_pool.close() <NEW_LINE> config.g_pool.terminate() <NEW_LINE> config.g_pool.join() | Close processes and quit pool at exit. | 625941d94c3428357757c5c8 |
def RenderAjax(self, request, response): <NEW_LINE> <INDENT> response = super(TreeRenderer, self).RenderAjax(request, response) <NEW_LINE> self.message = "" <NEW_LINE> result = [] <NEW_LINE> self._elements = [] <NEW_LINE> self._element_index = set() <NEW_LINE> path = request.REQ.get("path", "") <NEW_LINE> self.RenderBr... | Render the tree leafs for the tree path. | 625941d957b8e32f5248373d |
def test_render_with_request_none(self): <NEW_LINE> <INDENT> self.request = None <NEW_LINE> self.test_render() | Testing FallbackService.render with request=None | 625941d976d4e153a657edd3 |
def global_error_predict(X, D, sparse_coder, n_class_atoms, n_jobs=1): <NEW_LINE> <INDENT> E = global_error(X, D, sparse_coder, n_class_atoms, n_jobs=1) <NEW_LINE> n_samples = E.shape[1] <NEW_LINE> predictions = [] <NEW_LINE> for i in xrange(n_samples): <NEW_LINE> <INDENT> pred = np.argmin(E[:, i]) <NEW_LINE> predictio... | predict the labels of the datapoints in X
using a global SRC classifier. In other words, we first encode
each datapoint over the joint dictionary D = [D_{1} | ... | D_{C}]
and then we assign the datapoint to the class that its dictionary
achieves the best approximation. | 625941d9090684286d50ef88 |
def _detect_multi_byte(self, fb): <NEW_LINE> <INDENT> assert(len(fb) == 1) <NEW_LINE> return (ord(fb) & self._max_value) == self._max_value | _detect_multi_byte returns whether the AbstractUVarIntField is represented on
multiple bytes or not.
A multibyte representation is indicated by all of the first size bits being set
@param str fb: first byte, as a character.
@return bool: True if multibyte repr detected, else False.
@raise AssertionError | 625941d98da39b475bd65217 |
def _link(data, link, con): <NEW_LINE> <INDENT> foreigner_con = [] <NEW_LINE> for i in link: <NEW_LINE> <INDENT> i_con = i[2].split(".") <NEW_LINE> if len(i_con) == 2: <NEW_LINE> <INDENT> connector = con <NEW_LINE> table = i_con[0] <NEW_LINE> fid = i_con[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> connector = i_co... | link =
[
["sonKey","self","connetion.table.id",next_level_limit],
[null,"self","table.id"] 嵌入式且使用父级别的链接
]
:param link:
:param connection:
:return: | 625941d9ec188e330fd5aa3c |
def sample_delay(self, which): <NEW_LINE> <INDENT> return _EnergyBeamforming_swig.randphpert3_f_sptr_sample_delay(self, which) | sample_delay(randphpert3_f_sptr self, int which) -> unsigned int | 625941d97cff6e4e81117c26 |
def create_ssh(self, ip, *args, **kwargs): <NEW_LINE> <INDENT> ssh = SSH(ip, *args, **kwargs) <NEW_LINE> self.connections.setdefault(ssh, 'ssh connection') <NEW_LINE> return ssh | Create ssh connection objects. Multiple sessions supported | 625941d9be383301e01b5723 |
def capitalize(self, word): <NEW_LINE> <INDENT> return word[0].upper() + word[1:] | Returns word capitalized | 625941d9cad5886f8bd2727a |
def __init__(self, genomic_signal_objs, bed, **kwargs): <NEW_LINE> <INDENT> super(PeakMiniBrowser, self).__init__(genomic_signal_objs, **kwargs) <NEW_LINE> self.bed = bed | Signal on the top panel, peaks in the bottom panel. `bed` is a filename
or BedTool object (or list of these things) that will be used to make
a pybedtools.contrib.plotting.Track.
If genomic_signal_objs is None, then only show the peaks axes | 625941d9d10714528d5fff87 |
def generate(self, numRows): <NEW_LINE> <INDENT> if numRows <= 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> res = [[1]] <NEW_LINE> for i in range(1, numRows): <NEW_LINE> <INDENT> res.append([(0 if j == 0 else res[i - 1][j - 1]) + (0 if j == len( res[i - 1]) else res[i - 1][j]) for j in range(i + 1)]) <NEW_LINE>... | :type numRows: int
:rtype: List[List[int]] | 625941d9711fe17d82542607 |
def __repr__(self): <NEW_LINE> <INDENT> if len(self.consequent) == 1: <NEW_LINE> <INDENT> cons = self.consequent[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cons = self.consequent <NEW_LINE> <DEDENT> return ("IF {0} THEN {1}" "\n\tAND aggregation function : {2}" "\n\tOR aggregation function : {3}").format( self.a... | Concise, readable summary of the fuzzy rule. | 625941d9377c676e91272449 |
def get_items_sold_between(table, month_from, day_from, year_from, month_to, day_to, year_to): <NEW_LINE> <INDENT> games_in_years = [] <NEW_LINE> games_in_range = [] <NEW_LINE> for game in table: <NEW_LINE> <INDENT> if year_from <= int(game[game_year]) and year_to >= int(game[game_year]): <NEW_LINE> <INDENT> games_in_y... | Question: Which items are sold between two given dates? (from_date < sale_date < to_date)
Args:
table (list): data table to work on
month_from (int)
day_from (int)
year_from (int)
month_to (int)
day_to (int)
year_to (int)
Returns:
list: list of lists (the filtered table) | 625941d91f5feb6acb0c4ded |
def get_containers(self) -> typing.List["Container"]: <NEW_LINE> <INDENT> return self.spec.containers | Returns the list of containers stored in this resource if any such
containers exist. | 625941d991af0d3eaac9bcbc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.