code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@app.route('/api/token/<int:token_id>', methods = ['GET']) <NEW_LINE> def get_token_time_value(token_id): <NEW_LINE> <INDENT> appengine_user = users.get_current_user() <NEW_LINE> if not appengine_user: <NEW_LINE> <INDENT> abort(403) <NEW_LINE> <DEDENT> mfa_user = get_mfa_user(appengine_user) <NEW_LINE> if not mfa_user:...
Get the OTP code for a given Token for the current time
625941f77c178a314d6efae4
def __init__(self, *, logical_id: builtins.str, type: builtins.str) -> None: <NEW_LINE> <INDENT> self._values: typing.Dict[str, typing.Any] = { "logical_id": logical_id, "type": type, }
Type of the {@link CfnCodeDeployBlueGreenApplication.target} property. :param logical_id: The logical id of the target resource. :param type: The resource type of the target being deployed. Right now, the only allowed value is 'AWS::ECS::Service'.
625941f7fbf16365ca6f684b
def __rmul__(self, value): <NEW_LINE> <INDENT> if isinstance(value, vec3d): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return vec3d(self.x * value, self.y * value, self.z * value)
Definition of reverse-scalar multiplication, only works with float or integers; Returns a vec3d-object.s
625941f730c21e258bdfab1d
def _cache_support(self, name, obj, timeout, extra, caller): <NEW_LINE> <INDENT> if settings.DEBUG: <NEW_LINE> <INDENT> return caller() <NEW_LINE> <DEDENT> extra = ':'.join(map(encoding.smart_str, extra)) <NEW_LINE> key = 'fragment:%s:%s' % (name, extra) <NEW_LINE> return caching.base.cached_with(obj, caller, key, time...
Cache helper callback.
625941f7d486a94d0b98e7bf
def test_gender_japanese_name_pinyin_batch(self): <NEW_LINE> <INDENT> pass
Test case for gender_japanese_name_pinyin_batch Infer the likely gender of up to 100 Japanese names in LATIN (Pinyin). # noqa: E501
625941f7a79ad161976cc7be
def iterMatch(pathlist): <NEW_LINE> <INDENT> matchlist = [] <NEW_LINE> valid_matchtype = [[0],[1],[2],[3],[0,3],[1,2]] <NEW_LINE> for i,path in enumerate(pathlist): <NEW_LINE> <INDENT> restpaths = pathlist[(i+1):] <NEW_LINE> for restpath in restpaths: <NEW_LINE> <INDENT> match = matchPaths(path,restpath) <NEW_LINE> if ...
Iterate the pathlist to find the matches between each pairwise paths. All possible match type inlcudes [0],[1],[2],[3],[0,3],[1,2]. Only valid matches will be appended into the matchlist. Args: pathlist (list): The list of all the paths. Returns: A list of all the matches. Each match includes two paths and ...
625941f76fb2d068a760f720
def parse_field(self, field, field_value): <NEW_LINE> <INDENT> if type(field_value) is dict: <NEW_LINE> <INDENT> operator = list(field_value)[0] <NEW_LINE> if self.verify_operator(operator) is False: <NEW_LINE> <INDENT> return "Error: operador no exite", operator <NEW_LINE> <DEDENT> value = field_value[operator] <NEW_L...
Parse the operators and traduce: ES to SQLAlchemy operators
625941f70c0af96317bb885f
def showday(self, day, weekday): <NEW_LINE> <INDENT> if day == 0: <NEW_LINE> <INDENT> return '<div class="td_%d calendar_record">&nbsp;&nbsp;</div>' % (weekday + 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '<div class="td_%d calendar_record">%d</div>' % (weekday + 1, day)
Return a day as a table cell.
625941f766656f66f7cbc825
def on_torrent_resume_save(dummy_result, torrent_id): <NEW_LINE> <INDENT> self.waiting_on_resume_data.pop(torrent_id, None)
Recieved torrent resume_data alert so remove from waiting list
625941f7b830903b967e9f7c
def get_best_evaluation(self): <NEW_LINE> <INDENT> payload = {"expt_id" : self.experiment_id} <NEW_LINE> response = requests.post(server + "request_best_eval", json=payload) <NEW_LINE> return response.json()
Requests the best evaluation so far from the server. Args: None Returns: JSON/dict: Contains best configuration and matching reuslt.
625941f7aad79263cf3910c4
def write(self, data): <NEW_LINE> <INDENT> if data == 'GET /simpleresource HTTP/1.0\r\n\r\n': <NEW_LINE> <INDENT> self.protocol.transport.write(SAMPLE_CONTENT)
Write some data to the other end.
625941f7eab8aa0e5d26e1d3
def ensure_list(value): <NEW_LINE> <INDENT> if not isinstance(value, (list, tuple)): <NEW_LINE> <INDENT> return [value] <NEW_LINE> <DEDENT> return value
Ensures that the value is a list. If it is anything but a list or tuple, a list with a single element containing only value is returned.
625941f721bff66bcd684fc5
@numba.njit <NEW_LINE> def bisection(p, start, stop): <NEW_LINE> <INDENT> fstart = quad(start, p) <NEW_LINE> for __ in range(1000): <NEW_LINE> <INDENT> half = start + (stop - start)/2 <NEW_LINE> fhalf = quad(half, p) <NEW_LINE> if abs(fhalf) < 1e-12: <NEW_LINE> <INDENT> return half <NEW_LINE> <DEDENT> if fhalf * fstart...
Bisects start -> stop looking for roots of qudratic p
625941f7be383301e01b5af1
def get_file_names(self, day): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> for k,v in self.folders: <NEW_LINE> <INDENT> if i == day: <NEW_LINE> <INDENT> day = k <NEW_LINE> d = v <NEW_LINE> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> nfiles = list(d.keys()) <NEW_LINE> print('... total available files = %d ...' %(len(n...
Get folder name corresponding to day "day"
625941f7596a89723608a130
def get_albums_by_months(username, with_image_path=False): <NEW_LINE> <INDENT> from lastfm_data.models import PlayedTrack <NEW_LINE> from django.db.models.aggregates import Count <NEW_LINE> tracks = ( PlayedTrack.objects .filter(user__username=username) .extra(select={ 'played_year': "DATE_PART('year', lastfm_data_play...
Get top albums for each year and month :param username: str :param with_image_path: bool Include image path in result or no :return: dict like { 'top_albums': [{ 'year': 2016, 'months': [ { 'month': 'March', 'album': 'Mater of Puppets', 'artist': 'Metal...
625941f74e696a04525c9ac7
@node.commandWrap <NEW_LINE> def CreateSubCharacter(*args, **kwargs): <NEW_LINE> <INDENT> u <NEW_LINE> return cmds.CreateSubCharacter(*args, **kwargs)
:rtype: list|str|basestring|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941f7cc40096d61595fc6
def insert(self, intervals, newInterval): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> inserted = False <NEW_LINE> for interval in intervals: <NEW_LINE> <INDENT> if interval.end < newInterval.start: <NEW_LINE> <INDENT> ret.append(interval) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if interval.start <= newInterval.start:...
:type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval]
625941f7de87d2750b860413
def upgrade_settings(self, setting_values, variable_revision_number, module_name, from_matlab): <NEW_LINE> <INDENT> if not from_matlab and variable_revision_number == 1: <NEW_LINE> <INDENT> setting_values = setting_values + [E_SPECKLES, "1,10"] <NEW_LINE> variable_revision_number = 2 <NEW_LINE> <DEDENT> if not from_mat...
Adjust setting values if they came from a previous revision setting_values - a sequence of strings representing the settings for the module as stored in the pipeline variable_revision_number - the variable revision number of the module at the time the pipeline was saved. Use this ...
625941f75fcc89381b1e1d3e
def _get_column(self, *, table_uri: str, column_name: str) -> Dict: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> table_entity = self._get_table_entity(table_uri=table_uri) <NEW_LINE> columns = table_entity.entity[self.REL_ATTRS_KEY].get('columns') <NEW_LINE> for column in columns or list(): <NEW_LINE> <INDENT> col_deta...
Fetch the column information from referredEntities of the table entity :param table_uri: :param column_name: :return: A dictionary containing the column details
625941f7dd821e528d63b81c
def extract_adjacency_lists( lines: List[str] ) -> Tuple[int, List[int]]: <NEW_LINE> <INDENT> adjacency_pairs = list() <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> parts = line.split(':') <NEW_LINE> node_id = int(parts[0]) <NEW_LINE> neighbors = parts[1][0:-1] <NEW_LINE> neighbors_ids = list(map(int, neighbors.spl...
Extracts pairs of node id, neighbours list from nauty output.
625941f7ad47b63b2c50a5f9
def remove(self, target, value, initiator): <NEW_LINE> <INDENT> pass
Receive a collection remove event. :param target: the object instance receiving the event. If the listener is registered with ``raw=True``, this will be the :class:`.InstanceState` object. :param value: the value being removed. :param initiator: An instance of :class:`.attributes.Event` representing the initiati...
625941f7656771135c3ebef0
def test_user_registration_no_username(self): <NEW_LINE> <INDENT> response = self.client.post("/api/v1/auth/signup", data=json.dumps(dict(username="", email="jumaspay@gmail.com", password="thisispass", confirm="thisispass")), content_type="application/json") <NEW_LINE> self.assertEqual(response.status_code, 401) <NEW_L...
tests that a user cannot signup without a username
625941f71f5feb6acb0c51c1
def save(self, root_dir_path=None): <NEW_LINE> <INDENT> archived_name = f'issue-{self.number}.html' <NEW_LINE> location = root_dir_path / 'static' / 'issue' / archived_name <NEW_LINE> content = self.as_html() <NEW_LINE> if not location.parent.is_dir(): <NEW_LINE> <INDENT> location.parent.mkdir(parents=True) <NEW_LINE> ...
Save an issue in a specific location. root_dir: pathlib.Path full path to where the directory will be saved. return: pathlib.Path it returns the full file location of the archived issue. Probably /static/issue/issue-number.html for webcompat.com
625941f7bde94217f3683463
def __call__(self, cls, val=None): <NEW_LINE> <INDENT> if val is None: <NEW_LINE> <INDENT> if isinstance(cls, type): <NEW_LINE> <INDENT> return self.get(cls.__name__) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('the argument should be a class') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> i...
Get or set a value. :param class cls: Currency class child. :param (int, float) val: exchange rate. :raises ValueError: when got one argument and it is not a class. :raises ValueError: when exchange rate < 0.
625941f71f037a2d8b946875
def flush(self): <NEW_LINE> <INDENT> raise NotImplementedError
Flushes current state to disk.
625941f726238365f5f0f4f0
def __init__(self, tensors, dual_basis=DualBasis()): <NEW_LINE> <INDENT> if not isinstance(tensors, list): <NEW_LINE> <INDENT> raise TypeError("MultiTensor accepts a list") <NEW_LINE> <DEDENT> self.tensors = TMap(tensors) <NEW_LINE> self.off_set_map = self.make_offset_dict(self.tensors) <NEW_LINE> self.dual_basis = dua...
A collection of tensor objects with maps from name to tensor Args: tensors: a dictionary or tuple of tensors and their associated call name. DualBasisElement dual_basis: the set of linear operators restricting the feasible elements of the linear ...
625941f732920d7e50b2884f
def wait_etcd(host="localhost", port=4001, retries=30, sleep=10, **kwargs): <NEW_LINE> <INDENT> def not_yet_up(): <NEW_LINE> <INDENT> logger.warning("Etcd is not up yet.") <NEW_LINE> time.sleep(sleep) <NEW_LINE> <DEDENT> client = EtcdClient(host=host, port=port) <NEW_LINE> for i in range(0, retries): <NEW_LINE> <INDENT...
Wait for etcd to be up. Args: host (Optional[str]): Host name. Default to "localhost". port (Optional[int]): Etcd port. Defaults to 6379. retries (Optional[int]): Maximum number of retries. Defaults to 30. sleep (Optional[int]): Time of sleep between retries, in seconds. Defaults to 10 seconds. Return...
625941f70a366e3fb873ee9a
def getFechaEmision(self): <NEW_LINE> <INDENT> return self.fecha_emision
Devuelve la fecha emision de la Factura :return Fecha de emision: :rtype Datetime:
625941f77d847024c06be93b
def vtkGetDataRoot(): <NEW_LINE> <INDENT> dataRoot = None <NEW_LINE> for i, argv in enumerate(sys.argv): <NEW_LINE> <INDENT> if argv == '-D' and i+1 < len(sys.argv): <NEW_LINE> <INDENT> dataRoot = sys.argv[i+1] <NEW_LINE> <DEDENT> <DEDENT> if dataRoot is None: <NEW_LINE> <INDENT> dataRoot = os.environ.get('VTK_DATA_ROO...
vtkGetDataRoot() -- return vtk example data directory
625941f763d6d428bbe44b6b
def string_to_days(myString, date_format=None): <NEW_LINE> <INDENT> import datetime <NEW_LINE> from datetime import datetime <NEW_LINE> if not isinstance(myString, str): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> myDate = datetime.strptime(myString,'%Y-%m-%d') <NEW_LINE> refDate = datetime.strptime('2010-01-01...
Take a date in a string format and then return the days from 1970-01-01 in the integer format
625941f7004d5f362079a9a7
def featureVectorOfText(text, words, gender): <NEW_LINE> <INDENT> return ([(freqOfWordInText(text, w), w) for w in words], gender)
Returns the feature vector as a tuple with the frecuencies and gender
625941f7287bf620b61d40d8
def valid_cookie(self, cookie): <NEW_LINE> <INDENT> debug.virtual('SB_ServiceState.valid_cookie')
checks whether a state cookie is valid or expired. If the state corresponding to the cookie has been lost, valid_cookie will return false. **INPUTS** *SourceBuffCookie cookie* -- see store_current_state. Note that SourceBuffCookie is a dummy type, not an actual class. The actual type will vary with SB_ServiceState ...
625941f7cb5e8a47e48b8118
def main(orderfolder=None, orderfile_r=None, register=None, verbose=True, force=False): <NEW_LINE> <INDENT> if orderfile_r is None: <NEW_LINE> <INDENT> orderfile_r = 'order.yaml' <NEW_LINE> <DEDENT> if orderfolder is None: <NEW_LINE> <INDENT> orderfolder = os.path.join(INSTANCE_ROOT, 'scratch', 'production') <NEW_LINE>...
Production order generation function.
625941f7baa26c4b54cb1791
def get_request_rate(self, useragent="*"): <NEW_LINE> <INDENT> request_rate = None <NEW_LINE> try: <NEW_LINE> <INDENT> request_rate = self.rp.request_rate(useragent=useragent) <NEW_LINE> logger.info("Request rate is %s" % request_rate) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.error("get_req...
Returns the contents of the Request-rate parameter from robots.txt as a named tuple RequestRate(requests, seconds) :param useragent: :return: tuple RequestRate(requests, seconds) or None
625941f7d164cc61757833c8
def color_matrix(M, ax=None, fig=None, title=None, cmap=cm.jet): <NEW_LINE> <INDENT> if not fig: <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> ax = fig.add_subplot(1, 1, 1) <NEW_LINE> <DEDENT> if not ax: <NEW_LINE> <INDENT> ax = fig.add_subplot(1, 1, 1) <NEW_LINE> <DEDENT> if len(M.shape) == 1: <NEW_LINE> <INDENT> ...
uses a blue to red cmap for matrix visualization
625941f7435de62698dfe2c6
def threads(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return max(1,self.getInt('Forks')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> if self.debugging(): self.errorLog('self.threads() error',quitchoice=True) <NEW_LINE> <DEDENT> return 1
Returns number of threads to use (forks=INT with min=1) :return: threadnum
625941f77b180e01f3dc4e67
def json_file_to_object(directory_name="", file_name=""): <NEW_LINE> <INDENT> file_path = os.path.normpath(os.path.join(directory_name,file_name)) <NEW_LINE> return json.loads(codecs.open(file_path,'r',"utf-8").read())
Reads a json file and returns its equivalent python object.
625941f77b180e01f3dc4e68
def _hash(message, method_name): <NEW_LINE> <INDENT> if method_name not in HASH_METHODS: <NEW_LINE> <INDENT> raise ValueError('Invalid hash method: %s' % method_name) <NEW_LINE> <DEDENT> method = HASH_METHODS[method_name] <NEW_LINE> hasher = method() <NEW_LINE> if hasattr(message, 'read') and hasattr(message.read, '__c...
Returns the message digest. :param message: the signed message. Can be an 8-bit string or a file-like object. If ``message`` has a ``read()`` method, it is assumed to be a file-like object. :param method_name: the hash method, must be a key of :py:const:`HASH_METHODS`.
625941f7236d856c2ad44e5e
def pack_4byte_ibm(file, data, endian='>'): <NEW_LINE> <INDENT> if data.dtype != np.float64 and data.dtype != np.float32: <NEW_LINE> <INDENT> raise WrongDtypeException <NEW_LINE> <DEDENT> signs = np.empty(len(data), dtype=np.uint8) <NEW_LINE> temp_signs = np.sign(data) <NEW_LINE> signs[temp_signs == 1] = 0 <NEW_LINE> s...
Packs 4 byte IBM floating points. This will only work if the host system internally uses little endian byte orders.
625941f75fc7496912cc3ff6
def load_game(self, f): <NEW_LINE> <INDENT> print("load saved game %r" % f) <NEW_LINE> self.game.load(f) <NEW_LINE> self.close() <NEW_LINE> MessageBox( title="Game %r loaded." % os.path.splitext(os.path.basename(f))[0], window_stack=self.window_stack).open()
:param str f:
625941f7925a0f43d254a4f7
@prepost(preurl="http://pages.di.unipi.it/corradini/Didattica/AP-19/PROG-ASS/02/pre.py", posturl="http://pages.di.unipi.it/corradini/Didattica/AP-19/PROG-ASS/02/post.py") <NEW_LINE> def test(fibo_par): <NEW_LINE> <INDENT> f_1_16 = benchmark(th_aux, iter=16, csv_file="f-1-16.csv") <NEW_LINE> f_1_16(1, fibo_par) <NEW_LIN...
Funzione per l'esecuzione dei test richiesti.
625941f7d18da76e23532b58
def get_activity_file_processors(self, fit_file): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for plugin_name, plugin in self.plugins.items(): <NEW_LINE> <INDENT> if plugin.matches_activity_file(fit_file): <NEW_LINE> <INDENT> logger.info("Plugin %s matches file %s", plugin_name, fit_file) <NEW_LINE> plugin.init_activity...
Return a dict of all plugins that handle FIT file messages.
625941f7eab8aa0e5d26e1d4
def handle(self, *args, **kwargs): <NEW_LINE> <INDENT> import_helpers.fetch_blockbox_data(self.stdout) <NEW_LINE> import_helpers.set_permissions_pdf(self.stdout) <NEW_LINE> import_helpers.parse_shapes_blockbox(self.stdout) <NEW_LINE> import_helpers.parse_kilometers_json(self.stdout) <NEW_LINE> import_helpers.merge_meas...
Run subcommands
625941f74c3428357757c99d
def get_vertex_by_name(self, vertex_name): <NEW_LINE> <INDENT> return self.__get_vertex_by_name(vertex_name=vertex_name)
Obtains a vertex object by supplied label Proxies a call to :meth:`BreakpointGraph._BreakpointGraph__get_vertex_by_name`. :param vertex_name: a vertex label it is identified by. :type vertex_name: any hashable python object. ``str`` expected. :return: vertex with supplied label if present in current :class:`Breakpoin...
625941f7293b9510aa2c3909
def test_too_long_post(self): <NEW_LINE> <INDENT> with self.assertRaises(ValidationError): <NEW_LINE> <INDENT> post = 'a' * settings.post_length_max <NEW_LINE> validate_post_length(post * 2)
too long post is rejected
625941f7be383301e01b5af2
def get_cell(self, row, col: str, fresh=False): <NEW_LINE> <INDENT> col_index = self._col_index(col) <NEW_LINE> if fresh: <NEW_LINE> <INDENT> return self.wks.cell(row, col_index + 1).value <NEW_LINE> <DEDENT> if type(row) == int: <NEW_LINE> <INDENT> row = self.get_row(row) <NEW_LINE> <DEDENT> if col_index >= len(row): ...
returns the cell value from (row, col), where row can be an index (1-based) OR list of values as received from self.get_row(row) if fresh=True, the sheet is queried again for this cell
625941f74527f215b584caca
def store_answer(self, id, answer): <NEW_LINE> <INDENT> Session = sessionmaker(bind=self.engine) <NEW_LINE> session = Session() <NEW_LINE> ary = session.query(Question).filter_by(id=id).all() <NEW_LINE> for q in ary: <NEW_LINE> <INDENT> q.answer = answer <NEW_LINE> <DEDENT> session.commit()
Query base on rainbow id
625941f79c8ee82313fbbdf1
def __init__(self, png_bytes: bytes): <NEW_LINE> <INDENT> self.png_bytes = png_bytes
Initialize from bytes in PNG format.
625941f750485f2cf553d416
def post(self, request, project_id): <NEW_LINE> <INDENT> data = request.POST <NEW_LINE> context = self.get_context_data(project_id) <NEW_LINE> project = context.get('project') <NEW_LINE> if project: <NEW_LINE> <INDENT> cannot_create = 'New social interactions cannot be created.' <NEW_LINE> if project.islocked: <NEW_LIN...
Creates social post base on the data entered by the user. Parameters --------- request : django.http.HttpRequest Object representing the request. project_id : intyes Identifies the project in the database. socialinteraction_id : int Identifies the social interaction in the database. Returns ------- django...
625941f707d97122c4178f15
def _calculate_overall_performance(self): <NEW_LINE> <INDENT> return sum(self._episodic_performances) / len(self._episodic_performances)
Calculates the agent performance across all the episodes. By default, the method will return the average across all episodes. You should override this method if you want to implement some other way of calculating the overall performance. Returns: A float value summarizing the performance of the agent.
625941f767a9b606de4a852f
def get_zenoss_host(self): <NEW_LINE> <INDENT> return self.__get_option('connection/host', str)
Zenoss host URL. :return: URL. :rtype: str
625941f7460517430c3947ec
def is_iterable(item) -> bool: <NEW_LINE> <INDENT> return isinstance(item, collections.Iterable) and not isinstance(item, (bytes, str))
Checks if variable is sequence excluding string and bytes :param item: :return: boolean
625941f7d164cc61757833c9
def _calculate_pow_test_zero_(self, exponent): <NEW_LINE> <INDENT> zero = self.parent().coefficient_ring.zero() <NEW_LINE> try: <NEW_LINE> <INDENT> zero ** exponent <NEW_LINE> <DEDENT> except (TypeError, ValueError, ZeroDivisionError) as e: <NEW_LINE> <INDENT> from .misc import combine_exceptions <NEW_LINE> raise combi...
Helper function for :meth:`__pow__` which calculates the power of this element to the given ``exponent`` only if zero to this exponent is possible. INPUT: - ``exponent`` -- an element. OUTPUT: A term. TESTS:: sage: from sage.rings.asymptotic.term_monoid import GenericTermMonoid sage: from sage.rings.asymp...
625941f7d18da76e23532b59
def getCySioClientConfig(): <NEW_LINE> <INDENT> t = (config['Cytube']['domain'], config['Cytube']['channel']) <NEW_LINE> url = 'http://{0}/socketconfig/{1}.json'.format(*t) <NEW_LINE> url = url.encode('utf-8') <NEW_LINE> agent = Agent(reactor) <NEW_LINE> d = agent.request('GET', url) <NEW_LINE> d.addCallbacks(cbGetCySi...
GET Socket.IO client configuration for the server we are trying to connect to. Make a GET request to /socketconfig/<channelname>.json https://github.com/calzoneman/sync/blob/3.0/docs/socketconfig.md
625941f7f7d966606f6aa685
def minim(self, r, lattice): <NEW_LINE> <INDENT> dr = r - self.origin.reshape((r.ndim-1)*(1,)+(3,)) <NEW_LINE> for dim in range(3): <NEW_LINE> <INDENT> ind = N.where(dr[:,dim] > +0.5 * lattice.size[dim]) <NEW_LINE> dr[ind, dim] -= lattice.size[dim] <NEW_LINE> ind = N.where(dr[:,dim] < -0.5 * lattice.size[dim]) <NEW_LIN...
Calculate the minimum image displacement from the origin.
625941f7ab23a570cc250802
def set_gmax(self, g): <NEW_LINE> <INDENT> self.__gmax = csu.enforce_float(g)
Set the maximum gain for modal optimization :param g: (float) : maximum gain for modal optimization
625941f7796e427e537b0c46
def retrieve_data(self): <NEW_LINE> <INDENT> global body_name, method <NEW_LINE> for k, v in self.data.items(): <NEW_LINE> <INDENT> method_list = [] <NEW_LINE> for _k, _v in v.items(): <NEW_LINE> <INDENT> interface = {} <NEW_LINE> if(checkJSON().isExtend(v,'deprecated')): <NEW_LINE> <INDENT> if not _v['deprecated']: <N...
主函数
625941f7d8ef3951e3243bb7
def test_detail_reverse(coffee): <NEW_LINE> <INDENT> url = reverse('coffee:detail', kwargs={'slug': coffee.slug}) <NEW_LINE> assert url == f'/coffees/{coffee.slug}/'
coffee:detail should reverse to /coffees/coffeeslug/.
625941f75510c4643540fa4d
def get_task_output_info(self): <NEW_LINE> <INDENT> return self._task_output_info
Returns the task's output information for the task descriptor. :return: The task's output information for the task descriptor. :rtype: dict
625941f738b623060ff0b466
def isPalindrome(self, head): <NEW_LINE> <INDENT> if head == None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> vals, prev = [], None <NEW_LINE> while head.next: <NEW_LINE> <INDENT> vals.append(head.val) <NEW_LINE> temp = head.next <NEW_LINE> head.next = prev <NEW_LINE> prev = head <NEW_LINE> head = temp <NEW_LI...
:type head: ListNode :rtype: bool
625941f7187af65679ca579b
def testcase_DeleteCamera(self): <NEW_LINE> <INDENT> result = self.deviceManage.testDeleteDevice() <NEW_LINE> deleteResu = self.mysqlData.testIfDeviceDeleted() <NEW_LINE> if result and deleteResu: <NEW_LINE> <INDENT> assert True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False <NEW_LINE> <DEDENT> pass
Test Delete Camera
625941f74d74a7450ccd4840
def testSuccessIsTrueWhenRunnerFails(self): <NEW_LINE> <INDENT> with DatabaseFixture() as f: <NEW_LINE> <INDENT> job = CreateStubbedJob(f.db, runner=stubs.StubConverterRunnerSucceeds()) <NEW_LINE> j = f.session.query(model.Job).get(job.id) <NEW_LINE> assert j.success is None <NEW_LINE> job.Run() <NEW_LINE> f.session.re...
Test that success is True when the runner succeeds
625941f7d268445f265b54e9
def forecast(city_name, c): <NEW_LINE> <INDENT> complete_url = 'http://api.openweathermap.org/data/2.5/forecast?appid=f538bf262cebc1969a94e4de6c0974e5&q=' + city_name <NEW_LINE> response = requests.get(complete_url) <NEW_LINE> raw_json = response.json() <NEW_LINE> days = 'lol' <NEW_LINE> try: <NEW_LINE> <INDENT> main =...
IF YOU HAVE YOUR OWN OPENWEATHER API KEY, PLEASE REPLACED APPID WITH YOUR API KEY Thank you for doing this, as this reduces load on the api key.
625941f7bd1bec0571d90ca9
def create_student(self): <NEW_LINE> <INDENT> s_name = self.parsed_report['name'].split(" ") <NEW_LINE> joined_name = " ".join(s_name[1:]) <NEW_LINE> student_major_course_info = self.parsed_report['course'] <NEW_LINE> new_student_course = Course.objects.get(CourseID=student_major_course_info[0], Version=student_major_c...
Create a student object using the parsed PDF information if one does not already exist within that database. :return:
625941f7167d2b6e3121920e
def __repr__(self): <NEW_LINE> <INDENT> return '<User %r>' % self.name
Dummy.
625941f7462c4b4f79d1dd49
def solve_pass(self, workmem, tempmem, transposed): <NEW_LINE> <INDENT> sourceargs = [workmem[:self._localsize], self._source_transfer, self._mpi_type] <NEW_LINE> targetargs = [tempmem[:self._datasize], self._target_transfer, self._mpi_type] <NEW_LINE> self._comm.Alltoallv(sourceargs, targetargs) <NEW_LINE> self._block...
Solves the data available in workmem in a distributed manner, using MPI_Alltoallv. Parameters ---------- workmem : ndarray The data which is used for solving. All columns to be solved are ordered contiguously. Its minimum size is given by `self.required_mem()` tempmem : ndarray Temporary array of the ...
625941f715baa723493c45f5
def delete_API_dictionary(tenant, API_name, organization): <NEW_LINE> <INDENT> dictionary_table = connect_db(API_DICTIONARIES) <NEW_LINE> tenant_entry = dictionary_table.find({ORG:organization, TENANT : tenant}) <NEW_LINE> if tenant_entry.count()>0: <NEW_LINE> <INDENT> API_dictionaries = tenant_entry[0][API_DICTIONARIE...
Deletes the API_dictionary from the collection when the api is deleted.
625941f7097d151d1a2234d0
def test_get_absolute_url(self): <NEW_LINE> <INDENT> self.assertEqual( self.solo.get_absolute_url(), '/recordings/at-the-stratford-shakespearean-festival/falling-in-love-with-love/oscar-peterson/' )
Test that we can build a URL for a solo
625941f7099cdd3c635f12d2
def test_killLine(self): <NEW_LINE> <INDENT> for x in list("abcdef") + [self.transport.LEFT_ARROW] * 3: <NEW_LINE> <INDENT> self.protocol.keystrokeReceived(x, None) <NEW_LINE> <DEDENT> self.assertEqual(self.protocol.currentLineBuffer(), ("abc", "def")) <NEW_LINE> self.protocol.keystrokeReceived("\v", None) <NEW_LINE> s...
Receiving a vertical tab (C-k, " ") kills the rest of the line on the terminal, as well as trimming the line buffer.
625941f7a8ecb033257d3744
def extinction_check(current_type_number, current_type_attribute, s=0): <NEW_LINE> <INDENT> while s < len(current_type_number): <NEW_LINE> <INDENT> if current_type_number[s] == 0: <NEW_LINE> <INDENT> del current_type_number[s] <NEW_LINE> del current_type_attribute[s] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s += 1
Delete extinct species. If one kind of prey or predator species go extinct, remove it from current_type. That means delete its number and g value in list [current_type_number] and [current_type_attribute]. Args: current_type_number: A list that stores the population size of the species. current_type_a...
625941f7d6c5a102081446ca
def _saccade_terminated(self): <NEW_LINE> <INDENT> if self._saccade_prob > self._MIN_SACCADE_LEN * self.srate: <NEW_LINE> <INDENT> peak_start_idx, peak_end_idx = self._find_peak() <NEW_LINE> saccade_dur = peak_end_idx - peak_start_idx <NEW_LINE> saccade_prob_mass = sum(self._psn[round(peak_start_idx):-1]) <NEW_LINE> bu...
Process a saccade that just ended.
625941f78da39b475bd655f7
def get_template_path(self, filename): <NEW_LINE> <INDENT> if default_storage.exists(filename): <NEW_LINE> <INDENT> return filename <NEW_LINE> <DEDENT> for directory in self.template_dirs: <NEW_LINE> <INDENT> abstract_path = default_storage.generate_filename(os.path.join(directory, filename)) <NEW_LINE> if default_stor...
Check if a template named ``template_name`` can be found in a list of directories. Returns the path if the file exists or raises ``TemplateDoesNotExist`` otherwise.
625941f73c8af77a43ae3e22
def format_results(self, data, get_dict, path): <NEW_LINE> <INDENT> limit = int(get_dict.get('limit', 20)) <NEW_LINE> current_offset = int(get_dict.get('offset', 0)) <NEW_LINE> module_name = get_dict.get('module', '') <NEW_LINE> module_version = get_dict.get('version', None) <NEW_LINE> first_path = self._format_query_s...
Format the results and begin streaming out to the caller for the v3 API :param data: The module data to stream back to the caller :type data: dict :param get_dict: The GET parameters :type get_dict: dict :param path: The path starting with parameters :type get_dict: dict :return: the body of what should be streamed ou...
625941f7ab23a570cc250803
def glob(self, currentcheck): <NEW_LINE> <INDENT> glob = '' <NEW_LINE> while not self.finished() and currentcheck(self.current()): <NEW_LINE> <INDENT> glob += self.current() <NEW_LINE> self.skip(self.current()) <NEW_LINE> <DEDENT> return glob
Glob a bit of text that satisfies a check
625941f7be7bc26dc91cdc6d
def list_counter(records): <NEW_LINE> <INDENT> result = defaultdict(dict) <NEW_LINE> for each in records: <NEW_LINE> <INDENT> for k in records[0].keys(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result[k][each[k]] += 1 <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> result[k][each[k]] = 1 <NEW_LINE> <DEDEN...
The functions that creates a list of counters This function consists of two parts. In the first part we count the same values of keys and put them in a result dict and in the second part we form our dict to be a list and look according to our expectations Args: records (list): a list of records read from a CSV fi...
625941f7507cdc57c6307366
def delete(self): <NEW_LINE> <INDENT> return self.backend.delete(self.path)
Delete the file on storage.
625941f7e64d504609d74eba
def test_parse_args(): <NEW_LINE> <INDENT> args = parse_args("".split()) <NEW_LINE> assert not args.ifile_name or args.ofile_name <NEW_LINE> assert args.log_level
Test argument parsing
625941f710dbd63aa1bd321c
def read_group_filters(self): <NEW_LINE> <INDENT> result = ExternalApiFilterRequest(ExternalApiFilterRequest.READ_GROUPS, None, 0, None) <NEW_LINE> return self.http_post(self.API_FILTERS_URL, None, body=result.get_json_encode_for_filter_based_requests())
@return all group filters created
625941f7283ffb24f3c55f74
def plot_mult_Vs_var(pairs_tree, var, var_min=0, var_max=10, var_title=None, logY=False, logZ=False, normX=False, cut=None, title=None, oDir=os.getcwd(), output='rsp_mult.pdf'): <NEW_LINE> <INDENT> var_cut = '%s < %d && %s > %d' % (var, var_max, var, var_min) <NEW_LINE> cut = var_cut if not cut else '%s && %s' % (cut, ...
Plot multiplicities vs variable 2D hist, for each mulitplicity, on one big canvas. var: string of varibale name in tree var_min, var_max: cuts to put on response range var_title: variable description for axis title logZ: make Z axis logartithmic normX: normalise each X bin such that integral of all y values = 1. cut: ...
625941f7cdde0d52a9e536b4
def __eq__(self, vector): <NEW_LINE> <INDENT> if not isinstance(vector, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if ( self.x == vector.get_x() and self.y == vector.get_y() and self.z == vector.get_z() ): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Fa...
Overloads equality operator
625941f7f9cc0f698b140c70
def http_multipost_list(the_url_data, timeout=HTTP_TIMEOUT, cookies=None, headers=None, exception_handler=None): <NEW_LINE> <INDENT> error = None <NEW_LINE> rs = (grequests.post(each_url_data[0], data=each_url_data[1], timeout=timeout, cookies=cookies, headers=headers) for each_url_data in the_url_data) <NEW_LINE> resu...
the_url_data: [(the_url, data_by_url)] return: error, [(the_url, (each_error, content))] Args: the_url_data (TYPE): Description timeout (TYPE, optional): Description cookies (None, optional): Description headers (None, optional): Description exception_handler (None, optional): Description Returns:...
625941f74f88993c3716c6da
def get_event_iterator(self, plugin, group, track, column): <NEW_LINE> <INDENT> assert self._as_parameter_ <NEW_LINE> return PatternEventIterator._new_from_handle(zzub_pattern_get_event_iterator(self, plugin, group, track, column))
Returns an iterator for iterating over pattern events. Pass NULL for the plugin parameter to retreive all events. -1 can be sent to group, track and column to return only a selected group/track/column.
625941f78c0ade5d55d3f03c
def _async_connect(self, *args): <NEW_LINE> <INDENT> def _connect(): <NEW_LINE> <INDENT> err = self._rsock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR) <NEW_LINE> if err: <NEW_LINE> <INDENT> self._notifier.clear(self, _AsyncPoller._Write) <NEW_LINE> self._write_task.throw(socket.error(err)) <NEW_LINE> self._write_tas...
Internal use only; use 'connect' with 'yield' instead. Asynchronous version of socket connect method.
625941f7711fe17d825429d7
def _expand_xyfvc(self, x, y): <NEW_LINE> <INDENT> return x*self.xfvc_scale+self.xfvc_offset, y*self.yfvc_scale+self.yfvc_offset
Undo _redux_xyfvc() transform
625941f7379a373c97cfb1c2
def update_mini_batch(self, mini_batch, eta, lmbda, n, mu): <NEW_LINE> <INDENT> nabla_b = [np.zeros(b.shape) for b in self.biases] <NEW_LINE> nabla_w = [np.zeros(w.shape) for w in self.weights] <NEW_LINE> for x, y in mini_batch: <NEW_LINE> <INDENT> delta_nabla_b, delta_nabla_w = self.backprop(x, y) <NEW_LINE> nabla_b =...
Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the learning rate, ``lmbda`` is the regularization parameter, and ``n`` is the total size of the training data set.
625941f776e4537e8c351cf3
@app.route("/metadata/<sample>") <NEW_LINE> def sample_metadata(sample): <NEW_LINE> <INDENT> sel = [ Samples_Metadata.sample, Samples_Metadata.ETHNICITY, Samples_Metadata.GENDER, Samples_Metadata.AGE, Samples_Metadata.LOCATION, Samples_Metadata.BBTYPE, Samples_Metadata.WFREQ, ] <NEW_LINE> results = db.session.query(*se...
Return the MetaData
625941f7be383301e01b5af3
def rotate_int(N): <NEW_LINE> <INDENT> L = list(str(N)) <NEW_LINE> l = len(L) <NEW_LINE> for a in range(l): <NEW_LINE> <INDENT> yield int(''.join(rotate_list(L, a)))
rotate digits in N. Different from permutation because order is preserved
625941f756ac1b37e626483c
def _encoder(self, obj): <NEW_LINE> <INDENT> encoded = { '__class__': obj.__class__.__name__, 'ident': obj.ident, 'group': obj.group, 'name': obj.name, 'ctype': obj.ctype, 'pytype': obj.pytype, 'access': obj.access, } <NEW_LINE> if isinstance(obj, ParamTocElement): <NEW_LINE> <INDENT> encoded['extended'] = obj.extended...
Encode a toc element leaf-node
625941f7b545ff76a8914490
def update( self, resource_group_name, factory_name, tags=None, identity=None, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> factory_update_parameters = models.FactoryUpdateParameters(tags=tags, identity=identity) <NEW_LINE> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup...
Updates a factory. :param resource_group_name: The resource group name. :type resource_group_name: str :param factory_name: The factory name. :type factory_name: str :param tags: The resource tags. :type tags: dict[str, str] :param identity: Managed service identity of the factory. :type identity: ~azure.mgmt.datafact...
625941f7460517430c3947ed
def finalize(self, circuit, bases_in=None): <NEW_LINE> <INDENT> return circuit.finalize(bases_in=bases_in)
This function is aimed to perform post-processing operations on a circuit (such as, for example, adding waiting gates) and returns a finalized version of this circuit. Parameters ---------- circuit: quantumsim.circuits.CircuitBase A circuit bases_in: tuple of quantumsim.PauliBasis Returns ------- quantumsim.circu...
625941f738b623060ff0b467
def t_less_open_format(self, t): <NEW_LINE> <INDENT> t.lexer.push_state('parn') <NEW_LINE> return t
%\(
625941f79b70327d1c4e1453
def get( self, resource_group_name, express_route_gateway_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = ...
Fetches the details of a ExpressRoute gateway in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param express_route_gateway_name: The name of the ExpressRoute gateway. :type express_route_gateway_name: str :keyword callable cls: A custom type or function t...
625941f7de87d2750b860415
def _start_tunnel(address, port, args, user, identity, prefix): <NEW_LINE> <INDENT> if '@' in address: <NEW_LINE> <INDENT> user, host = address.split('@') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = user or getpass.getuser() <NEW_LINE> host = address <NEW_LINE> <DEDENT> if sys.platform == 'win32': <NEW_LINE> <...
Start an ssh tunnel process.
625941f71f5feb6acb0c51c4
def main(*args): <NEW_LINE> <INDENT> always = False <NEW_LINE> namespaces = [] <NEW_LINE> spamSite = '' <NEW_LINE> for arg in pywikibot.handle_args(args): <NEW_LINE> <INDENT> if arg == "-always": <NEW_LINE> <INDENT> always = True <NEW_LINE> <DEDENT> elif arg.startswith('-namespace:'): <NEW_LINE> <INDENT> try: <NEW_LINE...
Process command line arguments and perform task. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode
625941f75e10d32532c5f59f
def quickdef(world, obname, kind, props={}, **kwargs) : <NEW_LINE> <INDENT> world.activity.def_obj(obname, kind) <NEW_LINE> for prop, val in props.iteritems() : <NEW_LINE> <INDENT> world[prop(obname)] = val <NEW_LINE> <DEDENT> if "put_in" in kwargs : <NEW_LINE> <INDENT> world.activity.put_in(obname, kwargs["put_in"]) <...
Defines an object with less typing. The props argument is a dictionary of things like "Scenery: True", which is taken to mean "world[Scenery(obname)] = True
625941f760cbc95b062c6bbe
def NumSelectedRows(self): <NEW_LINE> <INDENT> return len(self.GetSelectedRows())
Returns the number of selected rows int he grid
625941f773bcbd0ca4b2c6f0
def cleanup_ips(self): <NEW_LINE> <INDENT> self.vlan_matrix["none"] = [] <NEW_LINE> for iface in self.hosts_matrix: <NEW_LINE> <INDENT> h = {"name": iface["name"]} <NEW_LINE> h["port"] = f"h{iface['id']}-eth0" <NEW_LINE> h["id"] = iface["id"] <NEW_LINE> if "ipv4" in iface: <NEW_LINE> <INDENT> h["ipv4"] = iface["ipv4"] ...
Cleans up ip addresses, in particular hosts with multiple interfaces and vlans
625941f7fff4ab517eb2fabc
def test_compare_size(self): <NEW_LINE> <INDENT> time = datetime.datetime.now() <NEW_LINE> src_file = FileStat(src='', dest='', compare_key='comparator_test.py', size=11, last_update=time, src_type='local', dest_type='s3', operation_name='upload') <NEW_LINE> dest_file = FileStat(src='', dest='', compare_key='comparator...
Confirms compare size works.
625941f7d486a94d0b98e7c2
def parse_stations(conf_arq): <NEW_LINE> <INDENT> config = ConfigParser.RawConfigParser() <NEW_LINE> config.read(conf_arq) <NEW_LINE> stations = [] <NEW_LINE> items = config.items('stations') <NEW_LINE> for item in items: <NEW_LINE> <INDENT> name = item[0] <NEW_LINE> rest = item[1].split() <NEW_LINE> if len(rest) == 0:...
Parse stations section from the conf file.
625941f7a934411ee3751d10
def euclidean(self): <NEW_LINE> <INDENT> dist = 0 <NEW_LINE> for i in range(1,9): <NEW_LINE> <INDENT> current = np.argwhere(self.state == i)[0] <NEW_LINE> target = np.argwhere(GOAL == i)[0] <NEW_LINE> if np.array_equal(current,target) == False: <NEW_LINE> <INDENT> dist += distance.euclidean(current,target) <NEW_LINE> <...
This method implements the euclidean distance heuristic where the total sum of each tile's euclidean distance is calculated. Parameters: 1) N/A Return: 1) dist: Total sum of the euclidean distance for each tile
625941f730bbd722463cc445