code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def __execute_scale(self, surface, size_to_scale_from):
x = size_to_scale_from[0] * self.__scale[0]
y = size_to_scale_from[1] * self.__scale[1]
scaled_value = (int(x), int(y))
self.image = pygame.transform.scale(self.image, scaled_value)
self.__resize_surface_extents() | Execute the scaling operation |
def getWorksheetServices(self):
services = []
for analysis in self.getAnalyses():
service = analysis.getAnalysisService()
if service and service not in services:
services.append(service)
return services | get list of analysis services present on this worksheet |
def to_dicts(recarray):
for rec in recarray:
yield dict(zip(recarray.dtype.names, rec.tolist())) | convert record array to a dictionaries |
def generic_find_fk_constraint_name(table, columns, referenced, insp):
for fk in insp.get_foreign_keys(table):
if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns:
return fk['name'] | Utility to find a foreign-key constraint name in alembic migrations |
def _load_attributes(new_class):
for field_name, field_obj in new_class.meta_.declared_fields.items():
new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj | Load list of attributes from declared fields |
def _get_go2nthdridx(self, gos_all):
go2nthdridx = {}
obj = GrouperInit.NtMaker(self)
for goid in gos_all:
go2nthdridx[goid] = obj.get_nt(goid)
return go2nthdridx | Get GO IDs header index for each user GO ID and corresponding parent GO IDs. |
def group_values(self, group_name):
group_index = self.groups.index(group_name)
values = []
for key in self.data_keys:
if key[group_index] not in values:
values.append(key[group_index])
return values | Return all distinct group values for given group. |
def disk(x, y, height, gaussian_width):
disk_radius = height/2.0
distance_from_origin = np.sqrt(x**2+y**2)
distance_outside_disk = distance_from_origin - disk_radius
sigmasq = gaussian_width*gaussian_width
if sigmasq==0.0:
falloff = x*0.0
else:
with float_error_ignore():
... | Circular disk with Gaussian fall-off after the solid central region. |
def mean_abs(self):
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
else:
return None | return the median of absolute values |
def timestamp(self):
"Return POSIX timestamp as float"
if self._tzinfo is None:
return _time.mktime((self.year, self.month, self.day,
self.hour, self.minute, self.second,
-1, -1, -1)) + self.microsecond / 1e6
else:
... | Return POSIX timestamp as float |
def bench(func):
sys.stdout.write("%44s " % format_func(func))
sys.stdout.flush()
for i in xrange(3, 10):
rounds = 1 << i
t = timer()
for _ in xrange(rounds):
func()
if timer() - t >= 0.2:
break
def _run():
gc.collect()
gc.disable... | Times a single function. |
def _ProcessMessageHandlerRequests(self, requests):
logging.debug("Leased message handler request ids: %s",
",".join(str(r.request_id) for r in requests))
grouped_requests = collection.Group(requests, lambda r: r.handler_name)
for handler_name, requests_for_handler in iteritems(grouped_req... | Processes message handler requests. |
def print_change(self, symbol, typ, changes=None, document=None, **kwargs):
values = ", ".join("{0}={1}".format(key, val) for key, val in sorted(kwargs.items()))
print("{0} {1}({2})".format(symbol, typ, values))
if changes:
for change in changes:
print("\n".join("\t{0... | Print out a change |
def _describe_list(self) -> List[Tuple[str, float]]:
number_nodes = self.number_of_nodes()
return [
('Number of Nodes', number_nodes),
('Number of Edges', self.number_of_edges()),
('Number of Citations', self.number_of_citations()),
('Number of Authors', s... | Return useful information about the graph as a list of tuples. |
def stop_charge(self):
if self.__charger_state:
data = self._controller.command(self._id, 'charge_stop',
wake_if_asleep=True)
if data and data['response']['result']:
self.__charger_state = False
self.__manual_update_... | Stop charging the Tesla Vehicle. |
def use_plenary_relationship_view(self):
self._object_views['relationship'] = PLENARY
for session in self._get_provider_sessions():
try:
session.use_plenary_relationship_view()
except AttributeError:
pass | Pass through to provider RelationshipLookupSession.use_plenary_relationship_view |
def prepare_message(self, message_data, delivery_mode,
content_type, content_encoding, **kwargs):
return (message_data, content_type, content_encoding) | Prepare message for sending. |
def generate(self, state):
if self.count >= random.randint(DharmaConst.VARIABLE_MIN, DharmaConst.VARIABLE_MAX):
return "%s%d" % (self.var, random.randint(1, self.count))
var = random.choice(self)
prefix = self.eval(var[0], state)
suffix = self.eval(var[1], state)
self... | Return a random variable if any, otherwise create a new default variable. |
async def play(self):
if self.repeat and self.current is not None:
self.queue.append(self.current)
self.current = None
self.position = 0
self._paused = False
if not self.queue:
await self.stop()
else:
self._is_playing = True
... | Starts playback from lavalink. |
def parameterize(self, call, host):
debug("Parameterizing {!r} for host {!r}".format(call, host))
clone = call.clone(into=ConnectionCall)
clone.host = host
return clone | Parameterize a Call with its Context set to a per-host Config. |
def wait_for_compactions(self, timeout=120):
pattern = re.compile("pending tasks: 0")
start = time.time()
while time.time() - start < timeout:
output, err, rc = self.nodetool("compactionstats")
if pattern.search(output):
return
time.sleep(1)
... | Wait for all compactions to finish on this node. |
def delayed_retry_gen(delay_schedule=[.1, 1, 10], msg=None, timeout=None, raise_=True):
import utool as ut
import time
if not ut.isiterable(delay_schedule):
delay_schedule = [delay_schedule]
tt = ut.tic()
yield 0
for count in it.count(0):
if timeout is not None and ut.toc(tt) > t... | template code for a infinte retry loop |
def removed_issues(self, board_id, sprint_id):
r_json = self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' % (board_id, sprint_id),
base=self.AGILE_BASE_URL)
issues = [Issue(self._options, self._session, raw_issues_json) for raw_issues_json in
... | Return the completed issues for the sprint. |
def parse_definition_docstring(obj, process_doc):
doc_lines, swag = None, None
full_doc = None
swag_path = getattr(obj, 'swag_path', None)
swag_type = getattr(obj, 'swag_type', 'yml')
if swag_path is not None:
full_doc = load_from_file(swag_path, swag_type)
else:
full_doc = inspe... | Gets swag data from docstring for class based definitions |
def find_versions():
versions = []
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while True:
... | Return a list of MWVersion objects representing installed versions |
def _calc_min_width(self, table):
width = len(table.name)
cap = table.consumed_capacity["__table__"]
width = max(width, 4 + len("%.1f/%d" % (cap["read"], table.read_throughput)))
width = max(width, 4 + len("%.1f/%d" % (cap["write"], table.write_throughput)))
for index_name, cap i... | Calculate the minimum allowable width for a table |
def update_visual_baseline(self):
if '{PlatformVersion}' in self.baseline_name:
try:
platform_version = self.driver.desired_capabilities['platformVersion']
except KeyError:
platform_version = None
self.baseline_name = self.baseline_name.replace... | Configure baseline directory after driver is created |
def wipe_cfg_vals_from_git_cfg(*cfg_opts):
for cfg_key_suffix in cfg_opts:
cfg_key = f'cherry-picker.{cfg_key_suffix.replace("_", "-")}'
cmd = "git", "config", "--local", "--unset-all", cfg_key
subprocess.check_call(cmd, stderr=subprocess.STDOUT) | Remove a set of options from Git config. |
def _create_path(self):
if self.driver == 'sqlite' and 'memory' not in self.dsn and self.dsn != 'sqlite://':
dir_ = os.path.dirname(self.path)
if dir_ and not os.path.exists(dir_):
try:
os.makedirs(dir_)
except Exception:
... | Create the path to hold the database, if one wwas specified. |
def encoded_length(self, num_bytes=16):
factor = math.log(256) / math.log(self._alpha_len)
return int(math.ceil(factor * num_bytes)) | Returns the string length of the shortened UUID. |
def winrm_cmd(session, command, flags, **kwargs):
log.debug('Executing WinRM command: %s %s', command, flags)
session.protocol.transport.build_session()
r = session.run_cmd(command, flags)
return r.status_code | Wrapper for commands to be run against Windows boxes using WinRM. |
def download_containers(self, to_download, current_options):
if current_options["backend"] == "local":
self._display_info("Connecting to the local Docker daemon...")
try:
docker_connection = docker.from_env()
except:
self._display_error("Cannot... | Download the chosen containers on all the agents |
def _parse_date_nate(dateString):
m = _korean_nate_date_re.match(dateString)
if not m:
return
hour = int(m.group(5))
ampm = m.group(4)
if (ampm == _korean_pm):
hour += 12
hour = str(hour)
if len(hour) == 1:
hour = '0' + hour
w3dtfdate = '%(year)s-%(month)s-%(day)s... | Parse a string according to the Nate 8-bit date format |
def placeholder_data_view(self, request, id):
try:
layout = models.Layout.objects.get(pk=id)
except models.Layout.DoesNotExist:
json = {'success': False, 'error': 'Layout not found'}
status = 404
else:
placeholders = layout.get_placeholder_data()
... | Return placeholder data for the given layout's template. |
def xinfo_stream(self, stream):
fut = self.execute(b'XINFO', b'STREAM', stream)
return wait_make_dict(fut) | Retrieve information about the given stream. |
def cleanupFilename(self, name):
context = self.context
id = ''
name = name.replace('\\', '/')
name = name.split('/')[-1]
for c in name:
if c.isalnum() or c in '._':
id += c
if context.check_id(id) is None and getattr(context, id, None) is None... | Generate a unique id which doesn't match the system generated ids |
def to_coverage(ctx):
sm = Smother.load(ctx.obj['report'])
sm.coverage = coverage.coverage()
sm.write_coverage() | Produce a .coverage file from a smother file |
def Definition(self):
result = self._FormatDescriptionComment()
result += " enum %s {\n" % self.enum_name
for k, v in sorted(iteritems(self.reverse_enum)):
result += " %s = %s;\n" % (v, k)
result += " }\n"
result += self._FormatField()
return result | Return a string with the definition of this field. |
def mac_address(ip):
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | Get the MAC address |
def copy_to_clipboard(self, url):
if url is None:
self.term.flash()
return
try:
clipboard_copy(url)
except (ProgramError, OSError) as e:
_logger.exception(e)
self.term.show_notification(
'Failed to copy url: {0}'.format(... | Attempt to copy the selected URL to the user's clipboard |
def send_get_command(self, command):
res = requests.get("http://{host}:{port}{command}".format(
host=self._host, port=self._receiver_port, command=command),
timeout=self.timeout)
if res.status_code == 200:
return True
else:
_LOGGER.e... | Send command via HTTP get to receiver. |
def attach_issue(resource_id, table, user_id):
data = schemas.issue.post(flask.request.json)
issue = _get_or_create_issue(data)
if table.name == 'jobs':
join_table = models.JOIN_JOBS_ISSUES
else:
join_table = models.JOIN_COMPONENTS_ISSUES
key = '%s_id' % table.name[0:-1]
query = ... | Attach an issue to a specific job. |
def oauth_signup(self, provider, attrs, defaults, redirect_url=None):
session["oauth_user_defaults"] = defaults
session["oauth_user_attrs"] = dict(provider=provider, **attrs)
if not redirect_url:
redirect_url = request.args.get("next")
return redirect(url_for('users.oauth_sig... | Start the signup process after having logged in via oauth |
def configure(cls, global_, key, val):
scope = 'global' if global_ else 'local'
if scope not in cls._conffiles:
cls._conffiles[scope] = {}
config = cls._conffiles.get(scope, {})
cls._set(scope, key, val)
conf_file = cls.home_config if global_ else cls.local_config
... | Update and save configuration value to file. |
def change_ssh_port():
host = normalize(env.host_string)[1]
after = env.port
before = str(env.DEFAULT_SSH_PORT)
host_string=join_host_strings(env.user,host,before)
with settings(host_string=host_string, user=env.user):
if env.verbosity:
print env.host, "CHANGING SSH PORT TO: "+st... | For security woven changes the default ssh port. |
def xy2geom(x, y, t_srs=None):
geom_wkt = 'POINT({0} {1})'.format(x, y)
geom = ogr.CreateGeometryFromWkt(geom_wkt)
if t_srs is not None and not wgs_srs.IsSame(t_srs):
ct = osr.CoordinateTransformation(t_srs, wgs_srs)
geom.Transform(ct)
geom.AssignSpatialReference(t_srs)
return ge... | Convert x and y point coordinates to geom |
def read_array(self, infile, var_name):
file_handle = self.read_cdf(infile)
try:
return file_handle.variables[var_name][:]
except KeyError:
print("Cannot find variable: {0}".format(var_name))
raise KeyError | Directly return a numpy array for a given variable name |
def release(self, path, fh):
"Run after a read or write operation has finished. This is where we upload on writes"
try:
f = self.__newfiles[path]
f.seek(0, os.SEEK_END)
if f.tell() > 0:
self.client.up(path, f)
del self.__newfiles[path]
... | Run after a read or write operation has finished. This is where we upload on writes |
def load(target, source_module=None):
module, klass, function = _get_module(target)
if not module and source_module:
module = source_module
if not module:
raise MissingModule(
"No module name supplied or source_module provided.")
actual_module = sys.modules[module]
if not... | Get the actual implementation of the target. |
def Header(self):
_ = [option.OnGetValue() for option in self.options]
return self.name | Fetch the header name of this Value. |
def summarize(self, host):
return dict(
ok = self.ok.get(host, 0),
failures = self.failures.get(host, 0),
unreachable = self.dark.get(host,0),
changed = self.changed.get(host, 0),
skipped = self.skipped.get(host, 0)
) | return information about a particular host |
def generic_div(a, b):
logger.debug('Called generic_div({}, {})'.format(a, b))
return a / b | Simple function to divide two numbers |
def rm(self, fname=None):
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
pass | Remove a file, don't raise exception if file does not exist. |
def prep_args(arg_info):
filtered_args = [a for a in arg_info.args if getattr(arg_info, 'varargs', None) != a]
if filtered_args and (filtered_args[0] in ('self', 'cls')):
filtered_args = filtered_args[1:]
pos_args = []
if filtered_args:
for arg in filtered_args:
if isinstance... | Resolve types from ArgInfo |
def check_permissions(self, request):
objs = [None]
if hasattr(self, 'get_perms_objects'):
objs = self.get_perms_objects()
else:
if hasattr(self, 'get_object'):
try:
objs = [self.get_object()]
except Http404:
... | Permission checking for DRF. |
def qpinfo():
parser = qpinfo_parser()
args = parser.parse_args()
path = pathlib.Path(args.path).resolve()
try:
ds = load_data(path)
except UnknownFileFormatError:
print("Unknown file format: {}".format(path))
return
print("{} ({})".format(ds.__class__.__doc__, ds.__class... | Print information of a quantitative phase imaging dataset |
def get(self, path, watch=None):
_log.debug(
"ZK: Getting {path}".format(path=path),
)
return self.zk.get(path, watch) | Returns the data of the specified node. |
def chi_p_from_xi1_xi2(xi1, xi2):
xi1, xi2, input_is_array = ensurearray(xi1, xi2)
chi_p = copy.copy(xi1)
mask = xi1 < xi2
chi_p[mask] = xi2[mask]
return formatreturn(chi_p, input_is_array) | Returns effective precession spin from xi1 and xi2. |
def _get_recurse_directive_depth(field_name, field_directives):
recurse_directive = field_directives['recurse']
optional_directive = field_directives.get('optional', None)
if optional_directive:
raise GraphQLCompilationError(u'Found both @optional and @recurse on '
... | Validate and return the depth parameter of the recurse directive. |
def acquire(self,blocking=True,timeout=None,shared=False):
with self._lock:
if shared:
self._acquire_shared(blocking,timeout)
else:
self._acquire_exclusive(blocking,timeout)
assert not (self.is_shared and self.is_exclusive) | Acquire the lock in shared or exclusive mode. |
def addPhenotypeSearchOptions(parser):
parser.add_argument(
"--phenotype_association_set_id", "-s", default=None,
help="Only return phenotypes from this phenotype_association_set.")
parser.add_argument(
"--phenotype_id", "-p", default=None,
help="Only return this phenotype.")
... | Adds options to a phenotype searches command line parser. |
def format_local_dap(dap, full=False, **kwargs):
lines = []
label_width = dapi.DapFormatter.calculate_offset(BASIC_LABELS)
lines.append(dapi.DapFormatter.format_meta(dap.meta, labels=BASIC_LABELS,
offset=label_width, **kwargs))
lines.append('')
lines.ap... | Formaqts information about the given local DAP in a human readable form to list of lines |
def check_constraints(self, instance):
recalc_fields = []
for constraint in self.constraints:
try:
constraint(self.model, instance)
except constraints.InvalidConstraint as e:
recalc_fields.extend(e.fields)
return recalc_fields | Return fieldnames which need recalculation. |
def pusher_connected(self, data):
self.logger.info("Pusherclient connected")
self.callback_client.bind("payment_authorized",
self.payment_authorized)
self.callback_client.bind("shortlink_scanned",
self.shortlink_scanned) | Called when the pusherclient is connected |
def rewrite(self, path, expand, newmethod = None, host = None, vhost = None, method = [b'GET', b'HEAD'], keepquery = True):
"Automatically rewrite a request to another location"
async def func(env):
newpath = self.expand(env.path_match, expand)
if keepquery and getattr(env, 'quer... | Automatically rewrite a request to another location |
def str_check(*args, func=None):
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, (str, collections.UserString, collections.abc.Sequence)):
name = type(var).__name__
raise StringError(
f'Function {func} expected str, {name} got instead.... | Check if arguments are str type. |
def infer_operands_size(operands):
size = None
for oprnd in operands:
if oprnd.size:
size = oprnd.size
break
if size:
for oprnd in operands:
if not oprnd.size:
oprnd.size = size
else:
for oprnd in operands:
if isinst... | Infer x86 instruction operand size based on other operands. |
def sendBox(self, box):
if self.remoteRouteName is _unspecified:
raise RouteNotConnected()
if self.remoteRouteName is not None:
box[_ROUTE] = self.remoteRouteName.encode('ascii')
self.router._sender.sendBox(box) | Add the route and send the box. |
def add_lv_load_area_group(self, lv_load_area_group):
if lv_load_area_group not in self.lv_load_area_groups():
self._lv_load_area_groups.append(lv_load_area_group) | Adds a LV load_area to _lv_load_areas if not already existing. |
def _soap_client_call(method_name, *args):
soap_client = _build_soap_client()
soap_args = _convert_soap_method_args(*args)
if PYSIMPLESOAP_1_16_2:
return getattr(soap_client, method_name)(*soap_args)
else:
return getattr(soap_client, method_name)(soap_client, *soap_args) | Wrapper to call SoapClient method |
def queue_files(dirpath, queue):
for root, _, files in os.walk(os.path.abspath(dirpath)):
if not files:
continue
for filename in files:
queue.put(os.path.join(root, filename)) | Add files in a directory to a queue |
def lookup(sock, domain, cache = None):
domain = normalize_domain(domain)
reply = sam_cmd(sock, "NAMING LOOKUP NAME=%s" % domain)
b64_dest = reply.get('VALUE')
if b64_dest:
dest = Dest(b64_dest, encoding='base64')
if cache:
cache[dest.base32 + '.b32.i2p'] = dest
retur... | lookup an I2P domain name, returning a Destination instance |
def start_tag(self) -> str:
tag = '<' + self.tag
attrs = self._get_attrs_by_string()
if attrs:
tag = ' '.join((tag, attrs))
return tag + '>' | Return HTML start tag. |
def first(values, axis, skipna=None):
if (skipna or skipna is None) and values.dtype.kind not in 'iSU':
_fail_on_dask_array_input_skipna(values)
return nanfirst(values, axis)
return take(values, 0, axis=axis) | Return the first non-NA elements in this array along the given axis |
def start_scanner(path):
try:
observer = Observer()
observer.start()
stream = Stream(file_modified, path, file_events=True)
observer.schedule(stream)
print "Watching for changes. Press Ctrl-C to stop."
while 1:
pass
except (KeyboardInterrupt, OSError, IO... | watch for file events in the supplied path |
def update(self, **kwargs) -> "UpdateQuery":
return UpdateQuery(
db=self._db,
model=self.model,
update_kwargs=kwargs,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
) | Update all objects in QuerySet with given kwargs. |
def create_session(self):
url = self.build_url(self._endpoints.get('create_session'))
response = self.con.post(url, data={'persistChanges': self.persist})
if not response:
raise RuntimeError('Could not create session as requested by the user.')
data = response.json()
... | Request a new session id |
def update_text(self, mapping):
found = False
for node in self._page.iter("*"):
if node.text or node.tail:
for old, new in mapping.items():
if node.text and old in node.text:
node.text = node.text.replace(old, new)
... | Iterate over nodes, replace text with mapping |
def _get_master_proc_by_name(self, name, tags):
master_name = GUnicornCheck._get_master_proc_name(name)
master_procs = [p for p in psutil.process_iter() if p.cmdline() and p.cmdline()[0] == master_name]
if len(master_procs) == 0:
self.service_check(
self.SVC_NAME,
... | Return a psutil process for the master gunicorn process with the given name. |
def p_changeinfo(self):
post_data, def_dic = self.fetch_post_data()
usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass'])
if usercheck == 1:
MUser.update_info(self.userinfo.uid, post_data['user_email'], extinfo=def_dic)
output = {'changeinfo ': usercheck}
... | Change Infor via Ajax. |
def return_small_clade(treenode):
"used to produce balanced trees, returns a tip node from the smaller clade"
node = treenode
while 1:
if node.children:
c1, c2 = node.children
node = sorted([c1, c2], key=lambda x: len(x.get_leaves()))[0]
else:
return node | used to produce balanced trees, returns a tip node from the smaller clade |
def _set_affected_target_count_in_runtracker(self):
target_count = len(self.build_graph)
self.run_tracker.pantsd_stats.set_affected_targets_size(target_count)
return target_count | Sets the realized target count in the run tracker's daemon stats object. |
def _call_wrapper(self, time, function, *args):
function(*args)
if function in self._callback.keys():
repeat = self._callback[function][1]
if repeat:
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[functi... | Fired by tk.after, gets the callback and either executes the function and cancels or repeats |
def _get_run_info_dict(self, run_id):
run_info_path = os.path.join(self._settings.info_dir, run_id, 'info')
if os.path.exists(run_info_path):
return RunInfo(run_info_path).get_as_dict()
else:
return None | Get the RunInfo for a run, as a dict. |
def send_line(self, data, nowait=False):
data = data.replace('\n', ' ').replace('\r', ' ')
f = asyncio.Future(loop=self.loop)
if self.queue is not None and nowait is False:
self.queue.put_nowait((f, data))
else:
self.send(data.replace('\n', ' ').replace('\r', ' ')... | send a line to the server. replace CR by spaces |
def follow_shortlinks(shortlinks):
links_followed = {}
for shortlink in shortlinks:
url = shortlink
request_result = requests.get(url)
redirect_history = request_result.history
all_urls = []
for redirect in redirect_history:
all_urls.append(redirect.url)
... | Follow redirects in list of shortlinks, return dict of resulting URLs |
def parseprint(code, filename="<string>", mode="exec", **kwargs):
node = parse(code, mode=mode)
print(dump(node, **kwargs)) | Parse some code from a string and pretty-print it. |
def rollback(self, date):
if self.onOffset(date):
return date
else:
return date - YearEnd(month=self.month) | Roll date backward to nearest end of year |
def create_cluster_meta(cluster_groups):
meta = ClusterMeta()
meta.add_field('group')
cluster_groups = cluster_groups or {}
data = {c: {'group': v} for c, v in cluster_groups.items()}
meta.from_dict(data)
return meta | Return a ClusterMeta instance with cluster group support. |
def update_time_range(form_data):
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(
form_data.pop('since', '') or '',
form_data.pop('until', '') or '',
) | Move since and until to time_range. |
def scope_types(self, request, *args, **kwargs):
return response.Response(utils.get_scope_types_mapping().keys()) | Returns a list of scope types acceptable by events filter. |
def ctor(name, func, *args, **kwargs):
return globscope.ctor(name, func, *args, **kwargs) | Add a ctor callback to the global scope. |
def skeleton_path(parts):
return os.path.join(os.path.dirname(oz.__file__), "skeleton", parts) | Gets the path to a skeleton asset |
def generate_term(self, **kwargs):
term_map = kwargs.pop('term_map')
if hasattr(term_map, "termType") and\
term_map.termType == NS_MGR.rr.BlankNode.rdflib:
return rdflib.BNode()
if not hasattr(term_map, 'datatype'):
term_map.datatype = NS_MGR.xsd.anyURI.rdflib... | Method generates a rdflib.Term based on kwargs |
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None):
query = self.schema.query_builder.build_select(table, where, orderby, limit, columns)
return table.to_table(self.execute(query, values), columns=columns) | Support these keywords where, values, orderby, limit and columns |
def render_unicode(self, *args, **data):
return runtime._render(self,
self.callable_,
args,
data,
as_unicode=True) | Render the output of this template as a unicode object. |
def last_modified_date(filename):
mtime = os.path.getmtime(filename)
dt = datetime.datetime.utcfromtimestamp(mtime)
return dt.replace(tzinfo=pytz.utc) | Last modified timestamp as a UTC datetime |
def _finishAnimation(self):
self.setCurrentIndex(self._nextIndex)
self.widget(self._lastIndex).hide()
self.widget(self._lastIndex).move(self._lastPoint)
self._active = False
if not self.signalsBlocked():
self.animationFinished.emit() | Cleans up post-animation. |
def getStartingApplication(self, pchAppKeyBuffer, unAppKeyBufferLen):
fn = self.function_table.getStartingApplication
result = fn(pchAppKeyBuffer, unAppKeyBufferLen)
return result | Returns the app key for the application that is starting up |
def _generate_metadata_file(workdir,
archive_name,
platform,
python_versions,
package_name,
package_version,
build_tag,
pack... | Generate a metadata file for the package. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.