Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
351,300 | def _minion_event(self, load):
if not in load:
return False
if not in load and ( not in load or not in load):
return False
if in load:
for event in load[]:
if in event:
event_data = event[]
else... | Receive an event from the minion and fire it on the master event
interface |
351,301 | def _countEXT(self,extname="SCI"):
count=0
if (self._image[].header["EXTEND"]):
for i,hdu in enumerate(self._image):
if i > 0:
hduExtname = False
if in hdu.header:
self._image[i].extnum=i
... | Count the number of extensions in the file with the given name
(``EXTNAME``). |
351,302 | def readFile(
self,
fileName,
buffer,
numberOfBytesToRead,
numberOfBytesRead,
offset,
dokanFileInfo,
):
try:
ret = self.operations(, fileName, numberOfBytesToRead, offset)
data = ctypes.create_string_buffer(
... | Read a file.
:param fileName: name of file to read
:type fileName: ctypes.c_wchar_p
:param buffer: buffer for content read
:type buffer: ctypes.c_void_p
:param numberOfBytesToRead: number of bytes to read
:type numberOfBytesToRead: ctypes.c_ulong
:param numberOfB... |
351,303 | def perform_permissions_check(self, user, obj, perms):
return self.request.forum_permission_handler.can_delete_post(obj, user) | Performs the permission check. |
351,304 | def get_group(path, follow_symlinks=True):
*
return stats(os.path.expanduser(path), follow_symlinks=follow_symlinks).get(, False) | Return the group that owns a given file
path
file or directory of which to get the group
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_group /etc/passwd
.. versionchanged:: 0.16.4
``follow_symlinks``... |
351,305 | def do_help(self, command):
if command:
doc = getattr(self, + command).__doc__
print(cyan(doc.replace( * 8, )))
else:
print(magenta())
print(magenta())
names = self.get_names()
names.sort()
for name in names:
... | Display this help message. |
351,306 | def get_partition_id(self, key):
data = self._client.serialization_service.to_data(key)
count = self.get_partition_count()
if count <= 0:
return 0
return hash_to_index(data.get_partition_hash(), count) | Returns the partition id for a Data key.
:param key: (object), the data key.
:return: (int), the partition id. |
351,307 | def message_stanza_handler(stanza_type = None, payload_class = None,
payload_key = None, usage_restriction = "post-auth"):
if stanza_type is None:
stanza_type = "normal"
return _stanza_handler("message", stanza_type, payload_class, payload_key,
... | Method decorator generator for decorating <message/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
- `payload_class`: payload class expected
- `stanza_type`: expected value of the 'type' attribute of the stanza.
`None` means all types except 'error'
-... |
351,308 | def log_request_success(self, method, full_url, path, body, status_code, response, duration):
if body and not isinstance(body, dict):
body = body.decode()
logger.info(
, method, full_url,
status_code, duration
)
logger.debug(, body)
... | Log a successful API call. |
351,309 | def HStruct_unpack(structT, data, getDataFn=None, dataWidth=None):
if getDataFn is None:
assert dataWidth is not None
def _getDataFn(x):
return toHVal(x)._auto_cast(Bits(dataWidth))
getDataFn = _getDataFn
val = structT.fromPy(None)
fData = iter(data)
ac... | opposite of packAxiSFrame |
351,310 | def run(query, container=Null):
if container == None:
container = wrap(query)["from"]
query_op = QueryOp.wrap(query, container=container, namespace=container.schema)
else:
query_op = QueryOp.wrap(query, container, container.namespace)
if container == None:
from jx_pytho... | THIS FUNCTION IS SIMPLY SWITCHING BASED ON THE query["from"] CONTAINER,
BUT IT IS ALSO PROCESSING A list CONTAINER; SEPARATE TO A ListContainer |
351,311 | def to_coord_frame(self, frame, galactocentric_frame=None, **kwargs):
if self.ndim != 3:
raise ValueError("Can only change representation for "
"ndim=3 instances.")
if galactocentric_frame is None:
galactocentric_frame = coord.Galactocentri... | Transform the orbit from Galactocentric, cartesian coordinates to
Heliocentric coordinates in the specified Astropy coordinate frame.
Parameters
----------
frame : :class:`~astropy.coordinates.BaseCoordinateFrame`
The class or frame instance specifying the desired output fra... |
351,312 | def _prepare_retry(self, state, failure, original_list):
failed_recipient = failure.value.args[0]
new_list = copy.deepcopy(original_list)
if failed_recipient is not None:
if failed_recipient in new_list:
new_list.remove(failed_recipient)
else:
... | Here we prepare to ask another brother to resolve our problem.
The failure here is always ProtocolFailed. If contract finished
without getting a bid (resolver is not there) we are removing the guy
from our local list. If we just run into the timeout, we will retry
in the same setup. |
351,313 | def remove_file(master_ip, filename, spark_on_toil):
master_ip = master_ip.actual
ssh_call = [, , , master_ip]
if spark_on_toil:
output = check_output(ssh_call + [, ])
container_id = next(line.split()[0] for line in output.splitlines() if in line)
ssh_call += [, , container_i... | Remove the given file from hdfs with master at the given IP address
:type masterIP: MasterAddress |
351,314 | def create_appointment_group(self, appointment_group_title, appointment_group_context_codes, appointment_group_description=None, appointment_group_location_address=None, appointment_group_location_name=None, appointment_group_max_appointments_per_participant=None, appointment_group_min_appointments_per_participant=None... | Create an appointment group.
Create and return a new appointment group. If new_appointments are
specified, the response will return a new_appointments array (same format
as appointments array, see "List appointment groups" action) |
351,315 | def export(self, storage_client, overwrite=True):
title = % self.__class__.__name__
method_list = [ , , , , , , , ]
for method in method_list:
if not getattr(storage_client, method, None):
from labpack.parsing.gramma... | a method to export all the records in collection to another platform
:param storage_client: class object with storage client methods
:return: string with exit message |
351,316 | def keep_params(self, base_key, *params):
self.params[base_key + + .join(params)] = self.keep_params_s(
self.params[base_key], params) | Method to keep only specific parameters from a parameter documentation.
This method extracts the given `param` from the `base_key` item in the
:attr:`params` dictionary and creates a new item with the original
documentation with only the description of the param. This method works
for `... |
351,317 | def dict_contents(self, use_dict=None, as_class=dict):
if _debug: Choice._debug("dict_contents use_dict=%r as_class=%r", use_dict, as_class)
if use_dict is None:
use_dict = as_class()
for element in self.choiceElements:
value = getattr(self, e... | Return the contents of an object as a dict. |
351,318 | def create_cfg(self, cfg_file, defaults=None, mode=):
t exits
also sets up the first_run attribute.
also sets correct windows permissions
you can add custom stuff to the config by doing
app.cfg[] =
remember to call cfg.save()
jsonyamlcfg file found :... | set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
also sets correct windows permissions
you can add custom stuff to the c... |
351,319 | def main():
if OPTIONS.get():
disable_all_colors()
elif OPTIONS.get():
enable_all_colors()
if is_enabled() and os.name == :
Windows.enable(auto_colors=True, reset_atexit=True)
elif OPTIONS.get():
set_light_background()
elif OPTIONS.get():
set_dark_backgr... | Main function called upon script execution. |
351,320 | def find_links_or_emphs(text, root_node):
delimiters_re = re.compile(r)
i = 0
delimiters = []
escape = False
matches = []
code_pattern = re.compile(r)
while i < len(text):
if escape:
escape = False
i += 1
elif text[i] == :
escape = Tr... | Fink links/images or emphasis from text.
:param text: the original text.
:param root_node: a reference to the root node of the AST.
:returns: an iterable of match object. |
351,321 | def MessageToRepr(msg, multiline=False, **kwargs):
indent = kwargs.get(, 0)
def IndentKwargs(kwargs):
kwargs = dict(kwargs)
kwargs[] = kwargs.get(, 0) + 4
return kwargs
if isinstance(msg, list):
s =
for item in msg:
if multiline:
... | Return a repr-style string for a protorpc message.
protorpc.Message.__repr__ does not return anything that could be considered
python code. Adding this function lets us print a protorpc message in such
a way that it could be pasted into code later, and used to compare against
other things.
Args:
... |
351,322 | def shapeRecords(self):
return ShapeRecords([ShapeRecord(shape=rec[0], record=rec[1]) \
for rec in zip(self.shapes(), self.records())]) | Returns a list of combination geometry/attribute records for
all records in a shapefile. |
351,323 | def spread(symbol, token=, version=):
_raiseIfNotStr(symbol)
return _getJson( + symbol + , token, version) | This returns an array of effective spread, eligible volume, and price improvement of a stock, by market.
Unlike volume-by-venue, this will only return a venue if effective spread is not ‘N/A’. Values are sorted in descending order by effectiveSpread.
Lower effectiveSpread and higher priceImprovement values are ... |
351,324 | def _new_conn(self):
extra_kw = {}
if self.source_address:
extra_kw[] = self.source_address
if self.socket_options:
extra_kw[] = self.socket_options
try:
conn = connection.create_connection(
(self._dns_host, self.port), self.... | Establish a socket connection and set nodelay settings on it.
:return: New socket connection. |
351,325 | def _ParseLine(self, parser_mediator, structure):
month, day_of_month, year, hours, minutes, seconds, milliseconds = (
structure.date_time)
year += 2000
time_elements_tuple = (
year, month, day_of_month, hours, minutes, seconds, milliseconds)
try:
date_time = dfdatetime... | Parses a logline and store appropriate attributes.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure of tokens derived from
a line of a text file. |
351,326 | def streams(self, stream_types=None, sorting_excludes=None):
try:
ostreams = self._get_streams()
if isinstance(ostreams, dict):
ostreams = ostreams.items()
if ostreams:
ostreams = list(ostreams)
except NoStreamsE... | Attempts to extract available streams.
Returns a :class:`dict` containing the streams, where the key is
the name of the stream, most commonly the quality and the value
is a :class:`Stream` object.
The result can contain the synonyms **best** and **worst** which
points to the st... |
351,327 | def _block_device_mapping_handler(self):
mapping_counter = 1
mapping_device_name_fmt =
mapping_del_on_term_fmt =
while True:
mapping_device_name = mapping_device_name_fmt % mapping_counter
if mapping_device_name not in self.querystring.keys():
... | Handles requests which are generated by code similar to:
instance.modify_attribute(
BlockDeviceMappings=[{
'DeviceName': '/dev/sda1',
'Ebs': {'DeleteOnTermination': True}
}]
)
The querystring contains information s... |
351,328 | def get_field_list(fields, schema):
if not schema:
return []
return all_fields | Convert a field list spec into a real list of field names.
For tables, we return only the top-level non-RECORD fields as Google charts
can't handle nested data. |
351,329 | async def main(wallet_name: str) -> None:
logging.basicConfig(level=logging.WARN, format=)
logging.getLogger().setLevel(logging.ERROR)
path_start = join(RevRegBuilder.dir_tails_sentinel(wallet_name), )
with open(path_start, ) as fh_start:
start_data = json.loads(fh_start.read())
remo... | Main line for revocation registry builder operating in external process on behalf of issuer agent.
:param wallet_name: wallet name - must match that of issuer with existing wallet |
351,330 | def _cli_helper_dedicated_host(env, result, table):
dedicated_host_id = utils.lookup(result, , )
if dedicated_host_id:
table.add_row([, dedicated_host_id])
try:
dedicated_host = env.client.call(, ,
id=dedicated_host_id)
... | Get details on dedicated host for a virtual server. |
351,331 | async def get_input_sender(self):
if self.input_sender is None and self._sender_id:
await self._refetch_sender()
return self._input_sender | Returns `input_sender`, but will make an API call to find the
input sender unless it's already cached. |
351,332 | def displayhtml(site_key,
language=,
theme=,
fallback=False,
d_type=,
size=):
return % {
: language,
: site_key,
: theme,
: d_type,
: size,
: fallback,
} | Gets the HTML to display for reCAPTCHA
site_key -- The site key
language -- The language code for the widget.
theme -- The color theme of the widget. `light` or `dark`
fallback -- Old version recaptcha.
d_type -- The type of CAPTCHA to serve. `image` or `audio`
size -- The size of the dispalyed... |
351,333 | def p_switch_stmt(p):
def backpatch(expr, stmt):
if isinstance(stmt, node.if_stmt):
stmt.cond_expr.args[1] = expr
backpatch(expr, stmt.else_stmt)
backpatch(p[2], p[4])
p[0] = p[4] | switch_stmt : SWITCH expr semi_opt case_list END_STMT |
351,334 | def rename_file_group_to_serial_nums(file_lst):
file_lst.sort()
c = 1
for f in file_lst:
dirname = get_abspath(f.dirname())
fdest = f.joinpath(dirname, "{0:04d}".format(c) +
OUTPUT_DICOM_EXTENSION)
log.info(.format(f, fdest))
f.rename(fdest)
... | Will rename all files in file_lst to a padded serial
number plus its extension
:param file_lst: list of path.py paths |
351,335 | def rollapply(self, func, window=20, **kwargs):
return self.apply(func, window=window, **kwargs) | A generic :ref:`rolling function <rolling-function>`
for function *func*.
Same construct as :meth:`dynts.TimeSeries.apply` but with default
``window`` set to ``20``. |
351,336 | def sub_dfs_by_num(df, num):
size = len(df) / float(num)
for i in range(num):
yield df.iloc[int(round(size * i)): int(round(size * (i + 1)))] | Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
-------
generator
A ge... |
351,337 | def upgrade(name=None,
pkgs=None,
**kwargs):
<package>old<old-version>new<new-version>**
old = list_pkgs()
cmd = [, , ]
if kwargs.get(, False):
cmd.append()
if pkgs:
cmd.extend(pkgs)
elif name:
cmd.append(name)
result = __salt__[]... | Run a full package upgrade (``pkg_add -u``), or upgrade a specific package
if ``name`` or ``pkgs`` is provided.
``name`` is ignored when ``pkgs`` is specified.
Returns a dictionary containing the changes:
.. versionadded:: 2019.2.0
.. code-block:: python
{'<package>': {'old': '<old-versi... |
351,338 | def _determine_mjds_to_download(
self,
days):
self.log.info()
sqlQuery = u % locals()
mjds = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.atlasMoversDBConn,
quiet=False
)
if len... | *determine which ATLAS nights require to be cached locally*
**Key Arguments:**
- ``days`` -- the number of days data to cache locally
**Return:**
- ``mjds`` -- a list of the MJDs to be downloaded from the ATLAS datastore in hawaii |
351,339 | def _prepare_bam(bam_file, bed_file, config):
if not bam_file or not bed_file:
return bam_file
out_file = utils.append_stem(bam_file, )
bedtools = config_utils.get_program("bedtools", config)
if not utils.file_exists(out_file):
with file_transaction(out_file) as tx_out:
... | Remove regions from bed files |
351,340 | def metadata_add_endpoints(self):
metadata = load_mpe_service_metadata(self.args.metadata_file)
group_name = metadata.get_group_name_nonetrick(self.args.group_name)
for endpoint in self.args.endpoints:
metadata.add_endpoint(group_name, endpoint)
metadata.save_pretty(... | Metadata: add endpoint to the group |
351,341 | def get(self, url, params):
url = self.host + url
if params:
url = url + "?" + urllib.parse.urlencode(params)
try:
resp = requests.get(url, allow_redirects=False, headers=self.headers, auth=self.oauth)
except TooManyRedirects as e:
resp = e.r... | Issues a GET request against the API, properly formatting the params
:param url: a string, the url you are requesting
:param params: a dict, the key-value of all the paramaters needed
in the request
:returns: a dict parsed of the JSON response |
351,342 | def make_dynamic_prompt(self, prompt):
patterns = ["[\r\n]" + pattern_manager.pattern(
self.platform, pattern_name, compiled=False) for pattern_name in self.target_prompt_components]
patterns_re = "|".join(patterns).format(hostname=re.escape(prompt))
try:
promp... | Extend prompt with flexible mode handling regexp. |
351,343 | def calling(data):
chip_bam = data.get("work_bam")
input_bam = data.get("work_bam_input", None)
caller_fn = get_callers()[data["peak_fn"]]
name = dd.get_sample_name(data)
out_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), data["peak_fn"], name))
out_files = caller_fn(name, chi... | Main function to parallelize peak calling. |
351,344 | def set_encoding (parsobj, attrs):
charset = attrs.get_true(, u)
if charset:
charset = charset.encode(, ).lower()
elif attrs.get_true(, u).lower() == u"content-type":
charset = attrs.get_true(, u)
charset = charset.encode(, ).lower()
charset = ... | Set document encoding for the HTML parser according to the <meta>
tag attribute information.
@param attrs: attributes of a <meta> HTML tag
@type attrs: dict
@return: None |
351,345 | def add(self, order, cells, no_validation=False):
self._normalized = False
order = self._validate_order(order)
if no_validation:
self._orders[order].update(cells)
else:
cell_set = set()
for cell in cells:
... | Add cells at a given order to the MOC.
The cells are inserted into the MOC at the specified order. This
leaves the MOC in an un-normalized state. The cells are given
as a collection of integers (or types which can be converted
to integers).
>>> m = MOC()
>>> m.add(4, ... |
351,346 | def infer_x(self, y_desired, **kwargs):
sigma = kwargs.get(, self.sigma)
k = kwargs.get(, self.k)
xq = self._guess_x(y_desired, k = k, sigma = sigma, **kwargs)[0]
dists, index = self.fmodel.dataset.nn_x(xq, k = k)
w = self.fmodel._we... | Provide an inversion of yq in the input space
@param yq an array of float of length dim_y |
351,347 | def _draw_trees(trees, nrow=1, ncol=1, rmargin=.3, iopts=None, outdir=".",
shfile=None, **kwargs):
from jcvi.graphics.tree import draw_tree
if shfile:
SHs = DictFile(shfile, delimiter="\t")
ntrees = len(trees)
n = nrow * ncol
for x in xrange(int(ceil(float(ntrees)/n))):
fi... | Draw one or multiple trees on one plot. |
351,348 | def impact_table_extractor(impact_report, component_metadata):
context = {}
extra_args = component_metadata.extra_args
components_list = resolve_from_dictionary(
extra_args, )
if not impact_report.impact_function.debug_mode:
components_list.pop(, None)
context[]... | Extracting impact summary of the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactReport
:param component_metadata: the component metadata. Used to obtain
information ... |
351,349 | def getStore(self) :
store = self._store.getStore()
for priv in self.privates :
v = getattr(self, priv)
if v :
store[priv] = v
return store | return the store in a dict format |
351,350 | def getData(self):
haveOnCurve = False
for point in self._points:
if point.segmentType is not None:
haveOnCurve = True
break
if haveOnCurve:
_prepPointsForSegments(self._points)
firstPoin... | Return a list of normalized InputPoint objects
for the contour drawn with this pen. |
351,351 | def _extractCreations(self, dataSets):
for dataSet in dataSets:
modelObject = self._objectFromID(dataSet[self._IDENTIFIER_KEY])
if modelObject is self._NO_OBJECT_MARKER:
dataCopy = dataSet.copy()
identifier = dataCopy.pop(self._IDENTIFIER_KEY)
... | Find the elements of C{dataSets} which represent the creation of new
objects.
@param dataSets: C{list} of C{dict} mapping C{unicode} form submission
keys to form submission values.
@return: iterator of C{tuple}s with the first element giving the opaque
identifier of an ... |
351,352 | def crossings_nonzero_pos2neg(data):
import numpy as np
if isinstance(data, np.ndarray):
pass
elif isinstance(data, list):
data = np.asarray(data)
else:
raise IOError()
pos = data > 0
crossings = (pos[:-1] & ~pos[1:]).nonzero()[0]
return crossings | Find `indices of zero crossings from positive to negative values <http://stackoverflow.com/questions/3843017/efficiently-detect-sign-changes-in-python>`_.
:param data: numpy array of floats
:type data: numpy array of floats
:return crossings: crossing indices to data
:rtype crossings: n... |
351,353 | def set_interval(self, interval):
if type(interval) != float or type(interval) != int:
raise InvalidInput("Interval value must be of float or int")
self._config[] | Set the polling interval for the process thread.
:param interval: How often to poll the Hottop
:type interval: int or float
:returns: None
:raises: InvalidInput |
351,354 | def drop(self, table):
blueprint = self._create_blueprint(table)
blueprint.drop()
self._build(blueprint) | Drop a table from the schema.
:param table: The table
:type table: str |
351,355 | def sim(self, src, tar):
r
if src == tar:
return 1.0
elif not src or not tar:
return 0.0
return len(self.lcsseq(src, tar)) / max(len(src), len(tar)) | r"""Return the longest common subsequence similarity of two strings.
Longest common subsequence similarity (:math:`sim_{LCSseq}`).
This employs the LCSseq function to derive a similarity metric:
:math:`sim_{LCSseq}(s,t) = \frac{|LCSseq(s,t)|}{max(|s|, |t|)}`
Parameters
-------... |
351,356 | def parityOf(int_type):
parity = 0
while (int_type):
parity = ~parity
int_type = int_type & (int_type - 1)
return(parity) | Calculates the parity of an integer, returning 0 if there are an even number of set bits, and -1 if there are an odd number. |
351,357 | def regex_parse_template(self, template, pattern):
groups = []
literals = []
replacements = _compile_replacement_helper(pattern, template)
count = 0
for part in replacements:
if isinstance(part, int):
literals.append(None)
gro... | Parse template for the regex module.
Do NOT edit the literal list returned by
_compile_replacement_helper as you will edit
the original cached value. Copy the values
instead. |
351,358 | def _message_queryset(self, include_read=False):
expire = timezone.now()
qs = PersistentMessage.objects.\
filter(user=self.get_user()).\
filter(Q(expires=None) | Q(expires__gt=expire))
if not include_read:
qs = qs.exclude(read=True)
return qs | Return a queryset of messages for the request user |
351,359 | def from_stream(cls, stream, offset):
ifd_parser = _IfdParser(stream, offset)
entries = dict((e.tag, e.value) for e in ifd_parser.iter_entries())
return cls(entries) | Return a new |_IfdEntries| instance parsed from *stream* starting at
*offset*. |
351,360 | def run(self, *args, **kw):
log.debug(.format(
self.__class__.__name__, args
))
if self.kind == OperatorTypes.ATTRIBUTE:
return self.match(self.ctx)
else:
return self.run_matcher(*args, **kw) | Runs the current operator with the subject arguments to test.
This method is implemented by matchers only. |
351,361 | def add_log_entry(self, process_name, timeperiod, msg):
tree = self.get_tree(process_name)
node = tree.get_node(process_name, timeperiod)
node.add_log_entry([datetime.utcnow().strftime(), msg]) | adds a non-persistent log entry to the tree node |
351,362 | def __replace_an(sentence):
if sentence is not None:
while sentence.find() != -1:
an_index = sentence.find()
if an_index > -1:
an_index += 4
if sentence[an_index] in :
sentence = sentence.replace(, str(), 1)
... | Lets find and replace all instances of #AN
This is a little different, as this depends on whether the next
word starts with a vowel or a consonant.
:param _sentence: |
351,363 | def loadavg(name, maximum=None, minimum=None):
ret = {: name,
: False,
: ,
: {},
: {}}
data = __salt__[]()
if name not in data:
ret[] = False
ret[] += .format(
name
)
return ret
if minimum and maximum an... | Return the current load average for the specified minion. Available values
for name are `1-min`, `5-min` and `15-min`. `minimum` and `maximum` values
should be passed in as strings. |
351,364 | def _add_unique_file(self, item):
if item not in self.config[]:
self.config[].append(item) | adds a file in self.config['files'] only if not present already |
351,365 | def devopsy(self, *args):
args = .join(self.message[].split()[1:])
if args:
base_main = {
: ,
:
}
main_items = list(base_main.items())
key, val = random.choice(main_items)
else:
base_alt = {
... | Return a gif based on search of several *reactions
Ported to Legobot from:
"https://github.com/ricardokirkner/err-devops-reactions"
... and extended.
Return a random gif if no query is specified or query not found
Example:
!devopsy somefoofulquery
... |
351,366 | def get_controller(self, path):
path_info = path.lstrip().split(, 2)
try:
return self._routes.get(path_info[0] + + path_info[1])
except (IndexError, KeyError):
return self._routes.get(path_info[0] or ) | Return controller that handle given path.
Args:
- path: requested path, like: /blog/post_view/15 |
351,367 | def onSync(self, event):
SETUP = self.statement()
if SETUP:
sql, data = SETUP(self.database())
if event.context.dryRun:
print sql % data
else:
self.execute(sql, data, writeAccess=True) | Initializes the database by defining any additional structures that are required during selection. |
351,368 | def relabel(self, mapping):
if not isinstance(mapping, dict):
raise pycmMatrixError(MAPPING_FORMAT_ERROR)
if self.classes != list(mapping.keys()):
raise pycmMatrixError(MAPPING_CLASS_NAME_ERROR)
for row in self.classes:
temp_dict = {}
temp... | Rename ConfusionMatrix classes.
:param mapping: mapping dictionary
:type mapping : dict
:return: None |
351,369 | def _join_seq(d, k, v):
if k not in d:
d[k] = list(v)
elif isinstance(d[k], list):
for item in v:
if item not in d[k]:
d[k].insert(0, item)
elif isinstance(d[k], string_types):
v.append(d[k])
d[k] = v | Add a sequence value to env dict |
351,370 | def interface_to_str(interface):
if isinstance(interface, ModuleType):
interface = interface.__name__
return re.sub(r"optlang.|.interface", "", interface) | Give a string representation for an optlang interface.
Parameters
----------
interface : string, ModuleType
Full name of the interface in optlang or cobra representation.
For instance 'optlang.glpk_interface' or 'optlang-glpk'.
Returns
-------
string
The name of the inte... |
351,371 | def getElementByName(self, beamline, name):
try:
assert beamline.upper() in self.kws_bl
except AssertionError:
print( % beamline)
return
try:
assert name.lower() in self.getFullBeamline(beamline, extend=True)
orderedLattice_l... | return element list by literal name in beamline
each element is tuple like (name, type, order)
:param beamline: beamline name
:param name: element literal name |
351,372 | def write(self, outfile, encoding):
u
cal = Calendar()
cal.add(, )
cal.add(, )
for ifield, efield in FEED_FIELD_MAP:
val = self.feed.get(ifield)
if val is not None:
cal.add(efield, val)
self.write_items(cal)
to_ical = get... | u"""
Writes the feed to the specified file in the
specified encoding. |
351,373 | def emit(msg_dict):
usersuserlukeactionloginuid
log.debug()
log.debug(msg_dict)
ret = {}
extracted = napalm_logs.utils.extract(_RGX, msg_dict[], _RGX_PARTS)
if not extracted:
return ret
uid_key_path = .format(extracted)
uid_value = int(extracted[])
log.debug(, uid_value, uid_... | Extracts the details from the syslog message
and returns an object having the following structure:
.. code-block:: python
{
u'users': {
u'user': {
u'luke': {
u'action': {
u'login': True
... |
351,374 | def _adjacency_to_edges(adjacency):
edges = set()
for u in adjacency:
for v in adjacency[u]:
try:
edge = (u, v) if u <= v else (v, u)
except TypeError:
if (v, u) in edges:
continue
edge = (u... | determine from an adjacency the list of edges
if (u, v) in edges, then (v, u) should not be |
351,375 | def reset_game(self):
self.ms_game.reset_game()
self.update_grid()
self.time = 0
self.timer.start(1000) | Reset game board. |
351,376 | def load_module_from_file(filepath, path=None, use_sys=True, extrapath=None):
modpath = modpath_from_file(filepath, extrapath)
return load_module_from_modpath(modpath, path, use_sys) | Load a Python module from it's path.
:type filepath: str
:param filepath: path to the python module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
... |
351,377 | def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None):
threads = get_thread_block_dimensions(params, block_size_names)
current_problem_size = get_problem_size(problem_size, params)
grid = get_grid_dimensions(current_problem_size, params, grid_div, block_size_names)
return ... | compute problem size, thread block and grid dimensions for this kernel |
351,378 | def validate_list_of_identical_dicts(self, list_of_dicts):
hashes = []
for _dict in list_of_dicts:
hashes.append(hash(frozenset(_dict.items())))
self.log.debug(.format(hashes))
if len(set(hashes)) == 1:
self.log.debug()
else:
return
... | Check that all dicts within a list are identical. |
351,379 | def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whit... | Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines ... |
351,380 | def notify_contact(mail, owner, graas_url, repos, first_repo=False):
footer =
twitter_txt = "Check Cauldron.io dashboard for %s at %s/dashboards/%s" % (owner, graas_url, owner)
twitter_url = "https://twitter.com/intent/tweet?text=" + quote_plus(twitter_txt)
twitter_url += "&via=bitergia"
if... | Send an email to the contact with the details to access
the Kibana dashboard |
351,381 | def stderr(msg, silent=False):
if not silent:
print(msg, file=sys.stderr) | write msg to stderr if not silent |
351,382 | def _run_external_commands(self):
commands = cherrypy.request.json
with self.app.lock:
self.app.sched.run_external_commands(commands[]) | Post external_commands to scheduler (from arbiter)
Wrapper to to app.sched.run_external_commands method
:return: None |
351,383 | def PhyDMSParser():
parser = ArgumentParserNoArgHelp(description=(
).format(phydmslib.__acknowledgments__,
phydmslib.__version__, phydmslib.__url__),
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(, type=ExistingFile,
... | Returns *argparse.ArgumentParser* for ``phydms`` script. |
351,384 | def _reset_attributes(self):
self.channels = {}
self.users = {}
self._receive_buffer = b
self._pending = {}
self._handler_top_level = False
self._ping_checker_handle = None
self.logger = logging.getLogger(__name__)
... | Reset attributes. |
351,385 | def read_frames(self, copy=True):
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_bytes = [2, 4][is_float]
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
points = np.zeros((self.point_used, 5), float)
... | Iterate over the data frames from our C3D file handle.
Parameters
----------
copy : bool
If False, the reader returns a reference to the same data buffers
for every frame. The default is True, which causes the reader to
return a unique data buffer for each fr... |
351,386 | def recent_post(self, author=None, daysback=0, flag=0):
if not author:
author = self.mainaccount
for num_of_retries in range(default.max_retry):
try:
self.blog = self.steem_instance().get_blog(author, 0, 30)
except Exception as e:
... | Returns the most recent post from the account
given. If the days back is greater than zero
then the most recent post is returned for that
day. For instance if daysback is set to 2
then it will be the most recent post from 2 days
ago (48 hours). |
351,387 | def _to_dict(self):
return {
:
getattr(self, "auto_watering"),
:
getattr(self, "droplet"),
:
getattr(self, "is_watering"),
:
getattr(self, "name"),
:
getattr(self,... | Method to build zone dict. |
351,388 | def lookup(self, *coordinate_arrays):
assert len(coordinate_arrays) == self.dimensions
index_arrays = [np.clip(np.searchsorted(self.bin_edges[i], coordinate_arrays[i]) - 1,
0,
len(self.bin_edges[i]) - 2)
... | Lookup values at specific points.
coordinate_arrays: numpy arrays of coordinates, one for each dimension
e.g. lookup(np.array([0, 2]), np.array([1, 3])) looks up (x=0, y=1) and (x=2, y3).
Clips if out of range!! TODO: option to throw exception instead.
TODO: Needs tests!!
TODO: ... |
351,389 | def indent_string(string, num_spaces=2):
indent = .ljust(num_spaces)
return indent + re.sub(, + indent, string) | Add indentation to a string.
Replaces all new lines in the string with a new line followed by the
specified number of spaces, and adds the specified number of spaces to the
start of the string. |
351,390 | def add_non_hs_service(self, info, address):
if self.protocol and self.protocol != PROTOCOL_DMAP:
return
name = info.properties[b].decode()
self._handle_service(
address, name, conf.DmapService(None, port=info.port)) | Add a new device without Home Sharing to discovered list. |
351,391 | def _embedding_tsne(matrix, dimensions=3, early_exaggeration=12.0,
method=, perplexity=30, learning_rate=200,
n_iter=1000):
tsne = sklearn.manifold.TSNE(n_components=dimensions,
metric="precomputed",
early... | Private method to perform tSNE embedding
:param matrix: treeCl Distance Matrix
:param dimensions: Number of dimensions in which to embed points
:return: treeCl CoordinateMatrix |
351,392 | def handle_report_metric_data(self, data):
value = extract_scalar_reward(data[])
bracket_id, i, _ = data[].split()
bracket_id = int(bracket_id)
if data[] == :
self.brackets[bracket_id].set_config_perf(int(i), data[], sys.maxsize, value)
... | Parameters
----------
data:
it is an object which has keys 'parameter_id', 'value', 'trial_job_id', 'type', 'sequence'.
Raises
------
ValueError
Data type not supported |
351,393 | def post_series_unpublish(self, id, **data):
return self.post("/series/{0}/unpublish/".format(id), data=data) | POST /series/:id/unpublish/
Unpublishes a repeating event series and all of its occurrences that are not already completed, canceled, or deleted. In
order for a free series to be unpublished, it must not have any pending or completed orders for any dates, even past
dates. In order for a paid ser... |
351,394 | def count_by_type(self):
pistack = defaultdict(int)
for contact in self.timeseries:
pkey = (contact.ligandring,contact.type, contact.resid,contact.resname,contact.segid)
pistack[pkey]+=1
dtype = [("ligand_ring_ids",list),("type","|U4"),("resid",int),... | Count how many times each individual pi-pi interaction occured throughout the simulation.
Returns numpy array. |
351,395 | def is_within_limits(self, limit, date, dates):
return any((self.second_diff(date, d) <= limit for d in dates)) | Returns True if the difference between date and any value in dates
is less than or equal to limit. |
351,396 | def proc_polyline(self, tokens):
pts = [(p["x"], p["y"]) for p in tokens["points"]]
component = Polyline(pen=self.pen, points=pts)
return component | Returns the components of a polyline. |
351,397 | def get(self, historics_id=None, maximum=None, page=None, with_estimate=None):
params = {: historics_id}
if maximum:
params[] = maximum
if page:
params[] = page
params[] = 1 if with_estimate else 0
return self.request.get(, params=params) | Get the historics query with the given ID, if no ID is provided then get a list of historics queries.
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: (optional) ID of the query to retrieve
:type historics_id: str
... |
351,398 | def render_impl(self, template, context, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, **kwargs):
renderer = self._make_renderer(at_paths, at_encoding, **kwargs)
ctxs = [] if context is None else [context]
if os.path.sep in template:
return r... | Render given template file and return the result.
:param template: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param at_paths: Template search paths
:param at_encoding: Template encoding
:param kwargs: Keyword arg... |
351,399 | def gaussian(self, x, p):
y = (1.0 / (p[1] * np.sqrt(2 * np.pi)) *
np.exp(-(x - p[0]) ** 2 / (2 * p[1] ** 2))) * p[2]
return y | Gaussian fitting function in 1D. Makes a sine function with
amplitude determined by maxv. See calc_fwhm().
p[0]==mean, p[1]==sdev, p[2]=maxv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.