text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def build_uri(self, path, query_params):
'''
Build the URI for the API call.
'''
url = 'https://api.trello.com/1' + self.clean_path(path)
url += '?' + urlencode(query_params)
return url | [
"def",
"build_uri",
"(",
"self",
",",
"path",
",",
"query_params",
")",
":",
"url",
"=",
"'https://api.trello.com/1'",
"+",
"self",
".",
"clean_path",
"(",
"path",
")",
"url",
"+=",
"'?'",
"+",
"urlencode",
"(",
"query_params",
")",
"return",
"url"
] | 28.375 | 0.008547 |
def serialize(self, sw):
'''Serialize the object.'''
detail = None
if self.detail is not None:
detail = Detail()
detail.any = self.detail
pyobj = FaultType(self.code, self.string, self.actor, detail)
sw.serialize(pyobj, typed=False) | [
"def",
"serialize",
"(",
"self",
",",
"sw",
")",
":",
"detail",
"=",
"None",
"if",
"self",
".",
"detail",
"is",
"not",
"None",
":",
"detail",
"=",
"Detail",
"(",
")",
"detail",
".",
"any",
"=",
"self",
".",
"detail",
"pyobj",
"=",
"FaultType",
"(",... | 32.222222 | 0.010067 |
def regions():
"""
Get all available regions for the SNS service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo` instances
"""
return [RegionInfo(name='us-east-1',
endpoint='sns.us-east-1.amazonaws.com',
connection_cls=SNSConnec... | [
"def",
"regions",
"(",
")",
":",
"return",
"[",
"RegionInfo",
"(",
"name",
"=",
"'us-east-1'",
",",
"endpoint",
"=",
"'sns.us-east-1.amazonaws.com'",
",",
"connection_cls",
"=",
"SNSConnection",
")",
",",
"RegionInfo",
"(",
"name",
"=",
"'eu-west-1'",
",",
"en... | 44.137931 | 0.000765 |
def list_(prefix='', ruby=None, runas=None, gem_bin=None):
'''
List locally installed gems.
:param prefix: string :
Only list gems when the name matches this prefix.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv ... | [
"def",
"list_",
"(",
"prefix",
"=",
"''",
",",
"ruby",
"=",
"None",
",",
"runas",
"=",
"None",
",",
"gem_bin",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'list'",
"]",
"if",
"prefix",
":",
"cmd",
".",
"append",
"(",
"prefix",
")",
"stdout",
"=",
... | 27.714286 | 0.000996 |
def xml(self, **kwargs):
"""
Returns an XML representation of this node (including descendants). This method automatically creates an
:class:`XmlWriter` instance internally to handle the writing.
:param **kwargs: Any named arguments are passed along to the :class:`XmlWriter` constructor... | [
"def",
"xml",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"bytes_io",
"(",
")",
"writer",
"=",
"XmlWriter",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"write",
"(",
"writer",
")",
"return",
"s",
".",
"getvalue",
"(",
")"... | 40 | 0.008889 |
def enrich(self, column):
""" This method adds a new column depending on the extension
of the file.
:param column: column where the file path is found
:type column: string
:return: returns the original dataframe with a new column named as
'filetype' that contai... | [
"def",
"enrich",
"(",
"self",
",",
"column",
")",
":",
"if",
"column",
"not",
"in",
"self",
".",
"data",
":",
"return",
"self",
".",
"data",
"# Insert a new column with default values",
"self",
".",
"data",
"[",
"\"filetype\"",
"]",
"=",
"'Other'",
"# Insert... | 35.375 | 0.019495 |
def weak_lru_cache(maxsize=100):
"""Weak least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
Arguments to the cached function must be hashable. Any that are weak-
referenceable will be stored by weak reference. Once... | [
"def",
"weak_lru_cache",
"(",
"maxsize",
"=",
"100",
")",
":",
"class",
"desc",
"(",
"lazyval",
")",
":",
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"owner",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"try",
":",
"retu... | 33.736842 | 0.000758 |
def FFD(s,B):
"""First Fit Decreasing heuristics for the Bin Packing Problem.
Parameters:
- s: list with item widths
- B: bin capacity
Returns a list of lists with bin compositions.
"""
remain = [B] # keep list of empty space per bin
sol = [[]] # a list ot items (... | [
"def",
"FFD",
"(",
"s",
",",
"B",
")",
":",
"remain",
"=",
"[",
"B",
"]",
"# keep list of empty space per bin",
"sol",
"=",
"[",
"[",
"]",
"]",
"# a list ot items (i.e., sizes) on each used bin",
"for",
"item",
"in",
"sorted",
"(",
"s",
",",
"reverse",
"=",
... | 34.421053 | 0.008929 |
def read(file, system, header=True):
"""Read a dm format file and elem_add to system"""
retval = True
fid = open(file, 'r')
sep = re.compile(r'\s*,\s*')
comment = re.compile(r'^#\s*')
equal = re.compile(r'\s*=\s*')
math = re.compile(r'[*/+-]')
double = re.compile(r'[+-]? *(?:\d+(?:\.\d*)... | [
"def",
"read",
"(",
"file",
",",
"system",
",",
"header",
"=",
"True",
")",
":",
"retval",
"=",
"True",
"fid",
"=",
"open",
"(",
"file",
",",
"'r'",
")",
"sep",
"=",
"re",
".",
"compile",
"(",
"r'\\s*,\\s*'",
")",
"comment",
"=",
"re",
".",
"comp... | 34.988636 | 0.000316 |
def to_image_type(image_type):
'''
to_image_type(image_type) yields an image-type class equivalent to the given image_type
argument, which may be a type name or alias or an image or header object or class.
'''
if image_type is None: return None
if isinstance(image_type, type) and issubclas... | [
"def",
"to_image_type",
"(",
"image_type",
")",
":",
"if",
"image_type",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"image_type",
",",
"type",
")",
"and",
"issubclass",
"(",
"image_type",
",",
"ImageType",
")",
":",
"return",
"image_type",... | 49.947368 | 0.01758 |
def add_filter(ds, patterns):
"""
Add a filter or list of filters to a datasource. A filter is a simple
string, and it matches if it is contained anywhere within a line.
Args:
ds (@datasource component): The datasource to filter
patterns (str, [str]): A string, list of strings, or set of ... | [
"def",
"add_filter",
"(",
"ds",
",",
"patterns",
")",
":",
"if",
"not",
"plugins",
".",
"is_datasource",
"(",
"ds",
")",
":",
"raise",
"Exception",
"(",
"\"Filters are applicable only to datasources.\"",
")",
"delegate",
"=",
"dr",
".",
"get_delegate",
"(",
"d... | 33.806452 | 0.000928 |
def blake_encode_ngrams(ngrams, # type: Iterable[str]
keys, # type: Sequence[bytes]
ks, # type: Sequence[int]
l, # type: int
encoding # type: str
):
# type: (...) -> bitarray.b... | [
"def",
"blake_encode_ngrams",
"(",
"ngrams",
",",
"# type: Iterable[str]",
"keys",
",",
"# type: Sequence[bytes]",
"ks",
",",
"# type: Sequence[int]",
"l",
",",
"# type: int",
"encoding",
"# type: str",
")",
":",
"# type: (...) -> bitarray.bitarray",
"key",
",",
"=",
"k... | 42.260417 | 0.001686 |
def _interpolate_stream_track_kick(self):
"""Build interpolations of the stream track near the kick"""
if hasattr(self,'_kick_interpolatedThetasTrack'): #pragma: no cover
self._store_closest()
return None #Already did this
# Setup the trackpoints where the kick will be co... | [
"def",
"_interpolate_stream_track_kick",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_kick_interpolatedThetasTrack'",
")",
":",
"#pragma: no cover",
"self",
".",
"_store_closest",
"(",
")",
"return",
"None",
"#Already did this",
"# Setup the trackpoints ... | 56.859155 | 0.020209 |
def _decode_image(fobj, session, filename):
"""Reads and decodes an image from a file object as a Numpy array.
The SUN dataset contains images in several formats (despite the fact that
all of them have .jpg extension). Some of them are:
- BMP (RGB)
- PNG (grayscale, RGBA, RGB interlaced)
- JPEG (RGB)... | [
"def",
"_decode_image",
"(",
"fobj",
",",
"session",
",",
"filename",
")",
":",
"buf",
"=",
"fobj",
".",
"read",
"(",
")",
"image",
"=",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"imdecode",
"(",
"np",
".",
"fromstring",
"(",
"buf",
... | 33.5 | 0.00916 |
async def set_active(self):
"""Set this client as active.
While a client is active, no other clients will raise notifications.
Call this method whenever there is an indication the user is
interacting with this client. This method may be called very
frequently, and it will only m... | [
"async",
"def",
"set_active",
"(",
"self",
")",
":",
"is_active",
"=",
"(",
"self",
".",
"_active_client_state",
"==",
"hangouts_pb2",
".",
"ACTIVE_CLIENT_STATE_IS_ACTIVE",
")",
"timed_out",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"_last_a... | 44.508475 | 0.000745 |
def import_gpg_key(key):
"""Imports a GPG key"""
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnup... | [
"def",
"import_gpg_key",
"(",
"key",
")",
":",
"if",
"not",
"key",
":",
"raise",
"CryptoritoError",
"(",
"'Invalid GPG Key'",
")",
"key_fd",
",",
"key_filename",
"=",
"mkstemp",
"(",
"\"cryptorito-gpg-import\"",
")",
"key_handle",
"=",
"os",
".",
"fdopen",
"("... | 35.733333 | 0.001818 |
def parse_geometry(geometry):
"""Parse a geometry string and returns a (width, height) tuple
Eg:
'100x200' ==> (100, 200)
'50' ==> (50, None)
'50x' ==> (50, None)
'x100' ==> (None, 100)
None ==> None
A callable `geometry` parameter is also supported.
"""
if n... | [
"def",
"parse_geometry",
"(",
"geometry",
")",
":",
"if",
"not",
"geometry",
":",
"return",
"None",
",",
"None",
"if",
"callable",
"(",
"geometry",
")",
":",
"geometry",
"=",
"geometry",
"(",
")",
"geometry",
"=",
"str",
"(",
"geometry",
")",
".",
"spl... | 28.75 | 0.001403 |
def create_Dim(self, name,value):
'''
Adds a dimension to class.
:parameter name: dimension name
:parameter value: dimension value
'''
if not self._dimensions.has_key(name) :
self.message(3, 'Create dimension {0}:{1}'.format(name,value))
... | [
"def",
"create_Dim",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"_dimensions",
".",
"has_key",
"(",
"name",
")",
":",
"self",
".",
"message",
"(",
"3",
",",
"'Create dimension {0}:{1}'",
".",
"format",
"(",
"name",
",",... | 38.461538 | 0.019531 |
def validate_response(expected_responses):
""" Decorator to validate responses from QTM """
def internal_decorator(function):
@wraps(function)
async def wrapper(*args, **kwargs):
response = await function(*args, **kwargs)
for expected_response in expected_responses:
... | [
"def",
"validate_response",
"(",
"expected_responses",
")",
":",
"def",
"internal_decorator",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"async",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
... | 28.8 | 0.001681 |
def _calc_ARMA_noise(volume,
mask,
auto_reg_order=1,
ma_order=1,
sample_num=100,
):
""" Calculate the the ARMA noise of a volume
This calculates the autoregressive and moving average noise of the volume
... | [
"def",
"_calc_ARMA_noise",
"(",
"volume",
",",
"mask",
",",
"auto_reg_order",
"=",
"1",
",",
"ma_order",
"=",
"1",
",",
"sample_num",
"=",
"100",
",",
")",
":",
"# Pull out the non masked voxels",
"if",
"len",
"(",
"volume",
".",
"shape",
")",
">",
"1",
... | 34.690476 | 0.000334 |
def user_exists(name,
user=None, host=None, port=None, maintenance_db=None,
password=None,
runas=None):
'''
Checks if a user exists on the Postgres server.
CLI Example:
.. code-block:: bash
salt '*' postgres.user_exists 'username'
'''
re... | [
"def",
"user_exists",
"(",
"name",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"role_get",... | 25.954545 | 0.001689 |
def get_user_groups(self, user):
"""Returns a ``list`` with the user's groups or ``None`` if
unsuccessful.
:param str user: User we want groups for.
"""
conn = self.bind
try:
if current_app.config['LDAP_OPENLDAP']:
fields = \
... | [
"def",
"get_user_groups",
"(",
"self",
",",
"user",
")",
":",
"conn",
"=",
"self",
".",
"bind",
"try",
":",
"if",
"current_app",
".",
"config",
"[",
"'LDAP_OPENLDAP'",
"]",
":",
"fields",
"=",
"[",
"str",
"(",
"current_app",
".",
"config",
"[",
"'LDAP_... | 45.36 | 0.000863 |
def convert(self, value, param, ctx):
""" Try to find correct disk image regarding version. """
self.gandi = ctx.obj
# remove deprecated * prefix
choices = [choice.replace('*', '') for choice in self.choices]
value = value.replace('*', '')
# Exact match
if value i... | [
"def",
"convert",
"(",
"self",
",",
"value",
",",
"param",
",",
"ctx",
")",
":",
"self",
".",
"gandi",
"=",
"ctx",
".",
"obj",
"# remove deprecated * prefix",
"choices",
"=",
"[",
"choice",
".",
"replace",
"(",
"'*'",
",",
"''",
")",
"for",
"choice",
... | 34.391304 | 0.00246 |
def play_alert(zones, alert_uri, alert_volume=20, alert_duration=0, fade_back=False):
"""
Demo function using soco.snapshot across multiple Sonos players.
Args:
zones (set): a set of SoCo objects
alert_uri (str): uri that Sonos can play as an alert
alert_volume (int): volume level f... | [
"def",
"play_alert",
"(",
"zones",
",",
"alert_uri",
",",
"alert_volume",
"=",
"20",
",",
"alert_duration",
"=",
"0",
",",
"fade_back",
"=",
"False",
")",
":",
"# Use soco.snapshot to capture current state of each zone to allow restore",
"for",
"zone",
"in",
"zones",
... | 39.244444 | 0.001105 |
def duration_bool(b, rule, samplerate=None):
"""
Mask the parts in b being True but does not meet the duration
rules. Return an updated copy of b.
b: 1d array with True or False elements.
rule: str
The rule including the string 'dur' to be evaled.
samplerate: None or float
Has... | [
"def",
"duration_bool",
"(",
"b",
",",
"rule",
",",
"samplerate",
"=",
"None",
")",
":",
"if",
"rule",
"is",
"None",
":",
"return",
"b",
"slicelst",
"=",
"slicelist",
"(",
"b",
")",
"b2",
"=",
"np",
".",
"array",
"(",
"b",
")",
"if",
"samplerate",
... | 23.969697 | 0.001215 |
def get_connection_params(self):
"""
Default method to acquire database connection parameters.
Sets connection parameters to match settings.py, and sets
default values to blank fields.
"""
valid_settings = {
'NAME': 'name',
'HOST': 'host',
... | [
"def",
"get_connection_params",
"(",
"self",
")",
":",
"valid_settings",
"=",
"{",
"'NAME'",
":",
"'name'",
",",
"'HOST'",
":",
"'host'",
",",
"'PORT'",
":",
"'port'",
",",
"'USER'",
":",
"'username'",
",",
"'PASSWORD'",
":",
"'password'",
",",
"'AUTH_SOURCE... | 31.972222 | 0.001686 |
def make_query(args, other=None, limit=None, strand=None, featuretype=None,
extra=None, order_by=None, reverse=False,
completely_within=False):
"""
Multi-purpose, bare-bones ORM function.
This function composes queries given some commonly-used kwargs that can be
passed to ... | [
"def",
"make_query",
"(",
"args",
",",
"other",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"strand",
"=",
"None",
",",
"featuretype",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"complete... | 36.37037 | 0.00033 |
def event_source_mapping_present(name, EventSourceArn, FunctionName,
StartingPosition, Enabled=True, BatchSize=100,
region=None, key=None, keyid=None,
profile=None):
'''
Ensure event source mapping exists.
na... | [
"def",
"event_source_mapping_present",
"(",
"name",
",",
"EventSourceArn",
",",
"FunctionName",
",",
"StartingPosition",
",",
"Enabled",
"=",
"True",
",",
"BatchSize",
"=",
"100",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None"... | 39.669014 | 0.000173 |
def region(self, region=None, seqid=None, start=None, end=None,
strand=None, featuretype=None, completely_within=False):
"""
Return features within specified genomic coordinates.
Specifying genomic coordinates can be done in a flexible manner
Parameters
---------... | [
"def",
"region",
"(",
"self",
",",
"region",
"=",
"None",
",",
"seqid",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"strand",
"=",
"None",
",",
"featuretype",
"=",
"None",
",",
"completely_within",
"=",
"False",
")",
":",
... | 38.320225 | 0.000429 |
def aggregate_registry_timers():
"""Returns a list of aggregate timing information for registered timers.
Each element is a 3-tuple of
- timer description
- aggregate elapsed time
- number of calls
The list is sorted by the first start time of each aggregate timer.
"""
im... | [
"def",
"aggregate_registry_timers",
"(",
")",
":",
"import",
"itertools",
"timers",
"=",
"sorted",
"(",
"shared_registry",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"desc",
")",
"aggregate_timers",
"=",
"[",
"]",
"for",
"k",... | 32.185185 | 0.001117 |
def _apply_filter_settings(self):
"""Applies some hard-coded texture filtering settings."""
# TODO: Allow easy customization of filters
if self.mipmap:
gl.glTexParameterf(self.target, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR_MIPMAP_LINEAR)
else:
gl.glTexParameterf(s... | [
"def",
"_apply_filter_settings",
"(",
"self",
")",
":",
"# TODO: Allow easy customization of filters",
"if",
"self",
".",
"mipmap",
":",
"gl",
".",
"glTexParameterf",
"(",
"self",
".",
"target",
",",
"gl",
".",
"GL_TEXTURE_MIN_FILTER",
",",
"gl",
".",
"GL_LINEAR_M... | 55.272727 | 0.009709 |
def plot_movie_of_trajectory_with_matplotlib(
obs, figsize=6, grid=True,
wireframe=False, max_count=None, angle=None, noaxis=False,
interval=0.16, repeat_delay=3000, stride=1, rotate=None,
legend=True, output=None, crf=10, bitrate='1M', plot_range=None, **kwargs):
"""
Generate a ... | [
"def",
"plot_movie_of_trajectory_with_matplotlib",
"(",
"obs",
",",
"figsize",
"=",
"6",
",",
"grid",
"=",
"True",
",",
"wireframe",
"=",
"False",
",",
"max_count",
"=",
"None",
",",
"angle",
"=",
"None",
",",
"noaxis",
"=",
"False",
",",
"interval",
"=",
... | 35.688679 | 0.000772 |
def add_watch(self, path, mask, proc_fun=None, rec=False,
auto_add=False, do_glob=False, quiet=True,
exclude_filter=None):
"""
Add watch(s) on the provided |path|(s) with associated |mask| flag
value and optionally with a processing |proc_fun| function and
... | [
"def",
"add_watch",
"(",
"self",
",",
"path",
",",
"mask",
",",
"proc_fun",
"=",
"None",
",",
"rec",
"=",
"False",
",",
"auto_add",
"=",
"False",
",",
"do_glob",
"=",
"False",
",",
"quiet",
"=",
"True",
",",
"exclude_filter",
"=",
"None",
")",
":",
... | 52.481013 | 0.001657 |
def fit_shifts(xy, uv):
""" Performs a simple fit for the shift only between
matched lists of positions 'xy' and 'uv'.
Output: (same as for fit_arrays)
=================================
DEVELOPMENT NOTE:
Checks need to be put in place to verify that
enough ob... | [
"def",
"fit_shifts",
"(",
"xy",
",",
"uv",
")",
":",
"diff_pts",
"=",
"xy",
"-",
"uv",
"Pcoeffs",
"=",
"np",
".",
"array",
"(",
"[",
"1.0",
",",
"0.0",
",",
"diff_pts",
"[",
":",
",",
"0",
"]",
".",
"mean",
"(",
"dtype",
"=",
"np",
".",
"floa... | 36.043478 | 0.008226 |
def removeAllRecords(self):
"""Deletes all the values in the dataset"""
for field in self.fields:
field.encodings, field.values=[], []
field.numRecords, field.numEncodings= (0, 0) | [
"def",
"removeAllRecords",
"(",
"self",
")",
":",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"field",
".",
"encodings",
",",
"field",
".",
"values",
"=",
"[",
"]",
",",
"[",
"]",
"field",
".",
"numRecords",
",",
"field",
".",
"numEncodings",
"... | 32.5 | 0.025 |
def clone_wire(old_wire, name=None):
"""
Makes a copy of any existing wire
:param old_wire: The wire to clone
:param name: a name fo rhte new wire
Note that this function is mainly intended to be used when the
two wires are from different blocks. Making two wires with the
same name in the ... | [
"def",
"clone_wire",
"(",
"old_wire",
",",
"name",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"old_wire",
",",
"Const",
")",
":",
"return",
"Const",
"(",
"old_wire",
".",
"val",
",",
"old_wire",
".",
"bitwidth",
")",
"else",
":",
"if",
"name",
"... | 35.470588 | 0.001616 |
def get_children(engine, parent_ids, rank='species', schema=None):
"""
Recursively fetch children of tax_ids in `parent_ids` until the
rank of `rank`
"""
if not parent_ids:
return []
nodes = schema + '.nodes' if schema else 'nodes'
names = schema + '.names' if schema else 'names'
... | [
"def",
"get_children",
"(",
"engine",
",",
"parent_ids",
",",
"rank",
"=",
"'species'",
",",
"schema",
"=",
"None",
")",
":",
"if",
"not",
"parent_ids",
":",
"return",
"[",
"]",
"nodes",
"=",
"schema",
"+",
"'.nodes'",
"if",
"schema",
"else",
"'nodes'",
... | 34.366667 | 0.000943 |
def get_imported_repo(self, import_path):
"""Looks for a go-import meta tag for the provided import_path.
Returns an ImportedRepo instance with the information in the meta tag,
or None if no go-import meta tag is found.
"""
try:
session = requests.session()
# TODO: Support https with (o... | [
"def",
"get_imported_repo",
"(",
"self",
",",
"import_path",
")",
":",
"try",
":",
"session",
"=",
"requests",
".",
"session",
"(",
")",
"# TODO: Support https with (optional) fallback to http, as Go does.",
"# See https://github.com/pantsbuild/pants/issues/3503.",
"session",
... | 43.064516 | 0.011722 |
def cache_to_df(dir_path):
"""
Convert a directory of binary array data files to a Pandas DataFrame.
Parameters
----------
dir_path : str
"""
table = {}
for attrib in glob.glob(os.path.join(dir_path, '*')):
attrib_name, attrib_ext = os.path.splitext(os.path.basename(attrib))
... | [
"def",
"cache_to_df",
"(",
"dir_path",
")",
":",
"table",
"=",
"{",
"}",
"for",
"attrib",
"in",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"'*'",
")",
")",
":",
"attrib_name",
",",
"attrib_ext",
"=",
"os",
".",
... | 30.638298 | 0.000673 |
def rho_D_inv_A(A):
"""Return the (approx.) spectral radius of D^-1 * A.
Parameters
----------
A : sparse-matrix
Returns
-------
approximate spectral radius of diag(A)^{-1} A
Examples
--------
>>> from pyamg.gallery import poisson
>>> from pyamg.relaxation.smoothing import... | [
"def",
"rho_D_inv_A",
"(",
"A",
")",
":",
"if",
"not",
"hasattr",
"(",
"A",
",",
"'rho_D_inv'",
")",
":",
"D_inv",
"=",
"get_diagonal",
"(",
"A",
",",
"inv",
"=",
"True",
")",
"D_inv_A",
"=",
"scale_rows",
"(",
"A",
",",
"D_inv",
",",
"copy",
"=",
... | 24.964286 | 0.001377 |
def get_zipcode(self, ip):
''' Get zipcode '''
rec = self.get_all(ip)
return rec and rec.zipcode | [
"def",
"get_zipcode",
"(",
"self",
",",
"ip",
")",
":",
"rec",
"=",
"self",
".",
"get_all",
"(",
"ip",
")",
"return",
"rec",
"and",
"rec",
".",
"zipcode"
] | 29.25 | 0.016667 |
def custom_build(inputs, is_training, keep_prob):
"""A custom build method to wrap into a sonnet Module."""
outputs = snt.Conv2D(output_channels=32, kernel_shape=4, stride=2)(inputs)
outputs = snt.BatchNorm()(outputs, is_training=is_training)
outputs = tf.nn.relu(outputs)
outputs = snt.Conv2D(output_channels=... | [
"def",
"custom_build",
"(",
"inputs",
",",
"is_training",
",",
"keep_prob",
")",
":",
"outputs",
"=",
"snt",
".",
"Conv2D",
"(",
"output_channels",
"=",
"32",
",",
"kernel_shape",
"=",
"4",
",",
"stride",
"=",
"2",
")",
"(",
"inputs",
")",
"outputs",
"... | 50.166667 | 0.019576 |
def emit(self, key, value):
"""\
Handle an output key/value pair.
Reporting progress is strictly necessary only when using a Python
record writer, because sending an output key/value pair is an implicit
progress report. To take advantage of this, however, we would be
for... | [
"def",
"emit",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"__spilling",
":",
"self",
".",
"__actual_emit",
"(",
"key",
",",
"value",
")",
"else",
":",
"# key must be hashable",
"self",
".",
"__cache",
".",
"setdefault",
"(",
"k... | 46.409091 | 0.001919 |
def remove_non_latin(input_string, also_keep=None):
"""Remove non-Latin characters.
`also_keep` should be a list which will add chars (e.g. punctuation)
that will not be filtered.
"""
if also_keep:
also_keep += [' ']
else:
also_keep = [' ']
latin_chars = 'ABCDEFGHIJKLMNOPQRST... | [
"def",
"remove_non_latin",
"(",
"input_string",
",",
"also_keep",
"=",
"None",
")",
":",
"if",
"also_keep",
":",
"also_keep",
"+=",
"[",
"' '",
"]",
"else",
":",
"also_keep",
"=",
"[",
"' '",
"]",
"latin_chars",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYZ'",
"latin_char... | 35 | 0.001988 |
def comment (self, s, **args):
"""
Write XML comment.
"""
self.write(u"<!-- ")
self.write(s, **args)
self.writeln(u" -->") | [
"def",
"comment",
"(",
"self",
",",
"s",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"write",
"(",
"u\"<!-- \"",
")",
"self",
".",
"write",
"(",
"s",
",",
"*",
"*",
"args",
")",
"self",
".",
"writeln",
"(",
"u\" -->\"",
")"
] | 23.428571 | 0.017647 |
def tag_and_stem(self, text, cache=None):
"""
Given some text, return a sequence of (stem, pos, text) triples as
appropriate for the reader. `pos` can be as general or specific as
necessary (for example, it might label all parts of speech, or it might
only distinguish function wo... | [
"def",
"tag_and_stem",
"(",
"self",
",",
"text",
",",
"cache",
"=",
"None",
")",
":",
"analysis",
"=",
"self",
".",
"analyze",
"(",
"text",
")",
"triples",
"=",
"[",
"]",
"for",
"record",
"in",
"analysis",
":",
"root",
"=",
"self",
".",
"get_record_r... | 41.346154 | 0.001818 |
def array_bytes(shape, dtype):
""" Estimates the memory in bytes required for an array of the supplied shape and dtype """
return np.product(shape)*np.dtype(dtype).itemsize | [
"def",
"array_bytes",
"(",
"shape",
",",
"dtype",
")",
":",
"return",
"np",
".",
"product",
"(",
"shape",
")",
"*",
"np",
".",
"dtype",
"(",
"dtype",
")",
".",
"itemsize"
] | 59.333333 | 0.011111 |
def uniqualize(l,**kwargs):
'''
from elist.elist import *
l = [1, 2, 2]
new = uniqualize(l)
new
id(l)
id(new)
####
l = [1, 2, 2]
rslt = uniqualize(l,mode="original")
rslt
id(l)
id(rslt)
'''
if('mode' in kwargs):
... | [
"def",
"uniqualize",
"(",
"l",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"'mode'",
"in",
"kwargs",
")",
":",
"mode",
"=",
"kwargs",
"[",
"'mode'",
"]",
"else",
":",
"mode",
"=",
"'new'",
"pt",
"=",
"copy",
".",
"deepcopy",
"(",
"l",
")",
"s... | 20.153846 | 0.008495 |
def increase_volume(percentage):
'''Increase the volume.
Increase the volume by a given percentage.
Args:
percentage (int): The percentage (as an integer between 0 and 100) to increase the volume by.
Raises:
ValueError: if the percentage is >100 or <0.
'''
if percentage > 100 or percentage < 0:
raise ... | [
"def",
"increase_volume",
"(",
"percentage",
")",
":",
"if",
"percentage",
">",
"100",
"or",
"percentage",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'percentage must be an integer between 0 and 100'",
")",
"if",
"system",
".",
"get_name",
"(",
")",
"==",
"'win... | 22.702703 | 0.030822 |
def _do_upload(
self, client, stream, content_type, size, num_retries, predefined_acl
):
"""Determine an upload strategy and then perform the upload.
If the size of the data to be uploaded exceeds 5 MB a resumable media
request will be used, otherwise the content and the metadata wi... | [
"def",
"_do_upload",
"(",
"self",
",",
"client",
",",
"stream",
",",
"content_type",
",",
"size",
",",
"num_retries",
",",
"predefined_acl",
")",
":",
"if",
"size",
"is",
"not",
"None",
"and",
"size",
"<=",
"_MAX_MULTIPART_SIZE",
":",
"response",
"=",
"sel... | 41.509434 | 0.001332 |
def update(self, w, offset=0):
"""Compute gradient and Hessian matrix with respect to `w`."""
time = self.time
x = self.x
exp_xw = numpy.exp(offset + numpy.dot(x, w))
n_samples, n_features = x.shape
gradient = numpy.zeros((1, n_features), dtype=float)
hessian = n... | [
"def",
"update",
"(",
"self",
",",
"w",
",",
"offset",
"=",
"0",
")",
":",
"time",
"=",
"self",
".",
"time",
"x",
"=",
"self",
".",
"x",
"exp_xw",
"=",
"numpy",
".",
"exp",
"(",
"offset",
"+",
"numpy",
".",
"dot",
"(",
"x",
",",
"w",
")",
"... | 30.571429 | 0.00194 |
def price(usr, item, searches = 2, method = "AVERAGE", deduct = 0):
""" Searches the shop wizard for given item and determines price with given method
Searches the shop wizard x times (x being number given in searches) for the
given item and collects the lowest price from each result. U... | [
"def",
"price",
"(",
"usr",
",",
"item",
",",
"searches",
"=",
"2",
",",
"method",
"=",
"\"AVERAGE\"",
",",
"deduct",
"=",
"0",
")",
":",
"if",
"not",
"method",
"in",
"ShopWizard",
".",
"methods",
":",
"raise",
"invalidMethod",
"(",
")",
"if",
"isins... | 40.888889 | 0.012384 |
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper() | [
"def",
"prepare_method",
"(",
"self",
",",
"method",
")",
":",
"self",
".",
"method",
"=",
"method",
"if",
"self",
".",
"method",
"is",
"not",
"None",
":",
"self",
".",
"method",
"=",
"self",
".",
"method",
".",
"upper",
"(",
")"
] | 37.2 | 0.010526 |
def query(self, stringa):
"""SPARQL query / wrapper for rdflib sparql query method """
qres = self.rdflib_graph.query(stringa)
return list(qres) | [
"def",
"query",
"(",
"self",
",",
"stringa",
")",
":",
"qres",
"=",
"self",
".",
"rdflib_graph",
".",
"query",
"(",
"stringa",
")",
"return",
"list",
"(",
"qres",
")"
] | 41.25 | 0.011905 |
def get_characteristic_handle_from_uuid(self, uuid):
"""Given a characteristic UUID, return its handle.
Args:
uuid (str): a string containing the hex-encoded UUID
Returns:
None if an error occurs, otherwise an integer handle.
"""
ch = self.get_chara... | [
"def",
"get_characteristic_handle_from_uuid",
"(",
"self",
",",
"uuid",
")",
":",
"ch",
"=",
"self",
".",
"get_characteristic_from_uuid",
"(",
"uuid",
")",
"return",
"None",
"if",
"ch",
"is",
"None",
"else",
"ch",
".",
"char_handle"
] | 35.363636 | 0.010025 |
def add_get(self, *args, **kwargs):
"""
Shortcut for add_route with method GET
"""
return self.add_route(hdrs.METH_GET, *args, **kwargs) | [
"def",
"add_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"add_route",
"(",
"hdrs",
".",
"METH_GET",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 32.8 | 0.011905 |
def add_assay(self, name, assay):
"""
Add an assay to the material.
:param name: The name of the new assay.
:param assay: A numpy array containing the size class mass fractions
for the assay. The sequence of the assay's elements must correspond
to the sequence of the... | [
"def",
"add_assay",
"(",
"self",
",",
"name",
",",
"assay",
")",
":",
"if",
"not",
"type",
"(",
"assay",
")",
"is",
"numpy",
".",
"ndarray",
":",
"raise",
"Exception",
"(",
"\"Invalid assay. It must be a numpy array.\"",
")",
"elif",
"not",
"assay",
".",
"... | 42.45 | 0.002304 |
def list(self, identity=values.unset, limit=None, page_size=None):
"""
Lists MemberInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode identity: The `identity` value of the r... | [
"def",
"list",
"(",
"self",
",",
"identity",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"stream",
"(",
"identity",
"=",
"identity",
",",
"limit",
"=",
"limit",
... | 61.055556 | 0.008065 |
def closeEvent(self, event):
"""Verifies the stimulus before closing, warns user with a
dialog if there are any problems"""
self.ok.setText("Checking...")
QtGui.QApplication.processEvents()
self.model().cleanComponents()
self.model().purgeAutoSelected()
msg = self... | [
"def",
"closeEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"ok",
".",
"setText",
"(",
"\"Checking...\"",
")",
"QtGui",
".",
"QApplication",
".",
"processEvents",
"(",
")",
"self",
".",
"model",
"(",
")",
".",
"cleanComponents",
"(",
")",
"s... | 47.611111 | 0.008009 |
def compliance_report(self, validation_file=None, validation_source=None):
"""
Return a compliance report.
Verify that the device complies with the given validation file and writes a compliance
report file. See https://napalm.readthedocs.io/en/latest/validate/index.html.
:param... | [
"def",
"compliance_report",
"(",
"self",
",",
"validation_file",
"=",
"None",
",",
"validation_source",
"=",
"None",
")",
":",
"return",
"validate",
".",
"compliance_report",
"(",
"self",
",",
"validation_file",
"=",
"validation_file",
",",
"validation_source",
"=... | 48.8 | 0.008043 |
def append(self, item: TransItem):
"""
Append an item to the internal dictionary.
"""
self.data[item.key].append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
":",
"TransItem",
")",
":",
"self",
".",
"data",
"[",
"item",
".",
"key",
"]",
".",
"append",
"(",
"item",
")"
] | 24.333333 | 0.013245 |
def build_tokens_line(self):
"""Build a logical line from tokens."""
logical = []
comments = []
length = 0
prev_row = prev_col = mapping = None
for token_type, text, start, end, line in self.tokens:
if token_type in SKIP_TOKENS:
continue
... | [
"def",
"build_tokens_line",
"(",
"self",
")",
":",
"logical",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"length",
"=",
"0",
"prev_row",
"=",
"prev_col",
"=",
"mapping",
"=",
"None",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"li... | 41.28125 | 0.001479 |
def set(self, f):
"""Call a function after a delay, unless another function is set
in the meantime."""
self.stop()
self._create_timer(f)
self.start() | [
"def",
"set",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"stop",
"(",
")",
"self",
".",
"_create_timer",
"(",
"f",
")",
"self",
".",
"start",
"(",
")"
] | 30.666667 | 0.010582 |
def strace_data_store_event(self, operation, address, address_range=0):
"""Sets an event to trigger trace logic when data write access is made.
Args:
self (JLink): the ``JLink`` instance.
operation (int): one of the operations in ``JLinkStraceOperation``.
address (int): th... | [
"def",
"strace_data_store_event",
"(",
"self",
",",
"operation",
",",
"address",
",",
"address_range",
"=",
"0",
")",
":",
"cmd",
"=",
"enums",
".",
"JLinkStraceCommand",
".",
"TRACE_EVENT_SET",
"event_info",
"=",
"structs",
".",
"JLinkStraceEventInfo",
"(",
")"... | 40.481481 | 0.001787 |
def invalidate(self):
"""Invalidates the current transport and disconnects all redis connections"""
super(RedisTransport, self).invalidate()
for server in self._servers:
server['redis'].connection_pool.disconnect()
return False | [
"def",
"invalidate",
"(",
"self",
")",
":",
"super",
"(",
"RedisTransport",
",",
"self",
")",
".",
"invalidate",
"(",
")",
"for",
"server",
"in",
"self",
".",
"_servers",
":",
"server",
"[",
"'redis'",
"]",
".",
"connection_pool",
".",
"disconnect",
"(",... | 38 | 0.011029 |
def list_of_all_href(self,html):
'''
It will return all hyper links found in the mr-jatt page for download
'''
soup=BeautifulSoup(html)
links=[]
a_list=soup.findAll('a','touch')
for x in xrange(len(a_list)-1):
link = a_list[x].get('href')
name = a_list[x]
name = str(name)
name=re.sub(r'<a.*/>... | [
"def",
"list_of_all_href",
"(",
"self",
",",
"html",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"html",
")",
"links",
"=",
"[",
"]",
"a_list",
"=",
"soup",
".",
"findAll",
"(",
"'a'",
",",
"'touch'",
")",
"for",
"x",
"in",
"xrange",
"(",
"len",
"... | 26.941176 | 0.067511 |
def active_pt_window(self):
" The active prompt_toolkit layout Window. "
if self.active_tab:
w = self.active_tab.active_window
if w:
return w.pt_window | [
"def",
"active_pt_window",
"(",
"self",
")",
":",
"if",
"self",
".",
"active_tab",
":",
"w",
"=",
"self",
".",
"active_tab",
".",
"active_window",
"if",
"w",
":",
"return",
"w",
".",
"pt_window"
] | 33.666667 | 0.009662 |
def isInt(num):
"""Returns true if `num` is (sort of) an integer.
>>> isInt(3) == isInt(3.0) == 1
True
>>> isInt(3.2)
False
>>> import numpy
>>> isInt(numpy.array(1))
True
>>> isInt(numpy.array([1]))
False
"""
try:
len(num) # FIXME fails for Numeric but Numeric is... | [
"def",
"isInt",
"(",
"num",
")",
":",
"try",
":",
"len",
"(",
"num",
")",
"# FIXME fails for Numeric but Numeric is obsolete",
"except",
":",
"try",
":",
"return",
"(",
"num",
"-",
"math",
".",
"floor",
"(",
"num",
")",
"==",
"0",
")",
"==",
"True",
"e... | 23.368421 | 0.015152 |
def default(self, obj):
"""Overriding the default JSONEncoder.default for NDB support."""
obj_type = type(obj)
# NDB Models return a repr to calls from type().
if obj_type not in self._ndb_type_encoding:
if hasattr(obj, '__metaclass__'):
obj_type = obj.__metaclass__
else:
# T... | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"obj_type",
"=",
"type",
"(",
"obj",
")",
"# NDB Models return a repr to calls from type().",
"if",
"obj_type",
"not",
"in",
"self",
".",
"_ndb_type_encoding",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__meta... | 29.35 | 0.008251 |
def console_set_default_background(
con: tcod.console.Console, col: Tuple[int, int, int]
) -> None:
"""Change the default background color for a console.
Args:
con (Console): Any Console instance.
col (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color i... | [
"def",
"console_set_default_background",
"(",
"con",
":",
"tcod",
".",
"console",
".",
"Console",
",",
"col",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"None",
":",
"lib",
".",
"TCOD_console_set_default_background",
"(",
"_console",
... | 32.785714 | 0.002119 |
def get_user(user=None):
"""Get the user object
:param user: A user id, memberdata object or None for the current user
:returns: Plone User (PlonePAS) / Propertied User (PluggableAuthService)
"""
if user is None:
# Return the current authenticated user
user = getSecurityManager().ge... | [
"def",
"get_user",
"(",
"user",
"=",
"None",
")",
":",
"if",
"user",
"is",
"None",
":",
"# Return the current authenticated user",
"user",
"=",
"getSecurityManager",
"(",
")",
".",
"getUser",
"(",
")",
"elif",
"isinstance",
"(",
"user",
",",
"MemberData",
")... | 35.722222 | 0.001515 |
def some(ol,test_func,*args):
'''
from elist.elist import *
def test_func(ele,x):
cond = (ele > x)
return(cond)
ol = [1,2,3,4]
some(ol,test_func,3)
ol = [1,2,1,3]
some(ol,test_func,3)
'''
rslt = {'cond':False,'index':N... | [
"def",
"some",
"(",
"ol",
",",
"test_func",
",",
"*",
"args",
")",
":",
"rslt",
"=",
"{",
"'cond'",
":",
"False",
",",
"'index'",
":",
"None",
"}",
"length",
"=",
"ol",
".",
"__len__",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"length... | 23.045455 | 0.024621 |
def restoreState(self):
"""Utility method to restore plugin state from persistent storage to
permit access to previous plugin state.
@return: Object that stores plugin state.
"""
if os.path.exists(self._stateFile):
try:
fp = open(sel... | [
"def",
"restoreState",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_stateFile",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"self",
".",
"_stateFile",
",",
"'r'",
")",
"stateObj",
"=",
"pickle",
".",
"load",
... | 35.1875 | 0.012111 |
def parse(self, version):
"""
Splits a typical version string (e.g. <MAJOR>.<MINOR>.<MICRO>)
into a tuple that can be sorted properly. Ignores all leading
and trailing characters by using a regex search (instead of match) so
as to pick the version string out of a block of text.
... | [
"def",
"parse",
"(",
"self",
",",
"version",
")",
":",
"# Check to see if version is not a string but rather another type",
"# that can be interpreted as a version",
"if",
"isinstance",
"(",
"version",
",",
"int",
")",
":",
"return",
"(",
"version",
",",
")",
",",
"No... | 45.186813 | 0.000714 |
def db_handler(args):
"""db_handler."""
if args.type == 'create':
if args.db is None:
db.init_db()
return
if not db.setup(url=args.db, echo=args.db_echo):
return
if args.type == 'status':
current_rev = db_revision.current_db_revision()
print('The cu... | [
"def",
"db_handler",
"(",
"args",
")",
":",
"if",
"args",
".",
"type",
"==",
"'create'",
":",
"if",
"args",
".",
"db",
"is",
"None",
":",
"db",
".",
"init_db",
"(",
")",
"return",
"if",
"not",
"db",
".",
"setup",
"(",
"url",
"=",
"args",
".",
"... | 22.68 | 0.001692 |
def get_extension(self):
"""Returns the file extension."""
ext = os.path.splitext(self.img.name)[1]
if ext:
# Remove period from extension
return ext[1:]
return ext | [
"def",
"get_extension",
"(",
"self",
")",
":",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"img",
".",
"name",
")",
"[",
"1",
"]",
"if",
"ext",
":",
"# Remove period from extension",
"return",
"ext",
"[",
"1",
":",
"]",
"return"... | 30.571429 | 0.009091 |
def _copy_margin(self, cli, lazy_screen, new_screen, write_position, move_x, width):
"""
Copy characters from the margin screen to the real screen.
"""
xpos = write_position.xpos + move_x
ypos = write_position.ypos
margin_write_position = WritePosition(xpos, ypos, width,... | [
"def",
"_copy_margin",
"(",
"self",
",",
"cli",
",",
"lazy_screen",
",",
"new_screen",
",",
"write_position",
",",
"move_x",
",",
"width",
")",
":",
"xpos",
"=",
"write_position",
".",
"xpos",
"+",
"move_x",
"ypos",
"=",
"write_position",
".",
"ypos",
"mar... | 46.888889 | 0.011628 |
def delete_script(delete=None): # noqa: E501
"""Delete a script
Delete a script # noqa: E501
:param delete: The data needed to delete this script
:type delete: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
delete = Delete.from_dict(connexion.request.get_json()) ... | [
"def",
"delete_script",
"(",
"delete",
"=",
"None",
")",
":",
"# noqa: E501",
"if",
"connexion",
".",
"request",
".",
"is_json",
":",
"delete",
"=",
"Delete",
".",
"from_dict",
"(",
"connexion",
".",
"request",
".",
"get_json",
"(",
")",
")",
"# noqa: E501... | 26.894737 | 0.00189 |
def avg_n_nplusone(x):
""" returns x[0]/2, (x[0]+x[1])/2, ... (x[-2]+x[-1])/2, x[-1]/2
"""
y = np.zeros(1 + x.shape[0])
hx = 0.5 * x
y[:-1] = hx
y[1:] += hx
return y | [
"def",
"avg_n_nplusone",
"(",
"x",
")",
":",
"y",
"=",
"np",
".",
"zeros",
"(",
"1",
"+",
"x",
".",
"shape",
"[",
"0",
"]",
")",
"hx",
"=",
"0.5",
"*",
"x",
"y",
"[",
":",
"-",
"1",
"]",
"=",
"hx",
"y",
"[",
"1",
":",
"]",
"+=",
"hx",
... | 21 | 0.020305 |
def intersect_two(f1, f2, work_dir, data):
"""Intersect two regions, handling cases where either file is not present.
"""
bedtools = config_utils.get_program("bedtools", data, default="bedtools")
f1_exists = f1 and utils.file_exists(f1)
f2_exists = f2 and utils.file_exists(f2)
if not f1_exists a... | [
"def",
"intersect_two",
"(",
"f1",
",",
"f2",
",",
"work_dir",
",",
"data",
")",
":",
"bedtools",
"=",
"config_utils",
".",
"get_program",
"(",
"\"bedtools\"",
",",
"data",
",",
"default",
"=",
"\"bedtools\"",
")",
"f1_exists",
"=",
"f1",
"and",
"utils",
... | 45.052632 | 0.002288 |
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = ... | [
"def",
"_router_request",
"(",
"router",
",",
"method",
",",
"data",
"=",
"None",
")",
":",
"if",
"router",
"not",
"in",
"ROUTERS",
":",
"return",
"False",
"req_data",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"dumps",
"(",
"[",
"dict",
"(",
"acti... | 36.740741 | 0.001965 |
def pipeline_control_new(rst, clk, rx_rdy, rx_vld, tx_rdy, tx_vld, stage_enable, stop_rx=None, stop_tx=None):
""" Pipeline control unit
rx_rdy, rx_vld, - (o)(i) handshake at the pipeline input (front of the pipeline)
tx_rdy, tx_vld, - (i)(o) handshake at the pipeline output (back o... | [
"def",
"pipeline_control_new",
"(",
"rst",
",",
"clk",
",",
"rx_rdy",
",",
"rx_vld",
",",
"tx_rdy",
",",
"tx_vld",
",",
"stage_enable",
",",
"stop_rx",
"=",
"None",
",",
"stop_tx",
"=",
"None",
")",
":",
"NUM_STAGES",
"=",
"len",
"(",
"stage_enable",
")"... | 47.483871 | 0.013311 |
def getx(self, name, *args):
"""
Return value of one of parameter(s) or NULL is it has no value (or was not specified)
"""
return lib.zargs_getx(self._as_parameter_, name, *args) | [
"def",
"getx",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"return",
"lib",
".",
"zargs_getx",
"(",
"self",
".",
"_as_parameter_",
",",
"name",
",",
"*",
"args",
")"
] | 41.2 | 0.014286 |
def _send_file(self, filename):
"""
Sends a file via FTP.
"""
# pylint: disable=E1101
ftp = ftplib.FTP(host=self.host)
ftp.login(user=self.user, passwd=self.password)
ftp.set_pasv(True)
ftp.storbinary("STOR %s" % os.path.basename(filename),
fil... | [
"def",
"_send_file",
"(",
"self",
",",
"filename",
")",
":",
"# pylint: disable=E1101",
"ftp",
"=",
"ftplib",
".",
"FTP",
"(",
"host",
"=",
"self",
".",
"host",
")",
"ftp",
".",
"login",
"(",
"user",
"=",
"self",
".",
"user",
",",
"passwd",
"=",
"sel... | 32.9 | 0.008876 |
def getShocks(self):
'''
Finds permanent and transitory income "shocks" for each agent this period. As this is a
perfect foresight model, there are no stochastic shocks: PermShkNow = PermGroFac for each
agent (according to their t_cycle) and TranShkNow = 1.0 for all agents.
Par... | [
"def",
"getShocks",
"(",
"self",
")",
":",
"PermGroFac",
"=",
"np",
".",
"array",
"(",
"self",
".",
"PermGroFac",
")",
"self",
".",
"PermShkNow",
"=",
"PermGroFac",
"[",
"self",
".",
"t_cycle",
"-",
"1",
"]",
"# cycle time has already been advanced",
"self",... | 34.764706 | 0.009885 |
def find_files(directory, pattern, recursively=True):
"""
Yield a list of files with their base directories, recursively or not.
Returns:
A list of (base_directory, filename)
Args:
directory: base directory to start the search.
pattern: fnmatch pattern for filenames.
co... | [
"def",
"find_files",
"(",
"directory",
",",
"pattern",
",",
"recursively",
"=",
"True",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"directory",
")",
":",
"for",
"basename",
"in",
"files",
":",
"if",
"fnmatch",
"... | 30.8 | 0.001575 |
def clean(self):
"""
Empties the cache
"""
self._table.clear()
for item in self._usage_recency:
self._usage_recency.remove(item) | [
"def",
"clean",
"(",
"self",
")",
":",
"self",
".",
"_table",
".",
"clear",
"(",
")",
"for",
"item",
"in",
"self",
".",
"_usage_recency",
":",
"self",
".",
"_usage_recency",
".",
"remove",
"(",
"item",
")"
] | 21.75 | 0.01105 |
def _prints_status_file(self): # pylint: disable=too-many-branches
"""
Logic behind the printing (in file) when generating status file.
"""
if PyFunceble.INTERN["file_to_test"]:
# We are testing a file.
output = (
self.output_parent_dir
... | [
"def",
"_prints_status_file",
"(",
"self",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"PyFunceble",
".",
"INTERN",
"[",
"\"file_to_test\"",
"]",
":",
"# We are testing a file.",
"output",
"=",
"(",
"self",
".",
"output_parent_dir",
"+",
"PyFunceble",
".",
... | 40.438462 | 0.001671 |
def create_payment(self, data):
""" Creates a new payment object for an order. """
return OrderPayments(self.client).on(self).create(data) | [
"def",
"create_payment",
"(",
"self",
",",
"data",
")",
":",
"return",
"OrderPayments",
"(",
"self",
".",
"client",
")",
".",
"on",
"(",
"self",
")",
".",
"create",
"(",
"data",
")"
] | 50.666667 | 0.012987 |
def query_intersections(self, x_terms=None, y_terms=None, symmetric=False):
"""
Query for intersections of terms in two lists
Return a list of intersection result objects with keys:
- x : term from x
- y : term from y
- c : count of intersection
- j : jaccard... | [
"def",
"query_intersections",
"(",
"self",
",",
"x_terms",
"=",
"None",
",",
"y_terms",
"=",
"None",
",",
"symmetric",
"=",
"False",
")",
":",
"if",
"x_terms",
"is",
"None",
":",
"x_terms",
"=",
"[",
"]",
"if",
"y_terms",
"is",
"None",
":",
"y_terms",
... | 34.04878 | 0.009053 |
def present(name,
password=None,
force=False,
tags=None,
perms=(),
runas=None):
'''
Ensure the RabbitMQ user exists.
name
User name
password
User's password, if one needs to be set
force
If user exists, forcibly cha... | [
"def",
"present",
"(",
"name",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
",",
"tags",
"=",
"None",
",",
"perms",
"=",
"(",
")",
",",
"runas",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"... | 38.895105 | 0.001227 |
def execute_reports(
config,
path,
collector,
on_report_finish=None,
output_file=None):
"""
Executes the configured suite of issue reports.
:param config: the TidyPy configuration to use
:type config: dict
:param path: that path to the project that was analyz... | [
"def",
"execute_reports",
"(",
"config",
",",
"path",
",",
"collector",
",",
"on_report_finish",
"=",
"None",
",",
"output_file",
"=",
"None",
")",
":",
"reports",
"=",
"get_reports",
"(",
")",
"for",
"report",
"in",
"config",
".",
"get",
"(",
"'requested_... | 30.166667 | 0.001071 |
def stem(self, word):
"""Return Paice-Husk stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = PaiceHusk()
>>> stmr.stem('assumption')
... | [
"def",
"stem",
"(",
"self",
",",
"word",
")",
":",
"terminate",
"=",
"False",
"intact",
"=",
"True",
"while",
"not",
"terminate",
":",
"for",
"n",
"in",
"range",
"(",
"6",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"word",
"[",
"-",
"n",
":",
"... | 27.446429 | 0.001256 |
def pick_four_unique_nodes_quickly(n, seed=None):
'''
This is equivalent to np.random.choice(n, 4, replace=False)
Another fellow suggested np.random.random_sample(n).argpartition(4) which is
clever but still substantially slower.
'''
rng = get_rng(seed)
k = rng.randint(n**4)
a = k % n
... | [
"def",
"pick_four_unique_nodes_quickly",
"(",
"n",
",",
"seed",
"=",
"None",
")",
":",
"rng",
"=",
"get_rng",
"(",
"seed",
")",
"k",
"=",
"rng",
".",
"randint",
"(",
"n",
"**",
"4",
")",
"a",
"=",
"k",
"%",
"n",
"b",
"=",
"k",
"//",
"n",
"%",
... | 37.826087 | 0.002242 |
def Reduce(self):
"""Reduce the token stack into an AST."""
# Check for sanity
if self.state != 'INITIAL' and self.state != 'BINARY':
self.Error('Premature end of expression')
length = len(self.stack)
while length > 1:
# Precedence order
self._CombineParenthesis()
self._Comb... | [
"def",
"Reduce",
"(",
"self",
")",
":",
"# Check for sanity",
"if",
"self",
".",
"state",
"!=",
"'INITIAL'",
"and",
"self",
".",
"state",
"!=",
"'BINARY'",
":",
"self",
".",
"Error",
"(",
"'Premature end of expression'",
")",
"length",
"=",
"len",
"(",
"se... | 25.608696 | 0.018003 |
def deleteData(self, offset: int, count: int) -> None:
"""Delete data by offset to count letters."""
self._delete_data(offset, count) | [
"def",
"deleteData",
"(",
"self",
",",
"offset",
":",
"int",
",",
"count",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"_delete_data",
"(",
"offset",
",",
"count",
")"
] | 49 | 0.013423 |
def get_customer(self, customer_id):
"""
Queries the information related to the customer.
Args:
customer_id: Identifier of the client from which you want to find the associated information.
Returns:
"""
return self.client._get(self.url + 'customers/{}'.form... | [
"def",
"get_customer",
"(",
"self",
",",
"customer_id",
")",
":",
"return",
"self",
".",
"client",
".",
"_get",
"(",
"self",
".",
"url",
"+",
"'customers/{}'",
".",
"format",
"(",
"customer_id",
")",
",",
"headers",
"=",
"self",
".",
"get_headers",
"(",
... | 32.181818 | 0.010989 |
def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
""" Search for a object of given type in the database. """
fields = table.get_fields()
db_fields = {
name: field
for name, fie... | [
"def",
"search",
"(",
"table",
":",
"LdapObjectClass",
",",
"query",
":",
"Optional",
"[",
"Q",
"]",
"=",
"None",
",",
"database",
":",
"Optional",
"[",
"Database",
"]",
"=",
"None",
",",
"base_dn",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",... | 32.357143 | 0.002144 |
def _iterdump(connection):
"""
Returns an iterator to the dump of the database in an SQL text format.
Used to produce an SQL dump of the database. Useful to save an in-memory
database for later restoration. This function should not be called
directly but instead called from the Connection method,... | [
"def",
"_iterdump",
"(",
"connection",
")",
":",
"cu",
"=",
"connection",
".",
"cursor",
"(",
")",
"yield",
"(",
"'BEGIN TRANSACTION;'",
")",
"# sqlite_master table contains the SQL CREATE statements for the database.",
"q",
"=",
"\"\"\"\n SELECT \"name\", \"type\", \"... | 38.327869 | 0.001668 |
def get_r_df(self):
''' getter '''
if isinstance(self.__r_df, pd.DataFrame) is False and self.__r_df is not None:
raise TypeError("The type of `__r_df` must be `pd.DataFrame`.")
return self.__r_df | [
"def",
"get_r_df",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"__r_df",
",",
"pd",
".",
"DataFrame",
")",
"is",
"False",
"and",
"self",
".",
"__r_df",
"is",
"not",
"None",
":",
"raise",
"TypeError",
"(",
"\"The type of `__r_df` must be `p... | 45.6 | 0.012931 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.