code stringlengths 15 1.19k | docstring stringlengths 13 400 |
|---|---|
def normalize_spaces(s):
if not s:
return ""
return " ".join(s.split())
| replace any sequence of whitespace
characters with a single space |
def format_message(txt, context, msg_type):
return "{2} {0}: {1}".format(context, txt, msg_type)
| Format a message in a predefined format
Parameters
str
Text of the message itself
str
'Context' of where the message originated
str
Info, warning or error |
def is_stupid_mkr(name):
if name is None:
return False
return name.lower() == "mkr"
| Stupid mkr
Parameters
str
Name of user, maybe stupid mkr |
def override(msg):
content = msg.content.split()[0]
if content == "!duel":
return "Duel me you coward!"
return msg.content
| Override possible commands so that the
bot can respond instead of attempting to
parse the command
Paramters
Message
Message/command to override |
def sliding_window(sequence, window_size, step_size):
seq = []
for start in range(0, len(sequence), step_size):
end = start + window_size
if end > len(sequence):
seq.append(
sequence[start : len(sequence)]
+ "N" * (window_size - (len(sequence) - start)... | Converts a sequence into sliding windows. Returns a list of sequences.
sequence: a string containing only nucleotides.
window_size: Windows of equal size sequence. Default is 500 bp.
step_size: overlap required for sliding windows. Default is 250 bp. |
def check_valid_nucleotides(seq):
if re.match("^[ACTG]+$", seq):
return True
else:
return False
| Used to clean sequences with non-standard nucleotide symbols. |
def reset_project(outputs):
stamp = time.time()
for f in outputs:
if os.path.exists(f):
os.utime(f, (stamp, stamp))
| Set the timestamp of all files in a project to be the same. |
def _tosort(layerlist, parent=None, depth=0):
layers = []
thisgroup = []
for l in layerlist:
if pdb.gimp_item_is_group(l):
layers.extend(_tosort(l.children, l, depth + 1))
else:
thisgroup.append(l)
layers.append((depth, parent, list(thisgroup)))
layers.sort(ke... | Returns a list of lists of layers to sort, depth-first |
def without_group_layers(layerlist):
layers = []
for l in layerlist:
if pdb.gimp_item_is_group(l):
layers.extend(without_group_layers(l.children))
else:
layers.append(l)
return layers
| Returns a recursively flattened list of layers.
Group layers are recursed into but not included in results. |
def dt2doy(dt):
return int(dt.timetuple().tm_yday)
| Convert datetime to integer DOY (Julian) |
def _set_joint_velocities(physics, joint_ids, joint_velocities):
for i in range(0, physics.model.nv):
physics.data.qvel[i] = 0.0
for joint_id, velocity in zip(sorted(joint_ids), joint_velocities):
dof_adr = physics.model.jnt_dofadr[joint_id]
physics.data.qvel[dof_adr] = velocity
| Sets the joint velocities in physics for a subset of joints. |
def _call_string(call):
positional_args = call[0]
keyword_args = call[1]
arg_strings = []
if positional_args:
arg_strings.append(", ".join([str(arg) for arg in positional_args]))
if keyword_args:
arg_strings.append(", ".join([f"{k}={v}" for (k, v) in keyword_args.items()]))
arg_s... | Converts the provided call to string. |
def binding(physics, elements):
physics_elements = physics.bind(elements)
if physics_elements is None:
raise ValueError(f"Calling physics.bind with {elements} returns None.")
return physics_elements
| Binds the elements with physics and returns a non optional object.
The goal of this function is to return a non optional element so that when
the physics_elements object is used, there is no pytype error. |
def overrides(interface):
def overrider(method):
if not hasattr(interface, method.__name__):
raise Exception(
"method %s declared to be @override is not defined in %s"
% (method.__name__, interface.__name__)
)
return method
return override... | Overrides decorator to annotate method overrides parent's. |
def register_property(func):
if isinstance(func, property):
raise AssertionError("@register_property must be after @property")
argspec = inspect.getfullargspec(func)
if len(argspec.args) == 1:
func.register_getter = True
elif len(argspec.args) == 2:
func.register_setter = True
... | Adds a property to registered_properties. must appear after @property. |
def rmat_to_rot6(rmat):
return rmat[:, :-1].T.flatten()
| Projects rotation matrix to 6-dim "Gram-Schmidt-able" representation.
The "rot6" representation is a 6-DOF representation of an orientation that is
homeomorphic with SO(3). It is not minimal like an euler or axis-angle, but
it is smooth over the full range of rotations, unlike eulers, quaternions, and
axis-angle repres... |
def standard_compose(arm, gripper, wrist_ft=None, wrist_cameras=()):
if wrist_ft:
wrist_ft.attach(gripper)
arm.attach(wrist_ft)
else:
arm.attach(gripper)
for cam in wrist_cameras:
arm.attach(cam, arm.wrist_site)
| Creates arm and attaches gripper. |
def _is_pass_contype_conaffinity_check(model, geom1_id, geom2_id):
return (
model.geom_contype[geom1_id] & model.geom_conaffinity[geom2_id]
or model.geom_contype[geom2_id] & model.geom_conaffinity[geom1_id]
)
| Returns true if the geoms pass the contype/conaffinity check. |
def _logger_thread(q):
while True:
record = q.get()
if record is None:
break
logger = logging.getLogger(record.name)
logger.handle(record)
| Thread on main process to wait for logging events |
def load_one_pipeline(path):
with open(path, "r") as f:
pipeline = json.load(f)
return (pipeline["id"], pipeline["pipeline_rank"])
| read a pipeline, return its rank and pipeline |
def score_prediction(prediction_file, ground_truth_dir):
res = {}
return res
| using NIST to score the result and return a dict that contain informations |
def make_game_id(row):
game_id = "{} {}-{}".format(
row["date"].strftime("%Y-%m-%d"),
row["home_team"],
row["away_team"],
)
return game_id
| Return a game id based on date, home and away team. |
def _decrease_pool_count(pool_list, pool, count=1):
if pool["count"] > count:
pool["count"] -= count
count = 0
else:
count -= pool["count"]
pool_list.remove(pool)
return count
| Decrement pool's size by count.
If pool becomes empty, remove pool from pool_list. |
def _has_local_disk(instance, disk_mapping):
if disk_mapping:
if (
"disk.local" in disk_mapping
or "disk.swap" in disk_mapping
or "disk.config" in disk_mapping
):
return True
return False
| Determines whether the VM has a local disk
Determines whether the disk mapping indicates that the VM
has a local disk . |
def new(cls, context, instance_uuid):
info_cache = cls()
info_cache.instance_uuid = instance_uuid
info_cache.network_info = None
info_cache._context = context
return info_cache
| Create an InfoCache object that can be used to create the DB
entry for the first time.
When save()ing this object, the info_cache_update() DB call
will properly handle creating it if it doesn't exist already. |
def _translate_vif_summary_view(vif):
d = {}
d["id"] = vif.uuid
d["mac_address"] = vif.address
return d
| Maps keys for VIF summary view. |
def dgorganization(count):
total = count + (count // 4)
print(str(count // 4) + " leaders")
print(str(count) + " computers")
print(str(count // 5) + " tables")
print(str(total) + " chairs")
print(str(total) + " snacks")
print(str(total // 2) + " gifts")
| Prints necessary things to do Django Girls Workshop |
def datestr_from_filename(filename, datestr_format="yyyymmddHHMM"):
return os.path.splitext(filename)[0][-len(datestr_format) :]
| return date string from filename, assuming it consists of the last digits of the filename before the extension |
def generate_output_filename(basename, time, ext="nc"):
return "{}{}.{}".format(basename, time[-1].dt.strftime("%Y%m%d%H%M").data, ext)
| generate filename from basename, ext and end time inferred from data time vector (basename_yyyymmddHHMM.ext) |
def unsetbit(x, nth_bit):
if nth_bit < 0:
raise ValueError("position of bit cannot be negative")
mask = 1 << nth_bit
return x & ~mask
| unset n-th bit in an integer or array of integers |
def mutate(mutProp, programs):
mutNum = int(len(programs) * mutProp)
for index in range(mutNum):
program = random.choice(programs)
program.mutate()
| Mutates a given percent of a population of programs |
def converter(s):
picobotDict = {}
L = s.split("\n")
for item in L[1:]:
key = (int(item[1]), str(item[3:7]))
value = (str(item[11]), int(item[13]))
picobotDict[key] = value
return picobotDict
| Takes picobot code, as a string, and returns a picobot dictionary |
def converter(L):
picobotDict = {}
for item in L:
key = (int(item[0]), str(item[2:6]))
value = (str(item[10]), int(item[12]))
picobotDict[key] = value
return picobotDict
| Takes picobot code, as a list, and returns a picobot dictionary |
def _uid_or_str(node_or_entity):
return node_or_entity.uid if hasattr(node_or_entity, "uid") else str(node_or_entity)
| Helper function to support the transition from `Entitie`s to `Node`s. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.