_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q44100 | cli | train | def cli(ctx):
""" This is a command line app to get useful stats from a trello board
and report on them in useful ways.
Requires the following environment varilables:
TRELLOSTATS_APP_KEY=<your key here>
TRELLOSTATS_APP_TOKEN=<your token here>
"""
ctx.obj = dict()
ctx.ob... | python | {
"resource": ""
} |
q44101 | translation | train | def translation(language):
"""
Return a translation object in the default 'django' domain.
"""
global _translations
if language not in _translations:
_translations[language] = Translations(language)
return _translations[language] | python | {
"resource": ""
} |
q44102 | gettext | train | def gettext(message):
"""
Translate the 'message' string. It uses the current thread to find the
translation object to use. If no current translation is activated, the
message will be run through the default translation object.
"""
global _default
_default = _default or translation(DEFAULT_L... | python | {
"resource": ""
} |
q44103 | Translations._new_gnu_trans | train | def _new_gnu_trans(self, localedir, use_null_fallback=True):
"""
Return a mergeable gettext.GNUTranslations instance.
A convenience wrapper. By default gettext uses 'fallback=False'.
Using param `use_null_fallback` to avoid confusion with any other
references to 'fallback'.
... | python | {
"resource": ""
} |
q44104 | Translations.add_localedir_translations | train | def add_localedir_translations(self, localedir):
"""Merge translations from localedir."""
global _localedirs
if localedir in self.localedirs:
return
self.localedirs.append(localedir)
full_localedir = os.path.join(localedir, 'locale')
if os.path.exists(full_loc... | python | {
"resource": ""
} |
q44105 | Translations.merge | train | def merge(self, other):
"""Merge another translation into this catalog."""
if not getattr(other, '_catalog', None):
return # NullTranslations() has no _catalog
if self._catalog is None:
# Take plural and _info from first catalog found
self.plural = other.plur... | python | {
"resource": ""
} |
q44106 | decode_input | train | def decode_input(text_in):
""" Decodes `text_in`
If text_in is is a string,
then decode it as utf-8 string.
If text_in is is a list of strings,
then decode each string of it,
then combine them into one outpust string.
"""
if type(text_in) == list:
tex... | python | {
"resource": ""
} |
q44107 | File._set_local_file_path | train | def _set_local_file_path(self):
"""
Take from environment variable, create dirs and
create file if doesn' exist.
"""
self.FILE_LOCAL = self._transfer.get_env('FILE_LOCAL')
if not self.FILE_LOCAL:
filename = '{}_{}.{}'.format(str(self._transfer.prefix),
... | python | {
"resource": ""
} |
q44108 | gen_post_status | train | def gen_post_status():
"""
Show only published posts outside debug.
"""
if not app.config["DEBUG"]:
post_status = and_(Post.status == PostStatus.PUBLISH)
else:
post_status = or_(Post.status == PostStatus.PUBLISH,
Post.status == PostStatus.DRAFT)
return ... | python | {
"resource": ""
} |
q44109 | Subject.subscribe | train | def subscribe(self, observer):
"""Subscribe an observer to this subject and return a subscription id
"""
sid = self._sn
self.observers[sid] = observer
self._sn += 1
return SubscribeID(self, sid) | python | {
"resource": ""
} |
q44110 | Subject.unsubscribe | train | def unsubscribe(self, sid):
"""Disconnect an observer from this subject
"""
if sid not in self.observers:
raise KeyError(
'Cannot disconnect a observer does not connected to subject'
)
del self.observers[sid] | python | {
"resource": ""
} |
q44111 | make_module_class | train | def make_module_class(name):
"""Takes the module referenced by name and make it a full class.
"""
source = sys.modules[name]
members = vars(source)
is_descriptor = lambda x: not isinstance(x, type) and hasattr(x, '__get__')
descriptors = {k: v for (k, v) in members.items() if is_descriptor(v)}... | python | {
"resource": ""
} |
q44112 | build_ann | train | def build_ann(N_input=None, N_hidden=2, N_output=1, hidden_layer_type='Linear', verbosity=1):
"""Build a neural net with the indicated input, hidden, and outout dimensions
Arguments:
params (dict or PyBrainParams namedtuple):
default: {'N_hidden': 6}
(this is the only parameter that affec... | python | {
"resource": ""
} |
q44113 | inputs_from_dataframe | train | def inputs_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1):
""" Build a sequence of vectors suitable for "activation" by a neural net
Identical to `dataset_from_dataframe`, except that only the input vectors are
returned (not a full DataSet instance) and d... | python | {
"resource": ""
} |
q44114 | build_trainer | train | def build_trainer(nn, ds, verbosity=1):
"""Configure neural net trainer from a pybrain dataset"""
return pb.supervised.trainers.rprop.RPropMinusTrainer(nn, dataset=ds, batchlearning=True, verbose=bool(verbosity)) | python | {
"resource": ""
} |
q44115 | plot_network_results | train | def plot_network_results(network, ds=None, mean=0, std=1, title='', show=True, save=True):
"""Identical to plot_trainer except `network` and `ds` must be provided separately"""
df = sim_network(network=network, ds=ds, mean=mean, std=std)
df.plot()
plt.xlabel('Date')
plt.ylabel('Threshold (kW)')
... | python | {
"resource": ""
} |
q44116 | trainer_results | train | def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True):
"""Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer
DataSet target and output values are denormalized before plotting with:
output * std + mean
Which inverses the normalization
(out... | python | {
"resource": ""
} |
q44117 | lex | train | def lex(args):
""" Lex input and return a list of actions to perform. """
if len(args) == 0 or args[0] == SHOW:
return [(SHOW, None)]
elif args[0] == LOG:
return [(LOG, None)]
elif args[0] == ECHO:
return [(ECHO, None)]
elif args[0] == SET and args[1] == RATE:
return ... | python | {
"resource": ""
} |
q44118 | Action.run_svc_action | train | def run_svc_action(self, name, replace=None, svc=None):
"""
backwards compatible to reflex service object. This looks for hooks on
current object as well as in the actions sub-object.
"""
actions = svc.get('actions')
if actions and actions.get(name):
return se... | python | {
"resource": ""
} |
q44119 | Action.run | train | def run(self, name, replace=None, actions=None):
"""
Do an action.
If `replace` is provided as a dictionary, do a search/replace using
%{} templates on content of action (unique to action type)
"""
self.actions = actions # incase we use group
action = actions.g... | python | {
"resource": ""
} |
q44120 | Action._run__group | train | def _run__group(self, action, replace):
"""
Run a group of actions in sequence.
>>> Action().run("several", actions={
... "several": {
... "type": "group",
... "actions": ["hello","call","then"]
... }, "hello": {
... "type"... | python | {
"resource": ""
} |
q44121 | Action._run__exec | train | def _run__exec(self, action, replace):
"""
Run a system command
>>> Action().run("hello", actions={
... "hello": {
... "type": "exec",
... "cmd": "echo version=%{version}"
... }}, replace={
... "version": "1712.10"
... })
... | python | {
"resource": ""
} |
q44122 | _get_arg_names | train | def _get_arg_names(func):
''' this returns the arg names since dictionaries dont guarantee order '''
args, varargs, keywords, defaults = inspect.getargspec(func)
return(tuple(args)) | python | {
"resource": ""
} |
q44123 | strict_defaults | train | def strict_defaults(fn):
''' use this decorator to enforce type checking on functions based on the function's defaults '''
@wraps(fn)
def wrapper(*args, **kwargs):
defaults = _get_default_args(fn)
# dictionary that holds each default type
needed_types={
key:type(defaults[... | python | {
"resource": ""
} |
q44124 | update_mailing_lists_in_m2m | train | def update_mailing_lists_in_m2m(
sender=None,
userprofile=None,
pk_set=None,
subscribe=None,
unsubscribe=None,
verbose=None,
email_enabled=None,
):
"""
m2m_model = m2m model class for 'email_notifications' or
'sms_notifications'.
"""
response = None
email_enabled = em... | python | {
"resource": ""
} |
q44125 | superdict | train | def superdict(arg=()):
"""Recursive defaultdict which can init with other dict """
def update(obj, arg):
return obj.update(arg) or obj
return update(defaultdict(superdict), arg) | python | {
"resource": ""
} |
q44126 | deepcopy | train | def deepcopy(data):
"""Use pickle to do deep_copy"""
try:
return pickle.loads(pickle.dumps(data))
except TypeError:
return copy.deepcopy(data) | python | {
"resource": ""
} |
q44127 | deepcp | train | def deepcp(data):
"""Use ujson to do deep_copy"""
import ujson
try:
return ujson.loads(ujson.dumps(data))
except Exception:
return copy.deepcopy(data) | python | {
"resource": ""
} |
q44128 | _do_denormalize | train | def _do_denormalize (version_tuple):
"""separate action function to allow for the memoize decorator. Lists,
the most common thing passed in to the 'denormalize' below are not hashable.
"""
version_parts_list = []
for parts_tuple in itertools.imap(None,*([iter(version_tuple)]*4)):
version_pa... | python | {
"resource": ""
} |
q44129 | History.load | train | def load(self, revision_path):
"""
Load revision file.
:param revision_path:
:type revision_path: str
"""
if not os.path.exists(revision_path):
raise RuntimeError("revision file does not exist.")
with open(revision_path, mode='r') as f:
t... | python | {
"resource": ""
} |
q44130 | from_ast | train | def from_ast(
pyast_node, node=None, node_cls=None, Node=Node,
iter_fields=ast.iter_fields, AST=ast.AST):
'''Convert the ast tree to a tater tree.
'''
node_cls = node_cls or Node
node = node or node_cls()
name = pyast_node.__class__.__name__
attrs = []
for field, value in it... | python | {
"resource": ""
} |
q44131 | Ladder.load | train | def load(self, ladderName):
"""retrieve the ladder settings from saved disk file"""
self.name = ladderName # preset value to load self.filename
with open(self.filename, "rb") as f:
data = f.read()
self.__dict__.update( json.loads(data) ) | python | {
"resource": ""
} |
q44132 | import_localities | train | def import_localities(path, delimiter=';'):
"""
Import localities from a CSV file.
:param path: Path to the CSV file containing the localities.
"""
creates = []
updates = []
with open(path, mode="r") as infile:
reader = csv.DictReader(infile, delimiter=str(delimiter))
wit... | python | {
"resource": ""
} |
q44133 | get_netid_subscriptions | train | def get_netid_subscriptions(netid, subscription_codes):
"""
Returns a list of uwnetid.subscription objects
corresponding to the netid and subscription code or list provided
"""
url = _netid_subscription_url(netid, subscription_codes)
response = get_resource(url)
return _json_to_subscriptions... | python | {
"resource": ""
} |
q44134 | select_subscription | train | def select_subscription(subs_code, subscriptions):
"""
Return the uwnetid.subscription object with the subs_code.
"""
if subs_code and subscriptions:
for subs in subscriptions:
if (subs.subscription_code == subs_code):
return subs
return None | python | {
"resource": ""
} |
q44135 | modify_subscription_status | train | def modify_subscription_status(netid, subscription_code, status):
"""
Post a subscription 'modify' action for the given netid
and subscription_code
"""
url = _netid_subscription_url(netid, subscription_code)
body = {
'action': 'modify',
'value': str(status)
}
response = ... | python | {
"resource": ""
} |
q44136 | _netid_subscription_url | train | def _netid_subscription_url(netid, subscription_codes):
"""
Return UWNetId resource for provided netid and subscription
code or code list
"""
return "{0}/{1}/subscription/{2}".format(
url_base(), netid,
(','.join([str(n) for n in subscription_codes])
if isinstance(subscripti... | python | {
"resource": ""
} |
q44137 | _json_to_subscriptions | train | def _json_to_subscriptions(response_body):
"""
Returns a list of Subscription objects
"""
data = json.loads(response_body)
subscriptions = []
for subscription_data in data.get("subscriptionList", []):
subscriptions.append(Subscription().from_json(
data.get('uwNetID'), subscri... | python | {
"resource": ""
} |
q44138 | _json_to_subscription_post_response | train | def _json_to_subscription_post_response(response_body):
"""
Returns a list of SubscriptionPostResponse objects
"""
data = json.loads(response_body)
response_list = []
for response_data in data.get("responseList", []):
response_list.append(SubscriptionPostResponse().from_json(
... | python | {
"resource": ""
} |
q44139 | SignedPermission.has_permission | train | def has_permission(self, request, view):
"""Check list and create permissions based on sign and filters."""
if view.suffix == 'Instance':
return True
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
... | python | {
"resource": ""
} |
q44140 | SignedPermission.has_object_permission | train | def has_object_permission(self, request, view, obj=None):
"""Check object permissions based on filters."""
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(obj._meta.app_label, obj._meta.model_name))
... | python | {
"resource": ""
} |
q44141 | FileAwareParser.add_file_argument | train | def add_file_argument(self, *args, **kwargs):
""" Add an argument that represents the location of a file
:param args:
:param kwargs:
:return:
"""
rval = self.add_argument(*args, **kwargs)
self.file_args.append(rval)
return rval | python | {
"resource": ""
} |
q44142 | FileAwareParser.add_argument | train | def add_argument(self, *args, **kwargs):
""" Add an argument incorporating the default value into the help string
:param args:
:param kwargs:
:return:
"""
defhelp = kwargs.pop("help", None)
defaults = kwargs.pop("default", None)
default = defaults if self... | python | {
"resource": ""
} |
q44143 | pfdicom.tagsInString_process | train | def tagsInString_process(self, d_DICOM, astr, *args, **kwargs):
"""
This method substitutes DICOM tags that are '%'-tagged
in a string template with the actual tag lookup.
For example, an output filename that is specified as the
following string:
%PatientAge-%Patien... | python | {
"resource": ""
} |
q44144 | pfdicom.DICOMfile_read | train | def DICOMfile_read(self, *args, **kwargs):
"""
Read a DICOM file and perform some initial
parsing of tags.
NB!
For thread safety, class member variables
should not be assigned since other threads
might override/change these variables in mid-
flight!
... | python | {
"resource": ""
} |
q44145 | pfdicom.filelist_prune | train | def filelist_prune(self, at_data, *args, **kwargs):
"""
Given a list of files, possibly prune list by
extension.
"""
b_status = True
l_file = []
str_path = at_data[0]
al_file = at_data[1]
if len(self.str_extension):
al_... | python | {
"resource": ""
} |
q44146 | pfdicom.run | train | def run(self, *args, **kwargs):
"""
The run method is merely a thin shim down to the
embedded pftree run method.
"""
b_status = True
d_pftreeRun = {}
d_inputAnalysis = {}
d_env = self.env_check()
b_timerStart ... | python | {
"resource": ""
} |
q44147 | MajorDomoClient.reconnect_to_broker | train | def reconnect_to_broker(self):
"""Connect or reconnect to broker"""
#print "CONNECT !"
if self.client:
self.poller.unregister(self.client)
self.client.close()
self.client = self.ctx.socket(zmq.DEALER)
self.client.linger = 0
self.client.connect(self... | python | {
"resource": ""
} |
q44148 | MajorDomoClient.send | train | def send(self, service, request):
"""Send request to broker
"""
if not isinstance(request, list):
request = [request]
# Prefix request with protocol frames
# Frame 0: empty (REQ emulation)
# Frame 1: "MDPCxy" (six bytes, MDP/Client x.y)
# Frame 2: Ser... | python | {
"resource": ""
} |
q44149 | MajorDomoClient.recv | train | def recv(self):
"""Returns the reply message or None if there was no reply."""
try:
items = self.poller.poll(self.timeout)
except KeyboardInterrupt:
return # interrupted
if items:
# if we got a reply, process it
msg = self.client.recv_mul... | python | {
"resource": ""
} |
q44150 | get_identity_document | train | async def get_identity_document(client: Client, current_block: dict, pubkey: str) -> Identity:
"""
Get the identity document of the pubkey
:param client: Client to connect to the api
:param current_block: Current block data
:param pubkey: UID/Public key
:rtype: Identity
"""
# Here we r... | python | {
"resource": ""
} |
q44151 | get_certification_document | train | def get_certification_document(current_block: dict, self_cert_document: Identity, from_pubkey: str) -> Certification:
"""
Create and return a Certification document
:param current_block: Current block data
:param self_cert_document: Identity document
:param from_pubkey: Pubkey of the certifier
... | python | {
"resource": ""
} |
q44152 | detect_cycle | train | def detect_cycle(graph):
"""
search the given directed graph for cycles
returns None if the given graph is cycle free
otherwise it returns a path through the graph that contains a cycle
:param graph:
:return:
"""
visited_nodes = set()
for node in list(graph):
if node not i... | python | {
"resource": ""
} |
q44153 | main | train | def main():
cmd = sys.argv
cmd.pop(0)
"""
parse arguments and make go
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-s',
'--src',
help='source folder to watch',
default='.',
dest='src',
metavar='folder'
)
parser.add_argum... | python | {
"resource": ""
} |
q44154 | init_sources | train | def init_sources(path):
"""
initializes array of groups and their associated js files
"""
for f in dir_list(path):
if(os.path.splitext(f)[1][1:] == config.source_ext):
print "Source file discovered: %s" % (f)
script = Script(f)
if (script.filename not in confi... | python | {
"resource": ""
} |
q44155 | start_scanner | train | def start_scanner(path):
"""
watch for file events in the supplied path
"""
try:
observer = Observer()
observer.start()
stream = Stream(file_modified, path, file_events=True)
observer.schedule(stream)
print "Watching for changes. Press Ctrl-C to stop."
whi... | python | {
"resource": ""
} |
q44156 | file_modified | train | def file_modified(event):
"""
react to file events
"""
if re.match(config.file_regex,event.name) or (event.name in config.sources.keys()):
print "Change detected to: %s" % (event.name)
config.stack = []
script = config.sources[event.name]
if script.extension == config.sou... | python | {
"resource": ""
} |
q44157 | iter_tuple_from_csv | train | def iter_tuple_from_csv(path,
iterator=False,
chunksize=None,
skiprows=None,
nrows=None,
**kwargs):
"""A high performance, low memory usage csv file row iterator function.
:param path: csv fi... | python | {
"resource": ""
} |
q44158 | index_row_dict_from_csv | train | def index_row_dict_from_csv(path,
index_col=None,
iterator=False,
chunksize=None,
skiprows=None,
nrows=None,
use_ordered_dict=True,
... | python | {
"resource": ""
} |
q44159 | native_path | train | def native_path(path): # pragma: no cover
"""
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
Taken `from Django <http://bit.ly/1r3gogZ>`_.
"""
if PY2 and not isinstance(path, bytes):
return path.encode(fs_encoding)
return path | python | {
"resource": ""
} |
q44160 | select_field | train | def select_field(col, field_or_fields, filters=None):
"""Select single or multiple fields.
:params field_or_fields: str or list of str
:returns headers: headers
:return data: list of row
**中文文档**
- 在选择单列时, 返回的是 str, list.
- 在选择多列时, 返回的是 str list, list of list.
返回单列或多列的数据。
"""
... | python | {
"resource": ""
} |
q44161 | select_distinct_field | train | def select_distinct_field(col, field_or_fields, filters=None):
"""Select distinct value or combination of values of
single or multiple fields.
:params fields: str or list of str.
:return data: list of list.
**中文文档**
选择多列中出现过的所有可能的排列组合。
"""
fields = _preprocess_field_or_fields(field_or... | python | {
"resource": ""
} |
q44162 | random_sample | train | def random_sample(col, n=5, filters=None):
"""Randomly select n document from query result set. If no query specified,
then from entire collection.
**中文文档**
从collection中随机选择 ``n`` 个样本。
"""
pipeline = list()
if filters is not None:
pipeline.append({"$match": filters})
pipeline.a... | python | {
"resource": ""
} |
q44163 | _before_flush_handler | train | def _before_flush_handler(session, _flush_context, _instances):
"""Update version ID for all dirty, modified rows"""
dialect = get_dialect(session)
for row in session.dirty:
if isinstance(row, SavageModelMixin) and is_modified(row, dialect):
# Update row version_id
row.update... | python | {
"resource": ""
} |
q44164 | register_text_type | train | def register_text_type(content_type, default_encoding, dumper, loader):
"""
Register handling for a text-based content type.
:param str content_type: content type to register the hooks for
:param str default_encoding: encoding to use if none is present
in the request
:param dumper: called t... | python | {
"resource": ""
} |
q44165 | register_binary_type | train | def register_binary_type(content_type, dumper, loader):
"""
Register handling for a binary content type.
:param str content_type: content type to register the hooks for
:param dumper: called to decode bytes into a dictionary.
Calling convention: ``dumper(obj_dict) -> bytes``.
:param loader:... | python | {
"resource": ""
} |
q44166 | _ContentHandler.unpack_bytes | train | def unpack_bytes(self, obj_bytes, encoding=None):
"""Unpack a byte stream into a dictionary."""
assert self.bytes_to_dict or self.string_to_dict
encoding = encoding or self.default_encoding
LOGGER.debug('%r decoding %d bytes with encoding of %s',
self, len(obj_bytes)... | python | {
"resource": ""
} |
q44167 | _ContentHandler.pack_bytes | train | def pack_bytes(self, obj_dict, encoding=None):
"""Pack a dictionary into a byte stream."""
assert self.dict_to_bytes or self.dict_to_string
encoding = encoding or self.default_encoding or 'utf-8'
LOGGER.debug('%r encoding dict with encoding %s', self, encoding)
if self.dict_to_by... | python | {
"resource": ""
} |
q44168 | HandlerMixin.get_request_body | train | def get_request_body(self):
"""
Decodes the request body and returns it.
:return: the decoded request body as a :class:`dict` instance.
:raises: :class:`tornado.web.HTTPError` if the body cannot be
decoded (415) or if decoding fails (400)
"""
if self._reques... | python | {
"resource": ""
} |
q44169 | HandlerMixin.send_response | train | def send_response(self, response_dict):
"""
Encode a response according to the request.
:param dict response_dict: the response to send
:raises: :class:`tornado.web.HTTPError` if no acceptable content
type exists
This method will encode `response_dict` using the mo... | python | {
"resource": ""
} |
q44170 | parse_env | train | def parse_env(config_schema, env):
"""Parse the values from a given environment against a given config schema
Args:
config_schema: A dict which maps the variable name to a Schema object
that describes the requested value.
env: A dict which represents the value of each variable in th... | python | {
"resource": ""
} |
q44171 | Schema.parse | train | def parse(self, key, value):
"""Parse the environment value for a given key against the schema.
Args:
key: The name of the environment variable.
value: The value to be parsed.
"""
if value is not None:
try:
return self._parser(value)
... | python | {
"resource": ""
} |
q44172 | write_json_to_temp_file | train | def write_json_to_temp_file(data):
"""Writes JSON data to a temporary file and returns the path to it"""
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write(json.dumps(data).encode('utf-8'))
fp.close()
return fp.name | python | {
"resource": ""
} |
q44173 | mock_lockfile_update | train | def mock_lockfile_update(path):
"""
This is a mock update. In place of this, you might simply shell out
to a command like `yarn upgrade`.
"""
updated_lockfile_contents = {
'package1': '1.2.0'
}
with open(path, 'w+') as f:
f.write(json.dumps(updated_lockfile_contents, indent=4... | python | {
"resource": ""
} |
q44174 | print_settings_example | train | def print_settings_example():
"""
You can use settings to get additional information from the user via their
dependencies.io configuration file. Settings will be automatically injected as
env variables with the "SETTING_" prefix.
All settings will be passed as strings. More complex types will be js... | python | {
"resource": ""
} |
q44175 | otsu | train | def otsu(fpath):
"""
Returns value of otsu threshold for an image
"""
img = imread(fpath, as_grey=True)
thresh = skimage.filter.threshold_otsu(img)
return thresh | python | {
"resource": ""
} |
q44176 | move_to | train | def move_to(name):
"""
Path to image folders
"""
datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)
datapath = path.join(datapath, '../gzoo_data', 'images', name)
print path.normpath(datapath)
return path.normpath(datapath) | python | {
"resource": ""
} |
q44177 | labels | train | def labels():
"""
Path to labels file
"""
datapath = path.join(path.dirname(path.realpath(__file__)), path.pardir)
datapath = path.join(datapath, '../gzoo_data', 'train_solution.csv')
return path.normpath(datapath) | python | {
"resource": ""
} |
q44178 | _make_json_result | train | def _make_json_result(code, message="", results=None):
"""
An utility method to prepare a JSON result string, usable by the
SignalReceiver
:param code: A HTTP Code
:param message: An associated message
"""
return code, json.dumps({'code': code,
'message': messag... | python | {
"resource": ""
} |
q44179 | temp_file_context | train | def temp_file_context(raw_dump_path, logger=None):
"""this contextmanager implements conditionally deleting a pathname
at the end of a context if the pathname indicates that it is a temp
file by having the word 'TEMPORARY' embedded in it."""
try:
yield raw_dump_path
finally:
if 'TEMP... | python | {
"resource": ""
} |
q44180 | membership | train | async def membership(client: Client, membership_signed_raw: str) -> ClientResponse:
"""
POST a Membership document
:param client: Client to connect to the api
:param membership_signed_raw: Membership signed raw document
:return:
"""
return await client.post(MODULE + '/membership', {'members... | python | {
"resource": ""
} |
q44181 | blocks | train | async def blocks(client: Client, count: int, start: int) -> list:
"""
GET list of blocks from the blockchain
:param client: Client to connect to the api
:param count: Number of blocks
:param start: First block number
:return:
"""
assert type(count) is int
assert type(start) is int
... | python | {
"resource": ""
} |
q44182 | hardship | train | async def hardship(client: Client, pubkey: str) -> dict:
"""
GET hardship level for given member's public key for writing next block
:param client: Client to connect to the api
:param pubkey: Public key of the member
:return:
"""
return await client.get(MODULE + '/hardship/%s' % pubkey, sc... | python | {
"resource": ""
} |
q44183 | block_uid | train | def block_uid(value: Union[str, BlockUID, None]) -> BlockUID:
"""
Convert value to BlockUID instance
:param value: Value to convert
:return:
"""
if isinstance(value, BlockUID):
return value
elif isinstance(value, str):
return BlockUID.from_str(value)
elif value is None:
... | python | {
"resource": ""
} |
q44184 | make_heartbeat | train | def make_heartbeat(port, path, peer_uid, node_uid, app_id):
"""
Prepares the heart beat UDP packet
Format : Little endian
* Kind of beat (1 byte)
* Herald HTTP server port (2 bytes)
* Herald HTTP servlet path length (2 bytes)
* Herald HTTP servlet path (variable, UTF-8)
* Peer UID lengt... | python | {
"resource": ""
} |
q44185 | MulticastReceiver.start | train | def start(self):
"""
Starts listening to the socket
:return: True if the socket has been created
"""
# Create the multicast socket (update the group)
self._socket, self._group = create_multicast_socket(self._group,
... | python | {
"resource": ""
} |
q44186 | MulticastReceiver.stop | train | def stop(self):
"""
Stops listening to the socket
"""
# Stop the loop
self._stop_event.set()
# Join the thread
self._thread.join()
self._thread = None
# Close the socket
close_multicast_socket(self._socket, self._group) | python | {
"resource": ""
} |
q44187 | MulticastReceiver._handle_heartbeat | train | def _handle_heartbeat(self, sender, data):
"""
Handles a raw heart beat
:param sender: Sender (address, port) tuple
:param data: Raw packet data
"""
# Format of packet
parsed, data = self._unpack("<B", data)
format = parsed[0]
if format == PACKET_... | python | {
"resource": ""
} |
q44188 | MulticastReceiver._unpack_string | train | def _unpack_string(self, data):
"""
Unpacks the next string from the given data
:param data: A datagram, starting at a string size
:return: A (string, unread_data) tuple
"""
# Get the size of the string
result, data = self._unpack("<H", data)
size = resul... | python | {
"resource": ""
} |
q44189 | MulticastReceiver.__read | train | def __read(self):
"""
Reads packets from the socket
"""
# Set the socket as non-blocking
self._socket.setblocking(0)
while not self._stop_event.is_set():
# Watch for content
ready = select.select([self._socket], [], [], 1)
if ready[0]:... | python | {
"resource": ""
} |
q44190 | get_log_config | train | def get_log_config(component, handlers, level='DEBUG', path='/var/log/vfine/'):
"""Return a log config for django project."""
config = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s][%(thr... | python | {
"resource": ""
} |
q44191 | SplitColoredFormatter.format | train | def format(self, record):
"""Format a message from a record object."""
record = ColoredRecord(record)
record.log_color = self.color(self.log_colors, record.levelname)
# Set secondary log colors
if self.secondary_log_colors:
for name, log_colors in self.secondary_log_... | python | {
"resource": ""
} |
q44192 | get_console_logger | train | def get_console_logger():
""" just for kkconst demos """
global __console_logger
if __console_logger:
return __console_logger
logger = logging.getLogger("kkconst")
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = loggi... | python | {
"resource": ""
} |
q44193 | reduce_base | train | def reduce_base(amount: int, base: int) -> tuple:
"""
Compute the reduced base of the given parameters
:param amount: the amount value
:param base: current base value
:return: tuple containing computed (amount, base)
"""
if amount == 0:
return 0, 0
next_amount = amount
nex... | python | {
"resource": ""
} |
q44194 | InputSource.from_inline | train | def from_inline(cls: Type[InputSourceType], tx_version: int, inline: str) -> InputSourceType:
"""
Return Transaction instance from inline string format
:param tx_version: Version number of the document
:param inline: Inline string format
:return:
"""
if tx_versio... | python | {
"resource": ""
} |
q44195 | OutputSource.from_inline | train | def from_inline(cls: Type[OutputSourceType], inline: str) -> OutputSourceType:
"""
Return OutputSource instance from inline string format
:param inline: Inline string format
:return:
"""
data = OutputSource.re_inline.match(inline)
if data is None:
rai... | python | {
"resource": ""
} |
q44196 | OutputSource.condition_from_text | train | def condition_from_text(text) -> Condition:
"""
Return a Condition instance with PEG grammar from text
:param text: PEG parsable string
:return:
"""
try:
condition = pypeg2.parse(text, output.Condition)
except SyntaxError:
# Invalid condit... | python | {
"resource": ""
} |
q44197 | SIGParameter.from_parameter | train | def from_parameter(cls: Type[SIGParameterType], parameter: str) -> Optional[SIGParameterType]:
"""
Return a SIGParameter instance from an index parameter
:param parameter: Index parameter
:return:
"""
sig = SIGParameter.re_sig.match(parameter)
if sig:
... | python | {
"resource": ""
} |
q44198 | XHXParameter.from_parameter | train | def from_parameter(cls: Type[XHXParameterType], parameter: str) -> Optional[XHXParameterType]:
"""
Return a XHXParameter instance from an index parameter
:param parameter: Index parameter
:return:
"""
xhx = XHXParameter.re_xhx.match(parameter)
if xhx:
... | python | {
"resource": ""
} |
q44199 | UnlockParameter.from_parameter | train | def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]:
"""
Return UnlockParameter instance from parameter string
:param parameter: Parameter string
:return:
"""
sig_param = SIGParameter.from_parameter(parameter... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.