code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, date, end_time): <NEW_LINE> <INDENT> self.date = date.strftime('%d.%m') <NEW_LINE> self.start = timedelta(hours=date.hour, minutes=date.minute) <NEW_LINE> self.end = timedelta(hours=end_time.hour, minutes=end_time.minute)
Parameters ---------- date : datetime.datetime datetime object with information about record date and hour - beginning of work end_time : datetime.datetime datetime object with hour - end of work
625941d47d43ff24873a2e88
def _get_section_header_stringtable(self): <NEW_LINE> <INDENT> stringtable_section_num = self.get_shstrndx() <NEW_LINE> return StringTableSection( header=self._get_section_header(stringtable_section_num), name='', elffile=self)
Get the string table section corresponding to the section header table.
625941d463d6d428bbe446d8
def prepare(self): <NEW_LINE> <INDENT> file_name = os.path.splitext(self.fileName)[0] + '_pdf.txt' <NEW_LINE> path = self.get_path('Doc_Out',file_name) <NEW_LINE> i = 1 <NEW_LINE> while os.path.exists(path): <NEW_LINE> <INDENT> file_name = os.path.splitext(self.fileName)[0] + str(i) + '_pdf.txt' <NEW_LINE> path = self....
准备:生成的文件名和路径
625941d499cbb53fe6792dce
def additive_self_attention(units, n_hidden=None, n_output_features=None, activation=None): <NEW_LINE> <INDENT> n_input_features = K.int_shape(units)[2] <NEW_LINE> if n_hidden is None: <NEW_LINE> <INDENT> n_hidden = n_input_features <NEW_LINE> <DEDENT> if n_output_features is None: <NEW_LINE> <INDENT> n_output_features...
Computes additive self attention for time series of vectors (with batch dimension) the formula: score(h_i, h_j) = <v, tanh(W_1 h_i + W_2 h_j)> v is a learnable vector of n_hidden dimensionality, W_1 and W_2 are learnable [n_hidden, n_input_features] matrices Args: units: tf tensor with dimensionality [b...
625941d499cbb53fe6792dcf
def velocity_trace_directory(image_dir, piv_dir, *args, out_dir='', segment_images=True): <NEW_LINE> <INDENT> if not out_dir: <NEW_LINE> <INDENT> out_dir = image_dir <NEW_LINE> <DEDENT> all_images = glob.glob(image_dir+'/*.tif') <NEW_LINE> all_pivfiles = glob.glob(piv_dir+'/*.txt') <NEW_LINE> paired_files = zip(all_ima...
Given (1) the locations of a bunch of images, and (2) the locations of a bunch of PIV data sets for those images, go through the two directories and extract the boundary coordinates Parameters ---------- image_dir : str Directory of images to segment and used to extract the boundary profile out_dir : str Dir...
625941d424f1403a92600d4d
def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> h, c1 = affine_forward(X, self.params['W1'], self.params['b1']) <NEW_LINE> h, c2 = relu_forward(h) <NEW_LINE> h, c3 = affine_forward(h, self.params['W2'], self.params['b2']) <NEW_LINE> scores = h <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return ...
Compute loss and gradient for a minibatch of data. Inputs: - X: Array of input data of shape (N, d_1, ..., d_k) - y: Array of labels, of shape (N,). y[i] gives the label for X[i]. Returns: If y is None, then run a test-time forward pass of the model and return: - scores: Array of shape (N, C) giving classification sc...
625941d4cc40096d61595b38
def _convert(self, entry): <NEW_LINE> <INDENT> logger.debug(f"Found {self._get_identifier(entry)}") <NEW_LINE> logger.debug(f"Found {self._get_ingestiondate(entry)}") <NEW_LINE> return Item( harvester=self.name, source=self.source, identifier=self._get_identifier(entry), source_date=self._get_ingestiondate(entry), cont...
Convert an OpenSearch entry into an item that can be saved in the db.
625941d43eb6a72ae02ec6c8
def set_theme(self, theme): <NEW_LINE> <INDENT> self.theme = theme <NEW_LINE> self.load_theme.emit(theme) <NEW_LINE> if theme == 'contrast': <NEW_LINE> <INDENT> new_theme = ContrastTheme <NEW_LINE> new_icon = 'theme_day' <NEW_LINE> <DEDENT> elif theme == 'night': <NEW_LINE> <INDENT> new_theme = NightTheme <NEW_LINE> ne...
Sets the theme for the REPL and editor tabs.
625941d496565a6dacc8f8b3
def _s(key): <NEW_LINE> <INDENT> return merge_user_settings()[key]
Convenience function for getting the setting dict.
625941d4627d3e7fe0d69039
def __init__(self, worker_id, tasks_queue, results_queue, data, group=None, target=None, name=None, args=(), kwargs=None): <NEW_LINE> <INDENT> super(MultiprocModelsWorkerABC, self).__init__(group, target, name, args, kwargs or {}) <NEW_LINE> logger.debug(f'worker "{self.name}": creating worker with ID {worker_id}') <NE...
Initialize parallel model computations worker class with an ID `worker_id`, a queue to receive tasks from `tasks_queue`, a queue to send results to `results_queue` and the `data` to operate on. :param worker_id: process ID :param tasks_queue: queue to receive tasks from :param results_queue: queue to send results to :...
625941d423849d37ff7b3277
def Reckoning_from_10(x, n): <NEW_LINE> <INDENT> x = int(x) <NEW_LINE> X = '' <NEW_LINE> while x > n: <NEW_LINE> <INDENT> ost = x % n <NEW_LINE> x = x // n <NEW_LINE> ost = 'a' if ost == 10 else ost <NEW_LINE> ost = 'b' if ost == 11 else ost <NEW_LINE> ost = 'c' if ost == 12 else ost <NEW_LINE> ost = 'd' if ost == 13 e...
Перевод из десятичной системы в n-ю
625941d416aa5153ce36265f
def __init__(self): <NEW_LINE> <INDENT> packages = {'VERSION': {'release', 'proto_major', 'proto_minor', 'remote', 'rev'}, 'TPV': {'alt', 'climb', 'device', 'epc', 'epd', 'eps', 'ept', 'epv', 'epx', 'epy', 'lat', 'lon', 'mode', 'speed', 'tag', 'time', 'track'}, 'SKY': {'satellites', 'gdop', 'hdop', 'pdop', 'tdop', 'vdo...
Potential data packages from gpsd for a generator of class attribute dictionaries
625941d476d4e153a657ed1a
def mylog(bag, message='', verbose=True, mask_log=True): <NEW_LINE> <INDENT> if not verbose: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> mask_log_str = '' <NEW_LINE> if mask_log: <NEW_LINE> <INDENT> if test_avail(bag, "mask_log_str"): <NEW_LINE> <INDENT> mask_log_str = bag.mask_log_str <NEW_LINE> <DEDENT> else: <NEW...
# optionally prepends prefix to (all) lines of the message # and prints it out # options: # verbose (True of False) - if set to false, will not log # mask_log (True or False) - flag to mask (prepend) lines. # note: default value of the prefix_string 'mask_log' # can be changed by defining ba...
625941d44c3428357757c510
def save(self, builder_file): <NEW_LINE> <INDENT> id_persisted = True <NEW_LINE> if self._id is None: <NEW_LINE> <INDENT> id_persisted = False <NEW_LINE> self._id = uuid.uuid4().hex <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> with open(builder_file, 'wb') as f: <NEW_LINE> <INDENT> pickle.dump(self.to_dict(), f, protoc...
Serialize this RingBuilder instance to disk. :param builder_file: path to builder file to save
625941d4711fe17d82542551
def get_system_eeprom_info(self): <NEW_LINE> <INDENT> return self.sys_eeprom.system_eeprom_info()
Retrieves the full content of system EEPROM information for the chassis Returns: A dictionary where keys are the type code defined in OCP ONIE TlvInfo EEPROM format and values are their corresponding values.
625941d4b830903b967e9af2
def monitor(self, interval=1, conntimeout=3, querytimeout=3, activetimeout=1800): <NEW_LINE> <INDENT> self.log.info("%-8s: interl= %ds; querTout= %ds; actiTout= %ds; connTout= %ds;" % ( 'monitor', interval, querytimeout, activetimeout, conntimeout)) <NEW_LINE> while True: <NEW_LINE> <INDENT> gevent.sleep(interval) <NE...
监控socket链接情况,比如长时间不query,长时间不auth等,默认 1s 监控一次 conntimeout: 连接后,不 auth 步骤 querytimeout: 超时执行的query, activetimeout: 链接成功后,或者 距离上次最有一次 query,1800s没有发信息 (只对非root用户) monitor check every socket, conntimeout: after connecting, not to auth querytimeout: overtime query activetimeout: not active for a long time (just for NOT 'ro...
625941d4236d856c2ad449c3
def test_multiple_msgid(self): <NEW_LINE> <INDENT> post = {'livetranslation-popup-0-msgid': 'msgid-0', 'livetranslation-popup-1-msgid': 'msgid-1'} <NEW_LINE> data = extract_form_data(post) <NEW_LINE> self.assertEqual(data, {'1': {'msgid': 'msgid-1'}, '0': {'msgid': 'msgid-0'}})
extract_form_data gets multiple msgids from POST
625941d4462c4b4f79d1d8b8
def p_do_statement(p): <NEW_LINE> <INDENT> pass
do_statement : DO embedded_statement WHILE L_PAREN boolean_expression R_PAREN SEMI
625941d4a4f1c619b28b021e
def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp): <NEW_LINE> <INDENT> msg = MIMEText(msg, 'plain', 'utf-8') <NEW_LINE> msg['Subject'] = Header(title, 'utf-8').encode() <NEW_LINE> server = smtplib.SMTP(smtp, 25) <NEW_LINE> server.set_debuglevel(1) <NEW_LINE> server.login(from_user, from_passwor...
explanation: 邮件发送 params: * msg ->: meaning: 邮件内容 type: str optional: [null] * title ->: meaning: 标题 type: str optional: [null] * from_user ->: meaning: 来自用户 type: str optional: [null] * from_password ->: meaning: 密...
625941d44d74a7450ccd43ac
def utility(state, max_rounds): <NEW_LINE> <INDENT> if state["agents"][0] in state["goals"]: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> elif state["round"] >= max_rounds: <NEW_LINE> <INDENT> return 1
Utility function (or payoff function). Defines the final numeric value for the game that ends in the given state. Since the given state description dictionary identifies the previous player and the game is a two-player game, there is no need to pass the player as an argument. Parameters: state (dict): state descri...
625941d466673b3332b9227a
def xyz2nglview(xyz_array, cmaps=plt.cm.viridis, top=None): <NEW_LINE> <INDENT> if not isinstance(xyz_array, list): <NEW_LINE> <INDENT> xyz_array = [xyz_array] <NEW_LINE> <DEDENT> if not isinstance(cmaps, list): <NEW_LINE> <INDENT> cmaps = [cmaps] <NEW_LINE> <DEDENT> if top is None: <NEW_LINE> <INDENT> traj = [xyz2mdtr...
Display a trajectory / trajectories with nglview. Parameters ---------- xyz_array : np.array of shape (any, any, 3) or (any, 3), or list of such the trajectory data. If given as a list, the single arrays will be added to the view as different components. If the array is three-dimensional, the first dimensi...
625941d401c39578d7e75024
def password_validator(optdict, name, value): <NEW_LINE> <INDENT> return optparse.check_password(None, name, value)
validate and return a string for option of type 'password'
625941d4a4f1c619b28b021f
def pull_cells_workbook(workbook): <NEW_LINE> <INDENT> all_cells = [] <NEW_LINE> for sheet_index in range(0, len(workbook.sheet_names())): <NEW_LINE> <INDENT> sheet = None <NEW_LINE> try: <NEW_LINE> <INDENT> sheet = workbook.sheet_by_index(sheet_index) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> continue <NEW_LINE>...
Pull all the cells from all sheets in the given workbook. @param workbook (...) The ExcelBook workbook or xlrd book from which to pull cells. @return (list) A list of cells from the sheets in the workbook represented as a dict. Each cell dict is of the form { "value" : cell value, "row" : row index, "col" : column in...
625941d4442bda511e8be5fe
def _rasterize_single_polygon(self, i, method='full'): <NEW_LINE> <INDENT> if isinstance(i, Polygon): <NEW_LINE> <INDENT> global THE_POLYGONS <NEW_LINE> global THE_MASK <NEW_LINE> THE_POLYGONS = [i] <NEW_LINE> THE_MASK = np.zeros(self.lon.shape) * np.nan <NEW_LINE> _rasterize_polygon(self.lon, self.lat, 0, method) <NEW...
rasterize a single polygon; this function should in general not be used alone, but only be called from rasterize_polygons ! requires that the output array has already been initialized Parameters ---------- i : int, Polygon if an integer is provided it is assumed that it points to a global list THE_POLYGONS ...
625941d4435de62698dfde35
def __bool__(self): <NEW_LINE> <INDENT> return _pypl.DoubleVectorVector___bool__(self)
__bool__(DoubleVectorVector self) -> bool
625941d45166f23b2e1a5341
def min(self) -> KeyedItem: <NEW_LINE> <INDENT> from math import inf <NEW_LINE> min_key = inf <NEW_LINE> min_item = None <NEW_LINE> node = self._container.head <NEW_LINE> while node is not self._container._nil: <NEW_LINE> <INDENT> if node.item.key < min_key: <NEW_LINE> <INDENT> min_key = node.item.key <NEW_LINE> min_it...
O(n)
625941d4eab8aa0e5d26dd41
def remove_mask(self, name): <NEW_LINE> <INDENT> log.debug("Removing the '" + name + "' mask ...") <NEW_LINE> if name not in self.masks: raise RuntimeError("A mask with this name does not exist") <NEW_LINE> del self.masks[name]
This function ... :param name: :return:
625941d4090684286d50eecf
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(Marker, self).__init__(*args, **kwds) <NEW_LINE> if self.name is None: <NEW_LINE> <INDENT> self.name = '' <NEW_LINE> <DEDENT> if self.subject_name is None: <NEW_LINE> <INDENT> self.subject_name = '' <NEW_LINE> <DEDENT> if ...
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: name,subject_name,position,occlude...
625941d48c3a8732951585a4
def soft_update_params(net: ModelType, target_net: ModelType, tau: float) -> None: <NEW_LINE> <INDENT> for param, target_param in zip(net.parameters(), target_net.parameters()): <NEW_LINE> <INDENT> target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data)
Perform soft udpate on the net using target net. Args: net ([ModelType]): model to update. target_net (ModelType): model to update with. tau (float): control the extent of update.
625941d4293b9510aa2c347d
def downloadDatabases(self, savepath=None, unpack=False): <NEW_LINE> <INDENT> url = self.url('/diagnostics/databases') <NEW_LINE> filepath = utils.download(url, None, savepath, self._session, unpack=unpack) <NEW_LINE> return filepath
Download databases. Parameters: savepath (str): Defaults to current working dir. unpack (bool): Unpack the zip file.
625941d47047854f462a15f0
def create_detail(self, object_list, bundle): <NEW_LINE> <INDENT> self.generic_base_check(object_list, bundle) <NEW_LINE> return bundle.request.user.has_perm(self.create_permission_code)
For MakerScienceResources we let anyone with add permissions *FIXME* : this override should not be required since we assign global edit rights to all new users (see .models.py)
625941d47047854f462a15f1
def buildGo(self): <NEW_LINE> <INDENT> exe = self.getBuildArtifact("a.out") <NEW_LINE> system([[which('go'), 'build -gcflags "-N -l" -o %s main.go' % exe]])
Build the default go binary.
625941d45fdd1c0f98dc041c
def norv_correction(word): <NEW_LINE> <INDENT> return max(candidates(word), key=P)
Most probable spelling correction for word.
625941d4097d151d1a223041
def move_north(self, state): <NEW_LINE> <INDENT> return self.move(state, self.NORTH)
Return the new state when the agent moves to the North.
625941d482261d6c526ab68a
def append_provenance_step(self, provenance): <NEW_LINE> <INDENT> self._steps.append(provenance)
Append provenance object :param provenance: ProvenanceStep object :type provenance: ProvenanceStep
625941d4167d2b6e31218d7e
def flatten_column(A, col, split_func, name=None, drop=True, reset_index=True): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> name = col <NEW_LINE> <DEDENT> Y = pd.DataFrame([[i, x] for i, y in A[col].apply(split_func).iteritems() for x in y], columns=['I', name]) <NEW_LINE> Y = Y.set_index('I') <NEW_LINE> i...
column fn을 split_func 을 적용하여 나누어 여러개의 row 로 만든 DataFrame 을 돌려준다. Parameters ---------- A : DataFrame col : str, source column name split_func : object => list-like, name : str, default None * None 이면 col 을 덮어쓴다. * col 과 같으면 덮어쓴다. drop : boolean, whether drop col or not Returns ------- df : DataFrame
625941d4bd1bec0571d90818
def onEditDelete(self): <NEW_LINE> <INDENT> if self.getCurrentNodeEditorWidget(): <NEW_LINE> <INDENT> self.getCurrentNodeEditorWidget().scene.getView().deleteSelected()
Handle Delete Selected operation
625941d455399d3f0558889d
def cargarFac(cod): <NEW_LINE> <INDENT> query = QtSql.QSqlQuery() <NEW_LINE> query.prepare('select dni, apellidos from facturas where codfac = :codfac') <NEW_LINE> query.bindValue(':codfac', int(cod)) <NEW_LINE> if query.exec_(): <NEW_LINE> <INDENT> while query.next(): <NEW_LINE> <INDENT> var.ui.editDniclifac.setText(s...
Módulo que carga datos de un factura en los widgets al clickear sobre una fila de la tablaPro :param cod: código de la factura :type cod: int :return: None :rtype: None
625941d438b623060ff0afd6
def plot_3d(self, image, threshold=-300): <NEW_LINE> <INDENT> p = image.transpose(2,1,0) <NEW_LINE> verts, faces = measure.marching_cubes(p, threshold) <NEW_LINE> fig = plt.figure(figsize=(10, 10)) <NEW_LINE> ax = fig.add_subplot(111, projection='3d') <NEW_LINE> mesh = Poly3DCollection(verts[faces], alpha=0.1) <NEW_LIN...
Adapted from: https://www.kaggle.com/gzuidhof/data-science-bowl-2017/full-preprocessing-tutorial
625941d4d486a94d0b98e32f
def _deadline(self, cr, uid, ids, field_name, arg, context=None): <NEW_LINE> <INDENT> res = {} <NEW_LINE> for id in ids: <NEW_LINE> <INDENT> sprints = self.browse(cr, uid, id, context=context).sprint_ids <NEW_LINE> deadline = False <NEW_LINE> for sprint in sprints: <NEW_LINE> <INDENT> if not sprint.deadline and sprint....
Calculate the deadline from sprints related to each backlog
625941d4f9cc0f698b1407e3
def is_arm_z_image(fp): <NEW_LINE> <INDENT> return read(fp, 36, '<I', 4) == ARM_Z_IMAGE
Checks if an image is ARM zImage.
625941d45166f23b2e1a5342
@app.route('/<path:resource>-cropped-<int:width>x<int:height>.<ext>', methods=['GET', ]) <NEW_LINE> def crop(resource, width=None, height=None, ext=None): <NEW_LINE> <INDENT> return _rescale(resource, width, height, ext, True)
Resizes and crops resource object per specified qualifiers.
625941d46aa9bd52df036f8d
def hasPlayer(self, player): <NEW_LINE> <INDENT> return player in self.players
Check to see if a player is in the game @param player: Player @return: True if player is in the game @see: L{pyscrabble.game.player.Player}
625941d4462c4b4f79d1d8b9
def demo(sess, net, image_name): <NEW_LINE> <INDENT> im_file = os.path.join(img_dir, image_name) <NEW_LINE> im = cv2.imread(im_file) <NEW_LINE> timer = Timer() <NEW_LINE> timer.tic() <NEW_LINE> scores, boxes = im_detect(sess, net, im) <NEW_LINE> timer.toc() <NEW_LINE> print('Detection took {:.3f}s for {:d} object propo...
Detect object classes in an image using pre-computed object proposals.
625941d43539df3088e2e534
def __repr__(self): <NEW_LINE> <INDENT> return ('{:s}: nspec={:d}, spectrograph={:d}'.format( self.__class__.__name__, self.nspec, self.spectrograph))
Print formatting
625941d4f7d966606f6aa1ef
def valid_chain(self, chain): <NEW_LINE> <INDENT> last_block = chain[0] <NEW_LINE> current_index = 1 <NEW_LINE> while current_index < len(chain): <NEW_LINE> <INDENT> block = chain[current_index] <NEW_LINE> print('lastBlock: {last_block}'.format(last_block=last_block)) <NEW_LINE> print('currentBlock: {block}'.format(blo...
Determine if a given blockchain is valid. Consensus - longest valid chain is authoritative. :param chain: <list> a blockchain :return: <bool> True if valid, False if not.
625941d4d53ae8145f87a457
def rgb2interface(rgb): <NEW_LINE> <INDENT> if len(rgb) == 3: <NEW_LINE> <INDENT> rgb = rgb + (255,) <NEW_LINE> <DEDENT> return int('%02x%02x%02x%02x'%rgb,16)
Convert a color stored as rgb values to a 32 bit value as used by nuke for interface colors.
625941d4bde94217f3682fd9
def update_policy(self, feed_dict): <NEW_LINE> <INDENT> self.sess.run(self.pi_train_op, feed_dict=feed_dict) <NEW_LINE> return {}
update the policy based on the replay-buffer data (stored in feed_dict)
625941d4956e5f7376d71055
def subscribe(self, _message): <NEW_LINE> <INDENT> return []
noop.
625941d4b830903b967e9af3
def _check_parsed_data(self, cr, uid, stmts_vals, context=None): <NEW_LINE> <INDENT> if len(stmts_vals) == 0: <NEW_LINE> <INDENT> raise UserError(_('This file doesn\'t contain any statement.')) <NEW_LINE> <DEDENT> no_st_line = True <NEW_LINE> for vals in stmts_vals: <NEW_LINE> <INDENT> if vals['transactions'] and len(v...
Basic and structural verifications
625941d4b57a9660fec33a6f
def setAutoCommit(self, on): <NEW_LINE> <INDENT> assert self.sessionAlive, "AutoCommit can only be set on a session." <NEW_LINE> nullRequest(self, "POST", "/session/autoCommit?" + urlenc(on=on))
Only allowed when a session is active.
625941d4fbf16365ca6f63ae
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lead_generator.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 y...
Run administrative tasks.
625941d492d797404e304374
def _deserialize(self, serialized): <NEW_LINE> <INDENT> data = None <NEW_LINE> try: <NEW_LINE> <INDENT> data = json.loads(serialized) <NEW_LINE> <DEDENT> except json.decoder.JSONDecodeError: <NEW_LINE> <INDENT> if "|" in serialized: <NEW_LINE> <INDENT> data = serialized.split("|") <NEW_LINE> <DEDENT> else: <NEW_LINE> <...
internal function to deserialize multiple data types from transmission
625941d41d351010ab855d05
def get_or_create_tags(entry: FeedParserDict, feed: Feed) -> List[Tag]: <NEW_LINE> <INDENT> tags = [] <NEW_LINE> if not hasattr(entry, "tags"): <NEW_LINE> <INDENT> return tags <NEW_LINE> <DEDENT> for tag in entry.tags: <NEW_LINE> <INDENT> term = tag.term.lower().strip() <NEW_LINE> try: <NEW_LINE> <INDENT> db_tag = Tag....
From the parsed entry and given feed, get or create tags from the database.
625941d4187af65679ca5308
def unset(self, key, force=False): <NEW_LINE> <INDENT> key = upperfy(key.strip()) <NEW_LINE> if ( key not in dir(default_settings) and key not in self._defaults or force ): <NEW_LINE> <INDENT> with suppress(KeyError, AttributeError): <NEW_LINE> <INDENT> delattr(self, key) <NEW_LINE> del self.store[key]
Unset on all references :param key: The key to be unset :param force: Bypass default checks and force unset
625941d4925a0f43d254a061
def delete(self, n_days): <NEW_LINE> <INDENT> if n_days < 0: <NEW_LINE> <INDENT> raise ValueError("n_days cannot be negative") <NEW_LINE> <DEDENT> self._command.execute(DeleteLogTables.script.format(n_days))
Run the delete command from the database. :param n_days: Number of days to keep :type n_days: integer
625941d4d18da76e235326c1
def SendReply(self, response): <NEW_LINE> <INDENT> if not isinstance(response, rdfvalue.RDFValue): <NEW_LINE> <INDENT> raise RuntimeError("SendReply can only send a Semantic Value") <NEW_LINE> <DEDENT> if self.args.request_state.session_id and self.args.send_replies: <NEW_LINE> <INDENT> request_state = self.args.reques...
Allows this flow to send a message to its parent flow. If this flow does not have a parent, the message is ignored. Args: response: An RDFValue() instance to be sent to the parent. Raises: RuntimeError: If responses is not of the correct type.
625941d4c4546d3d9de72c1e
def fc_factor(self, state1, state2): <NEW_LINE> <INDENT> inx1 = state1.vsig <NEW_LINE> inx2 = state2.vsig <NEW_LINE> sta1 = state1.elstate.vibmodes <NEW_LINE> sta2 = state2.elstate.vibmodes <NEW_LINE> if not (len(sta1)==len(sta2)): <NEW_LINE> <INDENT> raise Exception("Incompatible states") <NEW_LINE> <DEDENT> res = 1.0...
Franck-Condon factors between two vibrational states Calculates Franck-Condon factor between two aggregate_states regardless of their electronic parts
625941d40fa83653e46571a4
def _deal(self) -> List[int]: <NEW_LINE> <INDENT> cards = [] <NEW_LINE> for i in range(self.num_players): <NEW_LINE> <INDENT> cards += [i for _ in range(5)] <NEW_LINE> <DEDENT> cards += [-1] * (self.num_cards - len(cards)) <NEW_LINE> random.shuffle(cards) <NEW_LINE> return cards
Overridden to deal five cards to each player.
625941d48a349b6b435e835d
def load_table_blocks(fname): <NEW_LINE> <INDENT> regionlist = [] <NEW_LINE> dflist = [] <NEW_LINE> with open(fname, errors='ignore') as f: <NEW_LINE> <INDENT> getphases = False <NEW_LINE> newregion = False <NEW_LINE> for line in f: <NEW_LINE> <INDENT> line = line.strip(' \t\n,') <NEW_LINE> if 'Phase Region for' in lin...
Load table generated by Thermo-Calc Parameters ---------- fname : string File name Returns ------- dflist : list of pandas DataFrame objects with the table data. regionlist : list with corresponding phase regions of the table
625941d4b545ff76a8913fff
def svd_get(): <NEW_LINE> <INDENT> return SVD(svd_main())
svd_get Display test accuracy of test images on compressed network after applying SVD on the original MNIST network # noqa: E501 :rtype: SVD
625941d471ff763f4b549877
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941d444b2445a3393227e
@app.route(REST_URL_PREFIX + '/questions/<int:question_id>/levels_map', methods=['GET']) <NEW_LINE> @requires_auth <NEW_LINE> def api_question_levels_map(question_id=None): <NEW_LINE> <INDENT> app.logger.debug("api_question_levels_map called with %s...\n", question_id) <NEW_LINE> if question_id is None: <NEW_LINE> <IND...
.. http:post:: questions/(int:question_id)/levels_map A map of proposal dominations. **Example request**: .. sourcecode:: http GET questions/42/levels_map HTTP/1.1 Host: example.com Accept: application/json **Example response**: .. sourcecode:: http Status Code...
625941d401c39578d7e75025
def __init__(self, expr): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parser = xpath.parser.XPath(xpath.parser.XPathScanner(str(expr))) <NEW_LINE> self.expr = parser.XPath() <NEW_LINE> <DEDENT> except xpath.yappsrt.SyntaxError as e: <NEW_LINE> <INDENT> raise xpath.exceptions.XPathParseError(str(expr), e.pos, e.msg)
Init docs.
625941d4aad79263cf390c2d
def convert_to_list(self): <NEW_LINE> <INDENT> self.reads = list(self.reads) <NEW_LINE> self.sampling = False
Method to convert reads to a list for efficient addition of reads
625941d432920d7e50b283bb
def setmaxnumselections(self, selmax): <NEW_LINE> <INDENT> if self.__validateint(selmax): <NEW_LINE> <INDENT> if selmax > 0: <NEW_LINE> <INDENT> self.maxnumselections = selmax <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Setmaxnumselections must be a positive integer.') <NEW_LINE> <DEDENT> <DEDENT> e...
Set a maximum permissible number of selections for items being selected from a validvalueset. The default for this property is 1. This property may only be safely set during the initial CI construction. Runtime changes will produce bad behavior. :param selmax: int @author: dkennel
625941d4796e427e537b07b1
def getNeighbors(self, node): <NEW_LINE> <INDENT> pass
Takes in a node index, and returns a list of the indices of the nodes neighbors. NOTE: This method does nothing in this class, and must be instantiated in subclasses.
625941d491af0d3eaac9bc04
def _assembleOption(self,option): <NEW_LINE> <INDENT> if not option.getDelimiter(): <NEW_LINE> <INDENT> delimit = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> delimit = option.getDelimiter() <NEW_LINE> <DEDENT> if not option.getSeparator(): <NEW_LINE> <INDENT> sep = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ...
Assembles the options elements
625941d496565a6dacc8f8b4
def test_auth(self): <NEW_LINE> <INDENT> response = self.client.describe_instances() <NEW_LINE> return response
测试接口权限等信息是否异常 :return:
625941d4a219f33f34628b51
def send_messages(self, email_messages): <NEW_LINE> <INDENT> if settings.MAILGUN_API_KEY is None: <NEW_LINE> <INDENT> raise MailerConfigError('Need mailgun api key') <NEW_LINE> <DEDENT> if settings.MAILGUN_DOMAIN is None: <NEW_LINE> <INDENT> raise MailerConfigError('Need mailgun domain name') <NEW_LINE> <DEDENT> base_e...
A method to send a list of emails Args: email_messages: A list of EmailMessage objects Returns: Number of successfully delivered messages Raises: commons.exceptions.MailerConfigError
625941d4b57a9660fec33a70
def check_lsmod(driver): <NEW_LINE> <INDENT> proc = Popen(["lsmod"], stdout=PIPE, stderr=PIPE) <NEW_LINE> output = proc.communicate()[0] <NEW_LINE> for line in output.decode('ascii').split('\n'): <NEW_LINE> <INDENT> if driver in line: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
Invoke lsmod and check for ftdi_sio driver.
625941d415baa723493c4160
def _setup_filter_graph(self): <NEW_LINE> <INDENT> self.current_audio_volume = self.req_audio_volume <NEW_LINE> logger.debug("Setting volume {} ".format(self.current_audio_volume)) <NEW_LINE> self.filter_graph = av.filter.Graph() <NEW_LINE> self.filter_graph_list = [] <NEW_LINE> self.filter_graph_list.append( self.filt...
Graph: buffer -> volume filter -> resample -> buffersink
625941d4dc8b845886cb571f
def touch(self): <NEW_LINE> <INDENT> self.session_start = datetime.datetime.utcnow()
Resets the session timer
625941d47cff6e4e81117b6f
def site_pip(self, site_name, site_type, bel, pin): <NEW_LINE> <INDENT> site = self.site_name_to_site[site_name][site_type] <NEW_LINE> return self.get_site_type(site.site_type_index).site_pip( site, bel, pin)
Return SitePip device resource for site PIP in site. site_name (str) - Name of site site_type (str) - Name of specific site type being queried. bel (str) - BEL name containing site PIP. pin (str) - BEL pin name for specific edge.
625941d426238365f5f0f05a
def remove_regions(query): <NEW_LINE> <INDENT> region_list_sorted = sorted(values.REGION, key=len, reverse=True) <NEW_LINE> pattern = r'(^|\s+)((?:%s)\s+)*(?:%s)\b' % ( "|".join(values.PREPOSITION), "|".join(region_list_sorted) ) <NEW_LINE> match = re.search(pattern, query) <NEW_LINE> if match: <NEW_LINE> <INDENT> quer...
Remove the names of regions in cases with prepositions.
625941d407f4c71912b1166d
def __init__(self, cbk): <NEW_LINE> <INDENT> self.rid = (os.getpid(), thread.get_ident(), time.time()) <NEW_LINE> self.cbk = cbk <NEW_LINE> self.lever = Condition() <NEW_LINE> self.done = False
- .rid: (process-wise) unique id - .cbk: what we do upon receiving reply
625941d4851cf427c661a6f7
def test_patterns_without_rules_from_config(self): <NEW_LINE> <INDENT> for pattern in AVRO_DICT['data']['patterns']: <NEW_LINE> <INDENT> if 'rules' not in pattern: <NEW_LINE> <INDENT> self.assertEqual(pattern['replace'], avro.parse(pattern['find']))
Tests all patterns from config that don't have rules
625941d4656771135c3eba5a
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941d46aa9bd52df036f8e
def vnic(self): <NEW_LINE> <INDENT> if not self.instance(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for vnic in self.instance().vnics(): <NEW_LINE> <INDENT> if vnic.mac_address.lower() == self.mac_address.lower(): <NEW_LINE> <INDENT> return vnic
Return the vnic that corresponds to this Port
625941d491f36d47f21ac6dd
def get_primary_disk(vm): <NEW_LINE> <INDENT> vmdisks = vm.get_disk_devices() <NEW_LINE> if len(vmdisks): <NEW_LINE> <INDENT> pri_target = ['vda', 'sda', 'hda'] <NEW_LINE> for target in pri_target: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return vmdisks[target]['source'] <NEW_LINE> <DEDENT> except KeyError: <NEW_LI...
Get primary disk source. :param vm: Libvirt VM object.
625941d4be8e80087fb20e2b
@contextmanager <NEW_LINE> @pytest.fixture <NEW_LINE> def fetch_api_lock(): <NEW_LINE> <INDENT> app = app_test.test_client() <NEW_LINE> app.testing = True <NEW_LINE> master_pty, slave_pty = pty.openpty() <NEW_LINE> slave_port = os.ttyname(slave_pty) <NEW_LINE> master_port = os.ttyname(master_pty) <NEW_LINE> lock_respon...
Context manager to setup and gain a lock on the serial port
625941d4dc8b845886cb5720
def cdata_section(content): <NEW_LINE> <INDENT> if content is None: <NEW_LINE> <INDENT> content = '' <NEW_LINE> <DEDENT> return "<![CDATA[%s]]>" % content
Returns a CDATA section for the given ``content``. CDATA sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string ``<![CDATA[`` and end with (and may not contain) the string ``]]>``.
625941d4a79ad161976cc32f
def test_write_to_readonly(self): <NEW_LINE> <INDENT> with zipfile.ZipFile(TESTFN2, mode="w") as zipfp: <NEW_LINE> <INDENT> zipfp.writestr("somefile.txt", "bogus") <NEW_LINE> <DEDENT> with zipfile.ZipFile(TESTFN2, mode="r") as zipfp: <NEW_LINE> <INDENT> self.assertRaises(RuntimeError, zipfp.write, TESTFN) <NEW_LINE> <D...
Check that trying to call write() on a readonly ZipFile object raises a RuntimeError.
625941d4377c676e91272392
def testClassificationsConsistentWithDiscriminants(self): <NEW_LINE> <INDENT> if not callable(getattr(self.classifier,"discriminants",None)): return <NEW_LINE> self.make_data() <NEW_LINE> self.classifier.train(self.train,self.cls,self.nclass,**self.params) <NEW_LINE> pred = self.classifier.classify(self.test) <NEW_LINE...
posteriors and discriminants need to be consistent
625941d45fdd1c0f98dc041d
def get_result(shell): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return shell.stdout.read() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return 'command complete'
returns any results from stderr and stdout using Popen.communicate() if there is nothing to read from stdout or stderr it returns an acknowledgement of the command completion
625941d4099cdd3c635f0e44
def parseSequence(self): <NEW_LINE> <INDENT> self._seqList = re.split('-|_|;|:|#', string=self._sequence) <NEW_LINE> self._seqListN = map(int, self._seqList) <NEW_LINE> self._nTypesinChain = len(set(self._seqListN)) <NEW_LINE> self._nBondTypes = ' '.join([i for i in self._sequence if not i.isdigit()]) <NEW_LINE> self._...
Parses sequences. Calculates: 1. nBondTypes - number of different bond types 2. nBondType - List containing bond information for chain (as integer) 3. numBondsPolymer - number of bonds per chain 4. nBondTypesList - original bond sequence from file 5. seqList - List containing seq...
625941d41f5feb6acb0c4d38
def change_state(hue, params, state, reset=False): <NEW_LINE> <INDENT> state = (state + 1) % (len(hue.lights) + 1) <NEW_LINE> if reset: <NEW_LINE> <INDENT> state = 0 <NEW_LINE> logger.debug("Reseting state to 0") <NEW_LINE> light_index = REF_LIGHT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> logger.debug("Changing sta...
Change the current lamp being controlled and reset buffers by default, state = 0 which means "control every lamps at once" but using change_state goes to lamp 1, then 2...and loop back to all lamps if reset is True then the state is reseting to all lamps and buffers are reset to REF_LIGHT values
625941d4d7e4931a7ee9e108
def is_view_edit_profile_inline_action_item_present(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.info('Start: is view edit profile inline action item present') <NEW_LINE> return self._system_admin_page.is_view_edit_profile_inline_action_item_present() <NEW_LINE> <DEDENT> except WebDriverException as ...
Returning is view edit profile inline action item present Implementing logging for is view edit profile inline action item present functionality :return: True/False
625941d4a934411ee375187d
def insertionSortList(self, head): <NEW_LINE> <INDENT> if head == None: return head <NEW_LINE> head, tail, tmp = head, head, head.next <NEW_LINE> head.next = None <NEW_LINE> while tmp != None: <NEW_LINE> <INDENT> ntmp = tmp.next <NEW_LINE> t = head; pre = None <NEW_LINE> while t != None: <NEW_LINE> <INDENT> if t.val > ...
:type head: ListNode :rtype: ListNode
625941d430bbd722463cbfb1
def barlineToMx(barObject): <NEW_LINE> <INDENT> mxBarline = musicxml.Barline() <NEW_LINE> mxBarline.set('barStyle', barObject.musicXMLBarStyle) <NEW_LINE> if barObject.location is not None: <NEW_LINE> <INDENT> mxBarline.set('location', barObject.location) <NEW_LINE> <DEDENT> return mxBarline
Translate a music21 bar.Bar object to an mxBar while making two substitutions: double -> light-light and final -> light-heavy as shown below. >>> b = bar.Barline('final') >>> mxBarline = musicxml.toMxObjects.barlineToMx(b) >>> mxBarline.get('barStyle') 'light-heavy'
625941d44f88993c3716c250
def download_file_by_id(file_id, download_path, drive, prompt='ask',file_count=1, total_count=1): <NEW_LINE> <INDENT> file = drive.CreateFile({ 'id' : file_id }) <NEW_LINE> fetchMetadata(file) <NEW_LINE> file_name = file['title'] <NEW_LINE> file_size = round(float(file['quotaBytesUsed'])/1000, 2) <NEW_LINE> print("Down...
Downloads a file at drive_path into the folder at download_path if file_id is known A typical drive path must be like this : Folder1_title/Folder2_title/Folder3_title or file_title Parameters ---------------- file_id : string file's id in drive download_path : string path to folder into which downloa...
625941d41b99ca400220ac9b
def read(self, name, pwd=None): <NEW_LINE> <INDENT> return self.open(name, "r", pwd).read()
Return file bytes (as a string) for name.
625941d44f88993c3716c251
def _command_matches_binary(binary, command): <NEW_LINE> <INDENT> assert isinstance(binary, str) <NEW_LINE> absolute_binary = binary.startswith('/') <NEW_LINE> absolute_command = command[0].startswith('/') <NEW_LINE> if absolute_binary: <NEW_LINE> <INDENT> if absolute_command: <NEW_LINE> <INDENT> return binary == comma...
Evaluates whether a given command matches a given binary. Example: _command_matches_binary('/bin/ls', ('ls', 'mydir')) == True
625941d4f9cc0f698b1407e4
def read_train_data() -> hlp.Trainset: <NEW_LINE> <INDENT> cat_dict = hlp.category_dict() <NEW_LINE> df_base = hlp.read_train_fillna() <NEW_LINE> df_p = predictors(df_base, cat_dict) <NEW_LINE> df_t = truth(df_base) <NEW_LINE> df_t = df_p.merge(df_t, how='outer', on=['shop_id', 'item_id']) <NEW_LINE> x: np.array = df_p...
:returns A trainset containing the data for training and cross validation
625941d4e1aae11d1e749ea2
def natural_file_size(value, binary=False, gnu=False, num_format="%.1f"): <NEW_LINE> <INDENT> suffixes = { "decimal": ("kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"), "binary": ("KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"), "gnu": "KMGTPEZY", } <NEW_LINE> if gnu: <NEW_LINE> <INDENT> suffix = suffixes["gnu"]...
Format a number of byteslike a human readable filesize (eg. 10 kB). By default, decimal suffixes (kB, MB) are used. Passing binary=true will use binary suffixes (KiB, MiB) are used and the base will be 2**10 instead of 10**3. If ``gnu`` is True, the binary argument is ignored and GNU-style (ls -sh style) prefixes ar...
625941d4d99f1b3c44c67776
def uvd2xyz(): <NEW_LINE> <INDENT> base_path = "./data/" <NEW_LINE> index = np.load('index.npy') <NEW_LINE> uvd = np.load('uvd_test.npy') <NEW_LINE> mat = np.array([[475.065948, 0, 315.944855], [0, 475.065857, 245.287079], [0, 0, 1]]) <NEW_LINE> joint_human = uvd.reshape(-1, 21, 3) <NEW_LINE> for i in range(joint_human...
test code : convert uvd to world coordinates
625941d4b545ff76a8914000
def test_remove_stopwords_phrase_first(self): <NEW_LINE> <INDENT> test_phrase = 'Matrices on a point as the theory of everything' <NEW_LINE> tokenizer = self._TOKENIZERS["BibIndexDefaultTokenizer"](remove_stopwords='stopwords.kb') <NEW_LINE> pairs_obtained = tokenizer.tokenize_for_pairs(test_phrase) <NEW_LINE> pairs_ex...
bibindex engine - getting pairs from phrase with stopwords removed first
625941d4b830903b967e9af4
def grep(self, request, response): <NEW_LINE> <INDENT> uri = response.get_uri() <NEW_LINE> if response.get_code() == 200 and uri not in self._already_inspected: <NEW_LINE> <INDENT> self._already_inspected.add(uri) <NEW_LINE> self.analyze_wsdl(request, response) <NEW_LINE> self.analyze_disco(request, response)
Plugin entry point. :param request: The HTTP request object. :param response: The HTTP response object :return: None, all results are saved in the kb.
625941d430dc7b7665901b4f
def train_model_and_predict(self, X_unlabeled): <NEW_LINE> <INDENT> model, misc = self._train(X_unlabeled) <NEW_LINE> y_pred = self._predict(model, misc) <NEW_LINE> return y_pred
trains on training data (with features also from $unlabeled_data_df) and classifies them :param X_unlabeled: ndarray containing the new unlabeled example's features :return: y_pred, the models prediction on each instance in $unlabeled_data_df
625941d463f4b57ef0001300
def iterate(iterable: Iterable) -> bool: <NEW_LINE> <INDENT> iterator = iter(iterable) <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> next(iterator) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> return True
Run over iterable to execute all elements. Useful for iterables with side-effects.
625941d4be7bc26dc91cd7e8