code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def add_device(dev):
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
if test_dev is DEFAULT_DEV:
DEFAULT_DEV = None
del DEVS[idx]
... | Adds a device to the list of devices we know about. |
def read_examples(input_file):
examples = []
unique_id = 0
with open(input_file, "r", encoding='utf-8') as reader:
while True:
line = reader.readline()
if not line:
break
line = line.strip()
text_a = None
text_b = None
... | Read a list of `InputExample`s from an input file. |
def cleanup_key(name):
name = name.lstrip('+')
is_keypad = name.startswith('KP_')
for mod in ('Meta_', 'Control_', 'dead_', 'KP_'):
if name.startswith(mod):
name = name[len(mod):]
if name == 'Remove':
name = 'Delete'
elif name == 'Delete':
name = 'Backspace'
i... | Formats a dumpkeys format to our standard. |
def export_modified_data(self):
result = {key: None for key in self.__deleted_fields__}
for key, value in self.__modified_data__.items():
if key in result.keys():
continue
try:
result[key] = value.export_modified_data()
except Attribute... | Get the modified data |
def headers(self):
d = {}
for k, v in self.message.items():
d[k] = decode_header_part(v)
return d | Return only the headers as Python object |
def initLogger():
global logger
logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(message)s", "%Y-%m-%d %H:%M:%S")
ch.setFormatter(formatter)
log... | This code taken from Matt's Suspenders for initializing a logger |
def post(self):
self._construct_post_data()
post_args = {"json": self.post_data}
self.http_method_args.update(post_args)
return self.http_method("POST") | Makes the HTTP POST to the url sending post_data. |
def getPyClass(self):
if self.hasExtPyClass():
classInfo = self.extPyClasses[self.name]
return ".".join(classInfo)
return 'Holder' | Name of generated inner class that will be specified as pyclass. |
def dump_edn_val(v):
" edn simple value dump"
if isinstance(v, (str, unicode)):
return json.dumps(v)
elif isinstance(v, E):
return unicode(v)
else:
return dumps(v) | edn simple value dump |
def _get_prog_memory(resources, cores_per_job):
out = None
for jvm_opt in resources.get("jvm_opts", []):
if jvm_opt.startswith("-Xmx"):
out = _str_memory_to_gb(jvm_opt[4:])
memory = resources.get("memory")
if memory:
out = _str_memory_to_gb(memory)
prog_cores = resources.... | Get expected memory usage, in Gb per core, for a program from resource specification. |
def namedb_get_num_historic_names_by_address( cur, address ):
select_query = "SELECT COUNT(*) FROM name_records JOIN history ON name_records.name = history.history_id " + \
"WHERE history.creator_address = ?;"
args = (address,)
count = namedb_select_count_rows( cur, select_query, args )
... | Get the number of names owned by an address throughout history |
def send_router_port_msg(self, tenant_id, tenant_name, router_id, net_id,
subnet_id, seg, status):
data = self.prepare_router_vm_msg(tenant_id, tenant_name, router_id,
net_id, subnet_id, seg, status)
if data is None:
retu... | Sends the router port message to the queue. |
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str:
for k, v in choices:
if k == value:
return v
return '' | Returns the explanation associated with a Django choice tuple-list. |
def tospark(self, engine=None):
from thunder.images.readers import fromarray
if self.mode == 'spark':
logging.getLogger('thunder').warn('images already in spark mode')
pass
if engine is None:
raise ValueError('Must provide a SparkContext')
return froma... | Convert to distributed spark mode. |
def c_member_funcs(self, for_struct=False):
decls = [
'{} *{};'.format(self._c_type_name(name), name)
for name, dummy_args in self.funcs
]
if for_struct:
return decls
return [self._c_mod_decl()] + decls | Get the decls of the module. |
def save(self, filename):
import dill
tmpmodelparams = self.modelparams.copy()
fv_extern_name = None
if "fv_extern" in tmpmodelparams:
tmpmodelparams.pop("fv_extern")
sv = {
"modelparams": tmpmodelparams,
"mdl": self.mdl,
}
sss ... | Save model to pickle file. External feature function is not stored |
def format_idp_cert_multi(self):
if 'x509certMulti' in self.__idp:
if 'signing' in self.__idp['x509certMulti']:
for idx in range(len(self.__idp['x509certMulti']['signing'])):
self.__idp['x509certMulti']['signing'][idx] = OneLogin_Saml2_Utils.format_cert(self.__idp... | Formats the Multple IdP certs. |
def makeHTML(self,mustachepath,htmlpath):
subs = dict()
if self.title:
subs["title"]=self.title
subs["has_title"]=True
else:
subs["has_title"]=False
subs["font_size"] = self.font_size
subs["font_family"] = self.font_family
subs["colorsc... | Write an html file by applying this ideogram's attributes to a mustache template. |
def _compute_fixed(self):
try:
lon, lat = np.meshgrid(self.lon, self.lat)
except:
lat = self.lat
phi = np.deg2rad(lat)
try:
albedo = self.a0 + self.a2 * P2(np.sin(phi))
except:
albedo = np.zeros_like(phi)
dom = next(iter(sel... | Recompute any fixed quantities after a change in parameters |
def _wrap_measure(individual_group_measure_process, group_measure, loaded_processes):
def wrapped_measure(state_collection,overriding_parameters=None,loggers=None):
if loggers == None:
loggers = funtool.logger.set_default_loggers()
if loaded_processes != None :
if group_meas... | Creates a function on a state_collection, which creates analysis_collections for each group in the collection. |
def skip_coords(c):
if c == "{{coord|LAT|LONG|display=inline,title}}":
return True
if c.find("globe:") >= 0 and c.find("globe:earth") == -1:
return True
return False | Skip coordinate strings that are not valid |
def truncate(self, table):
if isinstance(table, (list, set, tuple)):
for t in table:
self._truncate(t)
else:
self._truncate(table) | Empty a table by deleting all of its rows. |
def python_sidebar_help(python_input):
token = 'class:sidebar.helptext'
def get_current_description():
i = 0
for category in python_input.options:
for option in category.options:
if i == python_input.selected_option_index:
return option.description... | Create the `Layout` for the help text for the current item in the sidebar. |
def _init_obo_version(self, line):
if line[0:14] == "format-version":
self.format_version = line[16:-1]
if line[0:12] == "data-version":
self.data_version = line[14:-1] | Save obo version and release. |
async def run(self):
while self.eh_partition_pump.pump_status != "Errored" and not self.eh_partition_pump.is_closing():
if self.eh_partition_pump.partition_receive_handler:
try:
msgs = await self.eh_partition_pump.partition_receive_handler.receive(
... | Runs the async partion reciever event loop to retrive messages from the event queue. |
def OnTimer(self, event):
self.timer_updating = True
shape = self.grid.code_array.shape[:2]
selection = Selection([(0, 0)], [(shape)], [], [], [])
self.grid.actions.refresh_selected_frozen_cells(selection)
self.grid.ForceRefresh() | Update all frozen cells because of timer call |
def spawn(self, **kwargs):
copy = dict(self.kwargs)
copy.update(kwargs)
if isinstance(self.klass, string_types):
self.klass = util.import_class(self.klass)
return self.klass(self.queues, self.client, **copy) | Return a new worker for a child process |
def get(self, name):
"Get the first tag function matching the given name"
for bucket in self:
for k,v in self[bucket].items():
if k == name:
return v | Get the first tag function matching the given name |
def calc_piece_size(size, min_piece_size=20, max_piece_size=29, max_piece_count=1000):
logger.debug('Calculating piece size for %i' % size)
for i in range(min_piece_size, max_piece_size):
if size / (2**i) < max_piece_count:
break
return 2**i | Calculates a good piece size for a size |
def __get_switch_arr(work_sheet, row_num):
u_dic = []
for col_idx in FILTER_COLUMNS:
cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value
if cell_val in [1, '1']:
u_dic.append(work_sheet['{0}1'.format(col_idx)].value.strip().split(',')[0])
return u_dic | if valud of the column of the row is `1`, it will be added to the array. |
def promote(self, move: chess.Move) -> None:
variation = self[move]
i = self.variations.index(variation)
if i > 0:
self.variations[i - 1], self.variations[i] = self.variations[i], self.variations[i - 1] | Moves a variation one up in the list of variations. |
def this_year():
since = TODAY
while since.month != 3 or since.day != 1:
since -= delta(days=1)
until = since + delta(years=1)
return Date(since), Date(until) | Return start and end date of this fiscal year |
def remove_armor(armored_data):
stream = io.BytesIO(armored_data)
lines = stream.readlines()[3:-1]
data = base64.b64decode(b''.join(lines))
payload, checksum = data[:-3], data[-3:]
assert util.crc24(payload) == checksum
return payload | Decode armored data into its binary form. |
def run_gui():
try:
from gi.repository import Gtk
except ImportError as ie:
pass
except RuntimeError as e:
sys.stderr.write(GUI_MESSAGE)
sys.stderr.write("%s: %r" % (e.__class__.__name__, utils.exc_as_decoded_string(e)))
sys.stderr.flush()
sys.exit(1)
if n... | Function for running DevAssistant GUI |
def getExerciseDetails(self, identifier):
exercise = self._getExercise(identifier)
response = {
b"identifier": exercise.identifier,
b"title": exercise.title,
b"description": exercise.description,
b"solved": exercise.wasSolvedBy(self.user)
}
... | Gets the details for a particular exercise. |
def link(self, content, link, title=''):
link = links.resolve(link, self._search_path,
self._config.get('absolute'))
return '{}{}</a>'.format(
utils.make_tag('a', {
'href': link,
'title': title if title else None
}),
... | Emit a link, potentially remapped based on our embed or static rules |
def dump_index(args, idx):
import csv
import sys
from metatab import MetatabDoc
doc = MetatabDoc()
pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format'])
r = doc['Root']
r.new_term('Root.Title', 'Package Index')
for p in idx.list():
pack... | Create a metatab file for the index |
def multi_h1(cls, a_dict: Dict[str, Any], bins=None, **kwargs) -> "HistogramCollection":
from physt.binnings import calculate_bins
mega_values = np.concatenate(list(a_dict.values()))
binning = calculate_bins(mega_values, bins, **kwargs)
title = kwargs.pop("title", None)
name = kw... | Create a collection from multiple datasets. |
def min_branch_length(go_id1, go_id2, godag, branch_dist):
goterm1 = godag[go_id1]
goterm2 = godag[go_id2]
if goterm1.namespace == goterm2.namespace:
dca = deepest_common_ancestor([go_id1, go_id2], godag)
dca_depth = godag[dca].depth
depth1 = goterm1.depth - dca_depth
depth2 ... | Finds the minimum branch length between two terms in the GO DAG. |
def profile_path(self, path, must_exist=False):
full_path = self.session.profile / path
if must_exist and not full_path.exists():
raise FileNotFoundError(
errno.ENOENT,
os.strerror(errno.ENOENT),
PurePath(full_path).name,
)
... | Return path from current profile. |
def entry():
parser = argparse.ArgumentParser()
parser.add_argument(
'action', help='Action to take',
choices=['from_hex', 'to_rgb', 'to_hex'],
)
parser.add_argument(
'value', help='Value for the action',
)
parsed = parser.parse_args()
if parsed.action != "from_hex":
... | Parse command line arguments and run utilities. |
def _validate_optional_key(key, missing, value, validated, optional):
try:
validated[key] = optional[key](value)
except NotValid as ex:
return ['%r: %s' % (key, arg) for arg in ex.args]
if key in missing:
missing.remove(key)
return [] | Validate an optional key. |
def updateTitle(self):
title = 'Auto Parameters ({})'.format(self.paramList.model().rowCount())
self.titleChange.emit(title)
self.setWindowTitle(title) | Updates the Title of this widget according to how many parameters are currently in the model |
def merge_cameras(self):
combined = CaseInsensitiveDict({})
for sync in self.sync:
combined = merge_dicts(combined, self.sync[sync].cameras)
return combined | Merge all sync camera dicts into one. |
def vm_info(name, quiet=False):
data = query(quiet=True)
return _find_vm(name, data, quiet) | Return the information on the named VM |
def rsdl(self):
diff = self.Xf - self.Yfprv
return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN) | Compute fixed point residual in Fourier domain. |
def _metrics_get_endpoints(options):
if bool(options.start) ^ bool(options.end):
log.error('--start and --end must be specified together')
sys.exit(1)
if options.start and options.end:
start = options.start
end = options.end
else:
end = datetime.utcnow()
start... | Determine the start and end dates based on user-supplied options. |
def add_metadata(file_name, title, artist, album):
tags = EasyMP3(file_name)
if title:
tags["title"] = title
if artist:
tags["artist"] = artist
if album:
tags["album"] = album
tags.save()
return file_name | As the method name suggests |
def new_encoded_stream(args, stream):
if args.ascii_print:
return wpull.util.ASCIIStreamWriter(stream)
else:
return stream | Return a stream writer. |
def _clean_dict(row):
row_cleaned = {}
for key, val in row.items():
if val is None or val == '':
row_cleaned[key] = None
else:
row_cleaned[key] = val
return row_cleaned | Transform empty strings values of dict `row` to None. |
def cleanup(config=None, path=None):
if config is None:
config = parse()
if path is None:
path = os.getcwd()
root = config.get('root', 'path')
root = os.path.join(path, root)
if sys.path[0] == root:
sys.path.remove(root) | Cleanup by removing paths added during earlier in configuration. |
def download(self, storagemodel:object, modeldefinition = None):
if (storagemodel.name is None):
raise AzureStorageWrapException(storagemodel, "StorageBlobModel does not contain content nor content settings")
else:
container_name = modeldefinition['container']
blob_na... | load blob from storage into StorageBlobModelInstance |
def _set_defaults(self, defaults):
self.n_res = defaults.n_res
self.n_sub = defaults.n_sub
self.randomize = defaults.randomize
self.return_median = defaults.return_median
self.efficient = defaults.efficient
self.return_only_bw = defaults.return_only_bw
self.n_jobs... | Sets the default values for the efficient estimation |
def rpc_get_name_DID(self, name, **con_info):
did_info = None
if check_name(name):
did_info = self.get_name_DID_info(name)
elif check_subdomain(name):
did_info = self.get_subdomain_DID_info(name)
else:
return {'error': 'Invalid name or subdomain', 'htt... | Given a name or subdomain, return its DID. |
def copy(self, overrides=None, locked=False):
other = copy.copy(self)
if overrides is not None:
other.overrides = overrides
other.locked = locked
other._uncache()
return other | Create a separate copy of this config. |
def count(self) -> int:
counter = 0
for pool in self._host_pools.values():
counter += pool.count()
return counter | Return number of connections. |
def _addrs2nodes(addrs, G):
for i, n in enumerate(G.nodes()):
G.node[n]['addr'] = addrs[i] | Map agent addresses to nodes in the graph. |
def visit_constant(self, node, parent):
return nodes.Const(
node.value,
getattr(node, "lineno", None),
getattr(node, "col_offset", None),
parent,
) | visit a Constant node by returning a fresh instance of Const |
def child(self):
return self.stream.directory[self.child_id] \
if self.child_id != NOSTREAM else None | Root entry object has only one child entry and no siblings. |
def getpaths(self,libname):
if os.path.isabs(libname):
yield libname
else:
for path in self.getplatformpaths(libname):
yield path
path = ctypes.util.find_library(libname)
if path: yield path | Return a list of paths where the library might be found. |
def execute(cls, stage, state, data, next_allowed_exec_time=None):
try:
context = Context.from_state(state, stage)
now = datetime.utcnow()
if next_allowed_exec_time and now < next_allowed_exec_time:
Queue.queue(stage, state, data, delay=next_allowed_exec_time)... | Execute the operation, rate limiting allowing. |
def delete_gauge(self, slug):
key = self._gauge_key(slug)
self.r.delete(key)
self.r.srem(self._gauge_slugs_key, slug) | Removes all gauges with the given ``slug``. |
def _add_world_state(self, global_state: GlobalState):
for hook in self._add_world_state_hooks:
try:
hook(global_state)
except PluginSkipWorldState:
return
self.open_states.append(global_state.world_state) | Stores the world_state of the passed global state in the open states |
def on_button(callback, args=(), buttons=(LEFT, MIDDLE, RIGHT, X, X2), types=(UP, DOWN, DOUBLE)):
if not isinstance(buttons, (tuple, list)):
buttons = (buttons,)
if not isinstance(types, (tuple, list)):
types = (types,)
def handler(event):
if isinstance(event, ButtonEvent):
... | Invokes `callback` with `args` when the specified event happens. |
def adjustFiles(rec, op):
if isinstance(rec, MutableMapping):
if rec.get("class") == "File":
rec["path"] = op(rec["path"])
for d in rec:
adjustFiles(rec[d], op)
if isinstance(rec, MutableSequence):
for d in rec:
adjustFiles(d, op) | Apply a mapping function to each File path in the object `rec`. |
def save_to_json(self):
requestvalues = {
'DatasetId': self.dataset,
'Name': self.name,
'Description': self.description,
'Source': self.source,
'PubDate': self.publication_date,
'AccessedOn': self.accessed_on,
'Url': sel... | The method saves DatasetUpload to json from object |
def build_object(self, obj):
if not obj.exclude_from_static:
super(ShowPage, self).build_object(obj) | Override django-bakery to skip pages marked exclude_from_static |
def print_help(self, file=None):
output = file or self.stderr
CustomStderrOptionParser.print_help(self, output)
output.write("\nCommands:\n")
for command_def in self.command_definitions.values():
command_def.opt_parser.print_help(output)
output.write("\n") | recursively call all command parsers' helps |
def get(self, url, params=None, raw=False, stream=False, **request_kwargs):
full_url = self.build_url(url)
params = params or {}
if self._token:
params.setdefault('token', self._token)
response = requests.get(full_url, params=params, stream=stream,
... | GET request to AmigoCloud endpoint. |
def __get_package_manager(self):
package_manager = ""
args = ""
sudo_required = True
if system.is_osx():
package_manager = "brew"
sudo_required = False
args = " install"
elif system.is_debian():
package_manager = "apt-get"
... | Installs and verifies package manager |
def returner(ret):
consistency_level = getattr(pycassa.ConsistencyLevel,
__opts__['cassandra.consistency_level'])
pool = pycassa.ConnectionPool(__opts__['cassandra.keyspace'],
__opts__['cassandra.servers'])
ccf = pycassa.ColumnFamily(pool, __... | Return data to a Cassandra ColumnFamily |
def load_planet_list():
planet_list = []
with open(fldr + os.sep + 'planet_samples.csv') as f:
hdr = f.readline()
for line in f:
name, num_seeds, width, height, wind, rain, sun, lava = parse_planet_row(line)
planet_list.append({'name':name, 'num_seeds':num_seeds, 'width':... | load the list of prebuilt planets |
def node_inclusion_predicate_builder(nodes: Iterable[BaseEntity]) -> NodePredicate:
nodes = set(nodes)
@node_predicate
def node_inclusion_predicate(node: BaseEntity) -> bool:
return node in nodes
return node_inclusion_predicate | Build a function that returns true for the given nodes. |
def delete(self, ignore=None):
ignore = ignore or []
def _delete(tree_or_filename, alias=None):
if alias:
yield alias, self.client.indices.delete_alias(
index=list(_get_indices(tree_or_filename)),
name=alias,
ignore=... | Yield tuple with deleted index name and responses from a client. |
def write_html(self, text, image_map=None):
"Parse HTML and convert it to PDF"
h2p = HTML2FPDF(self, image_map)
text = h2p.unescape(text)
h2p.feed(text) | Parse HTML and convert it to PDF |
def tointerval(s):
if isinstance(s, basestring):
m = coord_re.search(s)
if m.group('strand'):
return pybedtools.create_interval_from_list([
m.group('chrom'),
m.group('start'),
m.group('stop'),
'.',
'0',
... | If string, then convert to an interval; otherwise just return the input |
def from_lines(pdb_file_lines, strict = True, parse_ligands = False):
return PDB("\n".join(pdb_file_lines), strict = strict, parse_ligands = parse_ligands) | A function to replace the old constructor call where a list of the file's lines was passed in. |
def setup_shiny():
name = 'shiny'
def _get_shiny_cmd(port):
conf = dedent(
).format(
user=getpass.getuser(),
port=str(port),
site_dir=os.getcwd()
)
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(conf)
f.close()
... | Manage a Shiny instance. |
def generic_visit(self, node):
super(RangeValues, self).generic_visit(node)
return self.add(node, UNKNOWN_RANGE) | Other nodes are not known and range value neither. |
def show_network_gateway(self, gateway_id, **_params):
return self.get(self.network_gateway_path % gateway_id, params=_params) | Fetch a network gateway. |
def _basename(station_code, fmt=None):
info = _station_info(station_code)
if not fmt:
fmt = info['data_format']
basename = '%s.%s' % (info['url'].rsplit('/', 1)[1].rsplit('.', 1)[0],
DATA_EXTENTIONS[fmt])
return basename | region, country, weather_station, station_code, data_format, url. |
def recognise(self):
if not isinstance(self.cube, Cube):
raise ValueError("Use Solver.feed(cube) to feed the cube to solver.")
result = ""
for face in "LFRB":
for square in self.cube.get_face(face)[0]:
result += str(int(square == self.cube["U"]["U"]))
... | Recognise which is Cube's OLL case. |
def word_texts(self):
if not self.is_tagged(WORDS):
self.tokenize_words()
return [word[TEXT] for word in self[WORDS]] | The list of words representing ``words`` layer elements. |
def raise_null_argument(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except TypeError as ex:
if any(statement in ex.args[0] for statement in ['takes exactly',
'required positional argument'... | decorator, to intercept num argument TypeError and raise as NullArgument |
async def set_config(self, on=None, tholddark=None, tholdoffset=None):
data = {
key: value for key, value in {
'on': on,
'tholddark': tholddark,
'tholdoffset': tholdoffset,
}.items() if value is not None
}
await self._reques... | Change config of a CLIP LightLevel sensor. |
def _perform_write(self, addr, data):
return self._machine_controller.write(addr, data, self._x, self._y, 0) | Perform a write using the machine controller. |
def parse_set(string):
string = string.strip()
if string:
return set(string.split(","))
else:
return set() | Parse set from comma separated string. |
def _create_skt(self):
log.debug('Creating the auth socket')
if ':' in self.auth_address:
self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
else:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.socket.bind((self... | Create the authentication socket. |
def check_url (aggregate):
while True:
try:
aggregate.urlqueue.join(timeout=30)
break
except urlqueue.Timeout:
aggregate.remove_stopped_threads()
if not any(aggregate.get_check_threads()):
break | Helper function waiting for URL queue. |
def proplist(self, rev, path=None):
rev, prefix = self._maprev(rev)
if path is None:
return self._proplist(str(rev), None)
else:
path = type(self).cleanPath(_join(prefix, path))
return self._proplist(str(rev), path) | List Subversion properties of the path |
def _get_plt_data(self, hdrgos_usr):
hdrgo2usrgos = self.grprobj.get_hdrgo2usrgos(hdrgos_usr)
usrgos_actual = set([u for us in hdrgo2usrgos.values() for u in us])
go2obj = self.gosubdag.get_go2obj(usrgos_actual.union(hdrgo2usrgos.keys()))
return hdrgo2usrgos, go2obj | Given User GO IDs, return their GO headers and other GO info. |
def parse_opml_file(filename: str) -> OPML:
root = parse_xml(filename).getroot()
return _parse_opml(root) | Parse an OPML document from a local XML file. |
async def push_stats(self):
snapshot = self._make_stats()
try:
serialized = json.dumps(snapshot)
await self._call_redis(aioredis.Redis.set, state.MANAGER_LISTENER_STATS, serialized)
await self._call_redis(aioredis.Redis.expire, state.MANAGER_LISTENER_STATS, 3600)
... | Push current stats to Redis. |
def save_rst(self, fd):
from pylon.io import ReSTWriter
ReSTWriter(self).write(fd) | Save a reStructuredText representation of the case. |
def __create_header(self, command, command_string, session_id, reply_id):
buf = pack('<4H', command, 0, session_id, reply_id) + command_string
buf = unpack('8B' + '%sB' % len(command_string), buf)
checksum = unpack('H', self.__create_checksum(buf))[0]
reply_id += 1
if reply_id >=... | Puts a the parts that make up a packet together and packs them into a byte string |
def reset(self):
self.scores = torch.FloatTensor(torch.FloatStorage())
self.targets = torch.LongTensor(torch.LongStorage())
self.weights = torch.FloatTensor(torch.FloatStorage()) | Resets the meter with empty member variables |
def _longoptl(self):
res = []
for o in self.options:
nm = o.long
if o.argName is not None:
nm += "="
res.append(nm)
return res | Get a list of string representations of the options in long format. |
def salt_config_to_yaml(configuration, line_break='\n'):
return salt.utils.yaml.safe_dump(
configuration,
line_break=line_break,
default_flow_style=False) | Return a salt configuration dictionary, master or minion, as a yaml dump |
def ParseMultiple(self, result_dicts):
for result_dict in result_dicts:
yield rdf_client.HardwareInfo(
serial_number=result_dict["IdentifyingNumber"],
system_manufacturer=result_dict["Vendor"]) | Parse the WMI output to get Identifying Number. |
def cancel(self, function):
if function in self._callback.keys():
callback_id = self._callback[function][0]
self.tk.after_cancel(callback_id)
self._callback.pop(function)
else:
utils.error_format("Could not cancel function - it doesnt exist, it may have al... | Cancel the scheduled `function` calls. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.