code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
wb = Workbook()
title = re.sub(r'\W+', '', title)[:30]
if isinstance(data, dict):
i = 0
for sheet_name, sheet_data in data.items():
if i > 0:
wb.create_sheet()
ws = wb.worksheets[i]
build_sheet(
sheet_data, ws, sheet_n... | def list_to_workbook(data, title='report', header=None, widths=None) | Create just a openpxl workbook from a list of data | 2.451219 | 2.561642 | 0.956893 |
title = generate_filename(title, '.xlsx')
myfile = BytesIO()
myfile.write(save_virtual_workbook(wb))
response = HttpResponse(
myfile.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filen... | def build_xlsx_response(wb, title="report") | Take a workbook and return a xlsx file response | 2.26 | 2.158574 | 1.046988 |
wb = list_to_workbook(data, title, header, widths)
return build_xlsx_response(wb, title=title) | def list_to_xlsx_response(data, title='report', header=None,
widths=None) | Make 2D list into a xlsx response for download
data can be a 2d array or a dict of 2d arrays
like {'sheet_1': [['A1', 'B1']]} | 3.52297 | 4.775122 | 0.737776 |
response = HttpResponse(content_type="text/csv; charset=UTF-8")
cw = csv.writer(response)
for row in chain([header] if header else [], data):
cw.writerow([force_text(s).encode(response.charset) for s in row])
return response | def list_to_csv_response(data, title='report', header=None, widths=None) | Make 2D list into a csv response for download data. | 2.944975 | 3.020586 | 0.974968 |
for line in iterate(lines):
prefix = suffix = ''
if line.first and line.last:
prefix = format.single.prefix
suffix = format.single.suffix
else:
prefix = format.multiple.prefix if line.first else format.intra.prefix
suffix = format.multiple.suffix if line.last else format.intra.suffi... | def wrap(scope, lines, format=BARE_FORMAT) | Wrap a stream of lines in armour.
Takes a stream of lines, for example, the following single line:
Line(1, "Lorem ipsum dolor.")
Or the following multiple lines:
Line(1, "Lorem ipsum")
Line(2, "dolor")
Line(3, "sit amet.")
Provides a generator of wrapped lines. For a single line, the f... | 4.365326 | 3.231352 | 1.350929 |
try:
line = input.next()
except StopIteration:
return
lead = True
buffer = []
# Gather contiguous (uninterrupted) lines of template text.
while line.kind == 'text':
value = line.line.rstrip().rstrip('\\') + ('' if line.continued else '\n')
if lead and line.stripped:
yield Lin... | def gather(input) | Collect contiguous lines of text, preserving line numbers. | 3.669299 | 3.39413 | 1.081072 |
handler = None
for line in lines:
for chunk in chunk_(line):
if 'strip' in context.flag:
chunk.line = chunk.stripped
if not chunk.line: continue # Eliminate empty chunks, i.e. trailing text segments, ${}, etc.
if not handler or handler[0] != chunk.kind:
if handler:
... | def process(self, context, lines) | Chop up individual lines into static and dynamic parts.
Applies light optimizations, such as empty chunk removal, and calls out to other methods to process different
chunk types.
The processor protocol here requires the method to accept values by yielding resulting lines while accepting
sent chunks. Defer... | 4.511414 | 4.491811 | 1.004364 |
result = None
while True:
chunk = yield None
if chunk is None:
if result:
yield result.clone(line=repr(result.line))
return
if not result:
result = chunk
continue
result.line += chunk.line | def process_text(self, kind, context) | Combine multiple lines of bare text and emit as a Python string literal. | 4.491146 | 3.929079 | 1.143053 |
result = None
while True:
chunk = yield result
if chunk is None:
return
result = chunk.clone(line='_' + kind + '(' + chunk.line + ')') | def process_generic(self, kind, context) | Transform otherwise unhandled kinds of chunks by calling an underscore prefixed function by that name. | 7.277 | 5.500573 | 1.322953 |
result = None
while True:
chunk = yield result
if chunk is None:
return
# We need to split the expression defining the format string from the values to pass when formatting.
# We want to allow any Python expression, so we'll need to piggyback on Python's own parser in order
# to ... | def process_format(self, kind, context) | Handle transforming format string + arguments into Python code. | 8.389109 | 7.992186 | 1.049664 |
if username != None:
return next((player for player in self.players if player.name == username), None)
else:
return None | def find_player(self, username: str = None) | Find the :class:`~.Player` with the given properties
Returns the player whose attributes match the given properties, or
``None`` if no match is found.
:param username: The username of the Player | 3.235014 | 4.934537 | 0.655586 |
if color != None:
if color is Team.Color.BLUE:
return self.blue_team
else:
return self.orange_team
else:
return None | def find_team(self, color: str = None) | Find the :class:`~.Team` with the given properties
Returns the team whose attributes match the given properties, or
``None`` if no match is found.
:param color: The :class:`~.Team.Color` of the Team | 4.63016 | 5.17548 | 0.894634 |
# The exact ordering of the address component fields that should be
# used to reconstruct the full street address is not specified in the
# Esri documentation, but the examples imply that it is this.
ordered_fields = ['AddNum', 'StPreDir', 'StPreType', 'StName', 'StType', 'StDir... | def _street_addr_from_response(self, attributes) | Construct a street address (no city, region, etc.) from a geocoder response.
:param attributes: A dict of address attributes as returned by the Esri geocoder. | 5.815847 | 5.837287 | 0.996327 |
endpoint = 'https://www.arcgis.com/sharing/rest/oauth2/token/'
query = {'client_id': self._client_id,
'client_secret': self._client_secret,
'grant_type': 'client_credentials'}
if expires is not None:
if not isinstance(expires, timedelta):
... | def get_token(self, expires=None) | :param expires: The time until the returned token expires.
Must be an instance of :class:`datetime.timedelta`.
If not specified, the token will expire in 2 hours.
:returns: A token suitable for use with the Esri geocoding API | 2.722357 | 2.72435 | 0.999269 |
pq.query = self.replace_range(pq.query)
pq.address = self.replace_range(pq.address)
return pq | def process(self, pq) | :arg PlaceQuery pq: PlaceQuery instance
:returns: PlaceQuery instance with truncated address range / number | 6.353871 | 5.280677 | 1.20323 |
if pq.query != '':
postcode = address = city = '' # define the vars we'll use
# global regex postcode search, pop off last result
postcode_matches = self.re_UK_postcode.findall(pq.query)
if len(postcode_matches) > 0:
postcode = postcode_... | def process(self, pq) | :arg PlaceQuery pq: PlaceQuery instance
:returns: PlaceQuery instance with :py:attr:`query`
converted to individual elements | 4.385086 | 4.343855 | 1.009492 |
# Map country, but don't let map overwrite
if pq.country not in self.acceptable_countries and pq.country in self.country_map:
pq.country = self.country_map[pq.country]
if pq.country != '' and \
self.acceptable_countries != [] and \
pq.country not in sel... | def process(self, pq) | :arg PlaceQuery pq: PlaceQuery instance
:returns: modified PlaceQuery, or ``False`` if country is not acceptable. | 4.75437 | 3.916501 | 1.213933 |
if pq.country.strip() == '':
if self.default_country == '':
return False
else:
pq.country = self.default_country
return pq | def process(self, pq) | :arg PlaceQuery pq: PlaceQuery instance
:returns: One of the three following values:
* unmodified PlaceQuery instance if pq.country is not empty
* PlaceQuery instance with pq.country changed to default country.
* ``False`` if pq.country is empty and self.... | 5.524601 | 2.369497 | 2.33155 |
# Same caveat as above regarding the ordering of these fields; the
# documentation is not explicit about the correct ordering for
# reconstructing a full address, but implies that this is the ordering.
ordered_fields = ['preQualifier', 'preDirection', 'preType', 'streetName',
... | def _street_addr_from_response(self, match) | Construct a street address (no city, region, etc.) from a geocoder response.
:param match: The match object returned by the geocoder. | 6.346999 | 6.219227 | 1.020545 |
self.make_body_seekable()
env = self.environ.copy()
new_req = self.__class__(env, *args, **kwargs)
new_req.copy_body()
new_req.identity = self.identity
return new_req | def copy(self, *args, **kwargs) | Copy the request and environment object.
This only does a shallow copy, except of wsgi.input | 5.127216 | 3.672299 | 1.396187 |
geocode_service = self._get_service_by_name(source[0])
self._sources.append(geocode_service(**source[1])) | def add_source(self, source) | Add a geocoding service to this instance. | 6.896372 | 4.25255 | 1.621703 |
geocode_service = self._get_service_by_name(source[0])
self._sources.remove(geocode_service(**source[1])) | def remove_source(self, source) | Remove a geocoding service from this instance. | 8.664581 | 4.819382 | 1.797861 |
if len(sources) == 0:
raise Exception('Must declare at least one source for a geocoder')
self._sources = []
for source in sources: # iterate through a list of sources
self.add_source(source) | def set_sources(self, sources) | Creates GeocodeServiceConfigs from each str source | 5.051107 | 4.222168 | 1.19633 |
waterfall = self.waterfall if waterfall is None else waterfall
if type(pq) in (str, str):
pq = PlaceQuery(pq)
processed_pq = copy.copy(pq)
for p in self._preprocessors: # apply universal address preprocessing
processed_pq = p.process(processed_pq)
... | def geocode(self, pq, waterfall=None, force_stats_logging=False) | :arg PlaceQuery pq: PlaceQuery object (required).
:arg bool waterfall: Boolean set to True if all geocoders listed should
be used to find results, instead of stopping after
the first geocoding service with valid candidates
(... | 3.874408 | 3.392119 | 1.14218 |
for key, val in schema_params.items():
if key not in params:
continue
if isinstance(val, dict):
self._apply_param_actions(params[key], schema_params[key])
elif isinstance(val, ResourceId):
resource_id = val
... | def _apply_param_actions(self, params, schema_params) | Traverse a schema and perform the updates it describes to params. | 4.22152 | 4.113882 | 1.026165 |
tstart = datetime.now()
v = validator.Validator(self.vcf_file)
std = v.run()
if std == 0:
self.is_validated = True
tend = datetime.now()
execution_time = tend - tstart | def validator(self) | VCF Validator | 6.565969 | 6.011087 | 1.09231 |
# logging.info('Starting Sanity Check...')
tstart = datetime.now()
# command = 'python %s/sanity_check.py -i %s' % (scripts_dir, self.vcf_file)
# self.shell(command)
sc = sanity_check.Sanity_check(self.vcf_file)
std = sc.run()
tend = datetime.now()
... | def sanitycheck(self) | Search and Remove variants with [0/0, ./.]
Search and Replace chr from the beggining of the chromossomes to get positionning.
Sort VCF by 1...22, X, Y, MT and nothing else
#Discard other variants | 5.074826 | 4.622281 | 1.097905 |
# calculate time thread took to finish
# logging.info('Starting snpEff')
tstart = datetime.now()
se = snpeff.Snpeff(self.vcf_file)
std = se.run()
tend = datetime.now()
execution_time = tend - tstart | def snpeff(self) | Annotation with snpEff | 8.300233 | 7.795634 | 1.064728 |
# calculate time thread took to finish
# logging.info('Starting VEP ')
tstart = datetime.now()
vep_obj = vep.Vep(self.vcf_file)
std = vep_obj.run()
# command = 'python %s/vep.py -i sanity_check/checked.vcf' % (scripts_dir)
# self.shell(command)
... | def vep(self) | VEP | 6.044252 | 6.050908 | 0.9989 |
# calculate time thread took to finish
# logging.info('Starting HI score')
tstart = datetime.now()
decipher_obj = decipher.Decipher(self.vcf_file)
decipher_obj.run()
tend = datetime.now()
execution_time = tend - tstart | def decipher(self) | Decipher | 11.546089 | 11.280334 | 1.023559 |
# calculate time thread took to finish
# logging.info('Starting HI score')
tstart = datetime.now()
if os.path.isfile(settings.hgmd_file):
hgmd_obj = hgmd.HGMD(self.vcf_file)
hgmd_obj.run()
tend = datetime.now()
execution_time = tend ... | def hgmd(self) | Hi Index | 9.743521 | 9.588944 | 1.01612 |
tstart = datetime.now()
# command = 'python %s/snpsift.py -i sanity_check/checked.vcf 2>log/snpsift.log' % (scripts_dir)
# self.shell(command)
ss = snpsift.SnpSift(self.vcf_file)
ss.run()
tend = datetime.now()
execution_time = tend - tstart | def snpsift(self) | SnpSift | 5.815565 | 5.890156 | 0.987336 |
tstart = datetime.now()
# python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genomes/ALL.wgs.integrated_phase1_v3.20101123.snps_indels_sv.sites.vcf.gz ../data/dbsnp138/00-All.vcf.gz ../data/dbsnp138/clinvar_00-latest.vcf.gz .... | def vcf_annotator(self) | Vcf annotator | 3.729713 | 3.724026 | 1.001527 |
tstart = datetime.now()
# python ../scripts/annotate_vcfs.py -i mm13173_14.ug.target1.vcf -r 1000genomes dbsnp138 clinvar esp6500 -a ../data/1000genomes/ALL.wgs.integrated_phase1_v3.20101123.snps_indels_sv.sites.vcf.gz ../data/dbsnp138/00-All.vcf.gz ../data/dbsnp138/clinvar_00-latest.vcf.gz .... | def dbnsfp(self) | dbnsfp | 7.143035 | 7.052542 | 1.012831 |
if app is None and settings is None:
print('Either --app or --settings must be supplied')
ctx.ensure_object(dict)
ctx.obj['app'] = app
ctx.obj['settings'] = settings | def cli(ctx, settings, app) | Manage Morp application services | 3.195492 | 3.122027 | 1.023531 |
if required_settings is not None:
for keyname in required_settings:
if keyname not in self._settings:
return keyname
if accept_none is False and self._settings[keyname] is None:
return keyname
return True | def _settings_checker(self, required_settings=None, accept_none=True) | Take a list of required _settings dictionary keys
and make sure they are set. This can be added to a custom
constructor in a subclass and tested to see if it returns ``True``.
:arg list required_settings: A list of required keys to look for.
:arg bool accept_none: Boolean set to True if... | 2.694992 | 2.832292 | 0.951523 |
timeout_secs = self._settings.get('timeout', 10)
headers = self._settings.get('request_headers', {})
try:
if is_post:
response = requests.post(
endpoint, data=query, headers=headers, timeout=timeout_secs)
else:
... | def _get_response(self, endpoint, query, is_post=False) | Returns response or False in event of failure | 2.1401 | 2.093154 | 1.022428 |
response = self._get_response(endpoint, query, is_post=is_post)
content = response.text
try:
return loads(content)
except ValueError:
raise Exception('Could not decode content to JSON:\n%s'
% self.__class__.__name__, content) | def _get_json_obj(self, endpoint, query, is_post=False) | Return False if connection could not be made.
Otherwise, return a response object from JSON. | 4.022207 | 3.950605 | 1.018124 |
response = self._get_response(endpoint, query, is_post=is_post)
return minidom.parse(response.text) | def _get_xml_doc(self, endpoint, query, is_post=False) | Return False if connection could not be made.
Otherwise, return a minidom Document. | 3.425779 | 3.034793 | 1.128835 |
processed_pq = copy.copy(pq)
for p in self._preprocessors:
processed_pq = p.process(processed_pq)
if not processed_pq:
return [], None
upstream_response_info = UpstreamResponseInfo(self.get_service_name(),
... | def geocode(self, pq) | :arg PlaceQuery pq: PlaceQuery instance
:rtype: tuple
:returns: post-processed list of Candidate objects and
and UpstreamResponseInfo object if an API call was made.
Examples:
Preprocessor throws out request::
([], None)
... | 3.444166 | 2.993875 | 1.150404 |
for c in candidates[:]:
if c.locator not in self.good_locators:
# TODO: search string, i.e. find "EU_Street_Name" in "EU_Street_Name.GBR_StreetName"
candidates.remove(c)
return candidates | def process(self, candidates) | :arg list candidates: list of Candidate instances | 11.756581 | 10.764692 | 1.092143 |
ordered_candidates = []
# make a new list of candidates in order of ordered_locators
for locator in self.ordered_locators:
for uc in unordered_candidates[:]:
if uc.locator == locator:
ordered_candidates.append(uc)
unord... | def process(self, unordered_candidates) | :arg list candidates: list of Candidate instances | 4.099648 | 3.869072 | 1.059595 |
high_score_candidates = [c for c in candidates if c.score >= self.min_score]
if high_score_candidates != []:
return high_score_candidates
return candidates | def process(self, candidates) | :arg list candidates: list of Candidates
:returns: list of Candidates where score is at least min_score,
if and only if one or more Candidates have at least min_score.
Otherwise, returns original list of Candidates. | 3.300362 | 2.747247 | 1.201334 |
return sorted(candidates, key=attrgetter('score'), reverse=self.reverse) | def process(self, candidates) | :arg list candidates: list of Candidates
:returns: score-sorted list of Candidates | 5.483791 | 4.495692 | 1.219788 |
lat1, lon1 = pnt1
lat2, lon2 = pnt2
radius = 6356752 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2) * math.sin(dlat / 2) + math.cos(math.radians(lat1)) \
* math.cos(math.radians(lat2)) * math.sin(dlon / ... | def _get_distance(self, pnt1, pnt2) | Get distance in meters between two lat/long points | 1.326347 | 1.280627 | 1.035701 |
if self._get_distance(pnt1, pnt2) <= self.distance:
return True
return False | def _points_within_distance(self, pnt1, pnt2) | Returns true if lat/lon points are within given distance in metres. | 3.741326 | 3.420665 | 1.093742 |
candidate = Candidate()
candidate.match_addr = result['formatted_address']
candidate.x = result['geometry']['location']['lng']
candidate.y = result['geometry']['location']['lat']
candidate.locator = self.LOCATOR_MAPPING.get(result['geometry']['location_type'], '')
... | def _make_candidate_from_result(self, result) | Make a Candidate from a Google geocoder results dictionary. | 2.69029 | 2.397275 | 1.122228 |
for component in result['address_components']:
if lookup['type'] in component['types']:
return component.get(lookup['key'], '')
return '' | def _get_component_from_result(self, result, lookup) | Helper function to get a particular address component from a Google result.
Since the address components in results are an array of objects containing a types array,
we have to search for a particular component rather than being able to look it up directly.
Returns the first match, so this sho... | 5.30288 | 3.618803 | 1.465368 |
print('Installing Requirements')
print(platform.dist())
if platform.dist()[0] in ['Ubuntu', 'LinuxMint']:
command = 'sudo apt-get install -y gcc git python3-dev zlib1g-dev make zip libssl-dev libbz2-dev liblzma-dev libcurl4-openssl-dev build-essential libxml2-dev apache2 zli... | def install_requirements(self) | Install Ubuntu Requirements | 4.767612 | 4.716352 | 1.010869 |
raise NotImplementedError | def search(self, query: Optional[dict] = None, offset: Optional[int] = None,
limit: Optional[int] = None,
order_by: Union[None, list, tuple] = None) -> Sequence['IModel'] | return search result based on specified rulez query | 750.273743 | 242.414307 | 3.095006 |
raise NotImplementedError | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Union[None, list, tuple] = None) -> list | return aggregation result based on specified rulez query and group | 6,640.106445 | 724.111328 | 9.170008 |
raise NotImplementedError | def put_blob(self, field: str, fileobj: BinaryIO,
filename: str,
mimetype: Optional[str] = None,
size: Optional[int] = None,
encoding: Optional[str] = None) -> IBlob | Receive and store blob object | 1,240.396729 | 470.706757 | 2.635179 |
def before_blobput(self, field: str, fileobj: BinaryIO,
filename: str,
mimetype: Optional[str] = None,
size: Optional[int] = None,
encoding: Optional[str] = None) -> None | Triggered before BLOB is stored | 10,241,808 | 173,745.140625 | 58.947306 | |
raise NotImplementedError | def search(self, query: Optional[dict] = None,
offset: int = 0,
limit: Optional[int] = None,
order_by: Optional[tuple] = None,
secure: bool = False) -> List[IModel] | Search for models
Filtering is done through ``rulez`` based JSON/dict query, which
defines boolean statements in JSON/dict structure.
: param query: Rulez based query
: param offset: Result offset
: param limit: Maximum number of result
: param order_by: Tuple of ``(fie... | 816.153748 | 7,110.66748 | 0.114779 |
raise NotImplementedError | def aggregate(self, query: Optional[dict] = None,
group: Optional[dict] = None,
order_by: Optional[tuple] = None) -> List[IModel] | Get aggregated results
: param query: Rulez based query
: param group: Grouping structure
: param order_by: Tuple of ``(field, order)`` where ``order`` is
``'asc'`` or ``'desc'``
: todo: Grouping structure need to be documented | 826.297729 | 3,780.136475 | 0.218589 |
response = requests.get(self._gamestate_url)
response_text = response.text.rstrip('\0')
return json.loads(response_text) | def fetch_state_data(self) | Fetch the raw JSON game state data from EchoVR's ``/session`` API
This method could be useful if you want to retrieve some API data not
directly exposed by this Python wrapper. Otherwise, you should probably
use :meth:`fetch_state` instead.
:returns:
An object (probably a :... | 6.000723 | 6.162665 | 0.973722 |
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.bottom, vb.left, vb.top, vb.right) | def to_bing_str(self) | Convert Viewbox object to a string that can be used by Bing
as a query parameter. | 5.904047 | 4.38752 | 1.345646 |
vb = self.convert_srs(4326)
return {
'boundary.rect.min_lat': vb.bottom,
'boundary.rect.min_lon': vb.left,
'boundary.rect.max_lat': vb.top,
'boundary.rect.max_lon': vb.right
} | def to_pelias_dict(self) | Convert Viewbox object to a string that can be used by Pelias
as a query parameter. | 3.482226 | 3.02831 | 1.149891 |
vb = self.convert_srs(4326)
return '%s,%s|%s,%s' % (vb.bottom, vb.left, vb.top, vb.right) | def to_google_str(self) | Convert to Google's bounds format: 'latMin,lonMin|latMax,lonMax' | 6.573897 | 4.23378 | 1.552725 |
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.left, vb.top, vb.right, vb.bottom) | def to_mapquest_str(self) | Convert Viewbox object to a string that can be used by
`MapQuest <http://www.mapquestapi.com/geocoding/#options>`_
as a query parameter. | 5.463822 | 4.55334 | 1.199959 |
try:
return ('{ "xmin" : %s, '
'"ymin" : %s, '
'"xmax" : %s, '
'"ymax" : %s, '
'"spatialReference" : {"wkid" : %d} }'
% (self.left,
self.bottom,
... | def to_esri_wgs_json(self) | Convert Viewbox object to a JSON string that can be used
by the ESRI World Geocoding Service as a parameter. | 3.140913 | 2.98234 | 1.05317 |
data = request.json
res = validate(data, dataclass_to_jsl(
RegistrationSchema).get_schema())
if res:
@request.after
def set_error(response):
response.status = 422
return {
'status': 'error',
'field_errors': [{'message': res[x]} for x i... | def register(context, request, load) | Validate the username and password and create the user. | 4.637972 | 4.611065 | 1.005835 |
username = request.json['username']
password = request.json['password']
# Do the password validation.
user = context.authenticate(username, password)
if not user:
@request.after
def adjust_status(response):
response.status = 401
return {
'status'... | def process_login(context, request) | Authenticate username and password and log in user | 3.58084 | 3.640405 | 0.983638 |
@request.after
def forget(response):
request.app.forget_identity(response, request)
return {
'status': 'success'
} | def logout(context, request) | Log out the user. | 11.70385 | 11.230655 | 1.042134 |
method = getattr(requests, method)
response = method(
url,
headers=self.headers,
data=self.process_json_for_cloudflare(data) if data else None
)
content = response.json()
if response.status_code != 200:
print(content)
... | def request(self, url, method, data=None) | The requester shortcut to submit a http request to CloutFlare
:param url:
:param method:
:param data:
:return: | 3.163736 | 3.648983 | 0.867018 |
# Initialize current zone
zones_content = self.request(self.api_url, 'get')
try:
if len(self.domain.split('.')) == 3:
domain = self.domain.split('.', 1)[1]
else:
domain = self.domain
zone = [zone for zone in zones_conte... | def setup_zone(self) | Setup zone for current domain.
It will also setup the dns records of the zone
:return: | 3.26499 | 3.055926 | 1.068413 |
try:
record = [record for record in self.dns_records
if record['type'] == dns_type and record['name'] == name][0]
except IndexError:
raise RecordNotFound(
'Cannot find the specified dns record in domain {domain}'
.for... | def get_record(self, dns_type, name) | Get a dns record
:param dns_type:
:param name:
:return: | 3.229982 | 3.289514 | 0.981902 |
data = {
'type': dns_type,
'name': name,
'content': content
}
if kwargs.get('ttl') and kwargs['ttl'] != 1:
data['ttl'] = kwargs['ttl']
if kwargs.get('proxied') is True:
data['proxied'] = True
else:
d... | def create_record(self, dns_type, name, content, **kwargs) | Create a dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: | 2.494976 | 2.545982 | 0.979966 |
record = self.get_record(dns_type, name)
data = {
'type': dns_type,
'name': name,
'content': content
}
if kwargs.get('ttl') and kwargs['ttl'] != 1:
data['ttl'] = kwargs['ttl']
if kwargs.get('proxied') is True:
d... | def update_record(self, dns_type, name, content, **kwargs) | Update dns record
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: | 2.431422 | 2.482029 | 0.979611 |
try:
return self.update_record(dns_type, name, content, **kwargs)
except RecordNotFound:
return self.create_record(dns_type, name, content, **kwargs) | def create_or_update_record(self, dns_type, name, content, **kwargs) | Create a dns record. Update it if the record already exists.
:param dns_type:
:param name:
:param content:
:param kwargs:
:return: | 1.976557 | 2.296521 | 0.860675 |
record = self.get_record(dns_type, name)
content = self.request(
urllib.parse.urljoin(self.api_url, self.zone['id'] + '/dns_records/' + record['id']),
'delete'
)
return content['result']['id'] | def delete_record(self, dns_type, name) | Delete a dns record
:param dns_type:
:param name:
:return: | 3.845496 | 4.095826 | 0.938882 |
ip_address = ''
for finder in self.public_ip_finder:
try:
result = requests.get(finder)
except requests.RequestException:
continue
if result.status_code == 200:
try:
socket.inet_aton(result.t... | def sync_dns_from_my_ip(self, dns_type='A') | Sync dns from my public ip address.
It will not do update if ip address in dns record is already same as
current public ip address.
:param dns_type:
:return: | 2.158287 | 2.125136 | 1.015599 |
for k in vars_:
if k == 'kwargs':
for kwarg in vars_[k]:
setattr(self, kwarg, vars_[k][kwarg])
elif k != 'self':
setattr(self, k, vars_[k]) | def _init_helper(self, vars_) | Overwrite defaults (if they exist) with arguments passed to constructor | 2.522926 | 2.275163 | 1.108899 |
members = context.members()
return {
'users': [{
'username': m.identifier,
'userid': m.userid,
'roles': context.get_member_roles(m.userid),
'links': [rellink(m, request)]
} for m in members]
} | def list_members(context, request) | Return the list of users in the group. | 4.732601 | 4.662419 | 1.015053 |
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
... | def grant_member(context, request) | Grant member roles in the group. | 2.614206 | 2.5023 | 1.044721 |
mapping = request.json['mapping']
for entry in mapping:
user = entry['user']
roles = entry['roles']
username = user.get('username', None)
userid = user.get('userid', None)
if userid:
u = context.get_user_by_userid(userid)
elif username:
... | def revoke_member(context, request) | Revoke member roles in the group. | 2.89304 | 2.560576 | 1.12984 |
if mediainfo_path is None:
mediainfo_path = find_MediaInfo()
result = subprocess.check_output(
[mediainfo_path, "-f", file_name], universal_newlines=True
)
D = collections.defaultdict(dict)
for line in result.splitlines():
line = line.split(':', 1)
# Skip separa... | def call_MediaInfo(file_name, mediainfo_path=None) | Returns a dictionary of dictionaries with the output of
MediaInfo -f file_name | 2.606353 | 2.515362 | 1.036174 |
D = call_MediaInfo(file_name, mediainfo_path)
err_msg = "Could not determine all video paramters"
if ("General" not in D) or ("Video" not in D):
raise MediaInfoError(err_msg)
general_keys = ("Count of audio streams", "File size", "Overall bit rate")
if any(k not in D["General"] for k ... | def check_video(file_name, mediainfo_path=None) | Scans the given file with MediaInfo and returns the video and audio codec
information if all the required parameters were found. | 3.708943 | 3.627695 | 1.022396 |
D = call_MediaInfo(file_name, mediainfo_path)
# Check that the file analyzed was a valid movie
if (
("Image" not in D) or
("Width" not in D["Image"]) or
("Height" not in D["Image"])
):
raise MediaInfoError("Could not determine all picture paramters")
return D | def check_picture(file_name, mediainfo_path=None) | Scans the given file with MediaInfo and returns the picture
information if all the required parameters were found. | 6.891976 | 6.04505 | 1.140102 |
with open(file_path, "rb") as infile:
checksum = hashlib.md5()
while 1:
data = infile.read(chunk_bytes)
if not data:
break
checksum.update(data)
return checksum.hexdigest() | def md5_checksum(file_path, chunk_bytes=4194304) | Return the MD5 checksum (hex digest) of the file | 1.865983 | 1.939655 | 0.962018 |
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxsize
for line in lines[1:]:
... | def trim(docstring) | Remove the tabs to spaces, and remove the extra spaces / tabs that are in
front of the text in docstrings.
Implementation taken from http://www.python.org/dev/peps/pep-0257/ | 1.336785 | 1.347126 | 0.992324 |
schema = DottedNameResolver(__name__).maybe_resolve(schema)
def _filter(attr):
if not hasattr(attr, "location"):
valid_location = 'body' in location
else:
valid_location = attr.location in to_list(location)
return valid_locati... | def _get_attributes(schema, location) | Return the schema's children, filtered by location. | 6.626364 | 5.330593 | 1.243082 |
'''
A decorator wrapper for :class:`ServerMainContextManager`
Usage example:
.. code:: python
@aiotools.main
def mymain():
server_args = do_init()
stop_sig = yield server_args
if stop_sig == signal.SIGINT:
do_graceful_shutdown()
... | def _main_ctxmgr(func) | A decorator wrapper for :class:`ServerMainContextManager`
Usage example:
.. code:: python
@aiotools.main
def mymain():
server_args = do_init()
stop_sig = yield server_args
if stop_sig == signal.SIGINT:
do_graceful_shutdown()
else:
... | 4.81339 | 1.53155 | 3.142822 |
self.lease = self.client.lease(self.ttl)
base64_key = _encode(self.key)
base64_value = _encode(self._uuid)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'CREATE',
'create_revisio... | def acquire(self) | Acquire the lock. | 3.330386 | 3.28618 | 1.013452 |
base64_key = _encode(self.key)
base64_value = _encode(self._uuid)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'VALUE',
'value': base64_value
}],
'success': [{
... | def release(self) | Release the lock | 4.230972 | 4.188926 | 1.010037 |
values = self.client.get(self.key)
return six.b(self._uuid) in values | def is_acquired(self) | Check if the lock is acquired | 15.945616 | 12.378174 | 1.288204 |
'''
Analogous to the builtin :func:`iter()`.
'''
if sentinel is _sentinel:
# Since we cannot directly return the return value of obj.__aiter__()
# as being an async-generator, we do the async-iteration here.
async for item in obj:
yield item
else:
while T... | async def aiter(obj, sentinel=_sentinel) | Analogous to the builtin :func:`iter()`. | 6.120224 | 4.637993 | 1.319584 |
return Etcd3Client(host=host,
port=port,
ca_cert=ca_cert,
cert_key=cert_key,
cert_cert=cert_cert,
timeout=timeout,
protocol=protocol) | def client(host='localhost', port=2379,
ca_cert=None, cert_key=None, cert_cert=None,
timeout=None, protocol="http") | Return an instance of an Etcd3Client. | 1.84927 | 1.627076 | 1.13656 |
host = ('[' + self.host + ']' if (self.host.find(':') != -1)
else self.host)
base_url = self.protocol + '://' + host + ':' + str(self.port)
return base_url + '/v3alpha/' + path.lstrip("/") | def get_url(self, path) | Construct a full url to the v3alpha API given a specific path
:param path:
:return: url | 3.977766 | 3.77271 | 1.054352 |
try:
resp = self.session.post(*args, **kwargs)
if resp.status_code in _EXCEPTIONS_BY_CODE:
raise _EXCEPTIONS_BY_CODE[resp.status_code](resp.reason)
if resp.status_code != requests.codes['ok']:
raise exceptions.Etcd3Exception(resp.reaso... | def post(self, *args, **kwargs) | helper method for HTTP POST
:param args:
:param kwargs:
:return: json response | 2.474219 | 2.512516 | 0.984757 |
result = self.post(self.get_url("/lease/grant"),
json={"TTL": ttl, "ID": 0})
return Lease(int(result['ID']), client=self) | def lease(self, ttl=DEFAULT_TIMEOUT) | Create a Lease object given a timeout
:param ttl: timeout
:return: Lease object | 8.565424 | 8.758846 | 0.977917 |
return Lock(id, ttl=ttl, client=self) | def lock(self, id=str(uuid.uuid4()), ttl=DEFAULT_TIMEOUT) | Create a Lock object given an ID and timeout
:param id: ID for the lock, creates a new uuid if not provided
:param ttl: timeout
:return: Lock object | 9.756687 | 14.876355 | 0.655852 |
base64_key = _encode(key)
base64_value = _encode(value)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'CREATE',
'create_revision': 0
}],
'success': [{
... | def create(self, key, value) | Atomically create the given key only if the key doesn't exist.
This verifies that the create_revision of a key equales to 0, then
creates the key with the value.
This operation takes place in a transaction.
:param key: key in etcd to create
:param value: value of the key
... | 3.291848 | 2.807918 | 1.172345 |
payload = {
"key": _encode(key),
"value": _encode(value)
}
if lease:
payload['lease'] = lease.id
self.post(self.get_url("/kv/put"), json=payload)
return True | def put(self, key, value, lease=None) | Put puts the given key into the key-value store.
A put request increments the revision of the key-value store
and generates one event in the event history.
:param key:
:param value:
:param lease:
:return: boolean | 3.710173 | 3.973592 | 0.933708 |
try:
order = 0
if sort_order:
order = _SORT_ORDER.index(sort_order)
except ValueError:
raise ValueError('sort_order must be one of "ascend" or "descend"')
try:
target = 0
if sort_target:
target ... | def get(self, key, metadata=False, sort_order=None,
sort_target=None, **kwargs) | Range gets the keys in the range from the key-value store.
:param key:
:param metadata:
:param sort_order: 'ascend' or 'descend' or None
:param sort_target: 'key' or 'version' or 'create' or 'mod' or 'value'
:param kwargs:
:return: | 2.452662 | 2.18516 | 1.122417 |
return self.get(
key=_encode(b'\0'),
metadata=True,
sort_order=sort_order,
sort_target=sort_target,
range_end=_encode(b'\0'),
) | def get_all(self, sort_order=None, sort_target='key') | Get all keys currently stored in etcd.
:returns: sequence of (value, metadata) tuples | 5.21571 | 5.23009 | 0.997251 |
return self.get(key_prefix,
metadata=True,
range_end=_encode(_increment_last_byte(key_prefix)),
sort_order=sort_order,
sort_target=sort_target) | def get_prefix(self, key_prefix, sort_order=None, sort_target=None) | Get a range of keys with a prefix.
:param sort_order: 'ascend' or 'descend' or None
:param key_prefix: first key in range
:returns: sequence of (value, metadata) tuples | 5.119316 | 5.24059 | 0.976859 |
base64_key = _encode(key)
base64_initial_value = _encode(initial_value)
base64_new_value = _encode(new_value)
txn = {
'compare': [{
'key': base64_key,
'result': 'EQUAL',
'target': 'VALUE',
'value': base6... | def replace(self, key, initial_value, new_value) | Atomically replace the value of a key with a new value.
This compares the current value of a key, then replaces it with a new
value if it is equal to a specified value. This operation takes place
in a transaction.
:param key: key in etcd to replace
:param initial_value: old val... | 2.530491 | 2.4557 | 1.030456 |
payload = {
"key": _encode(key),
}
payload.update(kwargs)
result = self.post(self.get_url("/kv/deleterange"),
json=payload)
if 'deleted' in result:
return True
return False | def delete(self, key, **kwargs) | DeleteRange deletes the given range from the key-value store.
A delete request increments the revision of the key-value store and
generates a delete event in the event history for every deleted key.
:param key:
:param kwargs:
:return: | 5.530595 | 5.533048 | 0.999557 |
return self.delete(
key_prefix, range_end=_encode(_increment_last_byte(key_prefix))) | def delete_prefix(self, key_prefix) | Delete a range of keys with a prefix in etcd. | 12.231058 | 10.62536 | 1.151119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.