code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if self._P is not None: return self._P sparse_P = sparse.lil_matrix((self.n, self.n)) alpha_size = len(self.alphabet) bitmask = (self.n-1) # Mask w/ all bits set hi within (k-1)mer range. for fr in range(self.n): for a in range(alpha_size): ...
def P(self)
Sparse [k-1]x[k-1] transition frequency matrix
5.574331
4.976721
1.120081
v, w = linalg.eigs(self.P.transpose(), which='LR') ssf = np.real(w[:, v.argmax()]) ssf /= ssf.sum() return ssf
def steady_state(self)
Steady-state frequencies of each [k-1]-mer
8.148267
6.968112
1.169365
stemfreq = self.array.sum(axis=1).astype(np.float) stemfreq /= stemfreq.sum() return stemfreq
def stem_frequencies(self)
Frequencies of each stem ([k-1]-mer)
5.017013
4.522583
1.109325
"Base request function" h = httplib2.Http() resp, content = h.request( self.base_url + path, method, body = json.dumps(body), ) if resp['status'] == "200": return json.loads(content) else: raise IOError( ...
def _request(self, path, method, body=None)
Base request function
3.25434
3.191875
1.01957
try: pid_filename = get_pid_filename(process_name) with open(pid_filename, mode='r') as pid_file: pid = int(pid_file.read().strip()) except IOError: pid = None return pid
def get_process_pid(process_name)
check for process' pid file and returns pid from there
2.20978
1.965921
1.124043
try: sys.stdout.write('killing: {0} {{ \n'.format(process_name)) pid = get_process_pid(process_name) if pid is not None and psutil.pid_exists(int(pid)): p = psutil.Process(pid) p.kill() p.wait() remove_pid_file(process_name) except Exc...
def kill_process(process_name)
method is called to kill a running process
2.648232
2.673566
0.990524
try: pid = get_process_pid(process_name) if pid is None: sys.stdout.write('PID file was not found. Process {0} is likely terminated.\n'.format(process_name)) return False p = psutil.Process(pid) return_code = p.wait(timeout=0.01) if return_code ...
def poll_process(process_name)
between killing a process and its actual termination lies poorly documented requirement - <purging process' io pipes and reading exit status>. this can be done either by os.wait() or process.wait() :return True if the process is alive and OK and False is the process was terminated
2.804624
2.680992
1.046114
self.event.clear() if self.__timer is not None: self.__timer.cancel()
def cancel(self)
stops the timer. call_back function is not called
5.649377
4.528329
1.247563
self.call_back(*self.args, **self.kwargs) if self.__timer is not None: self.__timer.cancel()
def trigger(self)
calls the call_back function. interrupts the timer to start a new countdown
5.277171
3.187299
1.655688
if utc_now is None: utc_now = datetime.utcnow() if self.is_alive(): next_run = timedelta(seconds=self.interval_current) + self.activation_dt return next_run - utc_now else: return None
def next_run_in(self, utc_now=None)
:param utc_now: optional parameter to be used by Unit Tests as a definition of "now" :return: timedelta instance presenting amount of time before the trigger is triggered next time or None if the RepeatTimer instance is not running
4.010185
3.672642
1.091907
t = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN) return t.strftime(SYNERGY_HOURLY_PATTERN)
def session_to_hour(timestamp)
:param timestamp: as string in YYYYMMDDHHmmSS format :return string in YYYYMMDDHH format
8.243901
7.031835
1.172368
t = datetime.strptime(timeperiod, SYNERGY_HOURLY_PATTERN) return t.strftime(SYNERGY_DAILY_PATTERN)
def hour_to_day(timeperiod)
:param timeperiod: as string in YYYYMMDDHH format :return string in YYYYMMDD00 format
5.86198
5.954242
0.984505
t = datetime.strptime(timeperiod, SYNERGY_DAILY_PATTERN) return t.strftime(SYNERGY_MONTHLY_PATTERN)
def day_to_month(timeperiod)
:param timeperiod: as string in YYYYMMDD00 format :return string in YYYYMM0000 format
6.085916
5.758752
1.056811
t = datetime.strptime(timeperiod, SYNERGY_MONTHLY_PATTERN) return t.strftime(SYNERGY_YEARLY_PATTERN)
def month_to_year(timeperiod)
:param timeperiod: as string in YYYYMM0000 format :return string in YYYY000000 format
6.274435
5.971196
1.050784
pattern = define_pattern(timeperiod) t = datetime.strptime(timeperiod, pattern) if time_qualifier == QUALIFIER_HOURLY: t = t + timedelta(hours=delta) return t.strftime(SYNERGY_HOURLY_PATTERN) elif time_qualifier == QUALIFIER_DAILY: t = t + timedelta(days=delta) re...
def increment_timeperiod(time_qualifier, timeperiod, delta=1)
method performs simple increment/decrement of the timeperiods For instance: 2010010119 with delta=1 -> 2010010120 Or 2010010000 with delta=-1 -> 2009120000, etc
1.7521
1.756025
0.997765
if time_qualifier == QUALIFIER_HOURLY: date_format = SYNERGY_HOURLY_PATTERN elif time_qualifier == QUALIFIER_DAILY: date_format = SYNERGY_DAILY_PATTERN elif time_qualifier == QUALIFIER_MONTHLY: date_format = SYNERGY_MONTHLY_PATTERN elif time_qualifier == QUALIFIER_YEARLY: ...
def cast_to_time_qualifier(time_qualifier, timeperiod)
method casts given timeperiod accordingly to time qualifier. For example, will cast session time format of 20100101193412 to 2010010119 with QUALIFIER_HOURLY
2.077705
1.997479
1.040164
if time_qualifier == QUALIFIER_HOURLY: date_format = SYNERGY_HOURLY_PATTERN elif time_qualifier == QUALIFIER_DAILY: date_format = SYNERGY_DAILY_PATTERN elif time_qualifier == QUALIFIER_MONTHLY: date_format = SYNERGY_MONTHLY_PATTERN elif time_qualifier == QUALIFIER_YEARLY: ...
def datetime_to_synergy(time_qualifier, dt)
method parses datetime and returns Synergy Date
1.756276
1.792096
0.980012
if time_qualifier == QUALIFIER_HOURLY: date_format = SYNERGY_HOURLY_PATTERN elif time_qualifier == QUALIFIER_DAILY: date_format = SYNERGY_DAILY_PATTERN elif time_qualifier == QUALIFIER_MONTHLY: date_format = SYNERGY_MONTHLY_PATTERN elif time_qualifier == QUALIFIER_YEARLY: ...
def synergy_to_datetime(time_qualifier, timeperiod)
method receives timeperiod in Synergy format YYYYMMDDHH and convert it to UTC _naive_ datetime
1.778666
1.799708
0.988308
utc_timetuple = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN).replace(tzinfo=None).utctimetuple() return calendar.timegm(utc_timetuple)
def session_to_epoch(timestamp)
converts Synergy Timestamp for session to UTC zone seconds since epoch
6.705761
4.545744
1.475173
assert len(timeperiod) == 10, 'timeperiod {0} does not match accepted format YYYYMMDDHH'.format(timeperiod) return timeperiod[:4], timeperiod[4: 6], timeperiod[6: 8], timeperiod[8:],
def tokenize_timeperiod(timeperiod)
method breaks given timeperiod into 4 parts: (year, month, day, hour) for instance: daily 2015031400 -> ('2013', '03', '14', '00') hourly 2015031413 -> ('2013', '03', '14', '13') monthly 2015030000 -> ('2013', '03', '00', '00') yearly 2015000000 -> ('2015', ...
3.450133
3.413261
1.010803
parts = kls.split('.') try: # First, try to import module hosting starter function module = '.'.join(parts[:-1]) m = __import__(module) except ImportError: # Alternatively, try to import module hosting Class with a starter method module = '.'.join(parts[:-2]) ...
def get_class(kls)
:param kls - string of fully identified starter function or starter method path for instance: - workers.abstract_worker.AbstractWorker.start - workers.example_script_worker.main :return tuple (type, object, starter) for instance: - (FunctionType, <function_main>, None) - (type, <Class_...
4.192449
3.098393
1.353104
sys.stdout.write('INFO: Starter path {0} \n'.format(context.process_context[process_name].classname)) t, m, starter = get_class(context.process_context[process_name].classname) if isinstance(m, class_types): sys.stdout.write('INFO: Starting process by calling starter method {0} \n'.format(start...
def start_by_process_name(process_name, *args)
Function starts the process by: 1. retrieving its fully specified path name 2. if the path name ends with starter method - then creates an instance of the wrapping class and calls <code>starter(*args)</code> method on it 3. if the path name ends with starter function - then retrieves its module ...
4.40011
3.866007
1.138154
effect.instance = self.instance_index self.instance_index += 1 self.connection.send(ProtocolParser.add(effect))
def add(self, effect)
Add an LV2 plugin encapsulated as a jack client :param Lv2Effect effect: Effect that will be loaded as LV2 plugin encapsulated
8.933215
13.365976
0.668355
if self.connection is not None: self.connection.close() if self.connection_fd is not None: self.connection_fd.close()
def close(self)
Quit the connection with mod-host
3.405898
2.93393
1.160865
source_collection_name = uow.source last_object_id = self.ds.lowest_primary_key(source_collection_name, start_timeperiod, end_timeperiod) uow.end_id = str(last_object_id) self.uow_dao.update(uow) msg = 'Updated processing range for {0}@{1} for collection {2}: [{3} : {4}...
def update_scope_of_processing(self, process_name, uow, start_timeperiod, end_timeperiod)
method reads collection and refine slice upper bound for processing
4.169599
4.004896
1.041125
source_collection_name = context.process_context[process_name].source start_id = self.ds.highest_primary_key(source_collection_name, start_timeperiod, end_timeperiod) end_id = self.ds.lowest_primary_key(source_collection_name, start_timeperiod, end_timeperiod) uow, is_duplicate ...
def _compute_and_transfer_to_progress(self, process_name, start_timeperiod, end_timeperiod, job_record)
method computes new unit_of_work for job record in STATE_IN_PROGRESS it also contains _fuzzy_ logic regard the DuplicateKeyError: - we try to compute new scope of processing - in case we face DuplicateKeyError, we try to recover from it by reading existing unit_of_work from DB: -- in cas...
4.252421
3.886303
1.094207
source_collection_name = context.process_context[process_name].source start_id = self.ds.highest_primary_key(source_collection_name, start_timeperiod, end_timeperiod) end_id = self.ds.lowest_primary_key(source_collection_name, start_timeperiod, end_timeperiod) uow, transfer_to_f...
def _compute_and_transfer_to_final_run(self, process_name, start_timeperiod, end_timeperiod, job_record)
method computes new unit_of_work and transfers the job to STATE_FINAL_RUN it also shares _fuzzy_ DuplicateKeyError logic from _compute_and_transfer_to_progress method
4.060873
3.538711
1.147557
start_timeperiod = self.compute_start_timeperiod(job_record.process_name, job_record.timeperiod) end_timeperiod = self.compute_end_timeperiod(job_record.process_name, job_record.timeperiod) self._compute_and_transfer_to_progress(job_record.process_name, start_timeperiod, ...
def _process_state_embryo(self, job_record)
method that takes care of processing job records in STATE_EMBRYO state
3.241676
3.03737
1.067264
start_timeperiod = self.compute_start_timeperiod(job_record.process_name, job_record.timeperiod) end_timeperiod = self.compute_end_timeperiod(job_record.process_name, job_record.timeperiod) time_qualifier = context.process_context[job_record.process_name].time_qualifier actual_...
def _process_state_in_progress(self, job_record)
method that takes care of processing job records in STATE_IN_PROGRESS state
3.560209
3.502332
1.016525
if self.time_qualifier == QUALIFIER_HOURLY: upper_boundary = 23 elif self.time_qualifier == QUALIFIER_DAILY: if timeperiod: # DAILY upper boundary is month-dependent # i.e. it is 28 for Feb 2015; and 31 for Mar 2015 year, ...
def _get_stem_upper_boundary(self, timeperiod=None)
:param timeperiod: optional parameter, applicable for QUALIFIER_DAILY qualifier only :return: upper boundary for dictionary's time_qualifier
2.660066
2.403128
1.106918
# exclude 00 from lower boundary, unless the grouping == 1 lower_boundary = 0 if self.time_grouping == 1 else 1 upper_boundary = self._get_stem_upper_boundary(timeperiod) for i in range(lower_boundary, upper_boundary): candidate = i * self.time_grouping ...
def _do_stem_grouping(self, timeperiod, stem)
method performs *timeperiod's stem grouping*. :param timeperiod: timeperiod to augment :param stem: inclusive lower boundary for the timeperiod's corresponding token. For instance: - for 2015010520 and QUALIFIER_MONTHLY, stem would be 01 - for 2015010520 and QUALIFIER_DAI...
4.842695
4.098397
1.181607
if self.time_grouping == 1: # no translation is performed for identity grouping return timeperiod # step 1: tokenize timeperiod into: (year, month, day, hour) # for instance: daily 2015031400 -> ('2015', '03', '14', '00') year, month, day, hour = time_he...
def _translate_timeperiod(self, timeperiod)
method translates given timeperiod to the grouped timeperiod
2.991216
2.9063
1.029218
# replace multiple spaces with one trigger_frequency = ' '.join(trigger_frequency.split()) if trigger_frequency.startswith(TRIGGER_PREAMBLE_AT): # EventClock block trigger_frequency = trigger_frequency[len(TRIGGER_PREAMBLE_AT):] parsed_trigger_frequency = trigger_frequency.repl...
def parse_time_trigger_string(trigger_frequency)
:param trigger_frequency: human-readable and editable string in one of two formats: - 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM' - 'every NNN' :return: return tuple (parsed_trigger_frequency, timer_klass)
2.919616
2.4421
1.195535
if isinstance(timer_instance, RepeatTimer): return TRIGGER_PREAMBLE_EVERY + str(timer_instance.interval_new) elif isinstance(timer_instance, EventClock): timestamps = [repr(x) for x in timer_instance.timestamps] return TRIGGER_PREAMBLE_AT + ','.join(timestamps) else: rai...
def format_time_trigger_string(timer_instance)
:param timer_instance: either instance of RepeatTimer or EventClock :return: human-readable and editable string in one of two formats: - 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM' - 'every NNN'
3.785491
2.994715
1.264057
l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDict) db = mc[str(database_name)] collection = db[str(colle...
def query_mongo( database_name, collection_name, query={}, include_num_results="0", skip=0, sort=None, limit=getattr( settings, 'MONGO_LIMIT', 200), cast_strings_to_integers=False, return_keys=())
return a response_dict with a list of search results
2.300635
2.236781
1.028547
l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDict) db = mc[str(database_name)] collection = db[str(c...
def query_mongo_sort_decend( database_name, collection_name, query={}, skip=0, limit=getattr( settings, 'MONGO_LIMIT', 200), return_keys=(), sortkey=None)
return a response_dict with a list of search results in decending order based on a sort key
2.450752
2.41433
1.015086
l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url, document_class=OrderedDict) db = mc[str(database_name)] collection = db[str(c...
def delete_mongo(database_name, collection_name, query={}, just_one=False)
delete from mongo helper
3.392402
3.352458
1.011915
l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDict) db = mc[str(database_name)] collection = db[str(collect...
def write_mongo(document, database_name, collection_name, update=False)
Write a document to the collection. Return a response_dict containing the written record. Method functions as both insert or update based on update parameter
2.941089
2.920712
1.006977
l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDict) db = mconnection[database_name] collection = db[co...
def bulk_csv_import_mongo(csvfile, database_name, collection_name, delete_collection_before_import=False)
return a response_dict with a list of search results
2.844694
2.794999
1.01778
# for key in kwargs: # print "arg: %s: %s" % (key, kwargs[key]) l = [] response_dict = {} try: mongodb_client_url = getattr(settings, 'MONGODB_CLIENT', 'mongodb://localhost:27017/') mc = MongoClient(mongodb_client_url,document_class=OrderedDi...
def raw_query_mongo_db(kwargs, database_name, collection_name)
return a result list or an empty list
3.285935
3.267681
1.005586
for k, v in d.items(): # print type(v) if determine_if_str_or_unicode(v): if v.isdigit(): d[k] = int(v) return d
def cast_number_strings_to_integers(d)
d is a dict
3.850483
3.902258
0.986732
rest_job = RestJob( process_name=node.process_name, timeperiod=node.timeperiod, time_qualifier=node.time_qualifier, number_of_children=len(node.children), number_of_failures='NA' if not node.job_record else node.job_record.number_of_failures, ...
def get_details(cls, node, as_model=False)
method returns either RestJob instance or corresponding document, depending on the as_model argument
3.471903
2.987375
1.162192
if self.manager is None: raise IndexError('Bank not contains a manager') return self.manager.banks.index(self)
def index(self)
Returns the first occurrence of the bank in your :class:`.PluginsManager`
12.069987
6.927033
1.742447
if parent_qualifier not in self.qualifiers: return None process_qualifiers = list(self.qualifiers) if parent_qualifier == process_qualifiers[-1]: return None parent_index = process_qualifiers.index(parent_qualifier) return self.qualifiers[proces...
def get_child_by_qualifier(self, parent_qualifier)
:param parent_qualifier: time_qualifier of the parent process :return: <HierarchyEntry> child entry to the HierarchyEntry associated with the parent_qualifier or None if the given parent_qualifier is not registered in this hierarchy or None if the given parent_qualifier is the bo...
2.577803
2.505667
1.028789
key = next(iter(self.entries)) return self.entries[key].process_entry
def top_process(self)
:return: <ManagedProcessEntry> of the hierarchy's top entry
11.049272
5.706371
1.936305
key = next(reversed(self.entries)) return self.entries[key].process_entry
def bottom_process(self)
:return: <ManagedProcessEntry> of the hierarchy's bottom entry
15.165505
6.451344
2.350751
path = path / Path('mod') sys.path.append(str(path))
def _load_mod_ui_libraries(self, path)
:param Path path:
10.568136
6.876546
1.536838
info = self.get_pedalboard_info(pedalboard_path) if system_effect is None: system_effect = self.discover_system_effect(info) pedalboard = Pedalboard(info['title']) effects_instance = {} for effect_data in info['plugins']: effect = self._genera...
def convert(self, pedalboard_path, system_effect=None)
:param Path pedalboard_path: Path that the pedalboard has been persisted. Generally is in format `path/to/pedalboard/name.pedalboard` :param SystemEffect system_effect: Effect that contains the audio interface outputs and inputs or ...
2.760204
2.774379
0.994891
# MOD swap ins and outs!!! hardware = pedalboard_info['hardware'] total_audio_outs = hardware['audio_ins'] total_audio_ins = hardware['audio_outs'] outputs = ['capture_{}'.format(i) for i in range(1, total_audio_outs+1)] inputs = ['playback_{}'.format(i) for i ...
def discover_system_effect(self, pedalboard_info)
Generate the system effect based in pedalboard_info :param dict pedalboard_info: For obtain this, see :meth:`~pluginsmanager.util.mod_pedalboard_converter.ModPedalboardConvert.get_pedalboard_info()` :return SystemEffect: SystemEffect generated based in pedalboard_info
3.120114
3.093461
1.008616
self.logger.log(level, msg) assert isinstance(freerun_entry, FreerunProcessEntry) event_log = freerun_entry.event_log if len(event_log) > MAX_NUMBER_OF_EVENTS: del event_log[-1] event_log.insert(0, msg) self.freerun_process_dao.update(freerun_entry)
def _log_message(self, level, freerun_entry, msg)
method performs logging into log file and the freerun_entry
3.104388
3.023667
1.026696
process_entry = context.process_context[freerun_entry.process_name] arguments = process_entry.arguments arguments.update(freerun_entry.arguments) if flow_request: schedulable_name = flow_request.schedulable_name timeperiod = flow_request.timeperiod ...
def _insert_uow(self, freerun_entry, flow_request=None)
creates unit_of_work and inserts it into the DB :raise DuplicateKeyError: if unit_of_work with given parameters already exists
2.387854
2.394883
0.997065
process_entry = context.process_context[freerun_entry.process_name] arguments = process_entry.arguments arguments.update(freerun_entry.arguments) arguments.update(flow_request.arguments) uow.created_at = datetime.utcnow() uow.submitted_at = datetime.utcnow() ...
def _reset_flow_uow(self, freerun_entry, uow, flow_request)
there can be multiple freeruns for a single combination of workflow+step+timeperiod hence, we have to *recycle* finished UOW
3.015124
2.959526
1.018786
msg = 'UOW for {0} found in state {1}.'.format(freerun_entry.schedulable_name, uow.state) self._log_message(INFO, freerun_entry, msg) self.insert_and_publish_uow(freerun_entry, flow_request, reset_uow=True)
def _process_terminal_state(self, freerun_entry, uow, flow_request=None)
method that takes care of processing unit_of_work records in STATE_PROCESSED, STATE_NOOP, STATE_INVALID, STATE_CANCELED states
5.81686
5.594502
1.039746
assert isinstance(freerun_entry, FreerunProcessEntry) uow = None if freerun_entry.related_unit_of_work: uow = self.uow_dao.get_one(freerun_entry.related_unit_of_work) try: if uow is None: self._process_state_embryo(freerun_entry, flow_re...
def manage_schedulable(self, freerun_entry, flow_request=None)
method main duty - is to _avoid_ publishing another unit_of_work, if previous was not yet processed In case the Scheduler sees that the unit_of_work is pending, it will issue new WorkerMqRequest for the same UOW
3.051798
2.948013
1.035205
def tupleize( rows, alphabetize_columns=getattr( settings, 'ALPHABETIZE_COLUMNS', False)): # define a blank list as our return object l = [] for r in rows: row = [] row = list(r.values()) l.append(row) # alphabetize if al...
Also alphabetizes columns and returns a tuple of tuples
null
null
null
if len(self.aggregated_objects) == 0: # nothing to do return 0 number_of_aggregated_objects = len(self.aggregated_objects) self.logger.info('Aggregated {0} documents. Performing flush.'.format(number_of_aggregated_objects)) for key in self.aggregated_ob...
def _flush_aggregated_objects(self)
method inserts aggregated objects into MongoDB :return number_of_aggregated_objects
3.182063
2.988903
1.064626
if composite_key not in self.aggregated_objects: self.aggregated_objects[composite_key] = self._init_sink_object(composite_key) return self.aggregated_objects[composite_key]
def _get_aggregated_object(self, composite_key)
method talks with the map of instances of aggregated objects :param composite_key presents tuple, comprising of domain_name and timeperiod
2.463289
2.700114
0.912291
collection_name = context.process_context[self.process_name].source iteration = 0 while True: cursor = self.ds.cursor_fine(collection_name, start_id_obj, end_id_obj, ...
def _run_custom_data_engine(self, start_id_obj, end_id_obj, start_timeperiod, end_timeperiod)
fine-tuned data engine. MongoDB legacy
3.635746
3.491863
1.041206
collection_name = context.process_context[self.process_name].source cursor = self.ds.cursor_batch(collection_name, start_timeperiod, end_timeperiod) for document in cursor: self._process_single_docum...
def _run_data_engine(self, start_timeperiod, end_timeperiod)
regular data engine
6.925177
6.762558
1.024047
"Sends back a static error page." try: sock.sendall("HTTP/1.0 %s %s\r\nConnection: close\r\nContent-length: 0\r\n\r\n" % (self.code, responses.get(self.code, "Unknown"))) except socket.error, e: if e.errno != errno.EPIPE: raise
def handle(self, sock, read_data, path, headers)
Sends back a static error page.
3.293114
2.69295
1.222865
"Sends back a static error page." assert self.type is not None try: # Get the correct file try: fh = open(os.path.join(self.balancer.static_dir, "%s.http" % self.type)) except IOError: fh = open(os.path.join(os.path.dirname(__fi...
def handle(self, sock, read_data, path, headers)
Sends back a static error page.
3.938497
3.60096
1.093735
"Sends back a static error page." if "://" not in self.redirect_to: destination = "http%s://%s" % ( "s" if headers.get('X-Forwarded-Protocol', headers.get('X-Forwarded-Proto', "")).lower() in ("https", "ssl") else "", self.redirect_to ) els...
def handle(self, sock, read_data, path, headers)
Sends back a static error page.
2.989652
2.663371
1.122507
"Sends back a static error page." for i in range(self.attempts): try: server_sock = eventlet.connect( tuple(random.choice(self.backends)), ) except socket.error: eventlet.sleep(self.delay) continu...
def handle(self, sock, read_data, path, headers)
Sends back a static error page.
6.116192
5.315787
1.150571
"Just waits, and checks for other actions to replace us" for i in range(self.timeout // self.check_interval): # Sleep first eventlet.sleep(self.check_interval) # Check for another action action = self.balancer.resolve_host(self.host) if not isi...
def handle(self, sock, read_data, path, headers)
Just waits, and checks for other actions to replace us
7.506831
5.149248
1.45785
result = { "data": { "type": type } } data = result['data'] if attributes is not None: data['attributes'] = attributes if relationships is not None: data['relationships'] = relationships if id is not None: data['id'] = id return result
def build_request_body(type, id, attributes=None, relationships=None)
Build a request body object. A body JSON object is used for any of the ``update`` or ``create`` methods on :class:`Resource` subclasses. In normal library use you should not have to use this function directly. Args: type(string): The resource type for the attribute id(uuid): The id o...
1.920397
2.573638
0.74618
if ids is None: return { 'data': None } elif isinstance(ids, str): return { 'data': {'id': ids, 'type': type} } else: return { "data": [{"id": id, "type": type} for id in ids] }
def build_request_relationship(type, ids)
Build a relationship list. A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API. Args: type(string): The resource type for the ids in the relatio...
2.324101
2.750364
0.845016
params = params or OrderedDict() if include is not None: params['include'] = ','.join([cls._resource_type() for cls in include]) return params
def build_request_include(include, params)
Augment request parameters with includes. When one or all resources are requested an additional set of resources can be requested as part of the request. This function extends the given parameters for a request with a list of resource types passed in as a list of :class:`Resource` subclasses. Args...
5.140603
5.679961
0.905042
url = session._build_url(cls._resource_path(), resource_id) params = build_request_include(include, None) process = cls._mk_one(session, include=include) return session.get(url, CB.json(200, process), params=params)
def find(cls, session, resource_id, include=None)
Retrieve a single resource. This should only be called from sub-classes. Args: session(Session): The session to find the resource in resource_id: The ``id`` for the resource to look up Keyword Args: include: Resource classes to include Returns: ...
9.224602
11.180867
0.825035
url = session._build_url(cls._resource_path()) params = build_request_include(include, None) if metadata is not None: params['filter[metadata]'] = to_json(metadata) process = cls._mk_many(session, include=include, filter=filter) return session.get(url, CB.jso...
def where(cls, session, include=None, metadata=None, filter=None)
Get filtered resources of the given resource class. This should be called on sub-classes only. The include argument allows relationship fetches to be optimized by including the target resources in the request of the containing resource. For example:: .. code-block:: python ...
6.979634
8.039541
0.868163
resource_type = cls._resource_type() resource_path = cls._resource_path() url = session._build_url(resource_path) json = build_request_body(resource_type, None, attributes=attributes, relationships=relationships...
def create(cls, session, attributes=None, relationships=None)
Create a resource of the resource. This should only be called from sub-classes Args: session(Session): The session to create the resource in. attributes(dict): Any attributes that are valid for the given resource type. relationships(dict): Any relationshi...
5.785988
6.15902
0.939433
params = build_request_include(include, None) url = session._build_url(cls._resource_path()) process = cls._mk_one(session, singleton=True, include=include) return session.get(url, CB.json(200, process), params=params)
def singleton(cls, session, include=None)
Get the a singleton API resource. Some Helium API resources are singletons. The authorized user and organization for a given API key are examples of this. .. code-block:: python authorized_user = User.singleton(session) will retrieve the authorized user for the given ...
10.896234
14.778105
0.737323
resource_type = self._resource_type() resource_path = self._resource_path() session = self._session singleton = self.is_singleton() id = None if singleton else self.id url = session._build_url(resource_path, id) attributes = build_request_body(resource_ty...
def update(self, attributes=None)
Update this resource. Not all aspects of a resource can be updated. If the server rejects updates an error will be thrown. Keyword Arguments: attributes(dict): Attributes that are to be updated Returns: Resource: A new instance of this type of resource with the ...
5.88422
6.109101
0.963189
session = self._session url = session._build_url(self._resource_path(), self.id) return session.delete(url, CB.boolean(204))
def delete(self)
Delete the resource. Returns: True if the delete is successful. Will throw an error if other errors occur
9.496066
14.094573
0.673739
successful = True mode = _ops_mode(mode) if user is not None: mode.user = user if group is not None: mode.group = group if other is not None: mode.other = other if recursive: for p in find(path, no_peek=True): successful = _chmod(p, mode) and succ...
def chmod(path, mode=None, user=None, group=None, other=None, recursive=False)
Changes file mode permissions. >>> if chmod('/tmp/one', 0755): ... print('OK') OK NOTE: The precending ``0`` is required when using a numerical mode.
3.044597
3.594497
0.847016
successful = True uid = -1 gid = -1 if user is not None: if isinstance(user, basestring_type): user = _ops_user(name=user) elif isinstance(user, numbers.Number): user = _ops_user(id=user) if isinstance(user, _ops_user): if user: ...
def chown(path, user=None, group=None, recursive=False)
Change file owner and group. >>> if chown('/tmp/one', user='root', group='wheel'): ... print('OK') OK
2.02358
2.160876
0.936463
successful = False try: if follow_links and os.path.islink(src_path): src_path = os.path.realpath(src_path) if follow_links and os.path.islink(dst_path): dst_path = os.path.realpath(dst_path) if os.path.isdir(src_path): if not recursive: ...
def cp(src_path, dst_path, follow_links=False, recursive=True)
Copy source to destination. >>> if cp('/tmp/one', '/tmp/two'): ... print('OK') OK
1.735695
1.981417
0.875987
if not isinstance(text, basestring_type): text = unicode_type(text) if code > 0: if text: if not isinstance(text, basestring_type): text = unicode_type(text) sys.stderr.write(text) sys.exit(code) else: if text: print(te...
def exit(code=0, text='')
Exit and print text (if defined) to stderr if code > 0 or stdout otherwise. >>> exit(code=1, text='Invalid directory path')
2.403824
2.786748
0.862591
if os.path.exists(path): return True try: if recursive: os.makedirs(path) else: os.mkdir(path) except OSError as error: log.error('mkdir: execute failed: %s (%s)' % (path, error)) return False return True
def mkdir(path, recursive=True)
Create a directory at the specified path. By default this function recursively creates the path. >>> if mkdir('/tmp/one/two'): ... print('OK') OK
2.572232
3.445159
0.746622
NUMBER_RE = re.compile('^[-+]?(([0-9]+\.?[0-9]*)|([0-9]*\.?[0-9]+))$') if type is None and default is None: type = unicode_type elif type is None: type = type_(default) if type in str_types: if value is not None: if isinstance(value, unicode_type): ...
def normalize(value, default=None, type=None, raise_exception=False)
Convert string variables to a specified type. >>> normalize('true', type='boolean') True >>> normalize('11', type='number') 11 >>> normalize('10.3', default=11.0) 10.3
1.871104
1.990303
0.94011
try: if recursive: if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path) else: if os.path.isfile(path): os.remove(path) else: os.rmdir(path) except OSError as error: ...
def rm(path, recursive=False)
Delete a specified file or directory. This function does not recursively delete by default. >>> if rm('/tmp/build', recursive=True): ... print('OK') OK
2.066637
2.565169
0.805654
env = None if 'env' in kwargs: if kwargs.get('env_empty'): env = {} else: env = copy.deepcopy(os.environ) env.update(kwargs['env']) stdin = kwargs.get('stdin') stdout = kwargs.get('stdout', False) stderr = kwargs.get('stderr', False) combine =...
def run(command, **kwargs)
Run a shell command and wait for the response. The result object will resolve to True if result.code == 0 and output/error results can be retrieved from result.stdout and result.stderr variables. >>> result = run('echo ${content}', content='Some $%^$## "" + \' content') >>> result.code 0 ...
2.11534
2.17555
0.972324
def method_builder(cls): method_doc = .format(cls.__name__) def method(self): session = self._session resource_id = None if self.is_singleton() else self.id resource_path = cls._resource_path() url = session._build_url(resource_path, resource_id,...
def metadata()
Create a metadata method builder. Returns: A builder function that, given a class, creates a metadata relationship for that class.
4.063811
4.122075
0.985865
hash_elements = defaultdict(list) for element in lista: key = self.similarity_key(element) hash_elements[key].append(element) return hash_elements
def _generate_hash(self, lista)
:return: defaultdict(list)
4.458849
3.131741
1.42376
name = % (collection_name) if request.method == 'POST': form = ConfirmDropForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] if name != collection_name: messages.error(request, _('The name did not match. \ ...
def drop_collection(request, database_name, collection_name)
Drop Collection
3.064474
3.05026
1.00466
name = "Ensure a MongoDB index on a particular field name" if request.method == 'POST': form = EnsureIndexForm(request.POST) if form.is_valid(): result = form.save(database_name, collection_name) messages.success(request, _("Index for %...
def simple_ensure_index(request, database_name, collection_name)
Ensure a MongoDB index on a particular field name
3.04426
2.688015
1.132531
name = "Create a New MongoDB Database" if request.method == 'POST': form = CreateDatabaseForm(request.POST) if form.is_valid(): result = form.save() if "error" in result: messages.error( request, "The database creation operation ...
def create_new_database(request)
Create a New Mongo Database by adding a single document.
3.268428
3.087156
1.058718
@functools.wraps(method) def _wrapper(self, *args, **kwargs): assert isinstance(self, BaseRequestHandler) if not self.is_request_valid: return self.reply_bad_request() try: return method(self, *args, **kwargs) except UserWarning as e: re...
def valid_action_request(method)
wraps method with verification for is_request_valid
2.423813
2.195976
1.103752
def _safe_document(document): assert isinstance(document, dict), 'Error: provided document is not of DICT type: {0}' \ .format(document.__class__.__name__) for key, value in document.items(): if isinstance(value, dict): document[key] = {k: str(...
def safe_json_response(method)
makes sure the response' document has all leaf-fields converted to string
2.427008
2.240912
1.083045
self.user_credentials = self.call('auth', {'username': username, 'password': password}) if 'error' in self.user_credentials: raise T411Exception('Error while fetching authentication token: %s'\ % self.user_credentials['error']) # Create or update...
def _auth(self, username, password)
Authentificate user and store token
3.766539
3.505714
1.0744
# authentification request if method == 'auth' : req = requests.post(API_URL % method, data=params) # download torrent request elif 'download' in method: torrentid = os.path.basename(method) # build torrent's filename ...
def call(self, method = '', params = None)
Call T411 API
3.761547
3.634146
1.035057
return self.call('torrents/download/%s' % torrent_id, params={'filename' : filename, 'directory' : directory})
def download(self, torrent_id, directory, filename)
Download a torrent
5.586584
5.092237
1.097079
try: since = settings.settings['synergy_start_timeperiod'] uow_list = self.uow_dao.get_reprocessing_candidates(since) except LookupError as e: self.logger.info('flow: no UOW candidates found for reprocessing: {0}'.format(e)) return for uo...
def scan_uow_candidates(self)
method performs two actions: - enlist stale or invalid units of work into reprocessing queue - cancel UOWs that are older than 2 days and have been submitted more than 1 hour ago
4.34315
4.010247
1.083013
assert isinstance(q, PriorityQueue) current_timestamp = compute_release_time(lag_in_minutes=0) for _ in range(len(q)): entry = q.pop() assert isinstance(entry, PriorityEntry) if ignore_priority or entry.release_time < current_timestamp: ...
def _flush_queue(self, q, ignore_priority=False)
:param q: PriorityQueue instance holding GarbageCollector entries :param ignore_priority: If True - all GarbageCollector entries should be resubmitted If False - only those entries whose waiting time has expired will be resubmitted
5.813268
4.65015
1.250125
for process_name, q in self.reprocess_uows.items(): self._flush_queue(q, ignore_priority)
def flush(self, ignore_priority=False)
method iterates over each reprocessing queues and re-submits UOW whose waiting time has expired
12.187726
5.839795
2.087013
for process_name, q in self.reprocess_uows.items(): if not q: continue invalid_entries = list() for entry in q.queue: assert isinstance(entry, PriorityEntry) uow = self.uow_dao.get_one(entry.entry.db_id) ...
def validate(self)
method iterates over the reprocessing queue and synchronizes state of every UOW with the DB should it change via the MX to STATE_CANCELED - remove the UOW from the queue
4.930393
3.879683
1.270824
q = self.reprocess_uows[process_name] self._flush_queue(q, ignore_priority)
def flush_one(self, process_name, ignore_priority=False)
method iterates over the reprocessing queue for the given process and re-submits UOW whose waiting time has expired
10.336218
7.02486
1.471377
print(message.encode('utf-8')) self.client.send(message.encode('utf-8')) received = self.client.recv(1024) return received
def send(self, message)
Sends message to *mod-host*. .. note:: Uses :class:`.ProtocolParser` for a high-level management. As example, view :class:`.Host` :param string message: Message that will be sent for *mod-host*
2.863375
4.395205
0.651477
resp = dict() for tree_name, tree in self.scheduler.timetable.trees.items(): if tree.mx_page == mx_page: rest_tree = self._get_tree_details(tree_name) resp[tree.tree_name] = rest_tree.document return resp
def mx_page_trees(self, mx_page)
return trees assigned to given MX Page
5.495606
4.989761
1.101377
if routing is None: routing = queue_name queue_entry = QueueContextEntry(mq_queue=queue_name, mq_exchange=exchange, mq_routing_key=routing) return queue_entry
def queue_context_entry(exchange, queue_name, routing=None)
forms queue's context entry
2.844006
2.97125
0.957175
if not request.content_type: return parsers[0], parsers[0].mimetype mimetype = MimeType.parse(request.content_type) for parser in parsers: if mimetype.match(parser.mimetype): return parser, mimetype return None, None
def select_parser(self, request, parsers)
Selects the appropriated parser which matches to the request's content type. :param request: The HTTP request. :param parsers: The lists of parsers. :return: The parser selected or none.
3.117886
2.675998
1.16513