Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
7,100 | def safe_evaluate(command, glob, local):
while True:
try:
return eval(command, glob, local)
except NameError as e:
match = re.match("name is not defined", e.message)
if not match:
raise e
try:
exec ( % (match.group... | Continue to attempt to execute the given command, importing objects which
cause a NameError in the command
:param command: command for eval
:param glob: globals dict for eval
:param local: locals dict for eval
:return: command result |
7,101 | def _remove_summary(self):
if self.size > 0:
print("\nRemoved summary")
print("=" * 79)
print("{0}Size of removed packages {1} {2}.{3}".format(
self.meta.color["GREY"], round(self.size, 2), self.unit,
self.meta.color["ENDC"])) | Removed packge size summary |
7,102 | def show_instance(name, call=None):
local = salt.client.LocalClient()
ret = local.cmd(name, )
ret.update(_build_required_items(ret))
return ret | List the a single node, return dict of grains. |
7,103 | def set_alarm_mode(self, mode):
values = {"desired_state": {"alarm_mode": mode}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(response) | :param mode: one of [None, "activity", "tamper", "forced_entry"]
:return: nothing |
7,104 | def add_service(self, service_type, service_endpoint=None, values=None):
if isinstance(service_type, Service):
service = service_type
else:
service = Service(service_endpoint, service_type, values, did=self._did)
logger.debug(f)
self._services.append(serv... | Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint. |
7,105 | def arity_evaluation_checker(function):
is_class = inspect.isclass(function)
if is_class:
function = function.__init__
function_info = inspect.getargspec(function)
function_args = function_info.args
if is_class:
function_... | Build an evaluation checker that will return True when it is
guaranteed that all positional arguments have been accounted for. |
7,106 | def cached_property(func):
name = func.__name__
doc = func.__doc__
def getter(self, name=name):
try:
return self.__dict__[name]
except KeyError:
self.__dict__[name] = value = func(self)
return value
getter.func_name = name
return property(ge... | Special property decorator that caches the computed
property value in the object's instance dict the first
time it is accessed. |
7,107 | def _parse_name(self, team_data):
name = team_data()
name = re.sub(r, , str(name))
name = re.sub(r, , name)
setattr(self, , name) | Parses the team's name.
On the pages being parsed, the team's name doesn't follow the standard
parsing algorithm that we use for the fields, and requires a special
one-off algorithm. The name is attached in the 'title' attribute from
within 'team_ID'. A few simple regex subs captures th... |
7,108 | def deploy_s3app(self):
utils.banner("Deploying S3 App")
primary_region = self.configs[][]
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
... | Deploys artifacts contents to S3 bucket |
7,109 | def render_js_template(self, template_path, element_id, context=None):
context = context or {}
return u"<script type= id=>\n{}\n</script>".format(
element_id,
self.render_template(template_path, context)
) | Render a js template. |
7,110 | def color_pack2rgb(packed):
r = packed & 255
g = (packed & (255 << 8)) >> 8
b = (packed & (255 << 16)) >> 16
return r, g, b | Returns r, g, b tuple from packed wx.ColourGetRGB value |
7,111 | def calculate_ecef_velocity(inst):
x = inst[]
vel_x = (x.values[2:] - x.values[0:-2])/2.
y = inst[]
vel_y = (y.values[2:] - y.values[0:-2])/2.
z = inst[]
vel_z = (z.values[2:] - z.values[0:-2])/2.
inst[1:-1, ] = vel_x
inst[1:-1, ] = vel_y
inst[1:-1, ] = vel_z
... | Calculates spacecraft velocity in ECEF frame.
Presumes that the spacecraft velocity in ECEF is in
the input instrument object as position_ecef_*. Uses a symmetric
difference to calculate the velocity thus endpoints will be
set to NaN. Routine should be run using pysat data padding feature
to c... |
7,112 | def nfa_json_importer(input_file: str) -> dict:
file = open(input_file)
json_file = json.load(file)
transitions = {}
for p in json_file[]:
transitions.setdefault((p[0], p[1]), set()).add(p[2])
nfa = {
: set(json_file[]),
: set(json_file[]),
: set(json_fi... | Imports a NFA from a JSON file.
:param str input_file: path+filename to JSON file;
:return: *(dict)* representing a NFA. |
7,113 | def get_processor_status(self, p, x, y):
address = (self.read_struct_field("sv", "vcpu_base", x, y) +
self.structs[b"vcpu"].size * p)
data = self.read(address, self.structs[b"vcpu"].size, x, y)
state = {
name.decode(): struct.u... | Get the status of a given core and the application executing on it.
Returns
-------
:py:class:`.ProcessorStatus`
Representation of the current state of the processor. |
7,114 | def get_out_streamids(self):
if self.outputs is None:
return set()
if not isinstance(self.outputs, (list, tuple)):
raise TypeError("Argument to outputs must be either list or tuple, given: %s"
% str(type(self.outputs)))
ret_lst = []
for output in self.outputs:
... | Returns a set of output stream ids registered for this component |
7,115 | def parse_time_trigger_string(trigger_frequency):
trigger_frequency = .join(trigger_frequency.split())
if trigger_frequency.startswith(TRIGGER_PREAMBLE_AT):
trigger_frequency = trigger_frequency[len(TRIGGER_PREAMBLE_AT):]
parsed_trigger_frequency = trigger_frequency.replace(,... | :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) |
7,116 | def altitude(SCALED_PRESSURE, ground_pressure=None, ground_temp=None):
from . import mavutil
self = mavutil.mavfile_global
if ground_pressure is None:
if self.param(, None) is None:
return 0
ground_pressure = self.param(, 1)
if ground_temp is None:
ground_temp = ... | calculate barometric altitude |
7,117 | def get_nvr(self, epoch=None):
name = self.get_tag(, expand_macros=True)
vr = self.get_vr(epoch=epoch)
return % (name, vr) | get NVR string from .spec Name, Version, Release and Epoch |
7,118 | def rowlengths(table):
counter = Counter()
for row in data(table):
counter[len(row)] += 1
output = [(, )]
output.extend(counter.most_common())
return wrap(output) | Report on row lengths found in the table. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['A', 1, 2],
... ['B', '2', '3.4'],
... [u'B', u'3', u'7.8', True],
... ['D', 'xyz', 9.0],
... ['E', None]... |
7,119 | def cmd_antenna(self, args):
if len(args) != 2:
if self.gcs_location is None:
print("GCS location not set")
else:
print("GCS location %s" % str(self.gcs_location))
return
self.gcs_location = (float(args[0]), float(args[1])) | set gcs location |
7,120 | def bandpass_filter(data, k, w1, w2):
data = np.asarray(data)
low_w = np.pi * 2 / w2
high_w = np.pi * 2 / w1
bweights = np.zeros(2 * k + 1)
bweights[k] = (high_w - low_w) / np.pi
j = np.arange(1, int(k) + 1)
weights = 1 / (np.pi * j) * (sin(high_w * j) - sin(low_w * j))
bweights[k +... | This function will apply a bandpass filter to data. It will be kth
order and will select the band between w1 and w2.
Parameters
----------
data: array, dtype=float
The data you wish to filter
k: number, int
The order of approximation for the filter. A max value for
... |
7,121 | def list_modules(desc=False):
win01win01
cmd =
modules = _pshell(cmd)
if isinstance(modules, dict):
ret = []
if desc:
modules_ret = {}
modules_ret[modules[]] = copy.deepcopy(modules)
modules = modules_ret
return modules
ret.append(... | List currently installed PSGet Modules on the system.
:param desc: If ``True``, the verbose description will be returned.
:type desc: ``bool``
CLI Example:
.. code-block:: bash
salt 'win01' psget.list_modules
salt 'win01' psget.list_modules desc=True |
7,122 | def unsetenv(key):
key = path2fsn(key)
if is_win:
try:
del_windows_env_var(key)
except WindowsError:
pass
else:
os.unsetenv(key) | Like `os.unsetenv` but takes unicode under Windows + Python 2
Args:
key (pathlike): The env var to unset |
7,123 | def n_at_a_time(
items: List[int], n: int, fillvalue: str
) -> Iterator[Tuple[Union[int, str]]]:
it = iter(items)
return itertools.zip_longest(*[it] * n, fillvalue=fillvalue) | Returns an iterator which groups n items at a time.
Any final partial tuple will be padded with the fillvalue
>>> list(n_at_a_time([1, 2, 3, 4, 5], 2, 'X'))
[(1, 2), (3, 4), (5, 'X')] |
7,124 | def simplex_select_entering_arc(self, t, pivot):
first_eligibledantzigdantzig
if pivot==:
candidate = {}
for e in self.edge_attr:
if e in t.edge_attr:
continue
flow_ij = self.edge_attr[e][]
potential... | API:
simplex_select_entering_arc(self, t, pivot)
Description:
Decides and returns entering arc using pivot rule.
Input:
t: current spanning tree solution
pivot: May be one of the following; 'first_eligible' or 'dantzig'.
'dantzig' is the defaul... |
7,125 | def add_index(self, mode, blob_id, path):
self.command_exec([, , , mode, blob_id, path]) | Add new entry to the current index
:param tree:
:return: |
7,126 | def split_qs(string, delimiter=):
open_list =
close_list =
quote_chars = '
level = index = last_index = 0
quoted = False
result = []
for index, letter in enumerate(string):
if letter in quote_chars:
if not quoted:
quoted = True
le... | Split a string by the specified unquoted, not enclosed delimiter |
7,127 | def members(self):
if self.serialized:
return set(map(
self._loads, self._client.smembers(self.key_prefix)))
else:
return set(map(
self._decode, self._client.smembers(self.key_prefix))) | -> #set of all members in the set |
7,128 | def _comm_tensor_data(device_name,
node_name,
maybe_base_expanded_node_name,
output_slot,
debug_op,
tensor_value,
wall_time):
output_slot = int(output_slot)
logger.info(
, nod... | Create a dict() as the outgoing data in the tensor data comm route.
Note: The tensor data in the comm route does not include the value of the
tensor in its entirety in general. Only if a tensor satisfies the following
conditions will its entire value be included in the return value of this
method:
1. Has a n... |
7,129 | def property_data_zpool():
zpool get
property_data = _property_parse_cmd(_zpool_cmd(), {
: ,
: ,
: ,
: ,
: ,
})
zpool_size_extra = [
, ,
, ,
, ,
, ,
]
zpool_numeric_extra = [
, ,
]
for prop in zpo... | Return a dict of zpool properties
.. note::
Each property will have an entry with the following info:
- edit : boolean - is this property editable after pool creation
- type : str - either bool, bool_alt, size, numeric, or string
- values : str - list of possible values... |
7,130 | def get_language_description(grammar_file):
LOGGER.debug("> Processing grammar file.".format(grammar_file))
sections_file_parser = foundations.parsers.SectionsFileParser(grammar_file)
sections_file_parser.parse(strip_quotation_markers=False)
name = sections_file_parser.get_value("Name", "Langua... | Gets the language description from given language grammar file.
:param grammar_file: Language grammar.
:type grammar_file: unicode
:return: Language description.
:rtype: Language |
7,131 | async def get_updates(self, offset: typing.Union[base.Integer, None] = None,
limit: typing.Union[base.Integer, None] = None,
timeout: typing.Union[base.Integer, None] = None,
allowed_updates:
typing.Union[typing.List... | Use this method to receive incoming updates using long polling (wiki).
Notes
1. This method will not work if an outgoing webhook is set up.
2. In order to avoid getting duplicate updates, recalculate offset after each server response.
Source: https://core.telegram.org/bots/api#getupdat... |
7,132 | def get_position_i(self):
data = []
data.append(0x09)
data.append(self.servoid)
data.append(RAM_READ_REQ)
data.append(POSITION_KI_RAM)
data.append(BYTE2)
send_data(data)
rxdata = []
try:
rxdata = SERPORT.read(13)
re... | Get the I value of the current PID for position |
7,133 | def create(self, email, tos=1, options=None):
data = {: email,
: str(tos)}
if options:
data.update(options)
return self.post(self.base_url, body=json.dumps(data)) | Creates an account with Zencoder, no API Key necessary.
https://app.zencoder.com/docs/api/accounts/create |
7,134 | def save(self, name, content):
if name is None:
name = content.name
name = self.get_available_name(name)
name = self._save(name, content)
return name.replace("\\", "/") | Saves new content to the file specified by name. The content should be a
proper File object, ready to be read from the beginning. |
7,135 | def updatej9DB(dbname = abrevDBname, saveRawHTML = False):
if saveRawHTML:
rawDir = .format(os.path.dirname(__file__))
if not os.path.isdir(rawDir):
os.mkdir(rawDir)
_j9SaveCurrent(sDir = rawDir)
dbLoc = os.path.join(os.path.normpath(os.path.dirname(__file__)), dbname)
... | Updates the database of Journal Title Abbreviations. Requires an internet connection. The data base is saved relative to the source file not the working directory.
# Parameters
_dbname_ : `optional [str]`
> The name of the database file, default is "j9Abbreviations.db"
_saveRawHTML_ : `optional [boo... |
7,136 | def execute(self):
if not in self.params:
raise MMException("Please include the type of log, or ")
if not in self.params:
raise MMException("Please include debug categories in dictionary format: e.g.: {:, :}")
request = {}
if self.params[] == :
... | params = {
"ApexCode" : "None",
"ApexProfiling" : "01pd0000001yXtYAAU",
"Callout" : True,
"Database" : 1,
"ExpirationDate" : 3,
"ScopeId" : "",
"System" ... |
7,137 | def tie_properties(self, class_list):
log.setLevel(self.log_level)
start = datetime.datetime.now()
log.info(" Tieing properties to the class")
for cls_name in class_list:
cls_obj = getattr(MODULE.rdfclass, cls_name)
prop_dict = dict(cls_obj.properties)
... | Runs through the classess and ties the properties to the class
args:
class_list: a list of class names to run |
7,138 | def change_email(self, email):
self.email_unconfirmed = email
salt, hash = generate_sha1(self.username)
self.email_confirmation_key = hash
self.email_confirmation_key_created = get_datetime_now()
self.save()
self.send_confirmation_email()
... | Changes the email address for a user.
A user needs to verify this new email address before it becomes
active. By storing the new email address in a temporary field
-- ``temporary_email`` -- we are able to set this email address
after the user has verified it by clicking on the verific... |
7,139 | def readBIM(fileName):
snps = set()
with open(fileName, "r") as inputFile:
for line in inputFile:
row = line.rstrip("\r\n").split("\t")
snpName = row[1]
snps.add(snpName)
return snps | Reads a BIM file.
:param fileName: the name of the BIM file to read.
:type fileName: str
:returns: the set of markers in the BIM file.
Reads a Plink BIM file and extract the name of the markers. There is one
marker per line, and the name of the marker is in the second column. There
is no hea... |
7,140 | def get_dataset(self, key, info):
if self.mdrs is None:
self._read_all(self.filename)
if key.name in [, ]:
lons, lats = self.get_full_lonlats()
if key.name == :
dataset = create_xarray(lons)
else:
dataset = create_... | Get calibrated channel data. |
7,141 | def put(self, namespacePrefix):
self.reqparse.add_argument(, type=str, required=True)
self.reqparse.add_argument(, type=int, required=True)
args = self.reqparse.parse_args()
ns = db.ConfigNamespace.find_one(ConfigNamespace.namespace_prefix == namespacePrefix)
if not ns:... | Update a specific configuration namespace |
7,142 | def AddExtraShapes(extra_shapes_txt, graph):
print("Adding extra shapes from %s" % extra_shapes_txt)
try:
tmpdir = tempfile.mkdtemp()
shutil.copy(extra_shapes_txt, os.path.join(tmpdir, ))
loader = transitfeed.ShapeLoader(tmpdir)
schedule = loader.Load()
for shape in schedule.GetShapeList():
... | Add extra shapes into our input set by parsing them out of a GTFS-formatted
shapes.txt file. Useful for manually adding lines to a shape file, since it's
a pain to edit .shp files. |
7,143 | def multicat(data, samples, ipyclient):
start = time.time()
printstr = " indexing clusters | {} | s6 |"
elapsed = datetime.timedelta(seconds=int(time.time() - start))
progressbar(20, 0, printstr.format(elapsed))
lbview = ipyclient.load_balanced_view()
last_sample = 0
... | Runs singlecat and cleanup jobs for each sample.
For each sample this fills its own hdf5 array with catg data & indels.
This is messy, could use simplifiying. |
7,144 | def error_messages(self, driver_id=None):
if driver_id is not None:
assert isinstance(driver_id, ray.DriverID)
return self._error_messages(driver_id)
error_table_keys = self.redis_client.keys(
ray.gcs_utils.TablePrefix_ERROR_INFO_string + "*")
driver... | Get the error messages for all drivers or a specific driver.
Args:
driver_id: The specific driver to get the errors for. If this is
None, then this method retrieves the errors for all drivers.
Returns:
A dictionary mapping driver ID to a list of the error messag... |
7,145 | def check_pdb_status(pdbid):
url = % pdbid
xmlf = urlopen(url)
xml = et.parse(xmlf)
xmlf.close()
status = None
current_pdbid = pdbid
for df in xml.xpath():
status = df.attrib[]
if status == :
current_pdbid = df.attrib[]
return [status, current_pdbid.... | Returns the status and up-to-date entry in the PDB for a given PDB ID |
7,146 | def run(self, node, client):
perms = os.stat(self.source).st_mode
client.put(path=self.target, chmod=perms,
contents=open(self.source, ).read())
return node | Upload the file, retaining permissions
See also L{Deployment.run} |
7,147 | def strptime(cls, value, format):
if cls.python_supports_z or not in format:
return datetime.strptime(value, format)
else:
assert format[-2:] == ,
dt = datetime.strptime(value[:-5], format[:-2])
tz = FixedOf... | Parse a datetime string using the provided format.
This also emulates `%z` support on Python 2.
:param value: Datetime string
:type value: str
:param format: Format to use for parsing
:type format: str
:rtype: datetime
:raises ValueError: Invalid format
... |
7,148 | def _opbend_transform_mean(rs, fn_low, deriv=0):
v = 0.0
d = np.zeros((4,3), float)
dd = np.zeros((4,3,4,3), float)
for p in np.array([[0,1,2], [2,0,1], [1,2,0]]):
opbend = _opbend_transform([rs[p[0]], rs[p[1]], rs[p[2]], rs[3]], fn_low, deriv)
v += opbend[0]/3
index0 =... | Compute the mean of the 3 opbends |
7,149 | def build_next_url(self, url):
if not url:
if self.split_urls:
self.total_count_flag = False
return self.split_urls.pop(0)
else:
return None
parsed_url = urlparse(url)
return "{0}?{1}".format(parsed_url.path, p... | Builds next url in a format compatible with cousteau. Path + query |
7,150 | def variant(case_id, variant_id):
case_obj = app.db.case(case_id)
variant = app.db.variant(case_id, variant_id)
if variant is None:
return abort(404, "variant not found")
comments = app.db.comments(variant_id=variant.md5)
template = if app.db.variant_type == else
return render_t... | Show a single variant. |
7,151 | def is_valid_path(path):
if not path.startswith():
msg =
raise ValueError(msg % path[:40])
for c in :
if c in path:
msg = (
)
raise ValueError(msg % c)
return True | :return: True if the path is valid, else raise a ValueError with the
specific error |
7,152 | def docker(ctx, docker_run_args, docker_image, nvidia, digest, jupyter, dir, no_dir, shell, port, cmd, no_tty):
if not find_executable():
raise ClickException(
"Docker not installed, install it from https://docker.com" )
args = list(docker_run_args)
image = docker_image or ""
... | W&B docker lets you run your code in a docker image ensuring wandb is configured. It adds the WANDB_DOCKER and WANDB_API_KEY
environment variables to your container and mounts the current directory in /app by default. You can pass additional
args which will be added to `docker run` before the image name is dec... |
7,153 | def _LogProgressUpdateIfReasonable(self):
next_log_time = (
self._time_of_last_status_log +
self.SECONDS_BETWEEN_STATUS_LOG_MESSAGES)
current_time = time.time()
if current_time < next_log_time:
return
completion_time = time.ctime(current_time + self.EstimateTimeRemaining())
... | Prints a progress update if enough time has passed. |
7,154 | def dependencies(request, ident, stateless=False, **kwargs):
_, app = DashApp.locate_item(ident, stateless)
with app.app_context():
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp.data,
content_type=resp.mimetype) | Return the dependencies |
7,155 | def save_imglist(self, fname=None, root=None, shuffle=False):
def progress_bar(count, total, suffix=):
import sys
bar_len = 24
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = * ... | save imglist to disk
Parameters:
----------
fname : str
saved filename |
7,156 | def name(self):
res = type(self).__name__
if self._id:
res += ".{}".format(self._id)
return res | Get the module name
:return: Module name
:rtype: str | unicode |
7,157 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.status is not None:
_dict[] = self.status
if hasattr(self, ) and self.last_updated is not None:
_dict[] = datetime_to_string(self.last_updated)
return _dict | Return a json dictionary representing this model. |
7,158 | def del_option(self, section, option):
if self.config.has_section(section):
if self.config.has_option(section, option):
self.config.remove_option(section, option)
return (True, self.config.options(section))
return (False, + option + )
ret... | Deletes an option if the section and option exist |
7,159 | def load_method(path,method,class_name = None,instance_creator = None):
module = load_module(path)
if class_name :
class_type = getattr(module, class_name)
if instance_creator:
ic_rest = instance_creator
nxt = module
while ( in... | Returns an instance of the method specified.
Args :
path : The path to the module contianing the method or function.
method : The name of the function.
class_name : The name of the class if the funtion is a method.
instance_creator: The na... |
7,160 | def rollback(self):
if self.save_dir is None:
logger.error(
"CanRolling back uninstall of %sReplacing %s', path)
renames(tmp_path, path)
for pth in self.pth.values():
pth.rollback() | Rollback the changes previously made by remove(). |
7,161 | def filter_by_moys(self, moys):
_filt_values, _filt_datetimes = self._filter_by_moys_slow(moys)
collection = HourlyDiscontinuousCollection(
self.header.duplicate(), _filt_values, _filt_datetimes)
collection._validated_a_period = self._validated_a_period
return collec... | Filter the Data Collection based on a list of minutes of the year.
Args:
moys: A List of minutes of the year [0..8759 * 60]
Return:
A new Data Collection with filtered data |
7,162 | def _build_vocab(filename, vocab_dir, vocab_name):
vocab_path = os.path.join(vocab_dir, vocab_name)
if not tf.gfile.Exists(vocab_path):
with tf.gfile.GFile(filename, "r") as f:
data = f.read().split()
counter = collections.Counter(data)
count_pairs = sorted(counter.items(), key=lambda x: (-x[1]... | Reads a file to build a vocabulary.
Args:
filename: file to read list of words from.
vocab_dir: directory where to save the vocabulary.
vocab_name: vocab file name.
Returns:
text encoder. |
7,163 | def load(self, *objs, consistent=False):
get_table_name = self._compute_table_name
objs = set(objs)
validate_not_abstract(*objs)
table_index, object_index, request = {}, {}, {}
for obj in objs:
table_name = get_table_name(obj.__class__)
key = du... | Populate objects from DynamoDB.
:param objs: objects to delete.
:param bool consistent: Use `strongly consistent reads`__ if True. Default is False.
:raises bloop.exceptions.MissingKey: if any object doesn't provide a value for a key column.
:raises bloop.exceptions.MissingObjects: if ... |
7,164 | def on_copy_local(self, pair):
status = pair.remote_classification
self._log_action("copy", status, ">", pair.local) | Called when the local resource should be copied to remote. |
7,165 | def _TypecheckDecorator(subject=None, **kwargs):
if subject is None:
return _TypecheckDecoratorFactory(kwargs)
elif inspect.isfunction(subject) or inspect.ismethod(subject):
return _TypecheckFunction(subject, {}, 2, None)
else:
raise TypeError() | Dispatches type checks based on what the subject is.
Functions or methods are annotated directly. If this method is called
with keyword arguments only, return a decorator. |
7,166 | def polygonVertices(x, y, radius, sides, rotationDegrees=0, stretchHorizontal=1.0, stretchVertical=1.0):
if sides % 2 == 1:
angleOfStartPointDegrees = 90 + rotationDegrees
else:
angleOfStartPointDegrees = 90 + rotationDegrees - (180 / sides)
for sideNum in range(sides):
... | Returns a generator that produces the (x, y) points of the vertices of a regular polygon.
`x` and `y` mark the center of the polygon, `radius` indicates the size,
`sides` specifies what kind of polygon it is.
Odd-sided polygons have a pointed corner at the top and flat horizontal
side at the bottom. Th... |
7,167 | def transitivity_wu(W):
triangles to triplets
K = np.sum(np.logical_not(W == 0), axis=1)
ws = cuberoot(W)
cyc3 = np.diag(np.dot(ws, np.dot(ws, ws)))
return np.sum(cyc3, axis=0) / np.sum(K * (K - 1), axis=0) | Transitivity is the ratio of 'triangles to triplets' in the network.
(A classical version of the clustering coefficient).
Parameters
----------
W : NxN np.ndarray
weighted undirected connection matrix
Returns
-------
T : int
transitivity scalar |
7,168 | def require_remote_ref_path(func):
def wrapper(self, *args):
if not self.is_remote():
raise ValueError("ref path does not point to a remote reference: %s" % self.path)
return func(self, *args)
wrapper.__name__ = func.__name__
return wrapper | A decorator raising a TypeError if we are not a valid remote, based on the path |
7,169 | def build_parser():
parser = argparse.ArgumentParser(
description=
)
parser.add_argument(
, ,
help=,
dest=,
default=None
)
parser.add_argument(
, ,
help=,
dest=,
default=os.getcwd()
)
parser.add_argument(
... | _build_parser_
Set up CLI parser options, parse the
CLI options an return the parsed results |
7,170 | def local_replace(self, dt, use_dst=True, _recurse=False, **kwds):
local_time = dt + self.standard_offset
if use_dst:
dst_offset = self.dst(local_time)
if dst_offset:
local_time += dst_offset
adjusted_time = local_time.replace(**kwds)
... | Return pywws timestamp (utc, no tzinfo) for the most recent
local time before the pywws timestamp dt, with datetime replace
applied. |
7,171 | def read(file, system):
try:
fid = open(file, )
raw_file = fid.readlines()
except IOError:
print()
return
ret_dict = dict()
ret_dict[] = file.split()[0].lower() +
key, val = None, None
for idx, line in enumerate(raw_file):
line = line.strip()
... | Parse an ANDES card file into internal variables |
7,172 | def call(command, silent=False):
try:
if silent:
with open(os.devnull, ) as FNULL:
return subprocess.check_call(command_to_array(command), stdout=FNULL)
else:
return check_call(command_to_array(command))
except CalledProcessError as e:
... | Runs a bash command safely, with shell=false, catches any non-zero
return codes. Raises slightly modified CalledProcessError exceptions
on failures.
Note: command is a string and cannot include pipes. |
7,173 | def find_mecab_dictionary(names):
suggested_pkg = names[0]
paths = [
os.path.expanduser(),
,
,
,
,
,
]
full_paths = [os.path.join(path, name) for path in paths for name in names]
checked_paths = [path for path in full_paths if len(path) <= MAX_PAT... | Find a MeCab dictionary with a given name. The dictionary has to be
installed separately -- see wordfreq's README for instructions. |
7,174 | def plot_shade_mask(ax, ind, mask, facecolor=, alpha=0.5):
ymin, ymax = ax.get_ylim()
ax.fill_between(ind, ymin, ymax, where=mask,
facecolor=facecolor, alpha=alpha)
return ax | Shade across x values where boolean mask is `True`
Args
----
ax: pyplot.ax
Axes object to plot with a shaded region
ind: ndarray
The indices to use for the x-axis values of the data
mask: ndarray
Boolean mask array to determine which regions should be shaded
facecolor: m... |
7,175 | def _is_accepted(self, element_tag):
element_tag = element_tag.lower()
if self._ignored_tags is not None \
and element_tag in self._ignored_tags:
return False
if self._followed_tags is not None:
return element_tag in self._followed_tags
else:... | Return if the link is accepted by the filters. |
7,176 | def in_builddir(sub=):
from functools import wraps
def wrap_in_builddir(func):
@wraps(func)
def wrap_in_builddir_func(self, *args, **kwargs):
p = local.path(self.builddir) / sub
if not p.exists():
LOG.error("%s does not exist."... | Decorate a project phase with a local working directory change.
Args:
sub: An optional subdirectory to change into. |
7,177 | def system(self) -> :
self.chat_name = "System"
self.chat_alias = None
self.chat_uid = EFBChat.SYSTEM_ID
self.chat_type = ChatType.System
return self | Set the chat as a system chat.
Only set for channel-level and group-level system chats.
Returns:
EFBChat: This object. |
7,178 | def _fake_openreferenceinstances(self, namespace, **params):
self._validate_namespace(namespace)
self._validate_open_params(**params)
params[] = params[]
del params[]
result = self._fake_references(namespace, **params)
objects = [] if result is None else [x[2] ... | Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.OpenReferenceInstances`
with data from the instance repository. |
7,179 | def pre_check(self, data):
sentences = len(re.findall(, data)) or 1
chars = len(data) - len(re.findall(, data))
num_words = len(re.findall(, data))
data = re.split(, data)
return data, sentences, chars, num_words | Count chars, words and sentences in the text. |
7,180 | def get(self, cycle_list, dataitem=None, isotope=None, sparse=1):
t1=time.time()
isotopes_of_interest = []
nested_list = False
if isinstance(cycle_list, basestring):
cycle_list = [cycle_list]
else:
try:
if len(cycle_lis... | Get Data from HDF5 files.
There are three ways to call this function
1. get(dataitem)
Fetches the datatiem for all cycles. If dataitem is a header
attribute or list of attributes then the data is retured.
If detaitem an individulal or list of column attributes,
... |
7,181 | def __recognize_scalar(self, node: yaml.Node,
expected_type: Type) -> RecResult:
logger.debug()
if (isinstance(node, yaml.ScalarNode)
and node.tag == scalar_type_to_tag[expected_type]):
return [expected_type],
message = .format(
... | Recognize a node that we expect to be a scalar.
Args:
node: The node to recognize.
expected_type: The type it is expected to be.
Returns:
A list of recognized types and an error message |
7,182 | def add_arguments(cls, parser, sys_arg_list=None):
parser.add_argument(,
dest=,
required=False, default=2, type=float,
help="TCP health-test interval in seconds, "
"default 2 "
... | Arguments for the TCP health monitor plugin. |
7,183 | def generate(self, information, timeout=-1):
return self._client.create(information, timeout=timeout) | Generates a self signed certificate or an internal CA signed certificate for RabbitMQ clients.
Args:
information (dict): Information to generate the certificate for RabbitMQ clients.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not a... |
7,184 | def pull_guest_properties(self):
(names, values, timestamps, flags) = self._call("pullGuestProperties")
return (names, values, timestamps, flags) | Get the list of the guest properties matching a set of patterns along
with their values, timestamps and flags and give responsibility for
managing properties to the console.
out names of type str
The names of the properties returned.
out values of type str
The v... |
7,185 | def compile_mof_string(self, mof_str, namespace=None, search_paths=None,
verbose=None):
namespace = namespace or self.default_namespace
self._validate_namespace(namespace)
mofcomp = MOFCompiler(_MockMOFWBEMConnection(self),
... | Compile the MOF definitions in the specified string and add the
resulting CIM objects to the specified CIM namespace of the mock
repository.
If the namespace does not exist, :exc:`~pywbem.CIMError` with status
CIM_ERR_INVALID_NAMESPACE is raised.
This method supports all MOF pr... |
7,186 | def setup_database(config_data):
with chdir(config_data.project_directory):
env = deepcopy(dict(os.environ))
env[str()] = str(.format(config_data.project_name))
env[str()] = str(os.pathsep.join(map(shlex_quote, sys.path)))
commands = []
commands.append(
[sys... | Run the migrate command to create the database schema
:param config_data: configuration data |
7,187 | def filter_update(self, id, phrase = None, context = None, irreversible = None, whole_word = None, expires_in = None):
id = self.__unpack_id(id)
params = self.__generate_params(locals(), [])
url = .format(str(id))
return self.__api_request(, url, params) | Updates the filter with the given `id`. Parameters are the same
as in `filter_create()`.
Returns the `filter dict`_ of the updated filter. |
7,188 | def requires_user(fn):
@functools.wraps(fn)
def wrap(*args, **kwargs):
subject = Yosai.get_current_subject()
if subject.identifiers is None:
msg = ("Attempting to perform a user-only operation. The "
"current Subject is NOT a use... | Requires that the calling Subject be *either* authenticated *or* remembered
via RememberMe services before allowing access.
This method essentially ensures that subject.identifiers IS NOT None
:raises UnauthenticatedException: indicating that the decorated method is
... |
7,189 | def find_dups(file_dict):
found_hashes = {}
for f in file_dict:
if file_dict[f][] not in found_hashes:
found_hashes[file_dict[f][]] = []
found_hashes[file_dict[f][]].append(f)
final_hashes = dict(found_hashes)
for h in found_hashes:
if len(found_hashes[h])<2:
... | takes output from :meth:`scan_dir` and returns list of duplicate files |
7,190 | def refresh(self):
if self.exists:
self.delete()
self.populate()
self.open() | Refresh the cache by deleting the old one and creating a new one. |
7,191 | def prepare_dispatch(self):
if self.new_to_dispatch:
raise DispatcherError("A configuration is already prepared!")
self.new_to_dispatch = True
self.first_dispatch_done = False
for daemon_link in self.all_daemons_links:
daemon_... | Prepare dispatch, so prepare for each daemon (schedulers, brokers, receivers, reactionners,
pollers)
This function will only prepare something if self.new_to_dispatch is False
It will reset the first_dispatch_done flag
A DispatcherError exception is raised if a configuration is already... |
7,192 | def _commit_handler(self, cmd):
current_prompt = self.device.find_prompt().strip()
terminating_char = current_prompt[-1]
pattern1 = r"[>
pattern2 = r".*all username.*confirm"
patterns = r"(?:{}|{})".format(pattern1, pattern2)
output = self.devic... | Special handler for hostname change on commit operation. Also handles username removal
which prompts for confirmation (username removal prompts for each user...) |
7,193 | def _fix_permissions(self):
state = yield from self._get_container_state()
if state == "stopped" or state == "exited":
yield from self.manager.query("POST", "containers/{}/start".format(self._cid))
for volume in self._volumes:
log.debug("Docker con... | Because docker run as root we need to fix permission and ownership to allow user to interact
with it from their filesystem and do operation like file delete |
7,194 | def pad_to(unpadded, target_len):
under = target_len - len(unpadded)
if under <= 0:
return unpadded
return unpadded + ( * under) | Pad a string to the target length in characters, or return the original
string if it's longer than the target length. |
7,195 | def single_discriminator(x, filters=128, kernel_size=8,
strides=4, pure_mean=False):
with tf.variable_scope("discriminator"):
net = layers().Conv2D(
filters, kernel_size, strides=strides, padding="SAME", name="conv1")(x)
if pure_mean:
net = tf.reduce_mean(net, [1, 2])... | A simple single-layer convolutional discriminator. |
7,196 | def _histogram_data(iterator):
histogram_started = False
header_passed = False
for l in iterator:
if in l:
histogram_started = True
elif histogram_started:
if header_passed:
values = l.rstrip().split("\t")
problem_type, name = val... | Yields only the row contents that contain the histogram entries |
7,197 | def _compute_nfps_uniform(cum_counts, sizes):
nfps = np.zeros((len(sizes), len(sizes)))
for l in range(len(sizes)):
for u in range(l, len(sizes)):
nfps[l, u] = _compute_nfp_uniform(l, u, cum_counts, sizes)
return nfps | Computes the matrix of expected false positives for all possible
sub-intervals of the complete domain of set sizes, assuming uniform
distribution of set_sizes within each sub-intervals.
Args:
cum_counts: the complete cummulative distribution of set sizes.
sizes: the complete domain of set s... |
7,198 | def discovery_print(pkt):
if pkt.src in mac_id_list:
return
mac_id_list.append(pkt.src)
text = pkt_text(pkt)
click.secho(text, fg=) if in text else click.echo(text) | Scandevice callback. Register src mac to avoid src repetition.
Print device on screen.
:param scapy.packet.Packet pkt: Scapy Packet
:return: None |
7,199 | def deallocate_ip(self, hostipaddress):
delete_host_from_segment(hostipaddress, self.netaddr, self.auth, self.url) | Object method takes in input of hostip address,removes them from the parent ip scope.
:param hostid: str of the hostid of the target host ip record
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.