text
stringlengths
48
9.16k
def test_name(self): table = AddressTable(self.block_id) size = 100 step = 3 for i in range(0, size): if i % step == 0: table.create("res1", self.block_id + (1000 + i), i) for i in range(0, size): id_ = table.get_id('res1', i) self.assertEqual(id_, self.block_id ...
def get_access_token(self, code): payload = {'client_id': BII_GITHUB_OAUTH_CLIENT_ID, 'client_secret': BII_GITHUB_OAUTH_CLIENT_SECRET, 'code': code} headers = {'Accept': 'application/json'} res = requests.post('https://github.com/login/oauth/access_token', params=payload, ...
def _check_multiple_choice(self): if self.type == "multiple_choice": if self.mchoices is None: raise OptionError( "must supply a list of mchoices for type '%s'" % self.type, self) elif type(self.mchoices) not in (tuple, list): raise OptionError( ...
def working_on(self, job): setproctitle('pyres_minion:%s: working on job: %s' % (os.getppid(), job._payload)) self.logger.debug('marking as working on') data = { 'queue': job._queue, 'run_at': int(time.mktime(datetime.datetime.now().timetuple())), 'payload': job._payload } da...
def build_sig(type_signature, var_dict=None): """ Parse a TypeSignature object and convert it to the internal type system language. Args: type_signature: an instance of TypeSignature var_dict: a dictionary of already-bound type variables, or None Returns: A list of TypeVariable/Typ...
def test_list_of_dicts_with_missing_to_numpy(): data = [{'name': 'Alice', 'amount': 100}, {'name': 'Bob'}, {'amount': 200}] result = convert(np.ndarray, data) assert result.dtype.names == ('amount', 'name') expected = np.array([(100.0, 'Alice'), (np.nan, ...
def test_frame_to_redshift(temp_tb): tb = into(temp_tb, df) assert into(set, tb) == into(set, df)
def process_response(self, request, response): if request.is_ajax(): if request.REQUEST.get('ajax_redirect_passthrough'): return response if type(response) == HttpResponseRedirect: response.status_code = 278 return response
@staticmethod def repr_or_None(value): if value is not None: return "%x" % id(value) else: return "None"
def set_dict(prop, d): '''Helper to set values from json recursively''' for key, value in d.iteritems(): if isinstance(value, dict): if not prop.__data__.has_key(key) or not isinstance(prop[key], Properties): prop[key] = Properties() set_dict(prop[key], value) else: prop[key] = val...
def subpaths(path): '''List of all recursive parents of `path` in distance order''' def append_deeper(acc, name): return acc + [acc[-1] + os.sep + name] drive, dirs = os.path.splitdrive(path) dirs = dirs.split(os.sep) if os.path.isfile(path): dirs = dirs[:-1] paths = reduce(ap...
def __init__(self, rev=None, user=UNKNOWN_USER, message=EMPTY_MESSAGE, items=None, changelist=None, time=None): self.rev = rev self.user = user self.message = message self.items = items if items else [] self.time = time or current_repo_time() self.changelist = changelist
def do_GET(self): auth = self.headers.getheader('Authorization') if auth is None: self.send_response(401) self.send_header('WWW-Authenticate', 'Basic realm=\"Test\"') self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write('Authentication require...
def parse_timezone(tz_str): '''Parse a timezone suffix, as it appears on a date, returning offset in minutes.''' try: tz_str = tz_str.lower() if tz_str[0] in "+-" and len(tz_str) == 5 and tz_str[1:].isdigit(): sign = 1 if (tz_str[0] == "+") else -1 hours = int(tz_str[1:3]) minutes = int(tz...
def test_moments(self): """ Test the moments of binomial nodes. """ # Simple test X = Binomial(1, 0.7) u = X._message_to_child() self.assertEqual(len(u), 1) self.assertAllClose(u[0], 0.7) # Test n X = Binomial(10, 0.7) u = X._message_to_child() s...
def __repr__(self): return "<Way id='%s' n_nds=%d n_tags=%d>"%(self.id, len(self.nd_ids), len(self.tags))
def ifort_conf(ctx): import waflib import os ctx.env.FC=[] ctx.load('ifort') if sys.platform.lower()=="darwin": ctx.env.LINKFLAGS_fcshlib = ['-dynamiclib'] ctx.env.append_value('FCFLAGS',ctx.env.mopt.split()) ctx.env["FCFLAGS_fc_omp"]=[] ctx.env.append_value("FCFLAGS_fc_omp","-openmp") ctx.env.FCS...
def add_libdoc_file(self, filename): '''add all keywords from a libdoc-generated xml file''' tree = ET.parse(filename) root = tree.getroot() if root.tag != "keywordspec": raise Exception("expect root tag 'keywordspec', got '%s'" % root.tag) collection_id = self.add_collection(root.get("name...
def update(self): ''' Update the form in background ''' # get the information try: disk_info = self.statistics['Disk']['text']['/'] swap_info = self.statistics['Memory']['text']['swap_memory'] memory_info = self.statistics['Memory']['text']['memory'] proce...
def filter_instances(instances, filter_dict): """Takes a list of instances and returns the subset of that list that meets the filter_dict's criteria.""" filter_function = lambda instance: \ ("id" not in filter_dict or filter_dict["id"] == instance.id) and \ ("state" not in filter_dict or filter_...
def _initialise(self, options=None): if options is None: options = OPTION_DEFAULTS # initialise a few variables self.filename = None self._errors = [] self.raise_errors = options['raise_errors'] self.interpolation = options['interpolation'] self.list_values = options['list_v...
@staticmethod def work_dirs_for_path(path, require=False): ''' Given a path, return all enclosing Zinc working directories. This should be zero or one except in erroneous situations. Returns a list of (work_dir, rel_path) pairs, where rel_path is the relative path within the working directory. ''' out = [...
def compute_index(self, st, n): """Compute a 1D array representing the axis index. Parameters ---------- st : tuple A tuple of ``(scale, translate)`` parameters. n : int The number of bins along the dimension. Returns ------- index : ndarray """ px = np.arange(n...
def __init__(self, master_url, main_executable=None): self._master_url = master_url self._main_executable = main_executable or Configuration['main_executable_path'] self._logger = get_logger(__name__)
def _listen(self, cmd, *args): self.event_id += 1 for listener in self.listeners: listener.listen(self.event_id, cmd, args) if cmd == "pid": # our signal that a new test is starting self.reset() self.set_running_state() if cmd == "ready": self.set_running_s...
def get_host_id(host): if host in host_name_to_uid: return host_name_to_uid[host] else: return str(uuid.uuid4())
def add_row(self, row): if len(row) != len(self.field_names): raise ValueError('row has incorrect number of values ' '({0} given, {1} expected)' .format(len(row), len(self.field_names))) self._rows.append(_filter_row_values(row, self.__empty))
@register.tag def get_unread_message_count_for(parser, token): """ Returns the unread message count for a user. Syntax:: {% get_unread_message_count_for [user] as [var_name] %} Example usage:: {% get_unread_message_count_for pero as message_count %} """ try: tag_name...
def async_run(self, port, master_url, num_executors, log_level, eventlog_file): """ Run a ClusterRunner slave service. :param port: the port on which to run the slave service :type port: int | None :param master_url: the url of the master to which this slave should attach :type master_url: stri...
def parse_sat_output(stdout): """Parse a solver's standard competition-format output.""" match = re.search(r"^s +(.+)$", stdout, re.M) if match: (answer_type,) = map(str.upper, match.groups()) if answer_type == "SATISFIABLE": answer = [] for line in re.findall(r"^...
def currentAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.thread...
def remote_create_folder(dst_ssh, dst_path): """Create folder remotely by using ssh :param dst_ssh: str -- user name and host name of destination path just like: user@host :param dst_path: str -- destination path :return: None """ dst_command = "\"mkdir -p {}\"".forma...
def get_code_dir(self): #Rationale for the default code directory location: # PEP 3147 # http://www.python.org/dev/peps/pep-3147/ # # Which standardizes the __pycache__ directory as a place to put # compilation artifacts for python programs source_dir, source_file = os.path.split(inspect.get...
def test30_10(self): """Tests the RS(30,10) code""" coder = rs.RSCoder(30,10) m = "Hello, wor" code = coder.encode(m) self.assertTrue( coder.verify(code) ) self.assertEqual(m, coder.decode(code) ) self.assertEqual(30, len(code)) # Change 10 bytes. This code should tolerate up to 10 byt...
def _fetchWithBootstrap(requestContext, seriesList, **delta_kwargs): """ Request the same data but with a bootstrap period at the beginning. """ from .app import evaluateTarget, pathsFromTarget bootstrapContext = requestContext.copy() bootstrapContext['startTime'] = ( requestContext['sta...
def insertion_sort(seq): ''' sort a sequence using the insertion sort alg ''' for i in range(1, len(seq)): j = i while j > 0 and seq[j-1] > seq[j]: seq[j-1], seq[j] = seq[j], seq[j-1] j -= 1 return seq
def stream_decode_gzip(iterator): """Stream decodes a gzip-encoded iterator""" try: dec = zlib.decompressobj(16 + zlib.MAX_WBITS) for chunk in iterator: rv = dec.decompress(chunk) if rv: yield rv buf = dec.decompress('') rv = buf + dec.flus...
def ada_predict(self, X=[]): ''' adaboost predicting ''' if X == None: return X = np.array(X) N, d = X.shape Y = np.zeros(N) score = [] # T iterations for t in range(self.T): weak_learner = self.weak_classifier_ens[t] Y += self.alpha[t]*weak_learner.stump_predict(X) scor...
def _emit_test(): "write out a test" if test_name is None: return subunit.write("test %s\n" % test_name) if not log: subunit.write("%s %s\n" % (result, test_name)) else: subunit.write("%s %s [\n" % (result, test_name)) if log: for line in log: subunit....
def heartbeat(queue_name, task_id, owner, message, index): """Sets the heartbeat status of the task and extends its lease. The task's lease is extended by the same amount as its last lease to ensure that any operations following the heartbeat will still hold the lock for the original lock period. ...
@staticmethod def _char_to_base(chr_int, target_base): if chr_int == 0: return [0] return MarkovKeyState._char_to_base(chr_int / target_base, target_base) + [chr_int % target_base]
def is_override_notify_default(self): """Returns True if NTDS Connection should override notify default """ if self.options & dsdb.NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT == 0: return False return True
def is_column(k, columns): sanitized = strip_suffixes(k, ['__lt', '__gt', '__lte', '__gte']) if sanitized in columns: return True else: return False
def _iter_data(self, data): for tupl in self.iter_data(data): if len(tupl) != 2: raise Exception( 'The iter_data method must yield pair tuples containing ' 'the node and its body (empty if not available)') yield tupl
def test_people(self): self.cl.stub_request("clients/%s/people.json" % self.cl.client_id, "people.json") people = self.cl.people() self.assertEquals(2, len(people)) self.assertEquals('person1@blackhole.com', people[0].EmailAddress) self.assertEquals('Person One', people[0].Name) self.assertEquals('Active', ...
def run(self, address, credopts=None, sambaopts=None, versionopts=None): lp = sambaopts.get_loadparm() try: res = netcmd_get_domain_infos_via_cldap(lp, None, address) except RuntimeError: raise CommandError("Invalid IP address '" + address + "'!") self.outf.write("Forest : %s\n...
def get_db_prep_value(self, value, connection=None, prepared=False): """ Pickle and b64encode the object, optionally compressing it. The pickling protocol is specified explicitly (by default 2), rather than as -1 or HIGHEST_PROTOCOL, because we don't want the protocol to change over time. If it did...
def build_results(self): self.header("Scraping election candidates") url = urlparse.urljoin( self.base_url, '/Campaign/Candidates/list.aspx?view=certified&electNav=93' ) soup = self.get(url) # Get all the links out links = soup.findAll('a', href=re.compile(r'^.*&electNav=\d+'))...
def test_render_upload_template_filter_options(self): tpl = template.Template('{% load adminfiles_tags %}' '{{ img|render_upload:"alt=blah" }}') html = tpl.render(template.Context({'img': self.animage})) self.assertTrue('alt="blah"' in html)
def test_doesnt_contain_python_attr(self): self.assertFalse('PUBLISHED' in self.STATUS)
def test_bounces(self): min_date = "2010-01-01" self.campaign.stub_request("campaigns/%s/bounces.json?date=%s&orderfield=date&page=1&pagesize=1000&orderdirection=asc" % (self.campaign_id, urllib.quote(min_date, '')), "campaign_bounces.json") bounces = self.campaign.bounces(min_date) self.assertEquals(len(bounce...
def test_404(self): resp = self.app.get('/nope', follow_redirects=True) assert 'Page Not Found' in resp.data
def _format(self,*a): a = (self.element,)+a self.commands.append('LV%s.%s(%s);'%a)
def draw(self, gl=pyglet.gl): if not self.relative: gl.glLoadIdentity() if self.position is not None: px, py = self.position gl.glTranslatef(px, py, 0) if self.angle is not None: gl.glRotatef(self.angle, 0, 0, 1) if self.zoom is not None: sx, sy = self.zoom gl.glScalef(sx, sy ,0)
@property def is_bound(self): """Flag set if the channel is bound.""" return self._is_bound and self._channel is not None
@with_in_memory_connection def test_gather(self, conn): def collect_replies(): yield 1 yield 2 yield 3 ticket = uuid() actor = Actor(conn) actor._collect_replies = Mock(return_value=collect_replies()) ares = AsyncResult(ticket, actor) ares.to_python = Mock() all = ...
@register.simple_tag def clear_search_url(request): getvars = request.GET.copy() if 'search' in getvars: del getvars['search'] if len(getvars.keys()) > 0: return "%s?%s" % (request.path, getvars.urlencode()) else: return request.path
def test_disk_activate_help(self, capsys): with pytest.raises(SystemExit): self.parser.parse_args('disk activate --help'.split()) out, err = capsys.readouterr() assert 'usage: ceph-deploy disk activate' in out
def on_stderr_received(self, data): """ :type data: encoded bytes """ data, self.intermediate_stderr_buffer = self._split(self.intermediate_stderr_buffer + data) self.stderr_buffer += data self.interleaved_buffer += data self.log_file.write(data) # Get the decoded Python str decod...
def relative_svg_path_to_absolute_coord_list(path, bezier_steps=100, segment_length=0.05): """ return a list of absolute coordinates from an SVG *relative* path """ # get SVG path grammar look_for = svg_grammar() # parse the input based on this grammar pd = look_for.parseString(path) ...
def test_remove_entity(self): from grease import World, Entity world = World() comp1 = world.components.one = TestComponent() comp2 = world.components.two = TestComponent() comp3 = world.components.three = TestComponent() entity = Entity(world) comp1.add(entity) comp2.add(entity) self.assertTrue(entity in worl...
def disable_insecure_serializers(allowed=['json']): """Disable untrusted serializers. Will disable all serializers except ``json`` or you can specify a list of deserializers to allow. .. note:: Producers will still be able to serialize data in these formats, but consumers will not acc...
def __call__(self, request): url = self.creds.get('opsmgr').get('url') + '/uaa/oauth/token' username = self.creds.get('opsmgr').get('username') password = self.creds.get('opsmgr').get('password') headers = { 'Accept': 'application/json' } data = { 'grant_type': 'password', 'client_id': 'opsman', 'client_secr...
def test_isdir_on_non_existing_directory(): assert fs.isdir(os.path.join(TEST_DIR, "foo")) is False
def s3_has_uptodate_file(bucket, transfer_file, s3_key_name): """Check if S3 has an existing, up to date version of this file. """ s3_key = bucket.get_key(s3_key_name) if s3_key: s3_size = s3_key.size local_size = os.path.getsize(transfer_file) s3_time = rfc822.mktime_tz(rfc822.p...
def create_mds(distro, name, cluster, init): conn = distro.conn path = '/var/lib/ceph/mds/{cluster}-{name}'.format( cluster=cluster, name=name ) conn.remote_module.safe_mkdir(path) bootstrap_keyring = '/var/lib/ceph/bootstrap-mds/{cluster}.keyring'.format( cluster=clus...
def release(self, jid, priority=DEFAULT_PRIORITY, delay=0): """Release a reserved job back into the ready queue.""" self._interact('release %d %d %d\r\n' % (jid, priority, delay), ['RELEASED', 'BURIED'], ['NOT_FOUND'])
@classmethod def from_doc(cls, doc): """ Convert a dictionary (from to_doc) back to its native ObjectModel type @param doc: dict """ params = {} for _key, _value in doc.items(): if _key == '_metadata': continue elif _value: params[_key] = TargetingCri...
@_if_not_installed("macs14") def install_macs(env): """Model-based Analysis for ChIP-Seq. http://liulab.dfci.harvard.edu/MACS/ """ default_version = "1.4.2" version = env.get("tool_version", default_version) url = "https://github.com/downloads/taoliu/MACS/" \ "MACS-%s.tar.gz" % version...
def pop(self, count=1): if len(self.segments) < 1 + count: raise Exception('Cannot pop() from path') newSegments = [segment.copy() for segment in self.segments[:-count]] return TFSPath(self.closed, *newSegments)
def get_priority(self, level): """Naive implementation - does not consider duplicate priority levels""" for k, el in enumerate(self.items): if el['priority'] == level: return self.items.pop(k) return None
def keygen(get_keyring=get_keyring): """Generate a public/private key pair.""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64enco...
@wraps(func) def inner(*args, **kwargs): x, y = args assert type(x) == type(y) and x is not y return func(*args, **kwargs)
def make_padded_chars(words, seperator=' '): """Call `_make_padding_char` on a list of words. For example, to create a new format string to pad a list of values. (e.g. {:<3} {<:6} {<:9}""" fmt_string = '' for word in words: fmt_string += _make_padded_char(word) + seperator return fmt_str...
def _check_eq(self, other, not_equal_func): if type(self) != type(other): return not_equal_func(other, "types", type(self), type(other)) for attr in self.attrs(): name = attr.name if (getattr(self, name) != getattr(other, name)): return not_equal_func(other, "{!r} attribute"....
def __eq__(self, other): return self.person['lname'] == other.person['lname']
def getReward(self): # -1 reward for falling over # 0.01 reward for close to goal # return reward inversely proportional to heading error otherwise r_factor = 0.0001 if np.abs(self.env.getTilt()) > self.max_tilt: return -1.0 else: temp = self.calc_dist_to_goal() he...
def _fetch(self): """ Internal helper that fetches the ring from Redis, including only active nodes/replicas. Returns a list of tuples (start, replica) (see _fetch_all docs for more details). """ now = time.time() expiry_time = now - NODE_TIMEOUT data = self.conn.zrangebyscore(self.key,...
def _encode_key_name(key): key = bytes(key, "utf8") key_len = len(key) pbuf, pend, buf = _create_buffer(key_len + 2) librtmp.AMF_EncodeInt16(pbuf, pend, key_len) buf[2:key_len + 2] = key return buf[:]
def __init__(self, key, secret=None, secure=True, host=None, path=None, port=None): super(EucNodeDriver, self).__init__(key, secret, secure, host, port) if path is None: path = "/services/Eucalyptus" self.path = path
def find_by_value(self, value): return self.find_by_xpath('//*[@value="%s"]' % value, original_find="value", original_selector=value)
def generate_itemSimOnTypeSet(): prefs = {} result = {} try: with open(os.getcwd() + '//ml-100k' + '/u.item') as item: for line in item: typeVector = line.split('|')[5:24] itemId = line.split('|')[0] prefs[itemId] = typeVector ...
def Analysis(): test_size = 1000 X, y = Build_Data_Set() print(len(X)) clf = svm.SVC(kernel="linear", C=1.0) clf.fit(X[:-test_size],y[:-test_size]) # train data correct_count = 0 for x in range(1, test_size+1): if clf.predict(X[-x])[0] == y[-x]: correct_count += 1 print("correct_count=%s"...
def recv_heartbeat(self, from_uid, proposal_id): if proposal_id > self.leader_proposal_id: # Change of leadership self._acquiring = False old_leader_uid = self.leader_uid self.leader_uid = from_uid self.leader_proposal_id = proposal_id ...
def request(self, host, handler, request_body, verbose=0): self.verbose = 0 method = ET.XML(request_body).find('methodName').text mock = SoftLayerMockHttp(host, 80) mock.request('POST', "%s/%s" % (handler, method)) resp = mock.getresponse() return self._parse_response(resp.body, None)
def _parse_version_parts(s): parts = [] for part in _split_version_components(s): part = _replace_p(part,part) if not part or part=='.': continue if part[:1] in '0123456789': parts.append(zfill(part,8)) # pad for numeric comparison else: par...
def testNextMonthPlusOneWeek10am(self): self.assertEqual(self.today + relativedelta(months=+1, weeks=+1, hour=10), datetime(2003, 10, 24, 10, 0))
def make_key(self, *parts): """Generate a namespaced key for the given path.""" separator = getattr(self.model_class, 'index_separator', '.') parts = map(decode, parts) return '%s%s' % (self._base_key, separator.join(map(str, parts)))
def _SetEntryFormDate(self, year, month, day, id=-1): """Set the data on the entry form.""" if self._RefuseUnsavedModifications(): return False date = self._MakeDateTime(year, month, day) self.cal.SetDate(date) firstid = self.entries.get_first_id(year, month, day) if id == -1: ...
def prepare_query(self): clone = self.query.clone() select = [] joined = set() def ensure_join(query, m, p): if m not in joined: if '__' not in p: next_model = query.model_class else: next, _ = p.rsplit('__', 1) next_model...
def get_page(self): curr_page = request.args.get(self.page_var) if curr_page and curr_page.isdigit(): return int(curr_page) return 1
def key_table(keys): return TABLE( TR(TD(B(T('Key'))), TD(B(T('Time in Cache (h:m:s)')))), *[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys], **dict(_class='cache-keys', _style="border-collapse: separate; border-spacing: .5em;"))
def test_number_to_string(self): ''' Numbers are turned into strings. ''' cleaner = Cleaners() in_int = 85 in_float = 82.12 in_string = "big frame, small spirit!" in_list = ["hands", "by", "the", "halyards"] in_none = None assert cleaner.number_to_string(in_int) == str(in_int) as...
def close(self): if self.fp is not None: libc.fclose(self.fp) self.fp = None super(SecureStringPipe,self).close()
def get_tm_time_id_column(column, schema_name): name = 'tm_%s_id' % column.name populates = 'label.time.second.of.day.%s' % column.schemaReference return {'populates': [populates], 'columnName': name, 'mode': 'FULL', 'referenceKey': 1}
def do_test( dump_vcd, delay, ModelType ): # Test messages test_msgs = [ 0x0000, 0x0a0a, 0x0b0b, 0x0c0c, 0x0d0d, 0xf0f0, 0xe0e0, 0xd0d0, ] # Instantiate and elaborate the model model = ModelType( 16, test_msgs, delay ) model.vcd_file = dump_vcd model.elaborate() # Cr...
def filter_stop_words(self, words): """Remove any stop-words from the collection of words.""" return [w for w in words if w not in self._stopwords]
def translate( model, o=sys.stdout, enable_blackbox=False, verilator_xinit='zeros' ): # List of models to translate translation_queue = collections.OrderedDict() # FIXME: Additional source to append to end of translation append_queue = [] # Utility function to recursively collect all submodels in desi...
def xtick( s ): if s.out.rdy and s.out.val: s.data.popleft() if len( s.data ) != 0: s.out.msg.next = s.data[0] s.out.val.next = ( len( s.data ) != 0 )
def __init__( s, nbits, nports=3 ): assert nports == 3 s.in_ = [ InPort( nbits ) for x in range( nports ) ] s.out = OutPort( nbits ) s.sel = InPort ( clog2( nbits ) )