code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def initsysfonts_unix(path="fc-list"): <NEW_LINE> <INDENT> fonts = {} <NEW_LINE> try: <NEW_LINE> <INDENT> flout, flerr = subprocess.Popen('%s : file family style' % path, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True).communicate() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> r...
use the fc-list from fontconfig to get a list of fonts
625941d07cff6e4e81117af4
def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None): <NEW_LINE> <INDENT> self.use_batchnorm = use_batchnorm <NEW_LINE> self.use_dropout = dropout > 0 <NEW_LINE> self.reg = reg <NEW_LINE> self.num_layers = 1 + len(hid...
Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then th...
625941d0cb5e8a47e48b7c17
def join_trigger(registry, xml_parent, data): <NEW_LINE> <INDENT> jointrigger = XML.SubElement(xml_parent, 'join.JoinTrigger') <NEW_LINE> joinProjectsText = ','.join(data.get('projects', [''])) <NEW_LINE> XML.SubElement(jointrigger, 'joinProjects').text = joinProjectsText <NEW_LINE> publishers = XML.SubElement(jointrig...
yaml: join-trigger Trigger a job after all the immediate downstream jobs have completed :arg bool even-if-unstable: if true jobs will trigger even if some downstream jobs are marked as unstable (default false) :arg list projects: list of projects to trigger :arg list publishers: list of triggers from publishers mo...
625941d0d53ae8145f87a3dd
def describe_trainable_vars(): <NEW_LINE> <INDENT> train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES) <NEW_LINE> if len(train_vars) == 0: <NEW_LINE> <INDENT> logger.warn("No trainable variables in the graph!") <NEW_LINE> return <NEW_LINE> <DEDENT> total = 0 <NEW_LINE> total_bytes = 0 <NEW_LINE> data = [] ...
Print a description of the current model parameters. Skip variables starting with "tower", as they are just duplicates built by data-parallel logic.
625941d026238365f5f0efdc
def group_pre(self, group): <NEW_LINE> <INDENT> for package in group: <NEW_LINE> <INDENT> self.package_pre(package)
Called before processing all the packages in a group. It calls `package_pre` for each package in an arbitrary order.
625941d0187af65679ca528d
def mid_rgb( r, g, b ): <NEW_LINE> <INDENT> single_rgb(2, r, g, b, False) <NEW_LINE> single_rgb(3, r, g, b, False) <NEW_LINE> update()
Set the middle backlight to supplied r, g, b colour Args: r (int): red value between 0 and 255 g (int): green value between 0 and 255 b (int): blue value between 0 and 255
625941d0e1aae11d1e749e25
def h(self,node, method='man'): <NEW_LINE> <INDENT> if method == 'man': <NEW_LINE> <INDENT> init_state = node.state <NEW_LINE> goal_state = self.problem.goal_state <NEW_LINE> return sum(abs(b%3 - g%3) + abs(b//3 - g//3) for b, g in ((init_state.index(i), goal_state.index(i)) for i in range(1, 9))) <NEW_LINE> <DEDENT> e...
Returns a lower bound estimate on the cost from node to the goal using the different heuristics.
625941d0d6c5a102081441b9
def dump_selected(dumpFile, dumpPath, tarPath, dumpAll=False, dumpPersons=False): <NEW_LINE> <INDENT> totalSuccess = True <NEW_LINE> errorMsg = '' <NEW_LINE> if not dumpAll: <NEW_LINE> <INDENT> propagate_selections() <NEW_LINE> <DEDENT> errorMsg += dsh_utils.black_break_msg('dumping KeyWord table...') <NEW_LINE> keyWor...
called by views.dump(). dumps selected items from each table. if dumpPersons is True, we're dumping all persons and organizations, nothing else.
625941d06fb2d068a760f20c
def compute_gradient(y, tx, w): <NEW_LINE> <INDENT> tmp = np.dot(tx,w) <NEW_LINE> tmpp = y + (tmp<0).astype(np.float) - (tmp>=0).astype(np.float) <NEW_LINE> return -np.dot(tx.T, tmpp)/float(y.shape[0])
Compute the gradient.
625941d0d58c6744b4257dce
def __len__(self): <NEW_LINE> <INDENT> return len(self.__data)
Returns the size of the list of rentals (Overriding the len() built-in function)
625941d063f4b57ef0001285
def setRelation(self, start, end, length, direction=0): <NEW_LINE> <INDENT> if not self.isIn(start) or not self.isIn(end): <NEW_LINE> <INDENT> raise IndexError('out of index: (%d, %d)' % (start, end)) <NEW_LINE> <DEDENT> if (start == end): <NEW_LINE> <INDENT> raise ValueError('add edge with equal start and end: %d' % s...
direction : 0,1: | start(beginning of node) 2: start(end of node) |
625941d01f5feb6acb0c4cbe
def push(self, value: object) -> None: <NEW_LINE> <INDENT> self.sll_val.add_front(value)
TODO: Write this implementation
625941d0ff9c53063f47c361
def test_revcorr_1d(): <NEW_LINE> <INDENT> filt = np.array(((1, 0, 0))) <NEW_LINE> stim = np.zeros((10,)) <NEW_LINE> stim[5] = 1 <NEW_LINE> response = np.convolve(filt, stim, 'full')[:stim.size] <NEW_LINE> recovered, lags = flt.revcorr(stim, response, filt.size) <NEW_LINE> assert np.allclose(recovered, filt[::-1]) <NEW...
Test computation of 1D reverse correlation. The reverse-correlation should recover the time-reverse of the linear filter, and the lags should be start at negative values and be strictly increasing.
625941d01d351010ab855c8a
def fusion_liste(liste,n): <NEW_LINE> <INDENT> l=[] <NEW_LINE> i = len(liste) <NEW_LINE> for x in range(i//4): <NEW_LINE> <INDENT> l.append(deepcopy(liste[x][3])) <NEW_LINE> <DEDENT> for x in range(i//4): <NEW_LINE> <INDENT> l.append(fusion1(deepcopy(liste[2*x][3]),deepcopy(liste[2*x+1][3]),n)) <NEW_LINE> <DEDENT> for ...
renvoie la liste : [0]: score [1]: nbiteration max [2]: la table de fin [3]: la table de debut [4]: la table de strategie
625941d076d4e153a657ec9f
def gen_title(chapelfile): <NEW_LINE> <INDENT> with open(chapelfile, 'r') as handle: <NEW_LINE> <INDENT> line1 = handle.readline() <NEW_LINE> if titlecomment(line1): <NEW_LINE> <INDENT> title = line1.lstrip('//').strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> filename = os.path.split(chapelfile)[1] <NEW_LINE> ti...
Generate file title, based on if title comment exists
625941d0925a0f43d2549fe6
def bootstrap_sample(xs: List[X], n: int = 0) -> List[X]: <NEW_LINE> <INDENT> return [random.choice(xs) for _ in (range(n) if n > 0 else xs)]
Sample a dataset with replacement to get a sub-sample
625941d0d486a94d0b98e2b4
def _create_simulations_skeleton(record_list): <NEW_LINE> <INDENT> from .. import sxs_id <NEW_LINE> return { sxs_id(r.get('title', '')): { 'url': r['links']['conceptdoi'], 'metadata_file_info': max([f for f in r.get('files', []) if '/metadata.json' in f['filename']], default={}, key=lambda f: f['filename']) } for r in ...
Create a dictionary of simulations with information for downloading SXS metadata
625941d0b7558d58953c5081
def explode(self, contactgroups, notificationways): <NEW_LINE> <INDENT> self.apply_partial_inheritance('contactgroups') <NEW_LINE> for prop in Contact.special_properties: <NEW_LINE> <INDENT> if prop == 'contact_name': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.apply_partial_inheritance(prop) <NEW_LINE> <DEDE...
Explode all contact for each contactsgroup :param contactgroups: contactgroups to explode :type contactgroups: alignak.objects.contactgroup.Contactgroups :param notificationways: notificationways to explode :type notificationways: alignak.objects.notificationway.Notificationways :return: None
625941d023849d37ff7b31fd
def apply_transform( t: Union[List[List[float]], DoubleArray], pos: AxisPosition, ) -> Tuple[float, float, float]: <NEW_LINE> <INDENT> return tuple(dot(t, list(pos))[:3])
Change of base using a transform matrix. Primarily used to render a point in space in a way that is more readable for the user. :param t: A transformation matrix from one 3D space [A] to another [B] :param pos: XYZ point in space A :return: corresponding XYZ point in space B
625941d0d8ef3951e32436ac
def write_bem_surfaces(fname, surfs): <NEW_LINE> <INDENT> if isinstance(surfs, dict): <NEW_LINE> <INDENT> surfs = [surfs] <NEW_LINE> <DEDENT> with start_file(fname) as fid: <NEW_LINE> <INDENT> start_block(fid, FIFF.FIFFB_BEM) <NEW_LINE> write_int(fid, FIFF.FIFF_BEM_COORD_FRAME, surfs[0]['coord_frame']) <NEW_LINE> _writ...
Write BEM surfaces to a fiff file Parameters ---------- fname : str Filename to write. surfs : dict | list of dict The surfaces, or a single surface.
625941d085dfad0860c3afc9
def pickf(self, n, **arg): <NEW_LINE> <INDENT> assert is_int(n) <NEW_LINE> defaults = { 'pb': None, 'pattern': r"(['\\])", 'replacement': r'\\\1', 'sep': "', '", 'head': "'", 'tail': "'", 'log_vs_raise': True } <NEW_LINE> for key in defaults: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> forget = arg[key] <NEW_LINE> <DE...
pickf(self, n, pb = None, pattern = "(['])", replacement = r'\', sep = "', '", head = "'", tail = "'", log_vs_raise = True ) Pick `n` randomly selected honey-pots and return a string. The string is prepended with `head` and appended with `tail`. The honeypots are escaped with the regular ...
625941d09c8ee82313fbb8e4
def start(self): <NEW_LINE> <INDENT> creds = self.store.get() <NEW_LINE> if not creds or creds.invalid: <NEW_LINE> <INDENT> flow = client.flow_from_clientsecrets(expanduser('~/client_secrets.json'), self.scopes) <NEW_LINE> creds = tools.run_flow(flow, self.store) <NEW_LINE> <DEDENT> http = creds.authorize(Http()) <NEW_...
Initializes G-Sheet authorization using client secret file
625941d0498bea3a759b9c1d
def marks(scenario_file_path: Path) -> List: <NEW_LINE> <INDENT> scenario_config = load_resource_file( scenario_file_path.parent, scenario_file_path.stem) <NEW_LINE> markers = [] <NEW_LINE> for mark in scenario_config.get("marks", []): <NEW_LINE> <INDENT> if mark == "canary": <NEW_LINE> <INDENT> markers.append(pytest.m...
Provides pytest markers for the given scenario Args: scenario_file_path: test scenario file path Returns: pytest markers for the scenario
625941d063b5f9789fde7254
def p_expression_list (self, p): <NEW_LINE> <INDENT> pass
expression_list : expression | expression_list COMMA expression
625941d076e4537e8c3517e1
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(PtuGotoGoal, self).__init__(*args, **kwds) <NEW_LINE> if self.pan is None: <NEW_LINE> <INDENT> self.pan = 0. <NEW_LINE> <DEDENT> if self.tilt is None: <NEW_LINE> <INDENT> self.tilt = 0. <NEW_LINE> <DEDENT> if self.pan_vel ...
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: pan,tilt,pan_vel,tilt_vel @param ...
625941d0ac7a0e7691ed423a
def reset_downloads(self): <NEW_LINE> <INDENT> for download in self.downloads.values(): <NEW_LINE> <INDENT> self.layout.removeWidget(download.progress_bar) <NEW_LINE> download.progress_bar.close() <NEW_LINE> <DEDENT> self.downloads = {}
Reset the downloads back to zero
625941d05510c4643540f551
def where_end_with(self, key, value): <NEW_LINE> <INDENT> self.where(key, 'endswith', value) <NEW_LINE> return self
Make where_ends_with clause. :@param key :@param value :@type key,value: string :@return self
625941d0460517430c3942f2
def export_image(self, fname, size=sz_plot_img): <NEW_LINE> <INDENT> gc = _chaco.PlotGraphicsContext(self.outer_bounds) <NEW_LINE> gc.render_component(self) <NEW_LINE> gc.save(fname, file_format=None)
Save plot as png image.
625941d0f548e778e58cd6ec
def get_objects(self, ids__names): <NEW_LINE> <INDENT> ids, names = parse_ids_names(ids__names) <NEW_LINE> instances = self.storage.filter( self.model_class, any, **{'id.rcontains': ids, 'label.rcontains': names} ) <NEW_LINE> if not instances: <NEW_LINE> <INDENT> raise DoesNotExistException("There aren't any instance."...
Get model list. Models will match id and label with passed ids__names list.
625941d097e22403b379d108
def getSets(): <NEW_LINE> <INDENT> queries = { 'pathwayComplexes': 'pathwayComplexes/1430728', 'pathwayParticipants': 'pathwayParticipants/1430728', } <NEW_LINE> for key in queries: <NEW_LINE> <INDENT> fn = 'downloads/{}.json'.format(key) <NEW_LINE> if not os.path.isfile(fn): <NEW_LINE> <INDENT> r = requests.get("{}/{}...
Get collections of data from Reactome pathway participants and reference molecules and proteins
625941d091f36d47f21ac661
def __init__(self, computer, ui): <NEW_LINE> <INDENT> DSKY.dsky_instance = self <NEW_LINE> self.computer = computer <NEW_LINE> output_widgets = ui.get_output_widgets() <NEW_LINE> self.annunciators = output_widgets[0] <NEW_LINE> self._control_registers = output_widgets[1] <NEW_LINE> self._data_registers = output_widgets...
Class constructor. :type ui: object :param computer: the instance of the guidance computer :return: None
625941d015fb5d323cde0c7f
def get_deployments(self, refdes, deploy_num="-1", results=pd.DataFrame()): <NEW_LINE> <INDENT> array, node, instrument = refdes.split("-", 2) <NEW_LINE> deploy_url = "/".join((self.urls["deploy"], array, node, instrument, deploy_num)) <NEW_LINE> deployments = self._get_api(deploy_url) <NEW_LINE> while len(deployments)...
Get the deployment information for an instrument. Defaults to all deployments for a given instrument (reference designator) unless one is supplied. Args: refdes (str): The reference designator for the instrument for which to request deployment information. deploy_num (str): Optional to include a specif...
625941d0b830903b967e9a79
def get_default_transcripts(self, **kwargs): <NEW_LINE> <INDENT> return [], ''
Fetch transcripts list from a video platform. Arguments: kwargs (dict): Key-value pairs of API-specific identifiers (account_id, video_id, etc.) and tokens, necessary for API calls. Returns: list: List of dicts of transcripts. Example: [ { 'lang': 'en', 'label': 'En...
625941d091af0d3eaac9bb88
def contrast(self, value): <NEW_LINE> <INDENT> assert(0x00 <= value <= 0xFF) <NEW_LINE> self._brightness = value >> 4 <NEW_LINE> if self._last_image is not None: <NEW_LINE> <INDENT> self.display(self._last_image)
Sets the LED intensity to the desired level, in the range 0-255. :param level: Desired contrast level in the range of 0-255. :type level: int
625941d056b00c62f0f147c8
def main(self): <NEW_LINE> <INDENT> loss_history = self.history.history <NEW_LINE> epochs = range(1, len(loss_history['val_loss'])+1) <NEW_LINE> final_data = (pd.DataFrame(loss_history, index=epochs)) <NEW_LINE> final_data.to_csv('results.csv', index=True)
Utility function to save loss history as csv file.
625941d05fc7496912cc3aec
def randwords(num, inseed, fn): <NEW_LINE> <INDENT> words = [] <NEW_LINE> numlines = 0 <NEW_LINE> with open(fn, 'r') as tempfile: <NEW_LINE> <INDENT> numlines = sum([1 for x in tempfile]) <NEW_LINE> <DEDENT> with open(fn, 'r') as tempfile: <NEW_LINE> <INDENT> indices = [] <NEW_LINE> if inseed: <NEW_LINE> <INDENT> seed(...
Generate random words from that text file, ensure uniqueness.
625941d0851cf427c661a67d
def redo(self): <NEW_LINE> <INDENT> model = self.doc <NEW_LINE> layer = model.layer_stack.deepget(self._layer_path) <NEW_LINE> if self._stroke_seq is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> assert self._stroke_seq.finished, "Call stop_recording() first" <NEW_LINE> if self._sshot_after is None: <NEW_LINE> <...
Performs, or re-performs after undo
625941d016aa5153ce3625e6
def search(self, target): <NEW_LINE> <INDENT> tmp = self.head <NEW_LINE> while tmp != None: <NEW_LINE> <INDENT> if tmp.get_data() == target: <NEW_LINE> <INDENT> return tmp <NEW_LINE> <DEDENT> tmp = tmp.next_node <NEW_LINE> <DEDENT> return tmp
Searches the list for the node containing the target data. Return: Data within a node or None if the node is not found.
625941d085dfad0860c3afca
def cdf(expr, condition=None, evaluate=True, **kwargs): <NEW_LINE> <INDENT> if condition is not None: <NEW_LINE> <INDENT> return cdf(given(expr, condition, **kwargs), **kwargs) <NEW_LINE> <DEDENT> result = pspace(expr).compute_cdf(expr, **kwargs) <NEW_LINE> if evaluate and hasattr(result, 'doit'): <NEW_LINE> <INDENT> r...
Cumulative Distribution Function of a random expression. optionally given a second condition This density will take on different forms for different types of probability spaces. Discrete variables produce Dicts. Continuous variables produce Lambdas. Examples ======== >>> from sympy.stats import density, Die, Normal...
625941d04f6381625f114ba9
def follow_back(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> followers_iterator = tweepy.Cursor(self.api.followers).items(self.follower_retrieve_limit) <NEW_LINE> followers = [follower for follower in followers_iterator] <NEW_LINE> for follower in followers: <NEW_LINE> <INDENT> if not self.request_sent(follower....
Retrieves a follower list of length follower_retrieve_limit and checks with the database to see if a follow request has been sent to the user in the past. If not, send the user a follow request. A follow request will ONLY be sent if a request has not been sent already. Users with protected accounts have one chance to ...
625941d0a934411ee3751802
def main(feature_folder, create_learning_curve=False): <NEW_LINE> <INDENT> with open(os.path.join(feature_folder, "info.yml")) as ymlfile: <NEW_LINE> <INDENT> feature_description = yaml.safe_load(ymlfile) <NEW_LINE> <DEDENT> path_to_data = os.path.join( utils.get_project_root(), feature_description["data-source"] ) <NE...
main function of create_ffiles.py
625941d00a50d4780f667001
def uniformCostSearch(problem): <NEW_LINE> <INDENT> frontier = util.PriorityQueue() <NEW_LINE> cost = {} <NEW_LINE> parent = {} <NEW_LINE> action = {} <NEW_LINE> actions = [] <NEW_LINE> explored = [] <NEW_LINE> currentState = problem.getStartState() <NEW_LINE> cost[currentState] = 0 <NEW_LINE> action[currentState] = No...
Search the node of least total cost first.
625941d0ad47b63b2c50a0ee
def __init__(self, model, **kwargs): <NEW_LINE> <INDENT> name = kwargs.pop('out_name', model.__name__.lower() + 's') <NEW_LINE> super(ApiResourceIndex, self).__init__(model, 'get', name, **kwargs)
:type model: subclass(api.api.ModelBase)
625941d0656771135c3eb9de
def post(self, meetup_id, rsvp): <NEW_LINE> <INDENT> message = '' <NEW_LINE> status_code = 200 <NEW_LINE> response = {} <NEW_LINE> valid_responses = ('yes', 'no', 'maybe') <NEW_LINE> if not db.exists('id', meetup_id): <NEW_LINE> <INDENT> print('Meetup not found') <NEW_LINE> status_code = 404 <NEW_LINE> message = 'Meetu...
Endpoint to RSVP to meetup
625941d02eb69b55b151ca1f
def _walk(top, topdown=True, onerror=None, followlinks=False): <NEW_LINE> <INDENT> dirs = [] <NEW_LINE> nondirs = [] <NEW_LINE> try: <NEW_LINE> <INDENT> scandir_it = scandir(top) <NEW_LINE> <DEDENT> except OSError as error: <NEW_LINE> <INDENT> if onerror is not None: <NEW_LINE> <INDENT> onerror(error) <NEW_LINE> <DEDEN...
Like Python 3.5's implementation of os.walk() -- faster than the pre-Python 3.5 version as it uses scandir() internally.
625941d0e8904600ed9f209c
def calculate_columns(self, item_widths): <NEW_LINE> <INDENT> if not item_widths: <NEW_LINE> <INDENT> return ColumnConfig([], 0) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return self.get_column_config(item_widths) <NEW_LINE> <DEDENT> except LineTooSmallError: <NEW_LINE> <INDENT> if self.allow_exceeding and self.num_...
Calculate column widths based on `item_widths`, expecting `item_widths` to be a sequence of non-negative integers that represent the length of each corresponding string. The result is returned as a named tuple that consists of two elements: A sequence of calculated column widths and the number of lines needed to displa...
625941d07d43ff24873a2e0f
def render_ui(self, editor): <NEW_LINE> <INDENT> raise NotImplementedError
创建ueditor的ui扩展对象的js代码,如button,combo等
625941d030bbd722463cbf35
def fit(self, train_x, train_y): <NEW_LINE> <INDENT> m = len(train_y) <NEW_LINE> batch = int(math.ceil(m/self._batch_size)) <NEW_LINE> for t in xrange(1, self._max_iter): <NEW_LINE> <INDENT> eta_t = 1.0/(self._lambda_reg*t) <NEW_LINE> dW = [[0 for col in range(self._feature_size)] for row in range(self._label_size)] <N...
:param train_x: list of list :param train_y: list of list :return:
625941d073bcbd0ca4b2c1e5
def browser_for(self, user): <NEW_LINE> <INDENT> if user in ['she', 'he', 'user']: <NEW_LINE> <INDENT> return self.browser <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.browsers[user]
Convenience function to look up a given user's browser, or the current one if a more general term is used.
625941d0435de62698dfddbc
def run(self): <NEW_LINE> <INDENT> success = self.open() <NEW_LINE> if not success: <NEW_LINE> <INDENT> print('Failed to initialize!') <NEW_LINE> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> self.step()
Initialize components and start broadcasting.
625941d050485f2cf553cf09
def crontab_update(content, marker): <NEW_LINE> <INDENT> crontab_remove(marker) <NEW_LINE> crontab_add(content, marker)
Adds or updates a line in crontab.
625941d0b57a9660fec339f3
def test_autogo3(dev): <NEW_LINE> <INDENT> dev[1].global_request("SET p2p_no_group_iface 0") <NEW_LINE> autogo(dev[0], freq=2462) <NEW_LINE> res = connect_cli(dev[0], dev[1], social=True, freq=2462) <NEW_LINE> if "p2p-wlan" not in res['ifname']: <NEW_LINE> <INDENT> raise Exception("Unexpected group interface name on cl...
P2P autonomous GO and client with a separate group interface joining group
625941d044b2445a33932204
def peek(self, **kwargs): <NEW_LINE> <INDENT> self._validate_data_for_ploting() <NEW_LINE> figure = plt.figure() <NEW_LINE> self.plot(**kwargs) <NEW_LINE> figure.show()
Displays the time series in a new figure. Parameters ---------- **kwargs : `dict` Any additional plot arguments that should be used when plotting.
625941d0fb3f5b602dac3803
def _evaluate(self,*args,**kwargs): <NEW_LINE> <INDENT> fixed_quad= kwargs.pop('fixed_quad',False) <NEW_LINE> if len(args) == 5: <NEW_LINE> <INDENT> R,vR,vT, z, vz= args <NEW_LINE> <DEDENT> elif len(args) == 6: <NEW_LINE> <INDENT> R,vR,vT, z, vz, phi= args <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._parse_eval_...
NAME: __call__ (_evaluate) PURPOSE: evaluate the actions (jr,lz,jz) INPUT: Either: a) R,vR,vT,z,vz[,phi]: 1) floats: phase-space value for single object (phi is optional) (each can be a Quantity) 2) numpy.ndarray: [N] phase-space values for N objects (each can be a Quantity) b) Or...
625941d0442bda511e8be587
def setUp(self): <NEW_LINE> <INDENT> self.app = create_app("testing") <NEW_LINE> self.client = self.app.test_client <NEW_LINE> self.section = { 'title': 'Test Title', 'contents': 'Some test content' } <NEW_LINE> with self.app.app_context(): <NEW_LINE> <INDENT> db.create_all()
Test SetUp
625941d023e79379d52ee6d3
def get_weakness(self): <NEW_LINE> <INDENT> return self.weakness
Returns a string containing an Enemy's weakness
625941d0be383301e01b55f4
@parametric_function_api("bn", [ ('beta', 'Trainable bias :math:`\\beta`', '<see above>', True), ('gamma', 'Trainable scaling factor :math:`\\gamma`', '<see above>', True), ('mean', 'Moving average of batch mean', '<see above>', False), ('var', 'Moving average of batch variance', '<see above>', False), ]) <NEW_LINE> de...
Batch normalization layer. .. math:: \begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array} where :math:`x_i, y_i` are the inputs. I...
625941d0d486a94d0b98e2b5
def lineage_for_certname(cli_config, certname): <NEW_LINE> <INDENT> configs_dir = cli_config.renewal_configs_dir <NEW_LINE> util.make_or_verify_dir(configs_dir, mode=0o755, uid=misc.os_geteuid()) <NEW_LINE> try: <NEW_LINE> <INDENT> renewal_file = storage.renewal_file_for_certname(cli_config, certname) <NEW_LINE> <DEDEN...
Find a lineage object with name certname.
625941d050812a4eaa59c490
def forward(self, sentence_outputs, lengths): <NEW_LINE> <INDENT> packed = pack_padded_sequence(sentence_outputs, lengths, batch_first=True) <NEW_LINE> output, _ = self.gru(packed) <NEW_LINE> output, lens = pad_packed_sequence(output, batch_first=True, padding_value=0) <NEW_LINE> return output.float()
:param sentence_outputs: Sentence vecs from the word attention layer :return:
625941d099fddb7c1c9de500
def test_by_date_and_tag(imgdir): <NEW_LINE> <INDENT> with photo.index.Index(idxfile=imgdir) as idx: <NEW_LINE> <INDENT> date = (datetime.datetime(2016, 2, 28), datetime.datetime(2016, 2, 29)) <NEW_LINE> idxfilter = photo.idxfilter.IdxFilter(tags="Tokyo", date=date) <NEW_LINE> fnames = [ str(i.filename) for i in idxfil...
Select by date and tags. Multiple selection criteria, such as date and tags may be combined.
625941d0283ffb24f3c55a70
def main(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.mkdir(TMP_DIR) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> opts, args = acid.process_args() <NEW_LINE> if args: <NEW_LINE> <INDENT> names = list(args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> names = None <NEW_LINE> <D...
Run main.
625941d03eb6a72ae02ec64f
def GetMassListFromScanNum(self, scanNumber, scanFilter="", intensityCutoffType=0, intensityCutoffValue=0, maxNumberOfPeaks=0, centroidResult=False, centroidPeakWidth=0.0): <NEW_LINE> <INDENT> peakList = comtypes.automation.VARIANT() <NEW_LINE> peakFlags = comtypes.automation.VARIANT() <NEW_LINE> pnArraySize = c_long()...
This function is only applicable to scanning devices such as MS and PDA. If no scanFilter is supplied, the scan corresponding to pnScanNumber is returned. If a scanFilter is provided, the closest matching scan to pnScanNumber that matches the scanFilter is returned. scanFilter must match the Xcalibur scanFilter format...
625941d05fcc89381b1e182f
def change_text(self, num): <NEW_LINE> <INDENT> self.bomblabel.config(text='Bombs left {}'.format(num))
Changes the text on the bomb label
625941d00a366e3fb873e98a
def sp_to_vests(self, sp, timestamp=None, use_stored_data=True): <NEW_LINE> <INDENT> return sp * 1e6 / self.get_crea_per_mvest(timestamp, use_stored_data=use_stored_data)
Converts SP to vests :param float sp: Crea power to convert :param datetime timestamp: (Optional) Can be used to calculate the conversion rate from the past
625941d0cdde0d52a9e531a3
def SetForegroundValue(self, *args): <NEW_LINE> <INDENT> return _itkGridForwardWarpImageFilterPython.itkGridForwardWarpImageFilterIVF22IUL2_SetForegroundValue(self, *args)
SetForegroundValue(self, unsigned long _arg)
625941d0627d3e7fe0d68fc0
def get_file_parent_dir_path(level=1): <NEW_LINE> <INDENT> current_dir_path = dirname(abspath(__file__)) <NEW_LINE> path_sep = os.path.sep <NEW_LINE> components = current_dir_path.split(path_sep) <NEW_LINE> return path_sep.join(components[:-level])
return the path of the parent directory of current file
625941d0287bf620b61d3bd3
def REPLACEB(*args) -> Function: <NEW_LINE> <INDENT> return Function("REPLACEB", args)
Replaces part of a text string, based on a number of bytes, with a different text string. Learn more: https//support.google.com/docs/answer/9367752.
625941d0293b9510aa2c3405
def ImageToPdf(outputpath, imagepath): <NEW_LINE> <INDENT> lists = list(imagepath.glob("**/*")) <NEW_LINE> print(f'lists = {lists}') <NEW_LINE> with open(outputpath,"wb") as f: <NEW_LINE> <INDENT> f.write(img2pdf.convert([str(i) for i in lists if i.match("*.jpg") or i.match("*.png")])) <NEW_LINE> <DEDENT> print(outputp...
outputpath: pathlib.Path() imagepath: pathlib.Path()
625941d0aad79263cf390bb1
def get_sum_frequencies(list_files): <NEW_LINE> <INDENT> df_sum = pd.read_csv(list_files[0], sep="\t", index_col=0) <NEW_LINE> if len(list_files) == 1: <NEW_LINE> <INDENT> return df_sum.sort_values("frequencies", ascending=False) <NEW_LINE> <DEDENT> for i in range(1, len(list_files)): <NEW_LINE> <INDENT> df = pd.read_c...
Get the average frequencies of every hexanucleotide of ``list_files``. :param list_files: (list of string) list of files :return: (pandas DataFrame) the average frequencies of every hexanucleotide found in ``list_files``
625941d0236d856c2ad4494b
def __init__(self): <NEW_LINE> <INDENT> self.verts=None <NEW_LINE> self.color=None <NEW_LINE> self.texture=None <NEW_LINE> self.texverts=None
verts. Array de Coord3D color: Color del poligono is a Color object texture: Textura del pol´igno que es un TTextures value. Si no tiene debe valer None texCoord: Array de Coord2D de la textura
625941d0a934411ee3751803
def test_duplicate_normalized_unicode(self): <NEW_LINE> <INDENT> omega_username = 'iamtheΩ' <NEW_LINE> ohm_username = 'iamtheΩ' <NEW_LINE> self.assertNotEqual(omega_username, ohm_username) <NEW_LINE> User.objects.create_user(username=omega_username, password='pwd') <NEW_LINE> data = { 'username': ohm_username, 'passwor...
To prevent almost identical usernames, visually identical but differing by their unicode code points only, Unicode NFKC normalization should make appear them equal to Django.
625941d04a966d76dd55117f
def clear(self, fill = 0x00): <NEW_LINE> <INDENT> self._buffer = [ fill ] * ( self.width * self._mem_pages )
! \~english Clear buffer data and fill color into buffer @param fill: a color value, it will fill into buffer.<br> The SSD1306 only chosen two colors: <br> 0 (0x0): black <br> 1 (0x1): white <br> \~chinese 清除缓冲区数据并在缓冲区中填充颜色 @param fill: 一个颜色值,它会填充到缓冲区中 <br>              SSD1306只能选择两种颜色: <...
625941d0be7bc26dc91cd76e
def cutmix( self, data: torch.Tensor, labels: torch.Tensor, alpha: float = 0.4 ) -> MixupOutput: <NEW_LINE> <INDENT> indices = torch.randperm(data.size(0)) <NEW_LINE> shuffled_data = data[indices] <NEW_LINE> shuffled_labels = labels[indices] <NEW_LINE> lam = np.random.beta(alpha, alpha, size=len(indices)) <NEW_LINE> la...
Transforms input batch into cutmixed batch Args: data: input batch data labels: input batch labels alpha: Beta distribution argument to generate weights for cutmix Returns: MixupOutput with cutmixed data and labels
625941d0d18da76e23532646
def process_update(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> subprocess.check_output('git pull', stderr=subprocess.STDOUT, shell=True, universal_newlines=True) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> print(f'\nUnable to update application. Try to manually "git pull" or ' f'"git clone" this repos...
Update (git pull) project. :return: Void.
625941d0925a0f43d2549fe7
def update(self, fire_after=None, expire_after=None, callback=None, callback_error=None, init=False): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> if expire_after is not None: <NEW_LINE> <INDENT> self.expire_at = now + expire_after <NEW_LINE> if self.fire_at > self.expire_at: <NEW_LINE> <INDENT> self.fire_at = self...
Update the entry information Args: fire_after (float): set callback (periodical) to fire after given time (in second) expire_after (float): set expiration timer to given time (in second) callback (obj): callback method that will be called periodically callback_error (obj): callback method that will be ...
625941d0435de62698dfddbd
def redivideClusters(cosmatrix,k,docmatrix): <NEW_LINE> <INDENT> clusters = [[] for _ in range(k)] <NEW_LINE> x,y = np.where(cosmatrix == np.max(cosmatrix,axis=0)) <NEW_LINE> for i,j in zip(x,y): <NEW_LINE> <INDENT> clusters[i].append(j) <NEW_LINE> <DEDENT> nseeds = [] <NEW_LINE> for cluster in clusters: <NEW_LINE> <IN...
cosmatrix:根据中心点计算出的余弦矩阵 将文档划分到对应的簇,并返回新划分的簇和对应簇的中心点
625941d0004d5f362079a4a2
def nullspace(A, atol=1e-13, rtol=0): <NEW_LINE> <INDENT> A = np.atleast_2d(A) <NEW_LINE> u, s, vh = svd(A) <NEW_LINE> tol = max(atol, rtol * s[0]) <NEW_LINE> nnz = (s >= tol).sum() <NEW_LINE> ns = vh[nnz:].conj().T <NEW_LINE> return scipy.linalg.orth(ns)
Compute an approximate basis for the nullspace of A. The algorithm used by this function is based on the singular value decomposition of `A`. Parameters ---------- A : ndarray A should be at most 2-D. A 1-D array with length k will be treated as a 2-D with shape (1, k) atol : float The absolute tolerance...
625941d031939e2706e4cfd9
def suggest_model_using_sensitivity(self): <NEW_LINE> <INDENT> threshold = self._option[self._tenv.regression_sval_threshold] <NEW_LINE> norm_s = self.get_normalized_sensitivity() <NEW_LINE> dv = self.get_response() <NEW_LINE> predictors = self.get_predictors() <NEW_LINE> self.dv_iv_map = dict( [(d, [p for i, p in enum...
After doing linear regression (run()), one may want to call this function to see which terms are significant Select terms from a full expansion list by observing the Normalized Input Sensitivity (NIS) in [%] NIS >= threhold in [%]
625941d0bde94217f3682f60
def generate_monthly_time_axis(startyear, nyears, timefmt="ncar"): <NEW_LINE> <INDENT> nyears = nyears + 1 <NEW_LINE> years = np.arange(startyear, startyear + nyears) <NEW_LINE> years = [year for year in years for x in range(12)] <NEW_LINE> months = list(np.arange(1, 13)) * nyears <NEW_LINE> days = 1 if timefmt == "nca...
Construct a monthly noleap time dimension with associated bounds Parameters ---------- startyear : int Start year for requested time axis nyears : int Number of years in requested time axis timefmt : str, optional Time axis format, either "cmip", "gfdl" or "ncar", "ncar" by default Returns ------- xarray....
625941d0e5267d203edcde0c
def canDouble(self,hand): <NEW_LINE> <INDENT> if (self._wallet - hand._bet) <= 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True
Determines whether a player has enough money to double down
625941d026238365f5f0efde
def get_moved_pages_redirects(self): <NEW_LINE> <INDENT> if self.offset <= 0: <NEW_LINE> <INDENT> self.offset = 1 <NEW_LINE> <DEDENT> start = (datetime.datetime.utcnow() - datetime.timedelta(0, self.offset * 3600)) <NEW_LINE> offset_time = start.strftime("%Y%m%d%H%M%S") <NEW_LINE> pywikibot.output(u'Retrieving %s moved...
Generate redirects to recently-moved pages.
625941d0ac7a0e7691ed423b
def _set_B_and_lmove_(self,M,nmax=None,tol=None): <NEW_LINE> <INDENT> if self.cut==0: raise ValueError('MPS _set_B_and_lmove_ error: the cut is already zero.') <NEW_LINE> L,S,R=M.labels[MPS.L],M.labels[MPS.S],M.labels[MPS.R] <NEW_LINE> u,s,v=svd(M,row=[L],new=Label('__MPS_set_B_and_lmove__',None,None),col=[S,R],nmax=nm...
Set the B matrix at self.cut and move leftward. Parameters ---------- M : DTensor/STensor The tensor used to set the B matrix. nmax : int, optional The maximum number of singular values to be kept. tol : float, optional The truncation tolerance.
625941d08a349b6b435e82e3
def get_save_file_path(name): <NEW_LINE> <INDENT> return constants.SAVE_DATA_PATH + constants.SAVED_DATA_NAME_TAG + '_' + name + '.csv'
Returns the save file path of a file given its name. str -> str
625941d07c178a314d6ef5d1
def add(self, *objects): <NEW_LINE> <INDENT> for obj in objects: <NEW_LINE> <INDENT> if obj not in self._plotcontext.children: <NEW_LINE> <INDENT> self._plotcontext.children.append(obj) <NEW_LINE> self._plotcontext._dirty = True <NEW_LINE> <DEDENT> self._add(*obj.references())
Add top level objects to this Document. Also traverses references and adds those as well. This function should only be called on top level objects. lower level objects are added using _add Args: *objects (PlotObject) : objects to add to the Document Returns: None
625941d073bcbd0ca4b2c1e6
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
625941d0167d2b6e31218d06
def coverage_report_plain(): <NEW_LINE> <INDENT> test() <NEW_LINE> local('coverage report -m --fail-under=77')
Runs all tests and prints the coverage report.
625941d0fbf16365ca6f6336
def select_keypairs_name_substring(self, search_substring): <NEW_LINE> <INDENT> for keypair in self._cloud.list_keypairs(): <NEW_LINE> <INDENT> if search_substring in keypair['name']: <NEW_LINE> <INDENT> if keypair['name'] in ('rhos-jenkins'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self._add('keypairs', keypa...
Select keypairs based on substring.
625941d0a8370b7717052a0f
def prepare_empty_partition_btrfs(self, rootfs, oe_builddir, native_sysroot): <NEW_LINE> <INDENT> size = self.disk_size <NEW_LINE> with open(rootfs, 'w') as sparse: <NEW_LINE> <INDENT> os.ftruncate(sparse.fileno(), size * 1024) <NEW_LINE> <DEDENT> label_str = "" <NEW_LINE> if self.label: <NEW_LINE> <INDENT> label_str =...
Prepare an empty btrfs partition.
625941d06fb2d068a760f20e
def train(data_loader, model, optimizer, device): <NEW_LINE> <INDENT> model.train() <NEW_LINE> for data in data_loader: <NEW_LINE> <INDENT> reviews = data["reviews"] <NEW_LINE> targets = data["target"] <NEW_LINE> reviews = reviews.to(device, dtype=torch.long) <NEW_LINE> targets = targets.to(device, dtype=torch.float) <...
This is the main training function that trains model for one epoch :param data_loader: this is the torch dataloader :param model: model (lstm model) :param optimizer: torch optimizer, e.g. adam, sgd, etc. :param device: this can be "cuda" or "cpu"
625941d08a349b6b435e82e4
def count_events(self): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> self.fp.seek(0) <NEW_LINE> while True: <NEW_LINE> <INDENT> size = self._read_event_size() <NEW_LINE> if not size: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.fp.seek(size, 1) <NEW_LINE> count += 1 <NEW_LINE> <DEDENT> return count
Count events from file. This skips parsing any data so should be quite fast. Useful for progress bars etc.
625941d00fa83653e465712b
def describe_snapshots(DirectoryId=None, SnapshotIds=None, NextToken=None, Limit=None): <NEW_LINE> <INDENT> pass
Obtains information about the directory snapshots that belong to this account. This operation supports pagination with the use of the NextToken request and response parameters. If more results are available, the DescribeSnapshots.NextToken member contains a token that you pass in the next call to DescribeSnaps...
625941d01d351010ab855c8c
def vectordsc(corpus, train_text, test_text): <NEW_LINE> <INDENT> word_vectorizer = TfidfVectorizer( sublinear_tf=True, strip_accents='unicode', analyzer='word', token_pattern=r'\w{1,}', stop_words='english', ngram_range=(1, 2), max_features=10000) <NEW_LINE> word_vectorizer.fit(corpus) <NEW_LINE> train_word_features =...
Convert the description text into ngram vector of features. Sparse matrix format
625941d0566aa707497f46d8
def viewDelta(self, dt, file_parameters): <NEW_LINE> <INDENT> x = np.zeros((dt.num_rows, 1)) <NEW_LINE> y = np.zeros((dt.num_rows, 1)) <NEW_LINE> x[:, 0] = dt.data[:, 0] <NEW_LINE> y[:, 0] = np.arctan2(dt.data[:, 2], dt.data[:, 1]) * 180 / np.pi <NEW_LINE> return x, y, True
Loss or phase angle :math:`\delta(\omega)=\arctan(G''/G')\cdot 180/\pi` (in degrees, in logarithmic scale) vs :math:`\omega` (in logarithmic scale)
625941d0d8ef3951e32436ae
def create_product(self, data: Dict) -> Dict: <NEW_LINE> <INDENT> data = dict(product=data) <NEW_LINE> return self._post(self.URL_PRODUCTS, data)['product']
Create new product in the shop :param data: Data to be set on the product :return: Newly created product
625941d0a05bb46b383ec991
def tell_bots(self, lines, silently=False): <NEW_LINE> <INDENT> for bot in self.bots: <NEW_LINE> <INDENT> self.__tell_bot(bot, lines, silently) <NEW_LINE> silently = True
Tell all bots something through STDIN
625941d0dd821e528d63b319
def elementwise_sub(a, b): <NEW_LINE> <INDENT> c = copy.deepcopy(a) <NEW_LINE> for i, row in enumerate(a): <NEW_LINE> <INDENT> for j, num in enumerate(row): <NEW_LINE> <INDENT> c[i][j] -= b[i][j] <NEW_LINE> <DEDENT> <DEDENT> return c
Elementwise substraction.
625941d056ac1b37e626433e
def finish_job(self, job): <NEW_LINE> <INDENT> if not job.complete(): <NEW_LINE> <INDENT> raise eva.exceptions.RetryException("NcML aggregation to file '%s' failed.", job.output_filename) <NEW_LINE> <DEDENT> job.logger.info("NcML aggregation to file '%s' successful.", job.output_filename)
Retry on failure, log on completion.
625941d0e5267d203edcde0d
def run(action, errormsg="Connection error: %s", graceperiod=0): <NEW_LINE> <INDENT> starttime = time.time() <NEW_LINE> def routine(): <NEW_LINE> <INDENT> timeout = 1.0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> action() <NEW_LINE> timeout = 1.0 <NEW_LINE> <DEDENT> except Exception as e: <NEW_L...
Run action() in background forever and retry with exponential backoff in case of errors.
625941d0d10714528d5ffe54
def create_new(arxiv_id_str: str, arxiv_ver: int, payload: Dict[str, Any]) -> Response: <NEW_LINE> <INDENT> arxiv_id: ArXivID = resolve_arxiv_id(arxiv_id_str) <NEW_LINE> try: <NEW_LINE> <INDENT> rel: Relation = create.create(arxiv_id, arxiv_ver, payload['resource_type'], payload['resource_id'], payload.get('description...
Create a new relation for an e-print. Parameters ---------- arxiv_id_str: str The arXiv ID of the e-print. arxiv_ver: int The version of the e-print. payload: Dict[str, Any] Payload info. Returns ------- Dict[str, Any] The newly-created relation. HTTPStatus An HTTP status code. Dict[str, str] ...
625941d0379a373c97cfacb5
def add_fontSize_method(self, text_str, num): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> text_str.font.size = Pt(num) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> mylog.error('add_fontSize error') <NEW_LINE> self.ret['state'] = 1 <NEW_LINE> self.ret['stateMessage'] = 'add_fontSize error'
对文本,设置字号
625941d0f548e778e58cd6ee