_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q45100 | BasePageResource.get_prefix | train | def get_prefix(self):
""" Each resource defined in config for pages as dict. This method
returns key from config where located current resource.
"""
for key, value in self.pages_config.items():
if not hasattr(value, '__iter__'):
value = (value, )
f... | python | {
"resource": ""
} |
q45101 | bytes2zip | train | def bytes2zip(bytes):
"""
RETURN COMPRESSED BYTES
"""
if hasattr(bytes, "read"):
buff = TemporaryFile()
archive = gzip.GzipFile(fileobj=buff, mode='w')
for b in bytes:
archive.write(b)
archive.close()
buff.seek(0)
from pyLibrary.env.big_data im... | python | {
"resource": ""
} |
q45102 | ini2value | train | def ini2value(ini_content):
"""
INI FILE CONTENT TO Data
"""
from mo_future import ConfigParser, StringIO
buff = StringIO(ini_content)
config = ConfigParser()
config._read(buff, "dummy")
output = {}
for section in config.sections():
output[section]=s = {}
for k, v i... | python | {
"resource": ""
} |
q45103 | dict_partial_cmp | train | def dict_partial_cmp(target_dict, dict_list, ducktype):
"""
Whether partial dict are in dict_list or not
"""
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of two dicts
intersect... | python | {
"resource": ""
} |
q45104 | dict_partial_cmp_always | train | def dict_partial_cmp_always(target_dict, dict_list, ducktype):
"""
Whether partial dict are always in dict_list or not
"""
res = []
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of ... | python | {
"resource": ""
} |
q45105 | tuple_partial_cmp | train | def tuple_partial_cmp(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are in tuple_list or not
"""
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all argument from "current arg... | python | {
"resource": ""
} |
q45106 | tuple_partial_cmp_always | train | def tuple_partial_cmp_always(target_tuple, tuple_list, ducktype):
"""
Whether partial target_tuple are always in tuple_list or not
"""
res = []
for called_tuple in tuple_list:
# ignore invalid test case
if len(target_tuple) > len(called_tuple):
continue
# loop all... | python | {
"resource": ""
} |
q45107 | register_from_options | train | def register_from_options(options=None, template=None, extractor=None):
"""Register the spec codec using the provided options"""
if template is None:
from noseOfYeti.plugins.support.spec_options import spec_options as template
if extractor is None:
from noseOfYeti.plugins.support.spec_optio... | python | {
"resource": ""
} |
q45108 | TokeniserCodec.register | train | def register(self):
"""Register spec codec"""
# Assume utf8 encoding
utf8 = encodings.search_function('utf8')
class StreamReader(utf_8.StreamReader):
"""Used by cPython to deal with a spec file"""
def __init__(sr, stream, *args, **kwargs):
codecs.... | python | {
"resource": ""
} |
q45109 | TokeniserCodec.output_for_debugging | train | def output_for_debugging(self, stream, data):
"""It will write the translated version of the file"""
with open('%s.spec.out' % stream.name, 'w') as f: f.write(str(data)) | python | {
"resource": ""
} |
q45110 | ChoicesField.valid_value | train | def valid_value(self, value):
"""
Check if the provided value is a valid choice.
"""
if isinstance(value, Constant):
value = value.name
text_value = force_text(value)
for option_value, option_label, option_title in self.choices:
if value == option_... | python | {
"resource": ""
} |
q45111 | FileSize._unit_info | train | def _unit_info(self) -> Tuple[str, int]:
"""
Returns both the best unit to measure the size, and its power.
:return: A tuple containing the unit and its power.
"""
abs_bytes = abs(self.size)
if abs_bytes < 1024:
unit = 'B'
unit_divider = 1
... | python | {
"resource": ""
} |
q45112 | execute_sql | train | def execute_sql(
host,
username,
password,
sql,
schema=None,
param=None,
kwargs=None
):
"""EXECUTE MANY LINES OF SQL (FROM SQLDUMP FILE, MAYBE?"""
kwargs.schema = coalesce(kwargs.schema, kwargs.database)
if param:
with MySQL(kwargs) as temp:
sql = expand_temp... | python | {
"resource": ""
} |
q45113 | quote_value | train | def quote_value(value):
"""
convert values to mysql code for the same
mostly delegate directly to the mysql lib, but some exceptions exist
"""
try:
if value == None:
return SQL_NULL
elif isinstance(value, SQL):
return quote_sql(value.template, value.param)
... | python | {
"resource": ""
} |
q45114 | int_list_packer | train | def int_list_packer(term, values):
"""
return singletons, ranges and exclusions
"""
DENSITY = 10 # a range can have holes, this is inverse of the hole density
MIN_RANGE = 20 # min members before a range is allowed to be used
singletons = set()
ranges = []
exclude = set()
sorted =... | python | {
"resource": ""
} |
q45115 | MySQL.query | train | def query(self, sql, param=None, stream=False, row_tuples=False):
"""
RETURN LIST OF dicts
"""
if not self.cursor: # ALLOW NON-TRANSACTIONAL READS
Log.error("must perform all queries inside a transaction")
self._execute_backlog()
try:
if param:
... | python | {
"resource": ""
} |
q45116 | deactivate | train | def deactivate():
"""
Deactivate a state in this thread.
"""
if hasattr(_mode, "current_state"):
del _mode.current_state
if hasattr(_mode, "schema"):
del _mode.schema
for k in connections:
con = connections[k]
if hasattr(con, 'reset_schema'):
con.res... | python | {
"resource": ""
} |
q45117 | collections | train | def collections(record, key, value):
"""Parse custom MARC tag 980."""
return {
'primary': value.get('a'),
'secondary': value.get('b'),
'deleted': value.get('c'),
} | python | {
"resource": ""
} |
q45118 | reverse_collections | train | def reverse_collections(self, key, value):
"""Reverse colections field to custom MARC tag 980."""
return {
'a': value.get('primary'),
'b': value.get('secondary'),
'c': value.get('deleted'),
} | python | {
"resource": ""
} |
q45119 | _select1 | train | def _select1(data, field, depth, output):
"""
SELECT A SINGLE FIELD
"""
for d in data:
for i, f in enumerate(field[depth:]):
d = d[f]
if d == None:
output.append(None)
break
elif is_list(d):
_select1(d, field, i ... | python | {
"resource": ""
} |
q45120 | search_form | train | def search_form(*fields, **kwargs):
"""
Construct a search form filter form using the fields
provided as arguments to this function.
By default a field will be created for each field passed
and hidden field will be created for search. If you pass
the key work argument `search_only` then only a ... | python | {
"resource": ""
} |
q45121 | BaseFilterForm.get_filter_fields | train | def get_filter_fields(self, exclude=None):
"""
Get the fields that are normal filter fields
"""
exclude_set = set(self.exclude)
if exclude:
exclude_set = exclude_set.union(set(exclude))
return [name for name in self.fields
if name not in excl... | python | {
"resource": ""
} |
q45122 | BaseFilterForm.get_search_fields | train | def get_search_fields(self, exclude=None):
"""
Get the fields for searching for an item.
"""
exclude = set(exclude)
if self.search_fields and len(self.search_fields) > 1:
exclude = exclude.union(self.search_fields)
return self.get_filter_fields(exclude=exclud... | python | {
"resource": ""
} |
q45123 | BaseFilterForm.get_filter_kwargs | train | def get_filter_kwargs(self):
"""
Translates the cleaned data into a dictionary
that can used to generate the filter removing
blank values.
"""
if self.is_valid():
filter_kwargs = {}
for field in self.get_filter_fields():
empty_value... | python | {
"resource": ""
} |
q45124 | BaseFilterForm.get_filter | train | def get_filter(self):
"""
Returns a list of Q objects
that is created by passing for the keyword arguments
from `self.get_filter_kwargs`.
If search_fields are specified and we received
a seach query all search_fields will be queried use
using OR (|) for that term... | python | {
"resource": ""
} |
q45125 | parse_wiki_terms | train | def parse_wiki_terms(doc):
'''who needs an html parser. fragile hax, but checks the result at the end'''
results = []
last3 = ['', '', '']
header = True
for line in doc.split('\n'):
last3.pop(0)
last3.append(line.strip())
if all(s.startswith('<td>') and not s == '<td></td>' f... | python | {
"resource": ""
} |
q45126 | filter_short | train | def filter_short(terms):
'''
only keep if brute-force possibilities are greater than this word's rank in the dictionary
'''
return [term for i, term in enumerate(terms) if 26**(len(term)) > i] | python | {
"resource": ""
} |
q45127 | filter_dup | train | def filter_dup(lst, lists):
'''
filters lst to only include terms that don't have lower rank in another list
'''
max_rank = len(lst) + 1
dct = to_ranked_dict(lst)
dicts = [to_ranked_dict(l) for l in lists]
return [word for word in lst if all(dct[word] < dct2.get(word, max_rank) for dct2 in d... | python | {
"resource": ""
} |
q45128 | Matcher.__get_match_result | train | def __get_match_result(self, ret, ret2):
"""
Getting match result
"""
if self.another_compare == "__MATCH_AND__":
return ret and ret2
elif self.another_compare == "__MATCH_OR__":
return ret or ret2
return ret | python | {
"resource": ""
} |
q45129 | BindXmlReader.get_stats | train | def get_stats(self):
"""Given XML version, parse create XMLAbstract object and sets xml_stats attribute."""
self.gather_xml()
self.xml_version = self.bs_xml.find('statistics')['version']
if self.xml_version is None:
raise XmlError("Unable to determine XML version via 'statis... | python | {
"resource": ""
} |
q45130 | median | train | def median(values, simple=True, mean_weight=0.0):
"""
RETURN MEDIAN VALUE
IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE
MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION
IN THE MEDIAN RANGE
mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS
CLOSER TO T... | python | {
"resource": ""
} |
q45131 | percentile | train | def percentile(values, percent):
"""
PERCENTILE WITH INTERPOLATION
RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES
snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
N = sorted(values)
if not N:
return None
k = (len(N) - 1) * pe... | python | {
"resource": ""
} |
q45132 | AttrIndexedDict.map | train | def map(self, method: str, *args, _threaded: bool = True, **kwargs
) -> "AttrIndexedDict":
"For all stored items, run a method they possess."
work = lambda item: getattr(item, method)(*args, **kwargs)
if _threaded:
pool = ThreadPool(int(config.CFG["GENERAL"]["parallel_re... | python | {
"resource": ""
} |
q45133 | AttrIndexedDict.put | train | def put(self, *items) -> "AttrIndexedDict":
"Add items to the dict that will be indexed by self.attr."
for item in items:
self.data[getattr(item, self.attr)] = item
return self | python | {
"resource": ""
} |
q45134 | main | train | def main(host, password, username):
"""Console script for tplink."""
client = tplink.TpLinkClient(password)
devices = client.get_connected_devices()
click.echo(json.dumps(devices, indent=4))
return 0 | python | {
"resource": ""
} |
q45135 | flatten | train | def flatten(value):
"""value can be any nesting of tuples, arrays, dicts.
returns 1D numpy array and an unflatten function."""
if isinstance(value, np.ndarray):
def unflatten(vector):
return np.reshape(vector, value.shape)
return np.ravel(value), unflatten
elif isinstance... | python | {
"resource": ""
} |
q45136 | switch_state | train | def switch_state(request):
"""
Switch the default version state in
the session.
"""
if request.session.get(SESSION_KEY):
request.session[SESSION_KEY] = False
else:
request.session[SESSION_KEY] = True
# Get redirect location
# Don't go to non local paths
url = reques... | python | {
"resource": ""
} |
q45137 | _CollectHistory_ | train | def _CollectHistory_(lookupType, fromVal, toVal, using={}, pattern=''):
"""
Return a dictionary detailing what, if any, change was made to a record field
:param string lookupType: what cleaning rule made the change; one of: genericLookup, genericRegex, fieldSpecificLookup, fieldSpecificRegex, normLookup, n... | python | {
"resource": ""
} |
q45138 | _CollectHistoryAgg_ | train | def _CollectHistoryAgg_(contactHist, fieldHistObj, fieldName):
"""
Return updated history dictionary with new field change
:param dict contactHist: Existing contact history dictionary
:param dict fieldHistObj: Output of _CollectHistory_
:param string fieldName: field name
"""
if fieldHistO... | python | {
"resource": ""
} |
q45139 | _RunUserDefinedFunctions_ | train | def _RunUserDefinedFunctions_(config, data, histObj, position, namespace=__name__):
"""
Return a single updated data record and history object after running user-defined functions
:param dict config: DWM configuration (see DataDictionary)
:param dict data: single record (dictionary) to which user-defin... | python | {
"resource": ""
} |
q45140 | FakeGPS.feed | train | def feed(self):
"Feed a line from the contents of the GPS log to the daemon."
line = self.testload.sentences[self.index % len(self.testload.sentences)]
if "%Delay:" in line:
# Delay specified number of seconds
delay = line.split()[1]
time.sleep(int(delay))
... | python | {
"resource": ""
} |
q45141 | DaemonInstance.spawn | train | def spawn(self, options, port, background=False, prefix=""):
"Spawn a daemon instance."
self.spawncmd = None
# Look for gpsd in GPSD_HOME env variable
if os.environ.get('GPSD_HOME'):
for path in os.environ['GPSD_HOME'].split(':'):
_spawncmd = "%s/gpsd" % path
... | python | {
"resource": ""
} |
q45142 | DaemonInstance.wait_pid | train | def wait_pid(self):
"Wait for the daemon, get its PID and a control-socket connection."
while True:
try:
fp = open(self.pidfile)
except IOError:
time.sleep(0.1)
continue
try:
fp.seek(0)
pi... | python | {
"resource": ""
} |
q45143 | DaemonInstance.add_device | train | def add_device(self, path):
"Add a device to the daemon's internal search list."
if self.__get_control_socket():
self.sock.sendall("+%s\r\n\x00" % path)
self.sock.recv(12)
self.sock.close() | python | {
"resource": ""
} |
q45144 | DaemonInstance.remove_device | train | def remove_device(self, path):
"Remove a device from the daemon's internal search list."
if self.__get_control_socket():
self.sock.sendall("-%s\r\n\x00" % path)
self.sock.recv(12)
self.sock.close() | python | {
"resource": ""
} |
q45145 | DaemonInstance.kill | train | def kill(self):
"Kill the daemon instance."
if self.pid:
try:
os.kill(self.pid, signal.SIGTERM)
# Raises an OSError for ESRCH when we've killed it.
while True:
os.kill(self.pid, signal.SIGTERM)
time.sleep... | python | {
"resource": ""
} |
q45146 | addParts | train | def addParts(parentPart, childPath, count, index):
"""
BUILD A hierarchy BY REPEATEDLY CALLING self METHOD WITH VARIOUS childPaths
count IS THE NUMBER FOUND FOR self PATH
"""
if index == None:
index = 0
if index == len(childPath):
return
c = childPath[index]
parentPart.co... | python | {
"resource": ""
} |
q45147 | APIChoiceWidget.get_qs | train | def get_qs(self):
"""
Returns a mapping that will be used to generate
the query string for the api url. Any values
in the the `limit_choices_to` specified on the
foreign key field and any arguments specified on
self.extra_query_kwargs are converted to a format
tha... | python | {
"resource": ""
} |
q45148 | APIChoiceWidget.get_api_link | train | def get_api_link(self):
"""
Adds a query string to the api url. At minimum adds the type=choices
argument so that the return format is json. Any other filtering
arguments calculated by the `get_qs` method are then added to the
url. It is up to the destination url to respect them ... | python | {
"resource": ""
} |
q45149 | APIChoiceWidget.label_for_value | train | def label_for_value(self, value, key=None):
"""
Looks up the current value of the field and returns
a unicode representation. Default implementation does a lookup
on the target model and if a match is found calls force_unicode
on that object. Otherwise a blank string is returned.... | python | {
"resource": ""
} |
q45150 | APIManyChoiceWidget.update_links | train | def update_links(self, request, admin_site=None):
"""
Called to update the widget's urls. Tries to find the
bundle for the model that this foreign key points to and then
asks it for the urls for adding and listing and sets them on
this widget instance. The urls are only set if re... | python | {
"resource": ""
} |
q45151 | SchemaObjectFactory.schema_class | train | def schema_class(self, object_schema, model_name, classes=False):
"""
Create a object-class based on the object_schema. Use
this class to create specific instances, and validate the
data values. See the "python-jsonschema-objects" package
for details on further usage.
... | python | {
"resource": ""
} |
q45152 | SchemaObjectFactory.__model_class | train | def __model_class(self, model_name):
""" this method is used by the lru_cache, do not call directly """
build_schema = deepcopy(self.definitions[model_name])
return self.schema_class(build_schema, model_name) | python | {
"resource": ""
} |
q45153 | minimum_entropy_match_sequence | train | def minimum_entropy_match_sequence(password, matches):
"""
Returns minimum entropy
Takes a list of overlapping matches, returns the non-overlapping sublist with
minimum entropy. O(nm) dp alg for length-n password with m candidate matches.
"""
bruteforce_cardinality = calc_bruteforce_cardinality... | python | {
"resource": ""
} |
q45154 | round_to_x_digits | train | def round_to_x_digits(number, digits):
"""
Returns 'number' rounded to 'digits' digits.
"""
return round(number * math.pow(10, digits)) / math.pow(10, digits) | python | {
"resource": ""
} |
q45155 | Cube.values | train | def values(self):
"""
TRY NOT TO USE THIS, IT IS SLOW
"""
matrix = self.data.values()[0] # CANONICAL REPRESENTATIVE
if matrix.num == 0:
return
e_names = self.edges.name
s_names = self.select.name
parts = [e.domain.partitions.value if e.domain.... | python | {
"resource": ""
} |
q45156 | Client.save_swagger_spec | train | def save_swagger_spec(self, filepath=None):
"""
Saves a copy of the origin_spec to a local file in JSON format
"""
if filepath is True or filepath is None:
filepath = self.file_spec.format(server=self.server)
json.dump(self.origin_spec, open(filepath, 'w+'), indent=3... | python | {
"resource": ""
} |
q45157 | Client.load_swagger_spec | train | def load_swagger_spec(self, filepath=None):
"""
Loads the origin_spec from a local JSON file. If `filepath`
is not provided, then the class `file_spec` format will be used
to create the file-path value.
"""
if filepath is True or filepath is None:
filepath = ... | python | {
"resource": ""
} |
q45158 | OssAuth.set_more_headers | train | def set_more_headers(self, req, extra_headers=None):
"""Set content-type, content-md5, date to the request
Returns a new `PreparedRequest`
:param req: the origin unsigned request
:param extra_headers: extra headers you want to set, pass as dict
"""
oss_url = url.URL(req.... | python | {
"resource": ""
} |
q45159 | OssAuth.get_signature | train | def get_signature(self, req):
"""calculate the signature of the oss request
Returns the signatue
"""
oss_url = url.URL(req.url)
oss_headers = [
"{0}:{1}\n".format(key, val)
for key, val in req.headers.lower_items()
if key.startswith(self.X_OSS... | python | {
"resource": ""
} |
q45160 | Rename.convert | train | def convert(self, expr):
"""
EXPAND INSTANCES OF name TO value
"""
if expr is True or expr == None or expr is False:
return expr
elif is_number(expr):
return expr
elif expr == ".":
return "."
elif is_variable_name(expr):
... | python | {
"resource": ""
} |
q45161 | Rename._convert_clause | train | def _convert_clause(self, clause):
"""
JSON QUERY EXPRESSIONS HAVE MANY CLAUSES WITH SIMILAR COLUMN DELCARATIONS
"""
clause = wrap(clause)
if clause == None:
return None
elif is_data(clause):
return set_default({"value": self.convert(clause.value)... | python | {
"resource": ""
} |
q45162 | MeteorDatabase.get_obstory_ids | train | def get_obstory_ids(self):
"""
Retrieve the IDs of all obstorys.
:return:
A list of obstory IDs for all obstorys
"""
self.con.execute('SELECT publicId FROM archive_observatories;')
return map(lambda row: row['publicId'], self.con.fetchall()) | python | {
"resource": ""
} |
q45163 | MeteorDatabase.has_obstory_metadata | train | def has_obstory_metadata(self, status_id):
"""
Check for the presence of the given metadata item
:param string status_id:
The metadata item ID
:return:
True if we have a metadata item with this ID, False otherwise
"""
self.con.execute('SELECT 1 FR... | python | {
"resource": ""
} |
q45164 | MeteorDatabase.has_file_id | train | def has_file_id(self, repository_fname):
"""
Check for the presence of the given file_id
:param string repository_fname:
The file ID
:return:
True if we have a :class:`meteorpi_model.FileRecord` with this ID, False otherwise
"""
self.con.execute('... | python | {
"resource": ""
} |
q45165 | MeteorDatabase.has_observation_id | train | def has_observation_id(self, observation_id):
"""
Check for the presence of the given observation_id
:param string observation_id:
The observation ID
:return:
True if we have a :class:`meteorpi_model.Observation` with this Id, False otherwise
"""
... | python | {
"resource": ""
} |
q45166 | MeteorDatabase.has_obsgroup_id | train | def has_obsgroup_id(self, group_id):
"""
Check for the presence of the given group_id
:param string group_id:
The group ID
:return:
True if we have a :class:`meteorpi_model.ObservationGroup` with this Id, False otherwise
"""
self.con.execute('SELE... | python | {
"resource": ""
} |
q45167 | MeteorDatabase.get_user | train | def get_user(self, user_id, password):
"""
Retrieve a user record
:param user_id:
the user ID
:param password:
password
:return:
A :class:`meteorpi_model.User` if everything is correct
:raises:
ValueError if the user is fou... | python | {
"resource": ""
} |
q45168 | MeteorDatabase.get_users | train | def get_users(self):
"""
Retrieve all users in the system
:return:
A list of :class:`meteorpi_model.User`
"""
output = []
self.con.execute('SELECT userId, uid FROM archive_users;')
results = self.con.fetchall()
for result in results:
... | python | {
"resource": ""
} |
q45169 | MeteorDatabase.create_or_update_user | train | def create_or_update_user(self, user_id, password, roles):
"""
Create a new user record, or update an existing one
:param user_id:
user ID to update or create
:param password:
new password, or None to leave unchanged
:param roles:
new roles, o... | python | {
"resource": ""
} |
q45170 | MeteorDatabase.get_export_configuration | train | def get_export_configuration(self, config_id):
"""
Retrieve the ExportConfiguration with the given ID
:param string config_id:
ID for which to search
:return:
a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found.
"""
sql = ... | python | {
"resource": ""
} |
q45171 | MeteorDatabase.get_export_configurations | train | def get_export_configurations(self):
"""
Retrieve all ExportConfigurations held in this db
:return: a list of all :class:`meteorpi_model.ExportConfiguration` on this server
"""
sql = (
'SELECT uid, exportConfigId, exportType, searchString, targetURL, '
't... | python | {
"resource": ""
} |
q45172 | MeteorDatabase.create_or_update_export_configuration | train | def create_or_update_export_configuration(self, export_config):
"""
Create a new file export configuration or update an existing one
:param ExportConfiguration export_config:
a :class:`meteorpi_model.ExportConfiguration` containing the specification for the export. If this
... | python | {
"resource": ""
} |
q45173 | MeteorDatabase.get_high_water_mark | train | def get_high_water_mark(self, mark_type, obstory_name=None):
"""
Retrieves the high water mark for a given obstory, defaulting to the current installation ID
:param string mark_type:
The type of high water mark to set
:param string obstory_name:
The obstory ID to... | python | {
"resource": ""
} |
q45174 | baseglob | train | def baseglob(pat, base):
"""Given a pattern and a base, return files that match the glob pattern
and also contain the base."""
return [f for f in glob(pat) if f.startswith(base)] | python | {
"resource": ""
} |
q45175 | get_revision | train | def get_revision():
"""
GET THE CURRENT GIT REVISION
"""
proc = Process("git log", ["git", "log", "-1"])
try:
while True:
line = proc.stdout.pop().strip().decode('utf8')
if not line:
continue
if line.startswith("commit "):
... | python | {
"resource": ""
} |
q45176 | get_remote_revision | train | def get_remote_revision(url, branch):
"""
GET REVISION OF A REMOTE BRANCH
"""
proc = Process("git remote revision", ["git", "ls-remote", url, "refs/heads/" + branch])
try:
while True:
raw_line = proc.stdout.pop()
line = raw_line.strip().decode('utf8')
if ... | python | {
"resource": ""
} |
q45177 | get_branch | train | def get_branch():
"""
GET THE CURRENT GIT BRANCH
"""
proc = Process("git status", ["git", "status"])
try:
while True:
raw_line = proc.stdout.pop()
line = raw_line.decode('utf8').strip()
if line.startswith("On branch "):
return line[10:]
... | python | {
"resource": ""
} |
q45178 | Renderer._get_accept_languages_in_order | train | def _get_accept_languages_in_order(self):
"""
Reads an Accept HTTP header and returns an array of Media Type string in descending weighted order
:return: List of URIs of accept profiles in descending request order
:rtype: list
"""
try:
# split the header into... | python | {
"resource": ""
} |
q45179 | CmWalk.readCfgJson | train | def readCfgJson(cls, working_path):
"""Read cmWalk configuration data of a working directory from a json file.
:param working_path: working path for reading the configuration data.
:return: the configuration data represented in a json object, None if the configuration files does not
... | python | {
"resource": ""
} |
q45180 | CmWalk.genTopLevelDirCMakeListsFile | train | def genTopLevelDirCMakeListsFile(self, working_path, subdirs, files, cfg):
"""
Generate top level CMakeLists.txt.
:param working_path: current working directory
:param subdirs: a list of subdirectories of current working directory.
:param files: a list of files in current workin... | python | {
"resource": ""
} |
q45181 | CmWalk.genSubDirCMakeListsFile | train | def genSubDirCMakeListsFile(self, working_path, addToCompilerIncludeDirectories, subdirs, files):
"""
Generate CMakeLists.txt in subdirectories.
:param working_path: current working directory
:param subdirs: a list of subdirectories of current working directory.
:param files: a ... | python | {
"resource": ""
} |
q45182 | FileLoader._maybe_purge_cache | train | def _maybe_purge_cache(self):
"""
If enough time since last check has elapsed, check if any
of the cached templates has changed. If any of the template
files were deleted, remove that file only. If any were
changed, then purge the entire cache.
"""
if self._last_... | python | {
"resource": ""
} |
q45183 | FileLoader.load | train | def load(self, name):
"""
If not yet in the cache, load the named template and compiles it,
placing it into the cache.
If in cache, return the cached template.
"""
if self.reload:
self._maybe_purge_cache()
template = self.cache.get(name)
if ... | python | {
"resource": ""
} |
q45184 | MySQL.query | train | def query(self, query, stacked=False):
"""
TRANSLATE JSON QUERY EXPRESSION ON SINGLE TABLE TO SQL QUERY
"""
from jx_base.query import QueryOp
query = QueryOp.wrap(query)
sql, post = self._subquery(query, isolate=False, stacked=stacked)
query.data = post(sql)
... | python | {
"resource": ""
} |
q45185 | MySQL._sort2sql | train | def _sort2sql(self, sort):
"""
RETURN ORDER BY CLAUSE
"""
if not sort:
return ""
return SQL_ORDERBY + sql_list([quote_column(o.field) + (" DESC" if o.sort == -1 else "") for o in sort]) | python | {
"resource": ""
} |
q45186 | CustomAPIView.get_renderers | train | def get_renderers(self):
"""
Instantiates and returns the list of renderers that this view can use.
"""
try:
source = self.get_object()
except (ImproperlyConfigured, APIException):
self.renderer_classes = [RENDERER_MAPPING[i] for i in self.__class__.render... | python | {
"resource": ""
} |
q45187 | AVIFile.rebuild | train | def rebuild(self):
"""Rebuild RIFF tree and index from streams."""
movi = self.riff.find('LIST', 'movi')
movi.chunks = self.combine_streams()
self.rebuild_index() | python | {
"resource": ""
} |
q45188 | Lock.acquire | train | def acquire(self, **kwargs):
"""
Aquire the lock. Returns True if the lock was acquired; False otherwise.
timeout (int): Timeout to wait for the lock to change if it is already acquired.
Defaults to what was provided during initialization, which will block and retry until acquired. ... | python | {
"resource": ""
} |
q45189 | Lock.renew | train | def renew(self):
"""
Renew the lock if acquired.
"""
if self.token is not None:
try:
self.client.test_and_set(self.key, self.token, self.token, ttl=self.ttl)
return True
except ValueError, e:
self.token = None
... | python | {
"resource": ""
} |
q45190 | Lock.release | train | def release(self):
"""
Release the lock if acquired.
"""
# TODO: thread safety (currently the lock may be acquired for one more TTL length)
if self.token is not None:
try:
self.client.test_and_set(self.key, 0, self.token)
except (ValueError... | python | {
"resource": ""
} |
q45191 | AssetsFileField.deconstruct | train | def deconstruct(self):
"""
Denormalize is always false migrations
"""
name, path, args, kwargs = super(AssetsFileField, self).deconstruct()
kwargs['denormalize'] = False
return name, path, args, kwargs | python | {
"resource": ""
} |
q45192 | ActionView.get_context_data | train | def get_context_data(self, **kwargs):
"""
Hook for adding arguments to the context.
"""
context = {'obj': self.object }
if 'queryset' in kwargs:
context['conf_msg'] = self.get_confirmation_message(kwargs['queryset'])
context.update(kwargs)
return cont... | python | {
"resource": ""
} |
q45193 | ActionView.get_object | train | def get_object(self):
"""
If a single object has been requested, will set
`self.object` and return the object.
"""
queryset = None
slug = self.kwargs.get(self.slug_url_kwarg, None)
if slug is not None:
queryset = self.get_queryset()
slug_f... | python | {
"resource": ""
} |
q45194 | ActionView.get_selected | train | def get_selected(self, request):
"""
Returns a queryset of the selected objects as specified by \
a GET or POST request.
"""
obj = self.get_object()
queryset = None
# if single-object URL not used, check for selected objects
if not obj:
if requ... | python | {
"resource": ""
} |
q45195 | ActionView.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Checks for a modify confirmation and performs
the action by calling `process_action`.
"""
queryset = self.get_selected(request)
if request.POST.get('modify'):
response =... | python | {
"resource": ""
} |
q45196 | PublishActionView.process_action | train | def process_action(self, request, queryset):
"""
Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged as \... | python | {
"resource": ""
} |
q45197 | UnPublishActionView.process_action | train | def process_action(self, request, queryset):
"""
Unpublishes the selected objects by calling the object's \
unpublish method. The action is logged and the user is \
notified with a message.
Returns a 'render redirect' to the result of the \
`get_done_url` method.
... | python | {
"resource": ""
} |
q45198 | PublishView.get_object_url | train | def get_object_url(self):
"""
Returns the url to link to the object
The get_view_url will be called on the current bundle using
'edit` as the view name.
"""
return self.bundle.get_view_url('edit',
self.request.user, {}, self.kwargs) | python | {
"resource": ""
} |
q45199 | PublishView.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests. Publishes
the object passing the value of 'when' to the object's
publish method. The object's `purge_archives` method
is also called to limit the number of old items
that we keep around. The ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.