repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
emichael/PyREM | pyrem/host.py | RemoteHost.get_file | def get_file(self, file_name, local_destination=None, **kwargs):
"""Get a file from a remote host with rsync.
Args:
file_name (str): The relative location of the file on the remote
host.
local_destination (str): The destination for the file on the local
host. If `None`, will be assumed to be the same as
**file_name**. Default `None`.
**kwargs: Passed to ``SubprocessTask``'s init method.
Return:
``pyrem.task.SubprocessTask``: The resulting task.
"""
if not local_destination:
local_destination = file_name
return SubprocessTask(
self._rsync_cmd() +
['-ut', '%s:%s' % (self.hostname, file_name), local_destination],
**kwargs) | python | def get_file(self, file_name, local_destination=None, **kwargs):
"""Get a file from a remote host with rsync.
Args:
file_name (str): The relative location of the file on the remote
host.
local_destination (str): The destination for the file on the local
host. If `None`, will be assumed to be the same as
**file_name**. Default `None`.
**kwargs: Passed to ``SubprocessTask``'s init method.
Return:
``pyrem.task.SubprocessTask``: The resulting task.
"""
if not local_destination:
local_destination = file_name
return SubprocessTask(
self._rsync_cmd() +
['-ut', '%s:%s' % (self.hostname, file_name), local_destination],
**kwargs) | [
"def",
"get_file",
"(",
"self",
",",
"file_name",
",",
"local_destination",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"local_destination",
":",
"local_destination",
"=",
"file_name",
"return",
"SubprocessTask",
"(",
"self",
".",
"_rsync_cmd"... | Get a file from a remote host with rsync.
Args:
file_name (str): The relative location of the file on the remote
host.
local_destination (str): The destination for the file on the local
host. If `None`, will be assumed to be the same as
**file_name**. Default `None`.
**kwargs: Passed to ``SubprocessTask``'s init method.
Return:
``pyrem.task.SubprocessTask``: The resulting task. | [
"Get",
"a",
"file",
"from",
"a",
"remote",
"host",
"with",
"rsync",
"."
] | 2609249ead197cd9496d164f4998ca9985503579 | https://github.com/emichael/PyREM/blob/2609249ead197cd9496d164f4998ca9985503579/pyrem/host.py#L92-L114 | train | 49,900 |
Clinical-Genomics/trailblazer | trailblazer/mip/config.py | ConfigHandler.make_config | def make_config(self, data: dict):
"""Make a MIP config."""
self.validate_config(data)
config_data = self.prepare_config(data)
return config_data | python | def make_config(self, data: dict):
"""Make a MIP config."""
self.validate_config(data)
config_data = self.prepare_config(data)
return config_data | [
"def",
"make_config",
"(",
"self",
",",
"data",
":",
"dict",
")",
":",
"self",
".",
"validate_config",
"(",
"data",
")",
"config_data",
"=",
"self",
".",
"prepare_config",
"(",
"data",
")",
"return",
"config_data"
] | Make a MIP config. | [
"Make",
"a",
"MIP",
"config",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/config.py#L43-L47 | train | 49,901 |
Clinical-Genomics/trailblazer | trailblazer/mip/config.py | ConfigHandler.validate_config | def validate_config(data: dict) -> dict:
"""Convert to MIP config format."""
errors = ConfigSchema().validate(data)
if errors:
for field, messages in errors.items():
if isinstance(messages, dict):
for level, sample_errors in messages.items():
sample_id = data['samples'][level]['sample_id']
for sub_field, sub_messages in sample_errors.items():
LOG.error(f"{sample_id} -> {sub_field}: {', '.join(sub_messages)}")
else:
LOG.error(f"{field}: {', '.join(messages)}")
raise ConfigError('invalid config input', errors=errors) | python | def validate_config(data: dict) -> dict:
"""Convert to MIP config format."""
errors = ConfigSchema().validate(data)
if errors:
for field, messages in errors.items():
if isinstance(messages, dict):
for level, sample_errors in messages.items():
sample_id = data['samples'][level]['sample_id']
for sub_field, sub_messages in sample_errors.items():
LOG.error(f"{sample_id} -> {sub_field}: {', '.join(sub_messages)}")
else:
LOG.error(f"{field}: {', '.join(messages)}")
raise ConfigError('invalid config input', errors=errors) | [
"def",
"validate_config",
"(",
"data",
":",
"dict",
")",
"->",
"dict",
":",
"errors",
"=",
"ConfigSchema",
"(",
")",
".",
"validate",
"(",
"data",
")",
"if",
"errors",
":",
"for",
"field",
",",
"messages",
"in",
"errors",
".",
"items",
"(",
")",
":",... | Convert to MIP config format. | [
"Convert",
"to",
"MIP",
"config",
"format",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/config.py#L50-L62 | train | 49,902 |
Clinical-Genomics/trailblazer | trailblazer/mip/config.py | ConfigHandler.prepare_config | def prepare_config(data: dict) -> dict:
"""Prepare the config data."""
data_copy = deepcopy(data)
# handle single sample cases with 'unknown' phenotype
if len(data_copy['samples']) == 1:
if data_copy['samples'][0]['phenotype'] == 'unknown':
LOG.info("setting 'unknown' phenotype to 'unaffected'")
data_copy['samples'][0]['phenotype'] = 'unaffected'
# set the mother/father to '0' if they are not set for a sample
for sample_data in data_copy['samples']:
sample_data['mother'] = sample_data.get('mother') or '0'
sample_data['father'] = sample_data.get('father') or '0'
if sample_data['analysis_type'] == 'wgs' and sample_data.get('capture_kit') is None:
sample_data['capture_kit'] = DEFAULT_CAPTURE_KIT
return data_copy | python | def prepare_config(data: dict) -> dict:
"""Prepare the config data."""
data_copy = deepcopy(data)
# handle single sample cases with 'unknown' phenotype
if len(data_copy['samples']) == 1:
if data_copy['samples'][0]['phenotype'] == 'unknown':
LOG.info("setting 'unknown' phenotype to 'unaffected'")
data_copy['samples'][0]['phenotype'] = 'unaffected'
# set the mother/father to '0' if they are not set for a sample
for sample_data in data_copy['samples']:
sample_data['mother'] = sample_data.get('mother') or '0'
sample_data['father'] = sample_data.get('father') or '0'
if sample_data['analysis_type'] == 'wgs' and sample_data.get('capture_kit') is None:
sample_data['capture_kit'] = DEFAULT_CAPTURE_KIT
return data_copy | [
"def",
"prepare_config",
"(",
"data",
":",
"dict",
")",
"->",
"dict",
":",
"data_copy",
"=",
"deepcopy",
"(",
"data",
")",
"# handle single sample cases with 'unknown' phenotype",
"if",
"len",
"(",
"data_copy",
"[",
"'samples'",
"]",
")",
"==",
"1",
":",
"if",... | Prepare the config data. | [
"Prepare",
"the",
"config",
"data",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/config.py#L65-L79 | train | 49,903 |
Clinical-Genomics/trailblazer | trailblazer/mip/config.py | ConfigHandler.save_config | def save_config(self, data: dict) -> Path:
"""Save a config to the expected location."""
out_dir = Path(self.families_dir) / data['family']
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / 'pedigree.yaml'
dump = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2)
out_path.write_text(dump)
return out_path | python | def save_config(self, data: dict) -> Path:
"""Save a config to the expected location."""
out_dir = Path(self.families_dir) / data['family']
out_dir.mkdir(parents=True, exist_ok=True)
out_path = out_dir / 'pedigree.yaml'
dump = ruamel.yaml.round_trip_dump(data, indent=4, block_seq_indent=2)
out_path.write_text(dump)
return out_path | [
"def",
"save_config",
"(",
"self",
",",
"data",
":",
"dict",
")",
"->",
"Path",
":",
"out_dir",
"=",
"Path",
"(",
"self",
".",
"families_dir",
")",
"/",
"data",
"[",
"'family'",
"]",
"out_dir",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_o... | Save a config to the expected location. | [
"Save",
"a",
"config",
"to",
"the",
"expected",
"location",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/config.py#L81-L88 | train | 49,904 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | create_broadcast | def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x):
"""
This method creates a function, intended to be called as a
Processor posthook, that copies some of the processor's attributes
to other processors
"""
from functools import partial
if dest_atr_name == None:
dest_atr_name = src_atr_name
if not hasattr(dest_processors, "__iter__"): # a single processor was given instead
dest_processors = [dest_processors]
return partial(_broadcast, src_atr_name=src_atr_name, dest_processors=dest_processors, dest_atr_name=dest_atr_name,
transform_function=transform_function) | python | def create_broadcast(src_atr_name, dest_processors, dest_atr_name=None, transform_function=lambda x: x):
"""
This method creates a function, intended to be called as a
Processor posthook, that copies some of the processor's attributes
to other processors
"""
from functools import partial
if dest_atr_name == None:
dest_atr_name = src_atr_name
if not hasattr(dest_processors, "__iter__"): # a single processor was given instead
dest_processors = [dest_processors]
return partial(_broadcast, src_atr_name=src_atr_name, dest_processors=dest_processors, dest_atr_name=dest_atr_name,
transform_function=transform_function) | [
"def",
"create_broadcast",
"(",
"src_atr_name",
",",
"dest_processors",
",",
"dest_atr_name",
"=",
"None",
",",
"transform_function",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"from",
"functools",
"import",
"partial",
"if",
"dest_atr_name",
"==",
"None",
":",
"d... | This method creates a function, intended to be called as a
Processor posthook, that copies some of the processor's attributes
to other processors | [
"This",
"method",
"creates",
"a",
"function",
"intended",
"to",
"be",
"called",
"as",
"a",
"Processor",
"posthook",
"that",
"copies",
"some",
"of",
"the",
"processor",
"s",
"attributes",
"to",
"other",
"processors"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L25-L37 | train | 49,905 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | Processor.get_parameters | def get_parameters(self):
"""returns a dictionary with the processor's stored parameters"""
parameter_names = self.PARAMETERS.keys()
# TODO: Unresolved reference for processor
parameter_values = [getattr(processor, n) for n in parameter_names]
return dict(zip(parameter_names, parameter_values)) | python | def get_parameters(self):
"""returns a dictionary with the processor's stored parameters"""
parameter_names = self.PARAMETERS.keys()
# TODO: Unresolved reference for processor
parameter_values = [getattr(processor, n) for n in parameter_names]
return dict(zip(parameter_names, parameter_values)) | [
"def",
"get_parameters",
"(",
"self",
")",
":",
"parameter_names",
"=",
"self",
".",
"PARAMETERS",
".",
"keys",
"(",
")",
"# TODO: Unresolved reference for processor",
"parameter_values",
"=",
"[",
"getattr",
"(",
"processor",
",",
"n",
")",
"for",
"n",
"in",
... | returns a dictionary with the processor's stored parameters | [
"returns",
"a",
"dictionary",
"with",
"the",
"processor",
"s",
"stored",
"parameters"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L66-L71 | train | 49,906 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | Processor.set_parameters | def set_parameters(self, **args):
"""sets the processor stored parameters"""
for k, v in self.PARAMETERS.items():
new_value = args.get(k)
if new_value != None:
if not _same_type(new_value, v):
raise Exception(
"On processor {0}, argument {1} takes something like {2}, but {3} was given".format(self, k, v,
new_value))
setattr(self, k, new_value)
not_used = set(args.keys()).difference(set(self.PARAMETERS.keys()))
not_given = set(self.PARAMETERS.keys()).difference(set(args.keys()))
return not_used, not_given | python | def set_parameters(self, **args):
"""sets the processor stored parameters"""
for k, v in self.PARAMETERS.items():
new_value = args.get(k)
if new_value != None:
if not _same_type(new_value, v):
raise Exception(
"On processor {0}, argument {1} takes something like {2}, but {3} was given".format(self, k, v,
new_value))
setattr(self, k, new_value)
not_used = set(args.keys()).difference(set(self.PARAMETERS.keys()))
not_given = set(self.PARAMETERS.keys()).difference(set(args.keys()))
return not_used, not_given | [
"def",
"set_parameters",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"PARAMETERS",
".",
"items",
"(",
")",
":",
"new_value",
"=",
"args",
".",
"get",
"(",
"k",
")",
"if",
"new_value",
"!=",
"None",
":",
... | sets the processor stored parameters | [
"sets",
"the",
"processor",
"stored",
"parameters"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L73-L85 | train | 49,907 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | ProcessorStack.get_parameters | def get_parameters(self):
"""gets from all wrapped processors"""
d = {}
for p in self.processors:
parameter_names = list(p.PARAMETERS.keys())
parameter_values = [getattr(p, n) for n in parameter_names]
d.update(dict(zip(parameter_names, parameter_values)))
return d | python | def get_parameters(self):
"""gets from all wrapped processors"""
d = {}
for p in self.processors:
parameter_names = list(p.PARAMETERS.keys())
parameter_values = [getattr(p, n) for n in parameter_names]
d.update(dict(zip(parameter_names, parameter_values)))
return d | [
"def",
"get_parameters",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"processors",
":",
"parameter_names",
"=",
"list",
"(",
"p",
".",
"PARAMETERS",
".",
"keys",
"(",
")",
")",
"parameter_values",
"=",
"[",
"getattr",
"(... | gets from all wrapped processors | [
"gets",
"from",
"all",
"wrapped",
"processors"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L128-L135 | train | 49,908 |
andrewda/frc-livescore | livescore/simpleocr_utils/processor.py | ProcessorStack.set_parameters | def set_parameters(self, **args):
"""sets to all wrapped processors"""
not_used = set()
not_given = set()
for p in self.processors:
nu, ng = p.set_parameters(**args)
not_used = not_used.union(nu)
not_given = not_given.union(ng)
return not_used, not_given | python | def set_parameters(self, **args):
"""sets to all wrapped processors"""
not_used = set()
not_given = set()
for p in self.processors:
nu, ng = p.set_parameters(**args)
not_used = not_used.union(nu)
not_given = not_given.union(ng)
return not_used, not_given | [
"def",
"set_parameters",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"not_used",
"=",
"set",
"(",
")",
"not_given",
"=",
"set",
"(",
")",
"for",
"p",
"in",
"self",
".",
"processors",
":",
"nu",
",",
"ng",
"=",
"p",
".",
"set_parameters",
"(",
"... | sets to all wrapped processors | [
"sets",
"to",
"all",
"wrapped",
"processors"
] | 71594cd6d2c8b6c5feb3889bb05552d09b8128b1 | https://github.com/andrewda/frc-livescore/blob/71594cd6d2c8b6c5feb3889bb05552d09b8128b1/livescore/simpleocr_utils/processor.py#L137-L145 | train | 49,909 |
daskol/nls | nls/animation.py | AbstractAnimation.render | def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.saving(fig, filename, dpi):
for frame_id in xrange(self.frames + 1):
self.renderFrame(frame_id)
self.writer.grab_frame()
self.elapsed_time += time() | python | def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.saving(fig, filename, dpi):
for frame_id in xrange(self.frames + 1):
self.renderFrame(frame_id)
self.writer.grab_frame()
self.elapsed_time += time() | [
"def",
"render",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"elapsed_time",
"=",
"-",
"time",
"(",
")",
"dpi",
"=",
"100",
"fig",
"=",
"figure",
"(",
"figsize",
"=",
"(",
"16",
",",
"9",
")",
",",
"dpi",
"=",
"dpi",
")",
"with",
"self... | Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class. | [
"Perform",
"initialization",
"of",
"render",
"set",
"quality",
"and",
"size",
"video",
"attributes",
"and",
"then",
"call",
"template",
"method",
"that",
"is",
"defined",
"in",
"child",
"class",
"."
] | 00bb4555e4f56e222dc6f54faf2e286567519626 | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/animation.py#L30-L41 | train | 49,910 |
daskol/nls | nls/animation.py | AbstractAnimation.report | def report(self):
"""Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation.
"""
message = 'Elapsed in {0} seconds with {1} frames and {2} step.'
print(message.format(self.elapsed_time, self.frames, self.step)) | python | def report(self):
"""Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation.
"""
message = 'Elapsed in {0} seconds with {1} frames and {2} step.'
print(message.format(self.elapsed_time, self.frames, self.step)) | [
"def",
"report",
"(",
"self",
")",
":",
"message",
"=",
"'Elapsed in {0} seconds with {1} frames and {2} step.'",
"print",
"(",
"message",
".",
"format",
"(",
"self",
".",
"elapsed_time",
",",
"self",
".",
"frames",
",",
"self",
".",
"step",
")",
")"
] | Prints in standard output report about animation rendering. Namely, it prints seconds spent, number of
frames and step size that is used in functional animation. | [
"Prints",
"in",
"standard",
"output",
"report",
"about",
"animation",
"rendering",
".",
"Namely",
"it",
"prints",
"seconds",
"spent",
"number",
"of",
"frames",
"and",
"step",
"size",
"that",
"is",
"used",
"in",
"functional",
"animation",
"."
] | 00bb4555e4f56e222dc6f54faf2e286567519626 | https://github.com/daskol/nls/blob/00bb4555e4f56e222dc6f54faf2e286567519626/nls/animation.py#L48-L53 | train | 49,911 |
pytroll/posttroll | posttroll/subscriber.py | Subscriber.update | def update(self, addresses):
"""Updating with a set of addresses.
"""
if isinstance(addresses, six.string_types):
addresses = [addresses, ]
s0_, s1_ = set(self.addresses), set(addresses)
sr_, sa_ = s0_.difference(s1_), s1_.difference(s0_)
for a__ in sr_:
self.remove(a__)
for a__ in sa_:
self.add(a__)
return bool(sr_ or sa_) | python | def update(self, addresses):
"""Updating with a set of addresses.
"""
if isinstance(addresses, six.string_types):
addresses = [addresses, ]
s0_, s1_ = set(self.addresses), set(addresses)
sr_, sa_ = s0_.difference(s1_), s1_.difference(s0_)
for a__ in sr_:
self.remove(a__)
for a__ in sa_:
self.add(a__)
return bool(sr_ or sa_) | [
"def",
"update",
"(",
"self",
",",
"addresses",
")",
":",
"if",
"isinstance",
"(",
"addresses",
",",
"six",
".",
"string_types",
")",
":",
"addresses",
"=",
"[",
"addresses",
",",
"]",
"s0_",
",",
"s1_",
"=",
"set",
"(",
"self",
".",
"addresses",
")"... | Updating with a set of addresses. | [
"Updating",
"with",
"a",
"set",
"of",
"addresses",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L128-L139 | train | 49,912 |
pytroll/posttroll | posttroll/subscriber.py | Subscriber._add_hook | def _add_hook(self, socket, callback):
"""Generic hook. The passed socket has to be "receive only".
"""
self._hooks.append(socket)
self._hooks_cb[socket] = callback
if self.poller:
self.poller.register(socket, POLLIN) | python | def _add_hook(self, socket, callback):
"""Generic hook. The passed socket has to be "receive only".
"""
self._hooks.append(socket)
self._hooks_cb[socket] = callback
if self.poller:
self.poller.register(socket, POLLIN) | [
"def",
"_add_hook",
"(",
"self",
",",
"socket",
",",
"callback",
")",
":",
"self",
".",
"_hooks",
".",
"append",
"(",
"socket",
")",
"self",
".",
"_hooks_cb",
"[",
"socket",
"]",
"=",
"callback",
"if",
"self",
".",
"poller",
":",
"self",
".",
"poller... | Generic hook. The passed socket has to be "receive only". | [
"Generic",
"hook",
".",
"The",
"passed",
"socket",
"has",
"to",
"be",
"receive",
"only",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L166-L172 | train | 49,913 |
pytroll/posttroll | posttroll/subscriber.py | Subscriber._magickfy_topics | def _magickfy_topics(topics):
"""Add the magick to the topics if missing.
"""
# If topic does not start with messages._MAGICK (pytroll:/), it will be
# prepended.
if topics is None:
return None
if isinstance(topics, six.string_types):
topics = [topics, ]
ts_ = []
for t__ in topics:
if not t__.startswith(_MAGICK):
if t__ and t__[0] == '/':
t__ = _MAGICK + t__
else:
t__ = _MAGICK + '/' + t__
ts_.append(t__)
return ts_ | python | def _magickfy_topics(topics):
"""Add the magick to the topics if missing.
"""
# If topic does not start with messages._MAGICK (pytroll:/), it will be
# prepended.
if topics is None:
return None
if isinstance(topics, six.string_types):
topics = [topics, ]
ts_ = []
for t__ in topics:
if not t__.startswith(_MAGICK):
if t__ and t__[0] == '/':
t__ = _MAGICK + t__
else:
t__ = _MAGICK + '/' + t__
ts_.append(t__)
return ts_ | [
"def",
"_magickfy_topics",
"(",
"topics",
")",
":",
"# If topic does not start with messages._MAGICK (pytroll:/), it will be",
"# prepended.",
"if",
"topics",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"topics",
",",
"six",
".",
"string_types",
")",
... | Add the magick to the topics if missing. | [
"Add",
"the",
"magick",
"to",
"the",
"topics",
"if",
"missing",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L245-L262 | train | 49,914 |
pytroll/posttroll | posttroll/subscriber.py | NSSubscriber.start | def start(self):
"""Start the subscriber.
"""
def _get_addr_loop(service, timeout):
"""Try to get the address of *service* until for *timeout* seconds.
"""
then = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < then:
addrs = get_pub_address(service, nameserver=self._nameserver)
if addrs:
return [addr["URI"] for addr in addrs]
time.sleep(1)
return []
# Subscribe to those services and topics.
LOGGER.debug("Subscribing to topics %s", str(self._topics))
self._subscriber = Subscriber(self._addresses,
self._topics,
translate=self._translate)
if self._addr_listener:
self._addr_listener = _AddressListener(self._subscriber,
self._services,
nameserver=self._nameserver)
# Search for addresses corresponding to service.
for service in self._services:
addresses = _get_addr_loop(service, self._timeout)
if not addresses:
LOGGER.warning("Can't get any address for %s", service)
continue
else:
LOGGER.debug("Got address for %s: %s",
str(service), str(addresses))
for addr in addresses:
self._subscriber.add(addr)
return self._subscriber | python | def start(self):
"""Start the subscriber.
"""
def _get_addr_loop(service, timeout):
"""Try to get the address of *service* until for *timeout* seconds.
"""
then = datetime.now() + timedelta(seconds=timeout)
while datetime.now() < then:
addrs = get_pub_address(service, nameserver=self._nameserver)
if addrs:
return [addr["URI"] for addr in addrs]
time.sleep(1)
return []
# Subscribe to those services and topics.
LOGGER.debug("Subscribing to topics %s", str(self._topics))
self._subscriber = Subscriber(self._addresses,
self._topics,
translate=self._translate)
if self._addr_listener:
self._addr_listener = _AddressListener(self._subscriber,
self._services,
nameserver=self._nameserver)
# Search for addresses corresponding to service.
for service in self._services:
addresses = _get_addr_loop(service, self._timeout)
if not addresses:
LOGGER.warning("Can't get any address for %s", service)
continue
else:
LOGGER.debug("Got address for %s: %s",
str(service), str(addresses))
for addr in addresses:
self._subscriber.add(addr)
return self._subscriber | [
"def",
"start",
"(",
"self",
")",
":",
"def",
"_get_addr_loop",
"(",
"service",
",",
"timeout",
")",
":",
"\"\"\"Try to get the address of *service* until for *timeout* seconds.\n \"\"\"",
"then",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timedelta",
"("... | Start the subscriber. | [
"Start",
"the",
"subscriber",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/subscriber.py#L306-L343 | train | 49,915 |
thespacedoctor/sherlock | sherlock/transient_classifier.py | transient_classifier._get_transient_metadata_from_database_list | def _get_transient_metadata_from_database_list(
self):
"""use the transient query in the settings file to generate a list of transients to corssmatch and classify
**Return:**
- ``transientsMetadataList``
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_get_transient_metadata_from_database_list`` method')
sqlQuery = self.settings["database settings"][
"transients"]["transient query"] + " limit " + str(self.largeBatchSize)
thisInt = randint(0, 100)
if "where" in sqlQuery:
sqlQuery = sqlQuery.replace(
"where", "where %(thisInt)s=%(thisInt)s and " % locals())
transientsMetadataList = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.transientsDbConn,
quiet=False
)
self.log.debug(
'completed the ``_get_transient_metadata_from_database_list`` method')
return transientsMetadataList | python | def _get_transient_metadata_from_database_list(
self):
"""use the transient query in the settings file to generate a list of transients to corssmatch and classify
**Return:**
- ``transientsMetadataList``
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug(
'starting the ``_get_transient_metadata_from_database_list`` method')
sqlQuery = self.settings["database settings"][
"transients"]["transient query"] + " limit " + str(self.largeBatchSize)
thisInt = randint(0, 100)
if "where" in sqlQuery:
sqlQuery = sqlQuery.replace(
"where", "where %(thisInt)s=%(thisInt)s and " % locals())
transientsMetadataList = readquery(
log=self.log,
sqlQuery=sqlQuery,
dbConn=self.transientsDbConn,
quiet=False
)
self.log.debug(
'completed the ``_get_transient_metadata_from_database_list`` method')
return transientsMetadataList | [
"def",
"_get_transient_metadata_from_database_list",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_get_transient_metadata_from_database_list`` method'",
")",
"sqlQuery",
"=",
"self",
".",
"settings",
"[",
"\"database settings\"",
"]",
"["... | use the transient query in the settings file to generate a list of transients to corssmatch and classify
**Return:**
- ``transientsMetadataList``
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring | [
"use",
"the",
"transient",
"query",
"in",
"the",
"settings",
"file",
"to",
"generate",
"a",
"list",
"of",
"transients",
"to",
"corssmatch",
"and",
"classify"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L440-L477 | train | 49,916 |
thespacedoctor/sherlock | sherlock/transient_classifier.py | transient_classifier._remove_previous_ned_queries | def _remove_previous_ned_queries(
self,
coordinateList):
"""iterate through the transient locations to see if we have recent local NED coverage of that area already
**Key Arguments:**
- ``coordinateList`` -- set of coordinate to check for previous queries
**Return:**
- ``updatedCoordinateList`` -- coordinate list with previous queries removed
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug('starting the ``_remove_previous_ned_queries`` method')
# 1 DEGREE QUERY RADIUS
radius = 60. * 60.
updatedCoordinateList = []
keepers = []
# CALCULATE THE OLDEST RESULTS LIMIT
now = datetime.now()
td = timedelta(
days=self.settings["ned stream refresh rate in days"])
refreshLimit = now - td
refreshLimit = refreshLimit.strftime("%Y-%m-%d %H:%M:%S")
raList = []
raList[:] = [c[0] for c in coordinateList]
decList = []
decList[:] = [c[1] for c in coordinateList]
# MATCH COORDINATES AGAINST PREVIOUS NED SEARCHES
cs = conesearch(
log=self.log,
dbConn=self.cataloguesDbConn,
tableName="tcs_helper_ned_query_history",
columns="*",
ra=raList,
dec=decList,
radiusArcsec=radius,
separations=True,
distinct=True,
sqlWhere="dateQueried > '%(refreshLimit)s'" % locals(),
closest=False
)
matchIndies, matches = cs.search()
# DETERMINE WHICH COORDINATES REQUIRE A NED QUERY
curatedMatchIndices = []
curatedMatches = []
for i, m in zip(matchIndies, matches.list):
match = False
row = m
row["separationArcsec"] = row["cmSepArcsec"]
raStream = row["raDeg"]
decStream = row["decDeg"]
radiusStream = row["arcsecRadius"]
dateStream = row["dateQueried"]
angularSeparation = row["separationArcsec"]
if angularSeparation + self.settings["first pass ned search radius arcec"] < radiusStream:
curatedMatchIndices.append(i)
curatedMatches.append(m)
# NON MATCHES
for i, v in enumerate(coordinateList):
if i not in curatedMatchIndices:
updatedCoordinateList.append(v)
self.log.debug('completed the ``_remove_previous_ned_queries`` method')
return updatedCoordinateList | python | def _remove_previous_ned_queries(
self,
coordinateList):
"""iterate through the transient locations to see if we have recent local NED coverage of that area already
**Key Arguments:**
- ``coordinateList`` -- set of coordinate to check for previous queries
**Return:**
- ``updatedCoordinateList`` -- coordinate list with previous queries removed
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
self.log.debug('starting the ``_remove_previous_ned_queries`` method')
# 1 DEGREE QUERY RADIUS
radius = 60. * 60.
updatedCoordinateList = []
keepers = []
# CALCULATE THE OLDEST RESULTS LIMIT
now = datetime.now()
td = timedelta(
days=self.settings["ned stream refresh rate in days"])
refreshLimit = now - td
refreshLimit = refreshLimit.strftime("%Y-%m-%d %H:%M:%S")
raList = []
raList[:] = [c[0] for c in coordinateList]
decList = []
decList[:] = [c[1] for c in coordinateList]
# MATCH COORDINATES AGAINST PREVIOUS NED SEARCHES
cs = conesearch(
log=self.log,
dbConn=self.cataloguesDbConn,
tableName="tcs_helper_ned_query_history",
columns="*",
ra=raList,
dec=decList,
radiusArcsec=radius,
separations=True,
distinct=True,
sqlWhere="dateQueried > '%(refreshLimit)s'" % locals(),
closest=False
)
matchIndies, matches = cs.search()
# DETERMINE WHICH COORDINATES REQUIRE A NED QUERY
curatedMatchIndices = []
curatedMatches = []
for i, m in zip(matchIndies, matches.list):
match = False
row = m
row["separationArcsec"] = row["cmSepArcsec"]
raStream = row["raDeg"]
decStream = row["decDeg"]
radiusStream = row["arcsecRadius"]
dateStream = row["dateQueried"]
angularSeparation = row["separationArcsec"]
if angularSeparation + self.settings["first pass ned search radius arcec"] < radiusStream:
curatedMatchIndices.append(i)
curatedMatches.append(m)
# NON MATCHES
for i, v in enumerate(coordinateList):
if i not in curatedMatchIndices:
updatedCoordinateList.append(v)
self.log.debug('completed the ``_remove_previous_ned_queries`` method')
return updatedCoordinateList | [
"def",
"_remove_previous_ned_queries",
"(",
"self",
",",
"coordinateList",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_remove_previous_ned_queries`` method'",
")",
"# 1 DEGREE QUERY RADIUS",
"radius",
"=",
"60.",
"*",
"60.",
"updatedCoordinateList",... | iterate through the transient locations to see if we have recent local NED coverage of that area already
**Key Arguments:**
- ``coordinateList`` -- set of coordinate to check for previous queries
**Return:**
- ``updatedCoordinateList`` -- coordinate list with previous queries removed
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring | [
"iterate",
"through",
"the",
"transient",
"locations",
"to",
"see",
"if",
"we",
"have",
"recent",
"local",
"NED",
"coverage",
"of",
"that",
"area",
"already"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L542-L621 | train | 49,917 |
thespacedoctor/sherlock | sherlock/transient_classifier.py | transient_classifier._crossmatch_transients_against_catalogues | def _crossmatch_transients_against_catalogues(
self,
transientsMetadataListIndex,
colMaps):
"""run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database.
- ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_milliquas_v4_5`) as the key and the column-name dictary map as value (`{view_name: {columnMap}}`).
**Return:**
- ``crossmatches`` -- a list of dictionaries of the associated sources crossmatched from the catalogues database
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
global theseBatches
self.log.debug(
'starting the ``_crossmatch_transients_against_catalogues`` method')
# SETUP ALL DATABASE CONNECTIONS
transientsMetadataList = theseBatches[transientsMetadataListIndex]
dbConn = database(
log=self.log,
dbSettings=self.settings["database settings"]["static catalogues"]
).connect()
self.allClassifications = []
cm = transient_catalogue_crossmatch(
log=self.log,
dbConn=dbConn,
transients=transientsMetadataList,
settings=self.settings,
colMaps=colMaps
)
crossmatches = cm.match()
self.log.debug(
'completed the ``_crossmatch_transients_against_catalogues`` method')
return crossmatches | python | def _crossmatch_transients_against_catalogues(
self,
transientsMetadataListIndex,
colMaps):
"""run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database.
- ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_milliquas_v4_5`) as the key and the column-name dictary map as value (`{view_name: {columnMap}}`).
**Return:**
- ``crossmatches`` -- a list of dictionaries of the associated sources crossmatched from the catalogues database
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring
"""
global theseBatches
self.log.debug(
'starting the ``_crossmatch_transients_against_catalogues`` method')
# SETUP ALL DATABASE CONNECTIONS
transientsMetadataList = theseBatches[transientsMetadataListIndex]
dbConn = database(
log=self.log,
dbSettings=self.settings["database settings"]["static catalogues"]
).connect()
self.allClassifications = []
cm = transient_catalogue_crossmatch(
log=self.log,
dbConn=dbConn,
transients=transientsMetadataList,
settings=self.settings,
colMaps=colMaps
)
crossmatches = cm.match()
self.log.debug(
'completed the ``_crossmatch_transients_against_catalogues`` method')
return crossmatches | [
"def",
"_crossmatch_transients_against_catalogues",
"(",
"self",
",",
"transientsMetadataListIndex",
",",
"colMaps",
")",
":",
"global",
"theseBatches",
"self",
".",
"log",
".",
"debug",
"(",
"'starting the ``_crossmatch_transients_against_catalogues`` method'",
")",
"# SETUP... | run the transients through the crossmatch algorithm in the settings file
**Key Arguments:**
- ``transientsMetadataListIndex`` -- the list of transient metadata lifted from the database.
- ``colMaps`` -- dictionary of dictionaries with the name of the database-view (e.g. `tcs_view_agn_milliquas_v4_5`) as the key and the column-name dictary map as value (`{view_name: {columnMap}}`).
**Return:**
- ``crossmatches`` -- a list of dictionaries of the associated sources crossmatched from the catalogues database
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exists
- clip any useful text to docs mindmap
- regenerate the docs and check redendering of this docstring | [
"run",
"the",
"transients",
"through",
"the",
"crossmatch",
"algorithm",
"in",
"the",
"settings",
"file"
] | 2c80fb6fa31b04e7820e6928e3d437a21e692dd3 | https://github.com/thespacedoctor/sherlock/blob/2c80fb6fa31b04e7820e6928e3d437a21e692dd3/sherlock/transient_classifier.py#L623-L676 | train | 49,918 |
Clinical-Genomics/trailblazer | trailblazer/mip/fastq.py | FastqHandler.name_file | def name_file(lane: int, flowcell: str, sample: str, read: int,
undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str:
"""Name a FASTQ file following MIP conventions."""
flowcell = f"{flowcell}-undetermined" if undetermined else flowcell
date_str = date.strftime('%y%m%d') if date else '171015'
index = index if index else 'XXXXXX'
return f"{lane}_{date_str}_{flowcell}_{sample}_{index}_{read}.fastq.gz" | python | def name_file(lane: int, flowcell: str, sample: str, read: int,
undetermined: bool=False, date: dt.datetime=None, index: str=None) -> str:
"""Name a FASTQ file following MIP conventions."""
flowcell = f"{flowcell}-undetermined" if undetermined else flowcell
date_str = date.strftime('%y%m%d') if date else '171015'
index = index if index else 'XXXXXX'
return f"{lane}_{date_str}_{flowcell}_{sample}_{index}_{read}.fastq.gz" | [
"def",
"name_file",
"(",
"lane",
":",
"int",
",",
"flowcell",
":",
"str",
",",
"sample",
":",
"str",
",",
"read",
":",
"int",
",",
"undetermined",
":",
"bool",
"=",
"False",
",",
"date",
":",
"dt",
".",
"datetime",
"=",
"None",
",",
"index",
":",
... | Name a FASTQ file following MIP conventions. | [
"Name",
"a",
"FASTQ",
"file",
"following",
"MIP",
"conventions",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/fastq.py#L13-L19 | train | 49,919 |
Clinical-Genomics/trailblazer | trailblazer/mip/fastq.py | FastqHandler.link | def link(self, family: str, sample: str, analysis_type: str, files: List[str]):
"""Link FASTQ files for a sample."""
root_dir = Path(self.families_dir) / family / analysis_type / sample / 'fastq'
root_dir.mkdir(parents=True, exist_ok=True)
for fastq_data in files:
fastq_path = Path(fastq_data['path'])
fastq_name = self.name_file(
lane=fastq_data['lane'],
flowcell=fastq_data['flowcell'],
sample=sample,
read=fastq_data['read'],
undetermined=fastq_data['undetermined'],
)
dest_path = root_dir / fastq_name
if not dest_path.exists():
log.info(f"linking: {fastq_path} -> {dest_path}")
dest_path.symlink_to(fastq_path)
else:
log.debug(f"destination path already exists: {dest_path}") | python | def link(self, family: str, sample: str, analysis_type: str, files: List[str]):
"""Link FASTQ files for a sample."""
root_dir = Path(self.families_dir) / family / analysis_type / sample / 'fastq'
root_dir.mkdir(parents=True, exist_ok=True)
for fastq_data in files:
fastq_path = Path(fastq_data['path'])
fastq_name = self.name_file(
lane=fastq_data['lane'],
flowcell=fastq_data['flowcell'],
sample=sample,
read=fastq_data['read'],
undetermined=fastq_data['undetermined'],
)
dest_path = root_dir / fastq_name
if not dest_path.exists():
log.info(f"linking: {fastq_path} -> {dest_path}")
dest_path.symlink_to(fastq_path)
else:
log.debug(f"destination path already exists: {dest_path}") | [
"def",
"link",
"(",
"self",
",",
"family",
":",
"str",
",",
"sample",
":",
"str",
",",
"analysis_type",
":",
"str",
",",
"files",
":",
"List",
"[",
"str",
"]",
")",
":",
"root_dir",
"=",
"Path",
"(",
"self",
".",
"families_dir",
")",
"/",
"family",... | Link FASTQ files for a sample. | [
"Link",
"FASTQ",
"files",
"for",
"a",
"sample",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/mip/fastq.py#L21-L39 | train | 49,920 |
pytroll/posttroll | posttroll/bbmcast.py | mcast_sender | def mcast_sender(mcgroup=MC_GROUP):
"""Non-object interface for sending multicast messages.
"""
sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
if _is_broadcast_group(mcgroup):
group = '<broadcast>'
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
elif((int(mcgroup.split(".")[0]) > 239) or
(int(mcgroup.split(".")[0]) < 224)):
raise IOError("Invalid multicast address.")
else:
group = mcgroup
ttl = struct.pack('b', TTL_LOCALNET) # Time-to-live
sock.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
return sock, group | python | def mcast_sender(mcgroup=MC_GROUP):
"""Non-object interface for sending multicast messages.
"""
sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
if _is_broadcast_group(mcgroup):
group = '<broadcast>'
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
elif((int(mcgroup.split(".")[0]) > 239) or
(int(mcgroup.split(".")[0]) < 224)):
raise IOError("Invalid multicast address.")
else:
group = mcgroup
ttl = struct.pack('b', TTL_LOCALNET) # Time-to-live
sock.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, ttl)
return sock, group | [
"def",
"mcast_sender",
"(",
"mcgroup",
"=",
"MC_GROUP",
")",
":",
"sock",
"=",
"socket",
"(",
"AF_INET",
",",
"SOCK_DGRAM",
")",
"sock",
".",
"setsockopt",
"(",
"SOL_SOCKET",
",",
"SO_REUSEADDR",
",",
"1",
")",
"if",
"_is_broadcast_group",
"(",
"mcgroup",
... | Non-object interface for sending multicast messages. | [
"Non",
"-",
"object",
"interface",
"for",
"sending",
"multicast",
"messages",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/bbmcast.py#L80-L95 | train | 49,921 |
pytroll/posttroll | posttroll/bbmcast.py | mcast_receiver | def mcast_receiver(port, mcgroup=MC_GROUP):
"""Open a UDP socket, bind it to a port and select a multicast group.
"""
if _is_broadcast_group(mcgroup):
group = None
else:
group = mcgroup
# Create a socket
sock = socket(AF_INET, SOCK_DGRAM)
# Allow multiple copies of this program on one machine
# (not strictly needed)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
if group:
sock.setsockopt(SOL_IP, IP_MULTICAST_TTL, TTL_LOCALNET) # default
sock.setsockopt(SOL_IP, IP_MULTICAST_LOOP, 1) # default
# Bind it to the port
sock.bind(('', port))
# Look up multicast group address in name server
# (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
if group:
group = gethostbyname(group)
# Construct binary group address
bytes_ = [int(b) for b in group.split(".")]
grpaddr = 0
for byte in bytes_:
grpaddr = (grpaddr << 8) | byte
# Construct struct mreq from grpaddr and ifaddr
ifaddr = INADDR_ANY
mreq = struct.pack('!LL', grpaddr, ifaddr)
# Add group membership
sock.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
return sock, group or '<broadcast>' | python | def mcast_receiver(port, mcgroup=MC_GROUP):
"""Open a UDP socket, bind it to a port and select a multicast group.
"""
if _is_broadcast_group(mcgroup):
group = None
else:
group = mcgroup
# Create a socket
sock = socket(AF_INET, SOCK_DGRAM)
# Allow multiple copies of this program on one machine
# (not strictly needed)
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
if group:
sock.setsockopt(SOL_IP, IP_MULTICAST_TTL, TTL_LOCALNET) # default
sock.setsockopt(SOL_IP, IP_MULTICAST_LOOP, 1) # default
# Bind it to the port
sock.bind(('', port))
# Look up multicast group address in name server
# (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
if group:
group = gethostbyname(group)
# Construct binary group address
bytes_ = [int(b) for b in group.split(".")]
grpaddr = 0
for byte in bytes_:
grpaddr = (grpaddr << 8) | byte
# Construct struct mreq from grpaddr and ifaddr
ifaddr = INADDR_ANY
mreq = struct.pack('!LL', grpaddr, ifaddr)
# Add group membership
sock.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)
return sock, group or '<broadcast>' | [
"def",
"mcast_receiver",
"(",
"port",
",",
"mcgroup",
"=",
"MC_GROUP",
")",
":",
"if",
"_is_broadcast_group",
"(",
"mcgroup",
")",
":",
"group",
"=",
"None",
"else",
":",
"group",
"=",
"mcgroup",
"# Create a socket",
"sock",
"=",
"socket",
"(",
"AF_INET",
... | Open a UDP socket, bind it to a port and select a multicast group. | [
"Open",
"a",
"UDP",
"socket",
"bind",
"it",
"to",
"a",
"port",
"and",
"select",
"a",
"multicast",
"group",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/bbmcast.py#L135-L175 | train | 49,922 |
pytroll/posttroll | posttroll/bbmcast.py | MulticastReceiver.close | def close(self):
"""Close the receiver.
"""
self.socket.setsockopt(SOL_SOCKET, SO_LINGER,
struct.pack('ii', 1, 1))
self.socket.close() | python | def close(self):
"""Close the receiver.
"""
self.socket.setsockopt(SOL_SOCKET, SO_LINGER,
struct.pack('ii', 1, 1))
self.socket.close() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"socket",
".",
"setsockopt",
"(",
"SOL_SOCKET",
",",
"SO_LINGER",
",",
"struct",
".",
"pack",
"(",
"'ii'",
",",
"1",
",",
"1",
")",
")",
"self",
".",
"socket",
".",
"close",
"(",
")"
] | Close the receiver. | [
"Close",
"the",
"receiver",
"."
] | 8e811a0544b5182c4a72aed074b2ff8c4324e94d | https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/bbmcast.py#L125-L130 | train | 49,923 |
Clinical-Genomics/trailblazer | trailblazer/log.py | LogAnalysis._delete_temp_logs | def _delete_temp_logs(self, family_name: str):
"""Delete temporary logs for the current family."""
for temp_log in self.store.analyses(family=family_name, temp=True):
log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}")
temp_log.delete() | python | def _delete_temp_logs(self, family_name: str):
"""Delete temporary logs for the current family."""
for temp_log in self.store.analyses(family=family_name, temp=True):
log.debug(f"delete temporary log: {temp_log.id} - {temp_log.status}")
temp_log.delete() | [
"def",
"_delete_temp_logs",
"(",
"self",
",",
"family_name",
":",
"str",
")",
":",
"for",
"temp_log",
"in",
"self",
".",
"store",
".",
"analyses",
"(",
"family",
"=",
"family_name",
",",
"temp",
"=",
"True",
")",
":",
"log",
".",
"debug",
"(",
"f\"dele... | Delete temporary logs for the current family. | [
"Delete",
"temporary",
"logs",
"for",
"the",
"current",
"family",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/log.py#L44-L48 | train | 49,924 |
Clinical-Genomics/trailblazer | trailblazer/log.py | LogAnalysis.parse | def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict],
jobs: int) -> dict:
"""Parse information about a run."""
analysis_types = [sample['type'] for sample in config_data['samples']]
run_data = {
'user': config_data['email'],
'family': config_data['family'],
'priority': config_data['priority'],
'started_at': sampleinfo_data['date'],
'version': sampleinfo_data['version'],
'out_dir': config_data['out_dir'],
'config_path': config_data['config_path'],
'type': cls._get_analysis_type(analysis_types),
}
sacct_data, last_job_end = cls._parse_sacct(sacct_jobs, jobs_count=jobs)
run_data.update(sacct_data)
run_data['status'] = cls.get_status(sampleinfo_data['is_finished'],
len(run_data['failed_jobs']))
if run_data['status'] == 'completed':
run_data['completed_at'] = last_job_end
return run_data | python | def parse(cls, config_data: dict, sampleinfo_data: dict, sacct_jobs: List[dict],
jobs: int) -> dict:
"""Parse information about a run."""
analysis_types = [sample['type'] for sample in config_data['samples']]
run_data = {
'user': config_data['email'],
'family': config_data['family'],
'priority': config_data['priority'],
'started_at': sampleinfo_data['date'],
'version': sampleinfo_data['version'],
'out_dir': config_data['out_dir'],
'config_path': config_data['config_path'],
'type': cls._get_analysis_type(analysis_types),
}
sacct_data, last_job_end = cls._parse_sacct(sacct_jobs, jobs_count=jobs)
run_data.update(sacct_data)
run_data['status'] = cls.get_status(sampleinfo_data['is_finished'],
len(run_data['failed_jobs']))
if run_data['status'] == 'completed':
run_data['completed_at'] = last_job_end
return run_data | [
"def",
"parse",
"(",
"cls",
",",
"config_data",
":",
"dict",
",",
"sampleinfo_data",
":",
"dict",
",",
"sacct_jobs",
":",
"List",
"[",
"dict",
"]",
",",
"jobs",
":",
"int",
")",
"->",
"dict",
":",
"analysis_types",
"=",
"[",
"sample",
"[",
"'type'",
... | Parse information about a run. | [
"Parse",
"information",
"about",
"a",
"run",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/log.py#L51-L74 | train | 49,925 |
Clinical-Genomics/trailblazer | trailblazer/log.py | LogAnalysis._parse_sacct | def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None):
"""Parse out info from Sacct log."""
failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True)
completed_jobs = [job for job in sacct_jobs if job['is_completed']]
last_job_end = completed_jobs[-1]['end'] if len(completed_jobs) > 0 else None
data = {
'jobs': jobs_count,
'completed_jobs': len(completed_jobs),
'progress': (len(completed_jobs) / jobs_count) if jobs_count else None,
'failed_jobs': [{
'slurm_id': job['id'],
'started_at': job['start'],
'elapsed': job['elapsed'],
'status': job['state'].lower(),
'name': job['step'],
'context': job['context'],
} for job in failed_jobs]
}
return data, last_job_end | python | def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None):
"""Parse out info from Sacct log."""
failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True)
completed_jobs = [job for job in sacct_jobs if job['is_completed']]
last_job_end = completed_jobs[-1]['end'] if len(completed_jobs) > 0 else None
data = {
'jobs': jobs_count,
'completed_jobs': len(completed_jobs),
'progress': (len(completed_jobs) / jobs_count) if jobs_count else None,
'failed_jobs': [{
'slurm_id': job['id'],
'started_at': job['start'],
'elapsed': job['elapsed'],
'status': job['state'].lower(),
'name': job['step'],
'context': job['context'],
} for job in failed_jobs]
}
return data, last_job_end | [
"def",
"_parse_sacct",
"(",
"sacct_jobs",
":",
"List",
"[",
"dict",
"]",
",",
"jobs_count",
":",
"int",
"=",
"None",
")",
":",
"failed_jobs",
"=",
"sacct_api",
".",
"filter_jobs",
"(",
"sacct_jobs",
",",
"failed",
"=",
"True",
")",
"completed_jobs",
"=",
... | Parse out info from Sacct log. | [
"Parse",
"out",
"info",
"from",
"Sacct",
"log",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/log.py#L77-L95 | train | 49,926 |
Clinical-Genomics/trailblazer | trailblazer/log.py | LogAnalysis._get_analysis_type | def _get_analysis_type(analysis_types: List[str]) -> str:
"""Determine the overall analysis type."""
types_set = set(analysis_types)
return types_set.pop() if len(types_set) == 1 else 'wgs' | python | def _get_analysis_type(analysis_types: List[str]) -> str:
"""Determine the overall analysis type."""
types_set = set(analysis_types)
return types_set.pop() if len(types_set) == 1 else 'wgs' | [
"def",
"_get_analysis_type",
"(",
"analysis_types",
":",
"List",
"[",
"str",
"]",
")",
"->",
"str",
":",
"types_set",
"=",
"set",
"(",
"analysis_types",
")",
"return",
"types_set",
".",
"pop",
"(",
")",
"if",
"len",
"(",
"types_set",
")",
"==",
"1",
"e... | Determine the overall analysis type. | [
"Determine",
"the",
"overall",
"analysis",
"type",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/log.py#L108-L111 | train | 49,927 |
Clinical-Genomics/trailblazer | trailblazer/log.py | LogAnalysis.build | def build(self, run_data: dict) -> models.Analysis:
"""Build a new Analysis object."""
existing_run = self.store.find_analysis(family=run_data['family'],
started_at=run_data['started_at'],
status=run_data['status'])
if existing_run:
return None
run_data['user'] = self.store.user(run_data['user'])
new_failed_jobs = [self.store.Job(**job) for job in run_data['failed_jobs']]
del run_data['failed_jobs']
new_run = self.store.Analysis(**run_data)
new_run.failed_jobs = new_failed_jobs
return new_run | python | def build(self, run_data: dict) -> models.Analysis:
"""Build a new Analysis object."""
existing_run = self.store.find_analysis(family=run_data['family'],
started_at=run_data['started_at'],
status=run_data['status'])
if existing_run:
return None
run_data['user'] = self.store.user(run_data['user'])
new_failed_jobs = [self.store.Job(**job) for job in run_data['failed_jobs']]
del run_data['failed_jobs']
new_run = self.store.Analysis(**run_data)
new_run.failed_jobs = new_failed_jobs
return new_run | [
"def",
"build",
"(",
"self",
",",
"run_data",
":",
"dict",
")",
"->",
"models",
".",
"Analysis",
":",
"existing_run",
"=",
"self",
".",
"store",
".",
"find_analysis",
"(",
"family",
"=",
"run_data",
"[",
"'family'",
"]",
",",
"started_at",
"=",
"run_data... | Build a new Analysis object. | [
"Build",
"a",
"new",
"Analysis",
"object",
"."
] | 27f3cd21043a1077bd7029e85783459a50a7b798 | https://github.com/Clinical-Genomics/trailblazer/blob/27f3cd21043a1077bd7029e85783459a50a7b798/trailblazer/log.py#L113-L126 | train | 49,928 |
capless/valley | valley/mixins.py | VariableMixin.get_default_value | def get_default_value(self):
""" return default value """
default = self.default_value
if isinstance(default, collections.Callable):
default = default()
return default | python | def get_default_value(self):
""" return default value """
default = self.default_value
if isinstance(default, collections.Callable):
default = default()
return default | [
"def",
"get_default_value",
"(",
"self",
")",
":",
"default",
"=",
"self",
".",
"default_value",
"if",
"isinstance",
"(",
"default",
",",
"collections",
".",
"Callable",
")",
":",
"default",
"=",
"default",
"(",
")",
"return",
"default"
] | return default value | [
"return",
"default",
"value"
] | 491e4203e428a9e92264e204d44a1df96a570bbc | https://github.com/capless/valley/blob/491e4203e428a9e92264e204d44a1df96a570bbc/valley/mixins.py#L32-L37 | train | 49,929 |
OpenEnergyPlatform/oedialect | oedialect/dialect.py | OEExecutionContext._init_compiled | def _init_compiled(cls, dialect, connection, dbapi_connection,
compiled, parameters):
"""Initialize execution context for a Compiled construct."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
self.compiled = compiled
# this should be caught in the engine before
# we get here
assert compiled.can_execute
self.execution_options = compiled.execution_options.union(
connection._execution_options)
self.result_column_struct = (
compiled._result_columns, compiled._ordered_columns,
compiled._textual_ordered_columns)
self.unicode_statement = util.text_type(compiled)
if not dialect.supports_unicode_statements:
self.statement = self.unicode_statement.encode(
self.dialect.encoding)
else:
self.statement = self.unicode_statement
self.isinsert = compiled.isinsert
self.isupdate = compiled.isupdate
self.isdelete = compiled.isdelete
self.is_text = compiled.isplaintext
if not parameters:
self.compiled_parameters = [compiled.construct_params()]
else:
self.compiled_parameters = \
[compiled.construct_params(m, _group_number=grp) for
grp, m in enumerate(parameters)]
self.executemany = len(parameters) > 1
self.cursor = self.create_cursor()
if self.isinsert or self.isupdate or self.isdelete:
self.is_crud = True
self._is_explicit_returning = bool(compiled.statement._returning)
self._is_implicit_returning = bool(
compiled.returning and not compiled.statement._returning)
if self.compiled.insert_prefetch or self.compiled.update_prefetch:
if self.executemany:
self._process_executemany_defaults()
else:
self._process_executesingle_defaults()
processors = compiled._bind_processors
# Convert the dictionary of bind parameter values
# into a dict or list to be sent to the DBAPI's
# execute() or executemany() method.
parameters = []
if dialect.positional:
for compiled_params in self.compiled_parameters:
param = []
for key in self.compiled.positiontup:
if key in processors:
param.append(processors[key](compiled_params[key]))
else:
param.append(compiled_params[key])
parameters.append(dialect.execute_sequence_format(param))
else:
encode = not dialect.supports_unicode_statements
for compiled_params in self.compiled_parameters:
if encode:
param = dict(
(
dialect._encoder(key)[0],
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
else:
param = dict(
(
key,
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
parameters.append(param)
self.parameters = dialect.execute_sequence_format(parameters)
self.statement = compiled
return self | python | def _init_compiled(cls, dialect, connection, dbapi_connection,
compiled, parameters):
"""Initialize execution context for a Compiled construct."""
self = cls.__new__(cls)
self.root_connection = connection
self._dbapi_connection = dbapi_connection
self.dialect = connection.dialect
self.compiled = compiled
# this should be caught in the engine before
# we get here
assert compiled.can_execute
self.execution_options = compiled.execution_options.union(
connection._execution_options)
self.result_column_struct = (
compiled._result_columns, compiled._ordered_columns,
compiled._textual_ordered_columns)
self.unicode_statement = util.text_type(compiled)
if not dialect.supports_unicode_statements:
self.statement = self.unicode_statement.encode(
self.dialect.encoding)
else:
self.statement = self.unicode_statement
self.isinsert = compiled.isinsert
self.isupdate = compiled.isupdate
self.isdelete = compiled.isdelete
self.is_text = compiled.isplaintext
if not parameters:
self.compiled_parameters = [compiled.construct_params()]
else:
self.compiled_parameters = \
[compiled.construct_params(m, _group_number=grp) for
grp, m in enumerate(parameters)]
self.executemany = len(parameters) > 1
self.cursor = self.create_cursor()
if self.isinsert or self.isupdate or self.isdelete:
self.is_crud = True
self._is_explicit_returning = bool(compiled.statement._returning)
self._is_implicit_returning = bool(
compiled.returning and not compiled.statement._returning)
if self.compiled.insert_prefetch or self.compiled.update_prefetch:
if self.executemany:
self._process_executemany_defaults()
else:
self._process_executesingle_defaults()
processors = compiled._bind_processors
# Convert the dictionary of bind parameter values
# into a dict or list to be sent to the DBAPI's
# execute() or executemany() method.
parameters = []
if dialect.positional:
for compiled_params in self.compiled_parameters:
param = []
for key in self.compiled.positiontup:
if key in processors:
param.append(processors[key](compiled_params[key]))
else:
param.append(compiled_params[key])
parameters.append(dialect.execute_sequence_format(param))
else:
encode = not dialect.supports_unicode_statements
for compiled_params in self.compiled_parameters:
if encode:
param = dict(
(
dialect._encoder(key)[0],
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
else:
param = dict(
(
key,
processors[key](compiled_params[key])
if key in processors
else compiled_params[key]
)
for key in compiled_params
)
parameters.append(param)
self.parameters = dialect.execute_sequence_format(parameters)
self.statement = compiled
return self | [
"def",
"_init_compiled",
"(",
"cls",
",",
"dialect",
",",
"connection",
",",
"dbapi_connection",
",",
"compiled",
",",
"parameters",
")",
":",
"self",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"root_connection",
"=",
"connection",
"self",
"... | Initialize execution context for a Compiled construct. | [
"Initialize",
"execution",
"context",
"for",
"a",
"Compiled",
"construct",
"."
] | 40a8d9e9b272ea4674d2c40dd6b3e6cc15f91c1e | https://github.com/OpenEnergyPlatform/oedialect/blob/40a8d9e9b272ea4674d2c40dd6b3e6cc15f91c1e/oedialect/dialect.py#L38-L139 | train | 49,930 |
crccheck/django-object-actions | django_object_actions/utils.py | takes_instance_or_queryset | def takes_instance_or_queryset(func):
"""Decorator that makes standard Django admin actions compatible."""
@wraps(func)
def decorated_function(self, request, queryset):
# func follows the prototype documented at:
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions
if not isinstance(queryset, QuerySet):
try:
# Django >=1.8
queryset = self.get_queryset(request).filter(pk=queryset.pk)
except AttributeError:
try:
# Django >=1.6,<1.8
model = queryset._meta.model
except AttributeError: # pragma: no cover
# Django <1.6
model = queryset._meta.concrete_model
queryset = model.objects.filter(pk=queryset.pk)
return func(self, request, queryset)
return decorated_function | python | def takes_instance_or_queryset(func):
"""Decorator that makes standard Django admin actions compatible."""
@wraps(func)
def decorated_function(self, request, queryset):
# func follows the prototype documented at:
# https://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#writing-action-functions
if not isinstance(queryset, QuerySet):
try:
# Django >=1.8
queryset = self.get_queryset(request).filter(pk=queryset.pk)
except AttributeError:
try:
# Django >=1.6,<1.8
model = queryset._meta.model
except AttributeError: # pragma: no cover
# Django <1.6
model = queryset._meta.concrete_model
queryset = model.objects.filter(pk=queryset.pk)
return func(self, request, queryset)
return decorated_function | [
"def",
"takes_instance_or_queryset",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorated_function",
"(",
"self",
",",
"request",
",",
"queryset",
")",
":",
"# func follows the prototype documented at:",
"# https://docs.djangoproject.com/en/dev/ref/con... | Decorator that makes standard Django admin actions compatible. | [
"Decorator",
"that",
"makes",
"standard",
"Django",
"admin",
"actions",
"compatible",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/django_object_actions/utils.py#L280-L299 | train | 49,931 |
crccheck/django-object-actions | django_object_actions/utils.py | BaseDjangoObjectActions.get_urls | def get_urls(self):
"""Prepend `get_urls` with our own patterns."""
urls = super(BaseDjangoObjectActions, self).get_urls()
return self._get_action_urls() + urls | python | def get_urls(self):
"""Prepend `get_urls` with our own patterns."""
urls = super(BaseDjangoObjectActions, self).get_urls()
return self._get_action_urls() + urls | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"BaseDjangoObjectActions",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"return",
"self",
".",
"_get_action_urls",
"(",
")",
"+",
"urls"
] | Prepend `get_urls` with our own patterns. | [
"Prepend",
"get_urls",
"with",
"our",
"own",
"patterns",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/django_object_actions/utils.py#L46-L49 | train | 49,932 |
crccheck/django-object-actions | django_object_actions/utils.py | BaseDjangoObjectActions._get_action_urls | def _get_action_urls(self):
"""Get the url patterns that route each action to a view."""
actions = {}
model_name = self.model._meta.model_name
# e.g.: polls_poll
base_url_name = '%s_%s' % (self.model._meta.app_label, model_name)
# e.g.: polls_poll_actions
model_actions_url_name = '%s_actions' % base_url_name
self.tools_view_name = 'admin:' + model_actions_url_name
# WISHLIST use get_change_actions and get_changelist_actions
# TODO separate change and changelist actions
for action in chain(self.change_actions, self.changelist_actions):
actions[action] = getattr(self, action)
return [
# change, supports the same pks the admin does
# https://github.com/django/django/blob/stable/1.10.x/django/contrib/admin/options.py#L555
url(r'^(?P<pk>.+)/actions/(?P<tool>\w+)/$',
self.admin_site.admin_view( # checks permissions
ChangeActionView.as_view(
model=self.model,
actions=actions,
back='admin:%s_change' % base_url_name,
current_app=self.admin_site.name,
)
),
name=model_actions_url_name),
# changelist
url(r'^actions/(?P<tool>\w+)/$',
self.admin_site.admin_view( # checks permissions
ChangeListActionView.as_view(
model=self.model,
actions=actions,
back='admin:%s_changelist' % base_url_name,
current_app=self.admin_site.name,
)
),
# Dupe name is fine. https://code.djangoproject.com/ticket/14259
name=model_actions_url_name),
] | python | def _get_action_urls(self):
"""Get the url patterns that route each action to a view."""
actions = {}
model_name = self.model._meta.model_name
# e.g.: polls_poll
base_url_name = '%s_%s' % (self.model._meta.app_label, model_name)
# e.g.: polls_poll_actions
model_actions_url_name = '%s_actions' % base_url_name
self.tools_view_name = 'admin:' + model_actions_url_name
# WISHLIST use get_change_actions and get_changelist_actions
# TODO separate change and changelist actions
for action in chain(self.change_actions, self.changelist_actions):
actions[action] = getattr(self, action)
return [
# change, supports the same pks the admin does
# https://github.com/django/django/blob/stable/1.10.x/django/contrib/admin/options.py#L555
url(r'^(?P<pk>.+)/actions/(?P<tool>\w+)/$',
self.admin_site.admin_view( # checks permissions
ChangeActionView.as_view(
model=self.model,
actions=actions,
back='admin:%s_change' % base_url_name,
current_app=self.admin_site.name,
)
),
name=model_actions_url_name),
# changelist
url(r'^actions/(?P<tool>\w+)/$',
self.admin_site.admin_view( # checks permissions
ChangeListActionView.as_view(
model=self.model,
actions=actions,
back='admin:%s_changelist' % base_url_name,
current_app=self.admin_site.name,
)
),
# Dupe name is fine. https://code.djangoproject.com/ticket/14259
name=model_actions_url_name),
] | [
"def",
"_get_action_urls",
"(",
"self",
")",
":",
"actions",
"=",
"{",
"}",
"model_name",
"=",
"self",
".",
"model",
".",
"_meta",
".",
"model_name",
"# e.g.: polls_poll",
"base_url_name",
"=",
"'%s_%s'",
"%",
"(",
"self",
".",
"model",
".",
"_meta",
".",
... | Get the url patterns that route each action to a view. | [
"Get",
"the",
"url",
"patterns",
"that",
"route",
"each",
"action",
"to",
"a",
"view",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/django_object_actions/utils.py#L105-L146 | train | 49,933 |
crccheck/django-object-actions | django_object_actions/utils.py | BaseDjangoObjectActions._get_tool_dict | def _get_tool_dict(self, tool_name):
"""Represents the tool as a dict with extra meta."""
tool = getattr(self, tool_name)
standard_attrs, custom_attrs = self._get_button_attrs(tool)
return dict(
name=tool_name,
label=getattr(tool, 'label', tool_name),
standard_attrs=standard_attrs,
custom_attrs=custom_attrs,
) | python | def _get_tool_dict(self, tool_name):
"""Represents the tool as a dict with extra meta."""
tool = getattr(self, tool_name)
standard_attrs, custom_attrs = self._get_button_attrs(tool)
return dict(
name=tool_name,
label=getattr(tool, 'label', tool_name),
standard_attrs=standard_attrs,
custom_attrs=custom_attrs,
) | [
"def",
"_get_tool_dict",
"(",
"self",
",",
"tool_name",
")",
":",
"tool",
"=",
"getattr",
"(",
"self",
",",
"tool_name",
")",
"standard_attrs",
",",
"custom_attrs",
"=",
"self",
".",
"_get_button_attrs",
"(",
"tool",
")",
"return",
"dict",
"(",
"name",
"="... | Represents the tool as a dict with extra meta. | [
"Represents",
"the",
"tool",
"as",
"a",
"dict",
"with",
"extra",
"meta",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/django_object_actions/utils.py#L148-L157 | train | 49,934 |
crccheck/django-object-actions | django_object_actions/utils.py | BaseDjangoObjectActions._get_button_attrs | def _get_button_attrs(self, tool):
"""
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability.
"""
attrs = getattr(tool, 'attrs', {})
# href is not allowed to be set. should an exception be raised instead?
if 'href' in attrs:
attrs.pop('href')
# title is not allowed to be set. should an exception be raised instead?
# `short_description` should be set instead to parallel django admin
# actions
if 'title' in attrs:
attrs.pop('title')
default_attrs = {
'class': attrs.get('class', ''),
'title': getattr(tool, 'short_description', ''),
}
standard_attrs = {}
custom_attrs = {}
for k, v in dict(default_attrs, **attrs).items():
if k in default_attrs:
standard_attrs[k] = v
else:
custom_attrs[k] = v
return standard_attrs, custom_attrs | python | def _get_button_attrs(self, tool):
"""
Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability.
"""
attrs = getattr(tool, 'attrs', {})
# href is not allowed to be set. should an exception be raised instead?
if 'href' in attrs:
attrs.pop('href')
# title is not allowed to be set. should an exception be raised instead?
# `short_description` should be set instead to parallel django admin
# actions
if 'title' in attrs:
attrs.pop('title')
default_attrs = {
'class': attrs.get('class', ''),
'title': getattr(tool, 'short_description', ''),
}
standard_attrs = {}
custom_attrs = {}
for k, v in dict(default_attrs, **attrs).items():
if k in default_attrs:
standard_attrs[k] = v
else:
custom_attrs[k] = v
return standard_attrs, custom_attrs | [
"def",
"_get_button_attrs",
"(",
"self",
",",
"tool",
")",
":",
"attrs",
"=",
"getattr",
"(",
"tool",
",",
"'attrs'",
",",
"{",
"}",
")",
"# href is not allowed to be set. should an exception be raised instead?",
"if",
"'href'",
"in",
"attrs",
":",
"attrs",
".",
... | Get the HTML attributes associated with a tool.
There are some standard attributes (class and title) that the template
will always want. Any number of additional attributes can be specified
and passed on. This is kinda awkward and due for a refactor for
readability. | [
"Get",
"the",
"HTML",
"attributes",
"associated",
"with",
"a",
"tool",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/django_object_actions/utils.py#L159-L188 | train | 49,935 |
crccheck/django-object-actions | example_project/polls/admin.py | PollAdmin.question_mark | def question_mark(self, request, obj):
"""Add a question mark."""
obj.question = obj.question + '?'
obj.save() | python | def question_mark(self, request, obj):
"""Add a question mark."""
obj.question = obj.question + '?'
obj.save() | [
"def",
"question_mark",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"obj",
".",
"question",
"=",
"obj",
".",
"question",
"+",
"'?'",
"obj",
".",
"save",
"(",
")"
] | Add a question mark. | [
"Add",
"a",
"question",
"mark",
"."
] | fb908697a609f46889af15b543d444e5e19d6be2 | https://github.com/crccheck/django-object-actions/blob/fb908697a609f46889af15b543d444e5e19d6be2/example_project/polls/admin.py#L115-L118 | train | 49,936 |
InfoAgeTech/django-core | django_core/html/builders.py | build_link | def build_link(href, text, cls=None, icon_class=None, **attrs):
"""Builds an html link.
:param href: link for the anchor element
:param text: text for the anchor element
:param attrs: other attribute kwargs
>>> build_link('xyz.com', 'hello', 'big')
u'<a href="xyz.com" class="big">hello</a>'
>>> build_link('xyz.com', 'hello', 'big', 'fa fa-times')
u'<a href="xyz.com" class="big"><i class="fa fa-times"></i> hello</a>'
"""
return build_html_element(tag='a',
text=text,
href=href,
cls=cls,
icon_class=icon_class,
**attrs) | python | def build_link(href, text, cls=None, icon_class=None, **attrs):
"""Builds an html link.
:param href: link for the anchor element
:param text: text for the anchor element
:param attrs: other attribute kwargs
>>> build_link('xyz.com', 'hello', 'big')
u'<a href="xyz.com" class="big">hello</a>'
>>> build_link('xyz.com', 'hello', 'big', 'fa fa-times')
u'<a href="xyz.com" class="big"><i class="fa fa-times"></i> hello</a>'
"""
return build_html_element(tag='a',
text=text,
href=href,
cls=cls,
icon_class=icon_class,
**attrs) | [
"def",
"build_link",
"(",
"href",
",",
"text",
",",
"cls",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"build_html_element",
"(",
"tag",
"=",
"'a'",
",",
"text",
"=",
"text",
",",
"href",
"=",
"href",
",... | Builds an html link.
:param href: link for the anchor element
:param text: text for the anchor element
:param attrs: other attribute kwargs
>>> build_link('xyz.com', 'hello', 'big')
u'<a href="xyz.com" class="big">hello</a>'
>>> build_link('xyz.com', 'hello', 'big', 'fa fa-times')
u'<a href="xyz.com" class="big"><i class="fa fa-times"></i> hello</a>' | [
"Builds",
"an",
"html",
"link",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/html/builders.py#L8-L25 | train | 49,937 |
InfoAgeTech/django-core | django_core/html/builders.py | build_html_element | def build_html_element(tag, text=None, icon_class=None, cls=None, **kwargs):
"""Builds an html element.
:param tag: the html tag to build ('a', 'div', 'img', etc)
:param icon_class: the class to apply to an icon element. This only
applies to elements that allow a closing tag.
:param cls: the css class to apply to the tag. This can also be passed
in as a kwarg as "class".
>>> build_html_element(tag='a', href='someurl.com', text='hello')
'<a href='someurl.com'>hello</a>'
"""
if cls is not None:
kwargs['class'] = cls
tag_attrs = ' '.join(['{0}="{1}"'.format(k, v) for k, v in kwargs.items()])
tag_content = '{tag} {tag_attrs}'.format(tag=tag, tag_attrs=tag_attrs)
if tag in ('img', 'input', 'hr', 'br'):
return mark_safe('<{tag_content} />'.format(tag_content=tag_content))
icon = '<i class="{0}"></i> '.format(icon_class) if icon_class else ''
if not text:
text = ''
elif not isinstance(text, SafeText):
text = escape(text)
return mark_safe('<{tag_content}>{icon}{text}</{tag}>'.format(
tag_content=tag_content,
icon=icon,
tag=tag,
text=text)
) | python | def build_html_element(tag, text=None, icon_class=None, cls=None, **kwargs):
"""Builds an html element.
:param tag: the html tag to build ('a', 'div', 'img', etc)
:param icon_class: the class to apply to an icon element. This only
applies to elements that allow a closing tag.
:param cls: the css class to apply to the tag. This can also be passed
in as a kwarg as "class".
>>> build_html_element(tag='a', href='someurl.com', text='hello')
'<a href='someurl.com'>hello</a>'
"""
if cls is not None:
kwargs['class'] = cls
tag_attrs = ' '.join(['{0}="{1}"'.format(k, v) for k, v in kwargs.items()])
tag_content = '{tag} {tag_attrs}'.format(tag=tag, tag_attrs=tag_attrs)
if tag in ('img', 'input', 'hr', 'br'):
return mark_safe('<{tag_content} />'.format(tag_content=tag_content))
icon = '<i class="{0}"></i> '.format(icon_class) if icon_class else ''
if not text:
text = ''
elif not isinstance(text, SafeText):
text = escape(text)
return mark_safe('<{tag_content}>{icon}{text}</{tag}>'.format(
tag_content=tag_content,
icon=icon,
tag=tag,
text=text)
) | [
"def",
"build_html_element",
"(",
"tag",
",",
"text",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cls",
"is",
"not",
"None",
":",
"kwargs",
"[",
"'class'",
"]",
"=",
"cls",
"tag_at... | Builds an html element.
:param tag: the html tag to build ('a', 'div', 'img', etc)
:param icon_class: the class to apply to an icon element. This only
applies to elements that allow a closing tag.
:param cls: the css class to apply to the tag. This can also be passed
in as a kwarg as "class".
>>> build_html_element(tag='a', href='someurl.com', text='hello')
'<a href='someurl.com'>hello</a>' | [
"Builds",
"an",
"html",
"element",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/html/builders.py#L28-L62 | train | 49,938 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | dump_migration_session_state | def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. For example, rather than this:
- migration: [app, migration_name]
output: "line 1\nline2\nline3"
You get this:
- migration: [app, migration_name]
output: |
line 1
line 2
line 3
"""
class BlockStyle(str): pass
class SessionDumper(yaml.SafeDumper): pass
def str_block_formatter(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
SessionDumper.add_representer(BlockStyle, str_block_formatter)
raw = deepcopy(raw)
for step in raw:
step['output'] = BlockStyle(step['output'])
step['traceback'] = BlockStyle(step['traceback'])
return yaml.dump(raw, Dumper=SessionDumper) | python | def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. For example, rather than this:
- migration: [app, migration_name]
output: "line 1\nline2\nline3"
You get this:
- migration: [app, migration_name]
output: |
line 1
line 2
line 3
"""
class BlockStyle(str): pass
class SessionDumper(yaml.SafeDumper): pass
def str_block_formatter(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
SessionDumper.add_representer(BlockStyle, str_block_formatter)
raw = deepcopy(raw)
for step in raw:
step['output'] = BlockStyle(step['output'])
step['traceback'] = BlockStyle(step['traceback'])
return yaml.dump(raw, Dumper=SessionDumper) | [
"def",
"dump_migration_session_state",
"(",
"raw",
")",
":",
"class",
"BlockStyle",
"(",
"str",
")",
":",
"pass",
"class",
"SessionDumper",
"(",
"yaml",
".",
"SafeDumper",
")",
":",
"pass",
"def",
"str_block_formatter",
"(",
"dumper",
",",
"data",
")",
":",
... | Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. For example, rather than this:
- migration: [app, migration_name]
output: "line 1\nline2\nline3"
You get this:
- migration: [app, migration_name]
output: |
line 1
line 2
line 3 | [
"Serialize",
"a",
"migration",
"session",
"state",
"to",
"yaml",
"using",
"nicer",
"formatting"
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L16-L48 | train | 49,939 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession.add_migrations | def add_migrations(self, migrations):
"""
Add migrations to be applied.
Args:
migrations: a list of migrations to add of the form [(app, migration_name), ...]
Raises:
MigrationSessionError if called on a closed MigrationSession
"""
if self.__closed:
raise MigrationSessionError("Can't change applied session")
self._to_apply.extend(migrations) | python | def add_migrations(self, migrations):
"""
Add migrations to be applied.
Args:
migrations: a list of migrations to add of the form [(app, migration_name), ...]
Raises:
MigrationSessionError if called on a closed MigrationSession
"""
if self.__closed:
raise MigrationSessionError("Can't change applied session")
self._to_apply.extend(migrations) | [
"def",
"add_migrations",
"(",
"self",
",",
"migrations",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't change applied session\"",
")",
"self",
".",
"_to_apply",
".",
"extend",
"(",
"migrations",
")"
] | Add migrations to be applied.
Args:
migrations: a list of migrations to add of the form [(app, migration_name), ...]
Raises:
MigrationSessionError if called on a closed MigrationSession | [
"Add",
"migrations",
"to",
"be",
"applied",
"."
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L146-L157 | train | 49,940 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession._get_current_migration_state | def _get_current_migration_state(self, loader, apps):
"""
Extract the most recent migrations from the relevant apps.
If no migrations have been performed, return 'zero' as the most recent migration for the app.
This should only be called from list_migrations().
"""
# Only care about applied migrations for the passed-in apps.
apps = set(apps)
relevant_applied = [migration for migration in loader.applied_migrations if migration[0] in apps]
# Sort them by the most recent migration and convert to a dictionary,
# leaving apps as keys and most recent migration as values.
# NB: this is a dirty trick
most_recents = dict(sorted(relevant_applied, key=lambda m: m[1]))
# Fill in the apps with no migrations with 'zero'.
# NOTE: Unicode Django application names are unsupported.
most_recents = [[app, 'zero' if app not in most_recents else str(most_recents[app])] for app in apps]
return most_recents | python | def _get_current_migration_state(self, loader, apps):
"""
Extract the most recent migrations from the relevant apps.
If no migrations have been performed, return 'zero' as the most recent migration for the app.
This should only be called from list_migrations().
"""
# Only care about applied migrations for the passed-in apps.
apps = set(apps)
relevant_applied = [migration for migration in loader.applied_migrations if migration[0] in apps]
# Sort them by the most recent migration and convert to a dictionary,
# leaving apps as keys and most recent migration as values.
# NB: this is a dirty trick
most_recents = dict(sorted(relevant_applied, key=lambda m: m[1]))
# Fill in the apps with no migrations with 'zero'.
# NOTE: Unicode Django application names are unsupported.
most_recents = [[app, 'zero' if app not in most_recents else str(most_recents[app])] for app in apps]
return most_recents | [
"def",
"_get_current_migration_state",
"(",
"self",
",",
"loader",
",",
"apps",
")",
":",
"# Only care about applied migrations for the passed-in apps.",
"apps",
"=",
"set",
"(",
"apps",
")",
"relevant_applied",
"=",
"[",
"migration",
"for",
"migration",
"in",
"loader... | Extract the most recent migrations from the relevant apps.
If no migrations have been performed, return 'zero' as the most recent migration for the app.
This should only be called from list_migrations(). | [
"Extract",
"the",
"most",
"recent",
"migrations",
"from",
"the",
"relevant",
"apps",
".",
"If",
"no",
"migrations",
"have",
"been",
"performed",
"return",
"zero",
"as",
"the",
"most",
"recent",
"migration",
"for",
"the",
"app",
"."
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L186-L203 | train | 49,941 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession.list_migrations | def list_migrations(self):
"""
Returns a tuple of unapplied, current
"Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration
states for apps with unapplied migrations.
Both are tuples of the form (app, migration_name).
"""
connection = connections[self._database_name]
loader = MigrationLoader(connection, ignore_no_migrations=True)
unapplied = self._get_unapplied_migrations(loader)
currents = self._get_current_migration_state(loader, [u[0] for u in unapplied])
return unapplied, currents | python | def list_migrations(self):
"""
Returns a tuple of unapplied, current
"Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration
states for apps with unapplied migrations.
Both are tuples of the form (app, migration_name).
"""
connection = connections[self._database_name]
loader = MigrationLoader(connection, ignore_no_migrations=True)
unapplied = self._get_unapplied_migrations(loader)
currents = self._get_current_migration_state(loader, [u[0] for u in unapplied])
return unapplied, currents | [
"def",
"list_migrations",
"(",
"self",
")",
":",
"connection",
"=",
"connections",
"[",
"self",
".",
"_database_name",
"]",
"loader",
"=",
"MigrationLoader",
"(",
"connection",
",",
"ignore_no_migrations",
"=",
"True",
")",
"unapplied",
"=",
"self",
".",
"_get... | Returns a tuple of unapplied, current
"Unapplied" is a list of unapplied migrations. "Current" is a list of the current migration
states for apps with unapplied migrations.
Both are tuples of the form (app, migration_name). | [
"Returns",
"a",
"tuple",
"of",
"unapplied",
"current"
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L205-L218 | train | 49,942 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession.__apply | def __apply(self, migration=None, run_all=False):
"""
If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided.
"""
out = StringIO()
trace = None
migrate_kwargs = {
'interactive': False,
'stdout': out,
'database': self._database_name,
}
if migration is not None:
migrate_kwargs.update({
'app_label': migration[0],
'migration_name': migration[1],
})
elif not run_all:
raise ValueError('Either a migration must be provided or "run_all" must be True')
start = self._timer()
try:
call_command("migrate", **migrate_kwargs)
except Exception:
trace = ''.join(traceback.format_exception(*sys.exc_info()))
finally:
end = self._timer()
successes, failure = self._parse_migrate_output(out.getvalue())
self._migration_state.append({
'database': self._database_name,
'migration': 'all' if run_all else (migration[0], migration[1]),
'duration': end - start,
'output': _remove_escape_characters(out.getvalue()),
'succeeded_migrations': successes, # [(app, migration), ...]
'failed_migration': failure, # (app, migration)
'traceback': trace,
'succeeded': failure is None and trace is None,
})
if failure is not None:
raise CommandError("Migration failed for app '{}' - migration '{}'.\n".format(*failure))
elif trace is not None:
raise CommandError("Migrations failed unexpectedly. See self.state['traceback'] for details.") | python | def __apply(self, migration=None, run_all=False):
"""
If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided.
"""
out = StringIO()
trace = None
migrate_kwargs = {
'interactive': False,
'stdout': out,
'database': self._database_name,
}
if migration is not None:
migrate_kwargs.update({
'app_label': migration[0],
'migration_name': migration[1],
})
elif not run_all:
raise ValueError('Either a migration must be provided or "run_all" must be True')
start = self._timer()
try:
call_command("migrate", **migrate_kwargs)
except Exception:
trace = ''.join(traceback.format_exception(*sys.exc_info()))
finally:
end = self._timer()
successes, failure = self._parse_migrate_output(out.getvalue())
self._migration_state.append({
'database': self._database_name,
'migration': 'all' if run_all else (migration[0], migration[1]),
'duration': end - start,
'output': _remove_escape_characters(out.getvalue()),
'succeeded_migrations': successes, # [(app, migration), ...]
'failed_migration': failure, # (app, migration)
'traceback': trace,
'succeeded': failure is None and trace is None,
})
if failure is not None:
raise CommandError("Migration failed for app '{}' - migration '{}'.\n".format(*failure))
elif trace is not None:
raise CommandError("Migrations failed unexpectedly. See self.state['traceback'] for details.") | [
"def",
"__apply",
"(",
"self",
",",
"migration",
"=",
"None",
",",
"run_all",
"=",
"False",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"trace",
"=",
"None",
"migrate_kwargs",
"=",
"{",
"'interactive'",
":",
"False",
",",
"'stdout'",
":",
"out",
",",
... | If a migration is supplied, runs that migration and appends to state.
If run_all==True, runs all migrations.
Raises a ValueError if neither "migration" nor "run_all" are provided. | [
"If",
"a",
"migration",
"is",
"supplied",
"runs",
"that",
"migration",
"and",
"appends",
"to",
"state",
".",
"If",
"run_all",
"==",
"True",
"runs",
"all",
"migrations",
".",
"Raises",
"a",
"ValueError",
"if",
"neither",
"migration",
"nor",
"run_all",
"are",
... | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L247-L292 | train | 49,943 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession.apply | def apply(self):
"""
Applies all migrations that have been added.
Note that some migrations depend on others, so you might end up
running more than one.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
try:
while self._to_apply:
self.__apply(migration=self._to_apply.pop(0))
except:
raise
finally:
self.__closed = True | python | def apply(self):
"""
Applies all migrations that have been added.
Note that some migrations depend on others, so you might end up
running more than one.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
try:
while self._to_apply:
self.__apply(migration=self._to_apply.pop(0))
except:
raise
finally:
self.__closed = True | [
"def",
"apply",
"(",
"self",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't apply applied session\"",
")",
"try",
":",
"while",
"self",
".",
"_to_apply",
":",
"self",
".",
"__apply",
"(",
"migration",
"=",
"self... | Applies all migrations that have been added.
Note that some migrations depend on others, so you might end up
running more than one. | [
"Applies",
"all",
"migrations",
"that",
"have",
"been",
"added",
".",
"Note",
"that",
"some",
"migrations",
"depend",
"on",
"others",
"so",
"you",
"might",
"end",
"up",
"running",
"more",
"than",
"one",
"."
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L294-L308 | train | 49,944 |
edx/edx-django-release-util | release_util/management/commands/__init__.py | MigrationSession.apply_all | def apply_all(self):
"""
Applies all Django model migrations at once, recording the result.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
if self._to_apply:
raise MigrationSessionError("Can't apply_all with migrations added to session")
try:
self.__apply(run_all=True)
except:
raise
finally:
self.__closed = True | python | def apply_all(self):
"""
Applies all Django model migrations at once, recording the result.
"""
if self.__closed:
raise MigrationSessionError("Can't apply applied session")
if self._to_apply:
raise MigrationSessionError("Can't apply_all with migrations added to session")
try:
self.__apply(run_all=True)
except:
raise
finally:
self.__closed = True | [
"def",
"apply_all",
"(",
"self",
")",
":",
"if",
"self",
".",
"__closed",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't apply applied session\"",
")",
"if",
"self",
".",
"_to_apply",
":",
"raise",
"MigrationSessionError",
"(",
"\"Can't apply_all with migrations... | Applies all Django model migrations at once, recording the result. | [
"Applies",
"all",
"Django",
"model",
"migrations",
"at",
"once",
"recording",
"the",
"result",
"."
] | de0fde41d6a19885ab7dc309472b94fd0fccbc1d | https://github.com/edx/edx-django-release-util/blob/de0fde41d6a19885ab7dc309472b94fd0fccbc1d/release_util/management/commands/__init__.py#L310-L324 | train | 49,945 |
InfoAgeTech/django-core | django_core/mail/sending.py | send_email_from_template | def send_email_from_template(to_email, from_email, subject,
markdown_template=None,
text_template=None, html_template=None,
fail_silently=False, context=None,
**kwargs):
"""Send an email from a template.
:param to_email: the email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates
"""
return send_emails_from_template(
to_emails=[to_email],
from_email=from_email,
subject=subject,
markdown_template=markdown_template,
text_template=text_template,
html_template=html_template,
fail_silently=fail_silently,
context=context,
**kwargs
) | python | def send_email_from_template(to_email, from_email, subject,
markdown_template=None,
text_template=None, html_template=None,
fail_silently=False, context=None,
**kwargs):
"""Send an email from a template.
:param to_email: the email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates
"""
return send_emails_from_template(
to_emails=[to_email],
from_email=from_email,
subject=subject,
markdown_template=markdown_template,
text_template=text_template,
html_template=html_template,
fail_silently=fail_silently,
context=context,
**kwargs
) | [
"def",
"send_email_from_template",
"(",
"to_email",
",",
"from_email",
",",
"subject",
",",
"markdown_template",
"=",
"None",
",",
"text_template",
"=",
"None",
",",
"html_template",
"=",
"None",
",",
"fail_silently",
"=",
"False",
",",
"context",
"=",
"None",
... | Send an email from a template.
:param to_email: the email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates | [
"Send",
"an",
"email",
"from",
"a",
"template",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/mail/sending.py#L9-L39 | train | 49,946 |
InfoAgeTech/django-core | django_core/mail/sending.py | send_emails_from_template | def send_emails_from_template(to_emails, from_email, subject,
markdown_template=None, text_template=None,
html_template=None, fail_silently=False,
context=None, attachments=None, **kwargs):
"""Send many emails from single template. Each email address listed in the
``to_emails`` will receive an separate email.
:param to_emails: list of email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates
:param attachments: list of additional attachments to add to the email
(example: email.mime.image.MIMEImage object). The attachments will be
added to each email sent.
"""
if not to_emails:
return
if context is None:
context = {}
if markdown_template:
try:
from markdown import markdown
except ImportError:
raise ImportError(
'The application is attempting to send an email by using the '
'"markdown" library, but markdown is not installed. Please '
'install it. See: '
'http://pythonhosted.org/Markdown/install.html'
)
base_html_template = getattr(settings,
'CORE_BASE_HTML_EMAIL_TEMPLATE',
'django_core/mail/base_email.html')
text_content = render_to_string(markdown_template, context)
context['email_content'] = markdown(text_content)
html_content = render_to_string(base_html_template, context)
else:
text_content = render_to_string(text_template, context)
html_content = render_to_string(html_template, context)
emails = []
for email_address in to_emails:
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=from_email,
to=[email_address],
alternatives=[(html_content, 'text/html')]
)
if attachments:
email.mixed_subtype = 'related'
for attachment in attachments:
email.attach(attachment)
emails.append(email)
connection = mail.get_connection()
connection.open()
connection.send_messages(emails)
connection.close() | python | def send_emails_from_template(to_emails, from_email, subject,
markdown_template=None, text_template=None,
html_template=None, fail_silently=False,
context=None, attachments=None, **kwargs):
"""Send many emails from single template. Each email address listed in the
``to_emails`` will receive an separate email.
:param to_emails: list of email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates
:param attachments: list of additional attachments to add to the email
(example: email.mime.image.MIMEImage object). The attachments will be
added to each email sent.
"""
if not to_emails:
return
if context is None:
context = {}
if markdown_template:
try:
from markdown import markdown
except ImportError:
raise ImportError(
'The application is attempting to send an email by using the '
'"markdown" library, but markdown is not installed. Please '
'install it. See: '
'http://pythonhosted.org/Markdown/install.html'
)
base_html_template = getattr(settings,
'CORE_BASE_HTML_EMAIL_TEMPLATE',
'django_core/mail/base_email.html')
text_content = render_to_string(markdown_template, context)
context['email_content'] = markdown(text_content)
html_content = render_to_string(base_html_template, context)
else:
text_content = render_to_string(text_template, context)
html_content = render_to_string(html_template, context)
emails = []
for email_address in to_emails:
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=from_email,
to=[email_address],
alternatives=[(html_content, 'text/html')]
)
if attachments:
email.mixed_subtype = 'related'
for attachment in attachments:
email.attach(attachment)
emails.append(email)
connection = mail.get_connection()
connection.open()
connection.send_messages(emails)
connection.close() | [
"def",
"send_emails_from_template",
"(",
"to_emails",
",",
"from_email",
",",
"subject",
",",
"markdown_template",
"=",
"None",
",",
"text_template",
"=",
"None",
",",
"html_template",
"=",
"None",
",",
"fail_silently",
"=",
"False",
",",
"context",
"=",
"None",... | Send many emails from single template. Each email address listed in the
``to_emails`` will receive an separate email.
:param to_emails: list of email address to send the email to
:param from_email: the email address the email will be from
:param subject: the subject of the email
:param markdown_template: the markdown syntax template to use for the
email. If provided, this will generate both the text and html versions
of the email. You must have the "markdown" library installed in order
to use this. pip install markdown.
:param text_template: the template for the text version of the email. This
can be omitted if the markdown_template is provided.
:param html_template: the template for the html version of the email. This
can be omitted if the markdown_template is provided.
:param context: the context for the email templates
:param attachments: list of additional attachments to add to the email
(example: email.mime.image.MIMEImage object). The attachments will be
added to each email sent. | [
"Send",
"many",
"emails",
"from",
"single",
"template",
".",
"Each",
"email",
"address",
"listed",
"in",
"the",
"to_emails",
"will",
"receive",
"an",
"separate",
"email",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/mail/sending.py#L42-L116 | train | 49,947 |
MarcoFavorito/flloat | flloat/syntax/pl.py | PLFormula.all_models | def all_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]:
"""Find all the possible interpretations given a set of symbols"""
all_possible_interpretations = alphabet.powerset().symbols
all_models = set()
for i in all_possible_interpretations:
# compute current Interpretation, considering False
# all propositional symbols not present in current interpretation
current_interpretation = PLInterpretation(i)
if self.truth(current_interpretation):
all_models.add(current_interpretation)
self._all_models = all_models
return all_models | python | def all_models(self, alphabet: _Alphabet) -> Set[PLInterpretation]:
"""Find all the possible interpretations given a set of symbols"""
all_possible_interpretations = alphabet.powerset().symbols
all_models = set()
for i in all_possible_interpretations:
# compute current Interpretation, considering False
# all propositional symbols not present in current interpretation
current_interpretation = PLInterpretation(i)
if self.truth(current_interpretation):
all_models.add(current_interpretation)
self._all_models = all_models
return all_models | [
"def",
"all_models",
"(",
"self",
",",
"alphabet",
":",
"_Alphabet",
")",
"->",
"Set",
"[",
"PLInterpretation",
"]",
":",
"all_possible_interpretations",
"=",
"alphabet",
".",
"powerset",
"(",
")",
".",
"symbols",
"all_models",
"=",
"set",
"(",
")",
"for",
... | Find all the possible interpretations given a set of symbols | [
"Find",
"all",
"the",
"possible",
"interpretations",
"given",
"a",
"set",
"of",
"symbols"
] | 5e6de1bea444b68d46d288834031860a8b2f8c2d | https://github.com/MarcoFavorito/flloat/blob/5e6de1bea444b68d46d288834031860a8b2f8c2d/flloat/syntax/pl.py#L30-L43 | train | 49,948 |
InfoAgeTech/django-core | django_core/db/models/mixins/tokens.py | AbstractTokenModel.save | def save(self, *args, **kwargs):
"""Make sure token is added."""
self.save_prep(instance_or_instances=self)
return super(AbstractTokenModel, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Make sure token is added."""
self.save_prep(instance_or_instances=self)
return super(AbstractTokenModel, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"save_prep",
"(",
"instance_or_instances",
"=",
"self",
")",
"return",
"super",
"(",
"AbstractTokenModel",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
... | Make sure token is added. | [
"Make",
"sure",
"token",
"is",
"added",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/mixins/tokens.py#L17-L20 | train | 49,949 |
InfoAgeTech/django-core | django_core/db/models/mixins/tokens.py | AbstractTokenModel.save_prep | def save_prep(cls, instance_or_instances):
"""Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
"""
instances = make_obj_list(instance_or_instances)
tokens = set(cls.objects.get_available_tokens(
count=len(instances),
token_length=cls.token_length
))
for instance in instances:
if not instance.token:
instance.token = tokens.pop()
super(AbstractTokenModel, cls).save_prep(
instance_or_instances=instances
) | python | def save_prep(cls, instance_or_instances):
"""Preprocess the object before the object is saved. This
automatically gets called when the save method gets called.
"""
instances = make_obj_list(instance_or_instances)
tokens = set(cls.objects.get_available_tokens(
count=len(instances),
token_length=cls.token_length
))
for instance in instances:
if not instance.token:
instance.token = tokens.pop()
super(AbstractTokenModel, cls).save_prep(
instance_or_instances=instances
) | [
"def",
"save_prep",
"(",
"cls",
",",
"instance_or_instances",
")",
":",
"instances",
"=",
"make_obj_list",
"(",
"instance_or_instances",
")",
"tokens",
"=",
"set",
"(",
"cls",
".",
"objects",
".",
"get_available_tokens",
"(",
"count",
"=",
"len",
"(",
"instanc... | Preprocess the object before the object is saved. This
automatically gets called when the save method gets called. | [
"Preprocess",
"the",
"object",
"before",
"the",
"object",
"is",
"saved",
".",
"This",
"automatically",
"gets",
"called",
"when",
"the",
"save",
"method",
"gets",
"called",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/mixins/tokens.py#L23-L40 | train | 49,950 |
MarcoFavorito/flloat | flloat/base/Formula.py | BinaryOperator._popup | def _popup(self):
"""recursively find commutative binary operator
among child formulas and pop up them at the same level"""
res = ()
for child in self.formulas:
if type(child) == type(self):
superchilds = child.formulas
res += superchilds
else:
res += (child, )
return tuple(res) | python | def _popup(self):
"""recursively find commutative binary operator
among child formulas and pop up them at the same level"""
res = ()
for child in self.formulas:
if type(child) == type(self):
superchilds = child.formulas
res += superchilds
else:
res += (child, )
return tuple(res) | [
"def",
"_popup",
"(",
"self",
")",
":",
"res",
"=",
"(",
")",
"for",
"child",
"in",
"self",
".",
"formulas",
":",
"if",
"type",
"(",
"child",
")",
"==",
"type",
"(",
"self",
")",
":",
"superchilds",
"=",
"child",
".",
"formulas",
"res",
"+=",
"su... | recursively find commutative binary operator
among child formulas and pop up them at the same level | [
"recursively",
"find",
"commutative",
"binary",
"operator",
"among",
"child",
"formulas",
"and",
"pop",
"up",
"them",
"at",
"the",
"same",
"level"
] | 5e6de1bea444b68d46d288834031860a8b2f8c2d | https://github.com/MarcoFavorito/flloat/blob/5e6de1bea444b68d46d288834031860a8b2f8c2d/flloat/base/Formula.py#L80-L90 | train | 49,951 |
InfoAgeTech/django-core | django_core/views/mixins/generic.py | GenericObjectViewMixin.get_content_object_url | def get_content_object_url(self):
"""Gets the absolute url for the content object."""
if (self.content_object and
hasattr(self.content_object, 'get_absolute_url')):
return self.content_object.get_absolute_url()
return None | python | def get_content_object_url(self):
"""Gets the absolute url for the content object."""
if (self.content_object and
hasattr(self.content_object, 'get_absolute_url')):
return self.content_object.get_absolute_url()
return None | [
"def",
"get_content_object_url",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"content_object",
"and",
"hasattr",
"(",
"self",
".",
"content_object",
",",
"'get_absolute_url'",
")",
")",
":",
"return",
"self",
".",
"content_object",
".",
"get_absolute_url",
... | Gets the absolute url for the content object. | [
"Gets",
"the",
"absolute",
"url",
"for",
"the",
"content",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/mixins/generic.py#L49-L55 | train | 49,952 |
InfoAgeTech/django-core | django_core/forms/widgets.py | MultipleDecimalInputWidget.get_widget_css_class | def get_widget_css_class(self, attrs):
"""Gets the class for the widget."""
size_class = 'size-{0}'.format(self.num_inputs)
if 'class' in attrs:
attrs['class'] += ' {0}'.format(size_class)
else:
attrs['class'] = size_class | python | def get_widget_css_class(self, attrs):
"""Gets the class for the widget."""
size_class = 'size-{0}'.format(self.num_inputs)
if 'class' in attrs:
attrs['class'] += ' {0}'.format(size_class)
else:
attrs['class'] = size_class | [
"def",
"get_widget_css_class",
"(",
"self",
",",
"attrs",
")",
":",
"size_class",
"=",
"'size-{0}'",
".",
"format",
"(",
"self",
".",
"num_inputs",
")",
"if",
"'class'",
"in",
"attrs",
":",
"attrs",
"[",
"'class'",
"]",
"+=",
"' {0}'",
".",
"format",
"("... | Gets the class for the widget. | [
"Gets",
"the",
"class",
"for",
"the",
"widget",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/forms/widgets.py#L78-L85 | train | 49,953 |
InfoAgeTech/django-core | django_core/db/models/managers.py | BaseManager.get_or_none | def get_or_none(self, prefetch_related=None, select_related=False,
**kwargs):
"""Gets a single object based on kwargs or None if one is not found.
:param prefetch_related: list or tuple of fields to prefetch for an
object. This takes precedence over select_related.
Example:
>> get_or_none(prefetch_related=['some_field',
... 'some_field__some_fields_field'])
See:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
:param select_related: boolean when set to True will follow foreign-key
relationships to prevent many db queries when looping over foreign
keys. If this value is boolean True, the immediate foreign keys
will be selected, but not foreign keys of foreign keys. If this
value is set to a list or tuple, then those will be the fields to
to follow and select.
Example:
>> # Both of the following are valid
>> get_or_none(select_related=True)
>> get_or_none(select_related=['some_field',
... 'some_field__some_fields_field'])
See: https://docs.djangoproject.com/en/dev/ref/models/querysets/
:param kwargs: list of fields and their values to retrieve.
"""
try:
if prefetch_related:
query_set = self.prefetch_related(*prefetch_related)
elif select_related == True:
query_set = self.select_related()
elif isinstance(select_related, (list, tuple)):
query_set = self.select_related(*select_related)
else:
query_set = self
return query_set.get(**kwargs)
except self.model.DoesNotExist:
return None | python | def get_or_none(self, prefetch_related=None, select_related=False,
**kwargs):
"""Gets a single object based on kwargs or None if one is not found.
:param prefetch_related: list or tuple of fields to prefetch for an
object. This takes precedence over select_related.
Example:
>> get_or_none(prefetch_related=['some_field',
... 'some_field__some_fields_field'])
See:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
:param select_related: boolean when set to True will follow foreign-key
relationships to prevent many db queries when looping over foreign
keys. If this value is boolean True, the immediate foreign keys
will be selected, but not foreign keys of foreign keys. If this
value is set to a list or tuple, then those will be the fields to
to follow and select.
Example:
>> # Both of the following are valid
>> get_or_none(select_related=True)
>> get_or_none(select_related=['some_field',
... 'some_field__some_fields_field'])
See: https://docs.djangoproject.com/en/dev/ref/models/querysets/
:param kwargs: list of fields and their values to retrieve.
"""
try:
if prefetch_related:
query_set = self.prefetch_related(*prefetch_related)
elif select_related == True:
query_set = self.select_related()
elif isinstance(select_related, (list, tuple)):
query_set = self.select_related(*select_related)
else:
query_set = self
return query_set.get(**kwargs)
except self.model.DoesNotExist:
return None | [
"def",
"get_or_none",
"(",
"self",
",",
"prefetch_related",
"=",
"None",
",",
"select_related",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"prefetch_related",
":",
"query_set",
"=",
"self",
".",
"prefetch_related",
"(",
"*",
"prefet... | Gets a single object based on kwargs or None if one is not found.
:param prefetch_related: list or tuple of fields to prefetch for an
object. This takes precedence over select_related.
Example:
>> get_or_none(prefetch_related=['some_field',
... 'some_field__some_fields_field'])
See:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related
:param select_related: boolean when set to True will follow foreign-key
relationships to prevent many db queries when looping over foreign
keys. If this value is boolean True, the immediate foreign keys
will be selected, but not foreign keys of foreign keys. If this
value is set to a list or tuple, then those will be the fields to
to follow and select.
Example:
>> # Both of the following are valid
>> get_or_none(select_related=True)
>> get_or_none(select_related=['some_field',
... 'some_field__some_fields_field'])
See: https://docs.djangoproject.com/en/dev/ref/models/querysets/
:param kwargs: list of fields and their values to retrieve. | [
"Gets",
"a",
"single",
"object",
"based",
"on",
"kwargs",
"or",
"None",
"if",
"one",
"is",
"not",
"found",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L14-L59 | train | 49,954 |
InfoAgeTech/django-core | django_core/db/models/managers.py | CommonManager.get_by_id_or_404 | def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 | python | def get_by_id_or_404(self, id, **kwargs):
"""Gets by a instance instance r raises a 404 is one isn't found."""
obj = self.get_by_id(id=id, **kwargs)
if obj:
return obj
raise Http404 | [
"def",
"get_by_id_or_404",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"self",
".",
"get_by_id",
"(",
"id",
"=",
"id",
",",
"*",
"*",
"kwargs",
")",
"if",
"obj",
":",
"return",
"obj",
"raise",
"Http404"
] | Gets by a instance instance r raises a 404 is one isn't found. | [
"Gets",
"by",
"a",
"instance",
"instance",
"r",
"raises",
"a",
"404",
"is",
"one",
"isn",
"t",
"found",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L71-L78 | train | 49,955 |
InfoAgeTech/django-core | django_core/db/models/managers.py | CommonManager.bulk_create | def bulk_create(self, objs, *args, **kwargs):
"""Insert many object at once."""
if hasattr(self.model, 'save_prep'):
# Method from AbstractBaseModel. If the model class doesn't
# subclass AbstractBaseModel, then don't call this.
self.model.save_prep(instance_or_instances=objs)
return super(CommonManager, self).bulk_create(objs=objs,
*args,
**kwargs) | python | def bulk_create(self, objs, *args, **kwargs):
"""Insert many object at once."""
if hasattr(self.model, 'save_prep'):
# Method from AbstractBaseModel. If the model class doesn't
# subclass AbstractBaseModel, then don't call this.
self.model.save_prep(instance_or_instances=objs)
return super(CommonManager, self).bulk_create(objs=objs,
*args,
**kwargs) | [
"def",
"bulk_create",
"(",
"self",
",",
"objs",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"model",
",",
"'save_prep'",
")",
":",
"# Method from AbstractBaseModel. If the model class doesn't",
"# subclass AbstractBaseMo... | Insert many object at once. | [
"Insert",
"many",
"object",
"at",
"once",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L89-L98 | train | 49,956 |
InfoAgeTech/django-core | django_core/db/models/managers.py | CommonManager.delete_by_ids | def delete_by_ids(self, ids):
"""Delete objects by ids.
:param ids: list of objects ids to delete.
:return: True if objects were deleted. Otherwise, return False if no
objects were found or the delete was not successful.
"""
try:
self.filter(id__in=ids).delete()
return True
except self.model.DoesNotExist:
return False | python | def delete_by_ids(self, ids):
"""Delete objects by ids.
:param ids: list of objects ids to delete.
:return: True if objects were deleted. Otherwise, return False if no
objects were found or the delete was not successful.
"""
try:
self.filter(id__in=ids).delete()
return True
except self.model.DoesNotExist:
return False | [
"def",
"delete_by_ids",
"(",
"self",
",",
"ids",
")",
":",
"try",
":",
"self",
".",
"filter",
"(",
"id__in",
"=",
"ids",
")",
".",
"delete",
"(",
")",
"return",
"True",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
":",
"return",
"False"
] | Delete objects by ids.
:param ids: list of objects ids to delete.
:return: True if objects were deleted. Otherwise, return False if no
objects were found or the delete was not successful. | [
"Delete",
"objects",
"by",
"ids",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L104-L115 | train | 49,957 |
InfoAgeTech/django-core | django_core/db/models/managers.py | SlugManager.is_slug_available | def is_slug_available(self, slug, **kwargs):
"""Checks to see if a slug is available. If the slug is already being used
this method returns False. Otherwise, return True.
"""
try:
self.get(slug=slug, **kwargs)
return False
except self.model.DoesNotExist:
return True | python | def is_slug_available(self, slug, **kwargs):
"""Checks to see if a slug is available. If the slug is already being used
this method returns False. Otherwise, return True.
"""
try:
self.get(slug=slug, **kwargs)
return False
except self.model.DoesNotExist:
return True | [
"def",
"is_slug_available",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"self",
".",
"get",
"(",
"slug",
"=",
"slug",
",",
"*",
"*",
"kwargs",
")",
"return",
"False",
"except",
"self",
".",
"model",
".",
"DoesNotExist",
... | Checks to see if a slug is available. If the slug is already being used
this method returns False. Otherwise, return True. | [
"Checks",
"to",
"see",
"if",
"a",
"slug",
"is",
"available",
".",
"If",
"the",
"slug",
"is",
"already",
"being",
"used",
"this",
"method",
"returns",
"False",
".",
"Otherwise",
"return",
"True",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L135-L143 | train | 49,958 |
InfoAgeTech/django-core | django_core/db/models/managers.py | SlugManager.get_next_slug | def get_next_slug(self, slug, **kwargs):
"""Gets the next available slug.
:param slug: the slug to slugify
:param kwargs: additional filter criteria to check for when looking for
a unique slug.
Example:
if the value "my-slug" is already taken, this method will append "-n"
to the end of the slug until the next available slug is found.
"""
original_slug = slug = slugify(slug)
count = 0
while not self.is_slug_available(slug=slug, **kwargs):
count += 1
slug = '{0}-{1}'.format(original_slug, count)
return slug | python | def get_next_slug(self, slug, **kwargs):
"""Gets the next available slug.
:param slug: the slug to slugify
:param kwargs: additional filter criteria to check for when looking for
a unique slug.
Example:
if the value "my-slug" is already taken, this method will append "-n"
to the end of the slug until the next available slug is found.
"""
original_slug = slug = slugify(slug)
count = 0
while not self.is_slug_available(slug=slug, **kwargs):
count += 1
slug = '{0}-{1}'.format(original_slug, count)
return slug | [
"def",
"get_next_slug",
"(",
"self",
",",
"slug",
",",
"*",
"*",
"kwargs",
")",
":",
"original_slug",
"=",
"slug",
"=",
"slugify",
"(",
"slug",
")",
"count",
"=",
"0",
"while",
"not",
"self",
".",
"is_slug_available",
"(",
"slug",
"=",
"slug",
",",
"... | Gets the next available slug.
:param slug: the slug to slugify
:param kwargs: additional filter criteria to check for when looking for
a unique slug.
Example:
if the value "my-slug" is already taken, this method will append "-n"
to the end of the slug until the next available slug is found. | [
"Gets",
"the",
"next",
"available",
"slug",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L145-L165 | train | 49,959 |
InfoAgeTech/django-core | django_core/db/models/managers.py | TokenManager.get_next_token | def get_next_token(self, length=15, **kwargs):
"""Gets the next available token.
:param length: length of the token
:param kwargs: additional filter criteria to check for when looking for
a unique token.
"""
return self.get_available_tokens(count=1,
token_length=length,
**kwargs)[0] | python | def get_next_token(self, length=15, **kwargs):
"""Gets the next available token.
:param length: length of the token
:param kwargs: additional filter criteria to check for when looking for
a unique token.
"""
return self.get_available_tokens(count=1,
token_length=length,
**kwargs)[0] | [
"def",
"get_next_token",
"(",
"self",
",",
"length",
"=",
"15",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"get_available_tokens",
"(",
"count",
"=",
"1",
",",
"token_length",
"=",
"length",
",",
"*",
"*",
"kwargs",
")",
"[",
"0",
"]"
... | Gets the next available token.
:param length: length of the token
:param kwargs: additional filter criteria to check for when looking for
a unique token. | [
"Gets",
"the",
"next",
"available",
"token",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L183-L193 | train | 49,960 |
InfoAgeTech/django-core | django_core/db/models/managers.py | TokenManager.get_available_tokens | def get_available_tokens(self, count=10, token_length=15, **kwargs):
"""Gets a list of available tokens.
:param count: the number of tokens to return.
:param token_length: the length of the tokens. The higher the number
the easier it will be to return a list. If token_length == 1
there's a strong probability that the enough tokens will exist in
the db.
"""
# This is the number of extra tokens to try and retrieve so calls to
# the db can be limited
token_buffer = int(math.ceil(count * .05))
if token_buffer < 5:
token_buffer = 5
available = set([])
while True:
tokens = [random_alphanum(length=token_length)
for t in range(count + token_buffer)]
db_tokens = self.filter(token__in=tokens).values_list('token',
flat=True)
available.update(set(tokens).difference(db_tokens))
if len(available) >= count:
return list(available)[:count] | python | def get_available_tokens(self, count=10, token_length=15, **kwargs):
"""Gets a list of available tokens.
:param count: the number of tokens to return.
:param token_length: the length of the tokens. The higher the number
the easier it will be to return a list. If token_length == 1
there's a strong probability that the enough tokens will exist in
the db.
"""
# This is the number of extra tokens to try and retrieve so calls to
# the db can be limited
token_buffer = int(math.ceil(count * .05))
if token_buffer < 5:
token_buffer = 5
available = set([])
while True:
tokens = [random_alphanum(length=token_length)
for t in range(count + token_buffer)]
db_tokens = self.filter(token__in=tokens).values_list('token',
flat=True)
available.update(set(tokens).difference(db_tokens))
if len(available) >= count:
return list(available)[:count] | [
"def",
"get_available_tokens",
"(",
"self",
",",
"count",
"=",
"10",
",",
"token_length",
"=",
"15",
",",
"*",
"*",
"kwargs",
")",
":",
"# This is the number of extra tokens to try and retrieve so calls to",
"# the db can be limited",
"token_buffer",
"=",
"int",
"(",
... | Gets a list of available tokens.
:param count: the number of tokens to return.
:param token_length: the length of the tokens. The higher the number
the easier it will be to return a list. If token_length == 1
there's a strong probability that the enough tokens will exist in
the db. | [
"Gets",
"a",
"list",
"of",
"available",
"tokens",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L195-L222 | train | 49,961 |
InfoAgeTech/django-core | django_core/db/models/managers.py | GenericManager.create_generic | def create_generic(self, content_object=None, **kwargs):
"""Create a generic object.
:param content_object: the content object to create a new object for.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id
return self.create(**kwargs) | python | def create_generic(self, content_object=None, **kwargs):
"""Create a generic object.
:param content_object: the content object to create a new object for.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id
return self.create(**kwargs) | [
"def",
"create_generic",
"(",
"self",
",",
"content_object",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"content_object",
":",
"kwargs",
"[",
"'content_type'",
"]",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"content_object",
"... | Create a generic object.
:param content_object: the content object to create a new object for. | [
"Create",
"a",
"generic",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L241-L252 | train | 49,962 |
InfoAgeTech/django-core | django_core/db/models/managers.py | GenericManager.filter_generic | def filter_generic(self, content_object=None, **kwargs):
"""Filter by a generic object.
:param content_object: the content object to filter on.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id
return self.filter(**kwargs) | python | def filter_generic(self, content_object=None, **kwargs):
"""Filter by a generic object.
:param content_object: the content object to filter on.
"""
if content_object:
kwargs['content_type'] = ContentType.objects.get_for_model(
content_object
)
kwargs['object_id'] = content_object.id
return self.filter(**kwargs) | [
"def",
"filter_generic",
"(",
"self",
",",
"content_object",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"content_object",
":",
"kwargs",
"[",
"'content_type'",
"]",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"content_object",
"... | Filter by a generic object.
:param content_object: the content object to filter on. | [
"Filter",
"by",
"a",
"generic",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L254-L265 | train | 49,963 |
InfoAgeTech/django-core | django_core/db/models/managers.py | GenericManager.get_by_model | def get_by_model(self, model):
"""Gets all object by a specific model."""
content_type = ContentType.objects.get_for_model(model)
return self.filter(content_type=content_type) | python | def get_by_model(self, model):
"""Gets all object by a specific model."""
content_type = ContentType.objects.get_for_model(model)
return self.filter(content_type=content_type) | [
"def",
"get_by_model",
"(",
"self",
",",
"model",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"return",
"self",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
")"
] | Gets all object by a specific model. | [
"Gets",
"all",
"object",
"by",
"a",
"specific",
"model",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/managers.py#L286-L289 | train | 49,964 |
InfoAgeTech/django-core | django_core/templatetags/collection_tags.py | attr | def attr(obj, attr):
"""
Does the same thing as getattr.
getattr(obj, attr, '')
"""
if not obj or not hasattr(obj, attr):
return ''
return getattr(obj, attr, '') | python | def attr(obj, attr):
"""
Does the same thing as getattr.
getattr(obj, attr, '')
"""
if not obj or not hasattr(obj, attr):
return ''
return getattr(obj, attr, '') | [
"def",
"attr",
"(",
"obj",
",",
"attr",
")",
":",
"if",
"not",
"obj",
"or",
"not",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"return",
"''",
"return",
"getattr",
"(",
"obj",
",",
"attr",
",",
"''",
")"
] | Does the same thing as getattr.
getattr(obj, attr, '') | [
"Does",
"the",
"same",
"thing",
"as",
"getattr",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/templatetags/collection_tags.py#L29-L38 | train | 49,965 |
InfoAgeTech/django-core | django_core/templatetags/collection_tags.py | make_iterable | def make_iterable(obj):
"""Make an object iterable.
>>> make_iterable(obj='hello')
('hello',)
>>> make_iterable(obj=None)
()
"""
if not obj:
return tuple()
if isinstance(obj, (list, tuple, set)):
return obj
return (obj,) | python | def make_iterable(obj):
"""Make an object iterable.
>>> make_iterable(obj='hello')
('hello',)
>>> make_iterable(obj=None)
()
"""
if not obj:
return tuple()
if isinstance(obj, (list, tuple, set)):
return obj
return (obj,) | [
"def",
"make_iterable",
"(",
"obj",
")",
":",
"if",
"not",
"obj",
":",
"return",
"tuple",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
",",
"set",
")",
")",
":",
"return",
"obj",
"return",
"(",
"obj",
",",
")"
] | Make an object iterable.
>>> make_iterable(obj='hello')
('hello',)
>>> make_iterable(obj=None)
() | [
"Make",
"an",
"object",
"iterable",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/templatetags/collection_tags.py#L48-L62 | train | 49,966 |
InfoAgeTech/django-core | django_core/views/request.py | ApiFormView.get_form_kwargs | def get_form_kwargs(self):
"""Add the 'data' to the form args so you can validate the form
data on a get request.
"""
kwargs = super(ApiFormView, self).get_form_kwargs()
kwargs['data'] = kwargs.get('initial')
return kwargs | python | def get_form_kwargs(self):
"""Add the 'data' to the form args so you can validate the form
data on a get request.
"""
kwargs = super(ApiFormView, self).get_form_kwargs()
kwargs['data'] = kwargs.get('initial')
return kwargs | [
"def",
"get_form_kwargs",
"(",
"self",
")",
":",
"kwargs",
"=",
"super",
"(",
"ApiFormView",
",",
"self",
")",
".",
"get_form_kwargs",
"(",
")",
"kwargs",
"[",
"'data'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'initial'",
")",
"return",
"kwargs"
] | Add the 'data' to the form args so you can validate the form
data on a get request. | [
"Add",
"the",
"data",
"to",
"the",
"form",
"args",
"so",
"you",
"can",
"validate",
"the",
"form",
"data",
"on",
"a",
"get",
"request",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/request.py#L22-L28 | train | 49,967 |
InfoAgeTech/django-core | django_core/views/request.py | ApiFormView.form_invalid | def form_invalid(self, form, context=None, **kwargs):
"""This will return the request with form errors as well as any
additional context.
"""
if not context:
context = {}
context['errors'] = form.errors
return super(ApiFormView, self).render_to_response(context=context,
status=400) | python | def form_invalid(self, form, context=None, **kwargs):
"""This will return the request with form errors as well as any
additional context.
"""
if not context:
context = {}
context['errors'] = form.errors
return super(ApiFormView, self).render_to_response(context=context,
status=400) | [
"def",
"form_invalid",
"(",
"self",
",",
"form",
",",
"context",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"context",
":",
"context",
"=",
"{",
"}",
"context",
"[",
"'errors'",
"]",
"=",
"form",
".",
"errors",
"return",
"super",
... | This will return the request with form errors as well as any
additional context. | [
"This",
"will",
"return",
"the",
"request",
"with",
"form",
"errors",
"as",
"well",
"as",
"any",
"additional",
"context",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/request.py#L30-L39 | train | 49,968 |
InfoAgeTech/django-core | django_core/utils/validators.py | is_valid_hex | def is_valid_hex(value):
"""Boolean indicating of the value is a valid hex value."""
if not value:
return False
regex = re.compile(HEX_COLOR_REGEX)
return bool(regex.match(value)) | python | def is_valid_hex(value):
"""Boolean indicating of the value is a valid hex value."""
if not value:
return False
regex = re.compile(HEX_COLOR_REGEX)
return bool(regex.match(value)) | [
"def",
"is_valid_hex",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"False",
"regex",
"=",
"re",
".",
"compile",
"(",
"HEX_COLOR_REGEX",
")",
"return",
"bool",
"(",
"regex",
".",
"match",
"(",
"value",
")",
")"
] | Boolean indicating of the value is a valid hex value. | [
"Boolean",
"indicating",
"of",
"the",
"value",
"is",
"a",
"valid",
"hex",
"value",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/validators.py#L34-L40 | train | 49,969 |
InfoAgeTech/django-core | django_core/utils/validators.py | is_valid_rgb_color | def is_valid_rgb_color(value):
"""Checks whether the value is a valid rgb or rgba color string.
Valid colors consist of:
- rgb(255, 255, 255)
- rgba(23, 34, 45, .5)
"""
if not value:
return False
regex = re.compile(RGB_COLOR_REGEX)
return bool(regex.match(value)) | python | def is_valid_rgb_color(value):
"""Checks whether the value is a valid rgb or rgba color string.
Valid colors consist of:
- rgb(255, 255, 255)
- rgba(23, 34, 45, .5)
"""
if not value:
return False
regex = re.compile(RGB_COLOR_REGEX)
return bool(regex.match(value)) | [
"def",
"is_valid_rgb_color",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"False",
"regex",
"=",
"re",
".",
"compile",
"(",
"RGB_COLOR_REGEX",
")",
"return",
"bool",
"(",
"regex",
".",
"match",
"(",
"value",
")",
")"
] | Checks whether the value is a valid rgb or rgba color string.
Valid colors consist of:
- rgb(255, 255, 255)
- rgba(23, 34, 45, .5) | [
"Checks",
"whether",
"the",
"value",
"is",
"a",
"valid",
"rgb",
"or",
"rgba",
"color",
"string",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/validators.py#L51-L63 | train | 49,970 |
InfoAgeTech/django-core | django_core/utils/validators.py | validate_password_strength | def validate_password_strength(value):
"""Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter.
"""
min_length = 7
if len(value) < min_length:
raise ValidationError(_('Password must be at least {0} characters '
'long.').format(min_length))
# check for digit
if not any(char.isdigit() for char in value):
raise ValidationError(_('Password must contain at least 1 digit.'))
# check for letter
if not any(char.isalpha() for char in value):
raise ValidationError(_('Password must contain at least 1 letter.')) | python | def validate_password_strength(value):
"""Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter.
"""
min_length = 7
if len(value) < min_length:
raise ValidationError(_('Password must be at least {0} characters '
'long.').format(min_length))
# check for digit
if not any(char.isdigit() for char in value):
raise ValidationError(_('Password must contain at least 1 digit.'))
# check for letter
if not any(char.isalpha() for char in value):
raise ValidationError(_('Password must contain at least 1 letter.')) | [
"def",
"validate_password_strength",
"(",
"value",
")",
":",
"min_length",
"=",
"7",
"if",
"len",
"(",
"value",
")",
"<",
"min_length",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'Password must be at least {0} characters '",
"'long.'",
")",
".",
"format",
... | Validates that a password is as least 7 characters long and has at least
1 digit and 1 letter. | [
"Validates",
"that",
"a",
"password",
"is",
"as",
"least",
"7",
"characters",
"long",
"and",
"has",
"at",
"least",
"1",
"digit",
"and",
"1",
"letter",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/validators.py#L66-L82 | train | 49,971 |
InfoAgeTech/django-core | django_core/utils/random_utils.py | random_alphanum | def random_alphanum(length=10, lower_only=False):
"""
Gets a random alphanumeric value using both letters and numbers.
:param length: size of the random alphanumeric string.
:param lower_only: boolean indicating if only lower case letters should be
used.
:return: alphanumeric string size of length
This function uses all number except for:
* 0
* 1
and uses all letters except for:
* lower case "l" (el)
* lower and upper case "o" and "O" (oh)
For upper and lower cased letters...
------------------------------------
Upper and lower cased letters and numbers can be used more than once which
leaves the possible combinations as follows:
8 numbers used + 49 letters used (upper and lower) = 57 total characters
Which leads us to the following equation:
57 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
57 ^ 1 = 57
57 ^ 2 = 3,249
57 ^ 3 = 185,193
57 ^ 4 = 10,556,001
57 ^ 5 = 601,692,057
57 ^ 6 = 34,296,447,249
57 ^ 7 = 1,954,897,493,193
57 ^ 8 = 111,429,157,112,001
57 ^ 9 = 6,351,461,955,384,057
57 ^ 10 = 362,033,331,456,891,249
...
For lower cased letters...
--------------------------
Lower cased letters and numbers can be used more than once which leaves the
possible combinations as follows:
8 numbers used + 24 letters used (lower only) = 32 total characters
Which leads us to the following equation:
32 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
32 ^ 1 = 32
32 ^ 2 = 1,024
32 ^ 3 = 32,768
32 ^ 4 = 1,048,576
32 ^ 5 = 33,554,432
32 ^ 6 = 1,073,741,824
32 ^ 7 = 34,359,738,368
32 ^ 8 = 1,099,511,627,776
32 ^ 9 = 35,184,372,088,832
32 ^ 10 = 1,125,899,906,842,624
...
"""
character_set = ALPHANUM_LOWER if lower_only else ALPHANUM
sample_size = 5
chars = random.sample(character_set, sample_size)
while len(chars) < length:
chars += random.sample(character_set, sample_size)
random.shuffle(chars)
return ''.join(chars[:length]) | python | def random_alphanum(length=10, lower_only=False):
"""
Gets a random alphanumeric value using both letters and numbers.
:param length: size of the random alphanumeric string.
:param lower_only: boolean indicating if only lower case letters should be
used.
:return: alphanumeric string size of length
This function uses all number except for:
* 0
* 1
and uses all letters except for:
* lower case "l" (el)
* lower and upper case "o" and "O" (oh)
For upper and lower cased letters...
------------------------------------
Upper and lower cased letters and numbers can be used more than once which
leaves the possible combinations as follows:
8 numbers used + 49 letters used (upper and lower) = 57 total characters
Which leads us to the following equation:
57 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
57 ^ 1 = 57
57 ^ 2 = 3,249
57 ^ 3 = 185,193
57 ^ 4 = 10,556,001
57 ^ 5 = 601,692,057
57 ^ 6 = 34,296,447,249
57 ^ 7 = 1,954,897,493,193
57 ^ 8 = 111,429,157,112,001
57 ^ 9 = 6,351,461,955,384,057
57 ^ 10 = 362,033,331,456,891,249
...
For lower cased letters...
--------------------------
Lower cased letters and numbers can be used more than once which leaves the
possible combinations as follows:
8 numbers used + 24 letters used (lower only) = 32 total characters
Which leads us to the following equation:
32 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
32 ^ 1 = 32
32 ^ 2 = 1,024
32 ^ 3 = 32,768
32 ^ 4 = 1,048,576
32 ^ 5 = 33,554,432
32 ^ 6 = 1,073,741,824
32 ^ 7 = 34,359,738,368
32 ^ 8 = 1,099,511,627,776
32 ^ 9 = 35,184,372,088,832
32 ^ 10 = 1,125,899,906,842,624
...
"""
character_set = ALPHANUM_LOWER if lower_only else ALPHANUM
sample_size = 5
chars = random.sample(character_set, sample_size)
while len(chars) < length:
chars += random.sample(character_set, sample_size)
random.shuffle(chars)
return ''.join(chars[:length]) | [
"def",
"random_alphanum",
"(",
"length",
"=",
"10",
",",
"lower_only",
"=",
"False",
")",
":",
"character_set",
"=",
"ALPHANUM_LOWER",
"if",
"lower_only",
"else",
"ALPHANUM",
"sample_size",
"=",
"5",
"chars",
"=",
"random",
".",
"sample",
"(",
"character_set",... | Gets a random alphanumeric value using both letters and numbers.
:param length: size of the random alphanumeric string.
:param lower_only: boolean indicating if only lower case letters should be
used.
:return: alphanumeric string size of length
This function uses all number except for:
* 0
* 1
and uses all letters except for:
* lower case "l" (el)
* lower and upper case "o" and "O" (oh)
For upper and lower cased letters...
------------------------------------
Upper and lower cased letters and numbers can be used more than once which
leaves the possible combinations as follows:
8 numbers used + 49 letters used (upper and lower) = 57 total characters
Which leads us to the following equation:
57 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
57 ^ 1 = 57
57 ^ 2 = 3,249
57 ^ 3 = 185,193
57 ^ 4 = 10,556,001
57 ^ 5 = 601,692,057
57 ^ 6 = 34,296,447,249
57 ^ 7 = 1,954,897,493,193
57 ^ 8 = 111,429,157,112,001
57 ^ 9 = 6,351,461,955,384,057
57 ^ 10 = 362,033,331,456,891,249
...
For lower cased letters...
--------------------------
Lower cased letters and numbers can be used more than once which leaves the
possible combinations as follows:
8 numbers used + 24 letters used (lower only) = 32 total characters
Which leads us to the following equation:
32 total characters ^ length = total possible combinations
The following total possible combinations are below for a given length:
32 ^ 1 = 32
32 ^ 2 = 1,024
32 ^ 3 = 32,768
32 ^ 4 = 1,048,576
32 ^ 5 = 33,554,432
32 ^ 6 = 1,073,741,824
32 ^ 7 = 34,359,738,368
32 ^ 8 = 1,099,511,627,776
32 ^ 9 = 35,184,372,088,832
32 ^ 10 = 1,125,899,906,842,624
... | [
"Gets",
"a",
"random",
"alphanumeric",
"value",
"using",
"both",
"letters",
"and",
"numbers",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/random_utils.py#L20-L98 | train | 49,972 |
InfoAgeTech/django-core | django_core/utils/random_utils.py | generate_key | def generate_key(low=7, high=10, lower_only=False):
"""Gets a random alphanumeric key between low and high characters in
length.
"""
return random_alphanum(length=randint(7, 10), lower_only=lower_only) | python | def generate_key(low=7, high=10, lower_only=False):
"""Gets a random alphanumeric key between low and high characters in
length.
"""
return random_alphanum(length=randint(7, 10), lower_only=lower_only) | [
"def",
"generate_key",
"(",
"low",
"=",
"7",
",",
"high",
"=",
"10",
",",
"lower_only",
"=",
"False",
")",
":",
"return",
"random_alphanum",
"(",
"length",
"=",
"randint",
"(",
"7",
",",
"10",
")",
",",
"lower_only",
"=",
"lower_only",
")"
] | Gets a random alphanumeric key between low and high characters in
length. | [
"Gets",
"a",
"random",
"alphanumeric",
"key",
"between",
"low",
"and",
"high",
"characters",
"in",
"length",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/random_utils.py#L101-L105 | train | 49,973 |
InfoAgeTech/django-core | django_core/db/models/mixins/urls.py | AbstractUrlLinkModelMixin.get_absolute_url_link | def get_absolute_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html link for the object."""
if text is None:
text = self.get_link_text()
return build_link(href=self.get_absolute_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | python | def get_absolute_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html link for the object."""
if text is None:
text = self.get_link_text()
return build_link(href=self.get_absolute_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | [
"def",
"get_absolute_url_link",
"(",
"self",
",",
"text",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"self",
".",
"get_link_text",
"(",
")",
... | Gets the html link for the object. | [
"Gets",
"the",
"html",
"link",
"for",
"the",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/mixins/urls.py#L26-L36 | train | 49,974 |
InfoAgeTech/django-core | django_core/db/models/mixins/urls.py | AbstractUrlLinkModelMixin.get_edit_url_link | def get_edit_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html edit link for the object."""
if text is None:
text = 'Edit'
return build_link(href=self.get_edit_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | python | def get_edit_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html edit link for the object."""
if text is None:
text = 'Edit'
return build_link(href=self.get_edit_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | [
"def",
"get_edit_url_link",
"(",
"self",
",",
"text",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"'Edit'",
"return",
"build_link",
"(",
"href",... | Gets the html edit link for the object. | [
"Gets",
"the",
"html",
"edit",
"link",
"for",
"the",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/mixins/urls.py#L38-L48 | train | 49,975 |
InfoAgeTech/django-core | django_core/db/models/mixins/urls.py | AbstractUrlLinkModelMixin.get_delete_url_link | def get_delete_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html delete link for the object."""
if text is None:
text = 'Delete'
return build_link(href=self.get_delete_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | python | def get_delete_url_link(self, text=None, cls=None, icon_class=None,
**attrs):
"""Gets the html delete link for the object."""
if text is None:
text = 'Delete'
return build_link(href=self.get_delete_url(),
text=text,
cls=cls,
icon_class=icon_class,
**attrs) | [
"def",
"get_delete_url_link",
"(",
"self",
",",
"text",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"icon_class",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"text",
"is",
"None",
":",
"text",
"=",
"'Delete'",
"return",
"build_link",
"(",
"hr... | Gets the html delete link for the object. | [
"Gets",
"the",
"html",
"delete",
"link",
"for",
"the",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/mixins/urls.py#L50-L60 | train | 49,976 |
InfoAgeTech/django-core | django_core/managers.py | TokenAuthorizationManager.expire_by_email | def expire_by_email(self, email_address, **kwargs):
"""Expires tokens for an email address or email addresses.
:param email_address: the string email address or emails addresses to
expire tokens for.
:param reason: the codified reason for the tokens. If explicitly set
to None, this will expire all tokens for the email provided.
"""
if not email_address:
# no email(s) provided. Nothing to do.
return None
if isinstance(email_address, (set, list, tuple)):
email_address = [e.strip() for e in set(email_address)
if e and e.strip()]
# make sure there's at least 1 valid email address
if len(email_address) <= 0:
# no valid emails
return None
kwargs['email_address__in'] = email_address
else:
kwargs['email_address'] = email_address
# try setting the reason default if one exists (in the case of proxy
# models)
if 'reason' not in kwargs and self.model.reason_default:
kwargs['reason'] = self.model.reason_default
if 'reason' in kwargs and kwargs.get('reason') is None:
# explicitly setting the reason to None will expire all tokens for
# a user regardless of the reason.
del kwargs['reason']
self.filter(**kwargs).update(expires=datetime(1970, 1, 1)) | python | def expire_by_email(self, email_address, **kwargs):
"""Expires tokens for an email address or email addresses.
:param email_address: the string email address or emails addresses to
expire tokens for.
:param reason: the codified reason for the tokens. If explicitly set
to None, this will expire all tokens for the email provided.
"""
if not email_address:
# no email(s) provided. Nothing to do.
return None
if isinstance(email_address, (set, list, tuple)):
email_address = [e.strip() for e in set(email_address)
if e and e.strip()]
# make sure there's at least 1 valid email address
if len(email_address) <= 0:
# no valid emails
return None
kwargs['email_address__in'] = email_address
else:
kwargs['email_address'] = email_address
# try setting the reason default if one exists (in the case of proxy
# models)
if 'reason' not in kwargs and self.model.reason_default:
kwargs['reason'] = self.model.reason_default
if 'reason' in kwargs and kwargs.get('reason') is None:
# explicitly setting the reason to None will expire all tokens for
# a user regardless of the reason.
del kwargs['reason']
self.filter(**kwargs).update(expires=datetime(1970, 1, 1)) | [
"def",
"expire_by_email",
"(",
"self",
",",
"email_address",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"email_address",
":",
"# no email(s) provided. Nothing to do.",
"return",
"None",
"if",
"isinstance",
"(",
"email_address",
",",
"(",
"set",
",",
"list"... | Expires tokens for an email address or email addresses.
:param email_address: the string email address or emails addresses to
expire tokens for.
:param reason: the codified reason for the tokens. If explicitly set
to None, this will expire all tokens for the email provided. | [
"Expires",
"tokens",
"for",
"an",
"email",
"address",
"or",
"email",
"addresses",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/managers.py#L12-L47 | train | 49,977 |
InfoAgeTech/django-core | django_core/views/mixins/query.py | QueryStringAliasViewMixin.map_query_string | def map_query_string(self):
"""Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys.
"""
if (not self.query_key_mapper or
self.request.method == 'POST'):
# Nothing to map, don't do anything.
# return self.request.POST
return {}
keys = list(self.query_key_mapper.keys())
return {self.query_key_mapper.get(k) if k in keys else k: v.strip()
for k, v in self.request.GET.items()} | python | def map_query_string(self):
"""Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys.
"""
if (not self.query_key_mapper or
self.request.method == 'POST'):
# Nothing to map, don't do anything.
# return self.request.POST
return {}
keys = list(self.query_key_mapper.keys())
return {self.query_key_mapper.get(k) if k in keys else k: v.strip()
for k, v in self.request.GET.items()} | [
"def",
"map_query_string",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"query_key_mapper",
"or",
"self",
".",
"request",
".",
"method",
"==",
"'POST'",
")",
":",
"# Nothing to map, don't do anything.",
"# return self.request.POST",
"return",
"{",
"}",
... | Maps the GET query string params the the query_key_mapper dict and
updates the request's GET QueryDict with the mapped keys. | [
"Maps",
"the",
"GET",
"query",
"string",
"params",
"the",
"the",
"query_key_mapper",
"dict",
"and",
"updates",
"the",
"request",
"s",
"GET",
"QueryDict",
"with",
"the",
"mapped",
"keys",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/mixins/query.py#L40-L53 | train | 49,978 |
txomon/abot | abot/slack.py | SlackAPI.call | async def call(self, method, **params):
"""
Call an Slack Web API method
:param method: Slack Web API method to call
:param params: {str: object} parameters to method
:return: dict()
"""
url = self.SLACK_RPC_PREFIX + method
data = FormData()
data.add_fields(MultiDict(token=self.bot_token, charset='utf-8', **params))
response_body = await self.request(
method='POST',
url=url,
data=data
)
if 'warning' in response_body:
logger.warning(f'Warnings received from API call {method}: {response_body["warning"]}')
if 'ok' not in response_body:
logger.error(f'No ok marker in slack API call {method} {params} => {response_body}')
raise SlackCallException('There is no ok marker, ... strange', method=method)
if not response_body['ok']:
logger.error(f'Slack API call failed {method} {params} => {response_body}')
raise SlackCallException(f'No OK response returned', method=method)
return response_body | python | async def call(self, method, **params):
"""
Call an Slack Web API method
:param method: Slack Web API method to call
:param params: {str: object} parameters to method
:return: dict()
"""
url = self.SLACK_RPC_PREFIX + method
data = FormData()
data.add_fields(MultiDict(token=self.bot_token, charset='utf-8', **params))
response_body = await self.request(
method='POST',
url=url,
data=data
)
if 'warning' in response_body:
logger.warning(f'Warnings received from API call {method}: {response_body["warning"]}')
if 'ok' not in response_body:
logger.error(f'No ok marker in slack API call {method} {params} => {response_body}')
raise SlackCallException('There is no ok marker, ... strange', method=method)
if not response_body['ok']:
logger.error(f'Slack API call failed {method} {params} => {response_body}')
raise SlackCallException(f'No OK response returned', method=method)
return response_body | [
"async",
"def",
"call",
"(",
"self",
",",
"method",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"SLACK_RPC_PREFIX",
"+",
"method",
"data",
"=",
"FormData",
"(",
")",
"data",
".",
"add_fields",
"(",
"MultiDict",
"(",
"token",
"=",
"sel... | Call an Slack Web API method
:param method: Slack Web API method to call
:param params: {str: object} parameters to method
:return: dict() | [
"Call",
"an",
"Slack",
"Web",
"API",
"method"
] | 3ac23c6d14965d4608ed13c284ae1a886b462252 | https://github.com/txomon/abot/blob/3ac23c6d14965d4608ed13c284ae1a886b462252/abot/slack.py#L83-L107 | train | 49,979 |
txomon/abot | abot/slack.py | SlackAPI.rtm_handler | def rtm_handler(self, ws_message):
"""
Handle a message, processing it internally if required. If it's a message that should go outside the bot,
this function will return True
:param message:
:return: Boolean if message should be yielded
"""
message = json.loads(ws_message.data)
if 'reply_to' in message:
reply_to = message['reply_to']
future = self.response_futures.pop(reply_to, None)
if future is None:
logger.error(f'This should not happen, received reply to unknown message! {message}')
return None
future.set_result(message)
return None
if 'type' not in message:
logger.error(f'No idea what this could be {message}')
return
message_type = message['type']
if hasattr(self, f'handle_{message_type}'):
function = getattr(self, f'handle_{message_type}')
return function(message)
if message_type in self.SLACK_RTM_EVENTS:
logger.debug(f'Unhandled {message_type}. {message}')
else:
logger.warning(f'Unknown {message_type}. {message}')
return message | python | def rtm_handler(self, ws_message):
"""
Handle a message, processing it internally if required. If it's a message that should go outside the bot,
this function will return True
:param message:
:return: Boolean if message should be yielded
"""
message = json.loads(ws_message.data)
if 'reply_to' in message:
reply_to = message['reply_to']
future = self.response_futures.pop(reply_to, None)
if future is None:
logger.error(f'This should not happen, received reply to unknown message! {message}')
return None
future.set_result(message)
return None
if 'type' not in message:
logger.error(f'No idea what this could be {message}')
return
message_type = message['type']
if hasattr(self, f'handle_{message_type}'):
function = getattr(self, f'handle_{message_type}')
return function(message)
if message_type in self.SLACK_RTM_EVENTS:
logger.debug(f'Unhandled {message_type}. {message}')
else:
logger.warning(f'Unknown {message_type}. {message}')
return message | [
"def",
"rtm_handler",
"(",
"self",
",",
"ws_message",
")",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"ws_message",
".",
"data",
")",
"if",
"'reply_to'",
"in",
"message",
":",
"reply_to",
"=",
"message",
"[",
"'reply_to'",
"]",
"future",
"=",
"self"... | Handle a message, processing it internally if required. If it's a message that should go outside the bot,
this function will return True
:param message:
:return: Boolean if message should be yielded | [
"Handle",
"a",
"message",
"processing",
"it",
"internally",
"if",
"required",
".",
"If",
"it",
"s",
"a",
"message",
"that",
"should",
"go",
"outside",
"the",
"bot",
"this",
"function",
"will",
"return",
"True"
] | 3ac23c6d14965d4608ed13c284ae1a886b462252 | https://github.com/txomon/abot/blob/3ac23c6d14965d4608ed13c284ae1a886b462252/abot/slack.py#L591-L621 | train | 49,980 |
InfoAgeTech/django-core | django_core/forms/mixins/common.py | PrefixFormMixin.get_default_prefix | def get_default_prefix(self, instance=None):
"""Gets the prefix for this form.
:param instance: the form model instance. When calling this method
directly this should almost always stay None so it looks for
self.instance.
"""
if instance is None and hasattr(self, 'instance'):
instance = self.instance
if instance and instance.id is not None:
# it's an existing instance, use the instance prefix
instance_prefix = self.default_instance_prefix
if instance_prefix is None:
instance_prefix = self.__class__.__name__.lower() + 'i-'
return '{0}{1}'.format(instance_prefix,
instance.id)
if self.default_new_prefix is not None:
return self.default_new_prefix
return self.__class__.__name__.lower() + 'new-' | python | def get_default_prefix(self, instance=None):
"""Gets the prefix for this form.
:param instance: the form model instance. When calling this method
directly this should almost always stay None so it looks for
self.instance.
"""
if instance is None and hasattr(self, 'instance'):
instance = self.instance
if instance and instance.id is not None:
# it's an existing instance, use the instance prefix
instance_prefix = self.default_instance_prefix
if instance_prefix is None:
instance_prefix = self.__class__.__name__.lower() + 'i-'
return '{0}{1}'.format(instance_prefix,
instance.id)
if self.default_new_prefix is not None:
return self.default_new_prefix
return self.__class__.__name__.lower() + 'new-' | [
"def",
"get_default_prefix",
"(",
"self",
",",
"instance",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'instance'",
")",
":",
"instance",
"=",
"self",
".",
"instance",
"if",
"instance",
"and",
"instance",
"... | Gets the prefix for this form.
:param instance: the form model instance. When calling this method
directly this should almost always stay None so it looks for
self.instance. | [
"Gets",
"the",
"prefix",
"for",
"this",
"form",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/forms/mixins/common.py#L36-L58 | train | 49,981 |
InfoAgeTech/django-core | django_core/db/models/fields.py | ListField.formfield | def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""Make the default formfield a CommaSeparatedListField."""
defaults = {
'form_class': form_class or self.get_form_class()
}
defaults.update(kwargs)
return super(ListField, self).formfield(**defaults) | python | def formfield(self, form_class=None, choices_form_class=None, **kwargs):
"""Make the default formfield a CommaSeparatedListField."""
defaults = {
'form_class': form_class or self.get_form_class()
}
defaults.update(kwargs)
return super(ListField, self).formfield(**defaults) | [
"def",
"formfield",
"(",
"self",
",",
"form_class",
"=",
"None",
",",
"choices_form_class",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"defaults",
"=",
"{",
"'form_class'",
":",
"form_class",
"or",
"self",
".",
"get_form_class",
"(",
")",
"}",
"defa... | Make the default formfield a CommaSeparatedListField. | [
"Make",
"the",
"default",
"formfield",
"a",
"CommaSeparatedListField",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/fields.py#L94-L101 | train | 49,982 |
InfoAgeTech/django-core | django_core/db/models/fields.py | ListField.validate | def validate(self, value, model_instance, **kwargs):
"""This follows the validate rules for choices_form_class field used.
"""
self.get_choices_form_class().validate(value, model_instance, **kwargs) | python | def validate(self, value, model_instance, **kwargs):
"""This follows the validate rules for choices_form_class field used.
"""
self.get_choices_form_class().validate(value, model_instance, **kwargs) | [
"def",
"validate",
"(",
"self",
",",
"value",
",",
"model_instance",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"get_choices_form_class",
"(",
")",
".",
"validate",
"(",
"value",
",",
"model_instance",
",",
"*",
"*",
"kwargs",
")"
] | This follows the validate rules for choices_form_class field used. | [
"This",
"follows",
"the",
"validate",
"rules",
"for",
"choices_form_class",
"field",
"used",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/db/models/fields.py#L110-L113 | train | 49,983 |
InfoAgeTech/django-core | django_core/auth/views.py | AuthorizationTokenRequiredViewMixin.get_authorization | def get_authorization(self, **kwargs):
"""Gets the authorization object for the view."""
if self.authorization is not None:
return self.authorization
auth_class = self.get_authorization_class()
auth_user = self.get_authorization_user()
auth_kwargs = {
'token': self.get_authorization_token(**kwargs)
}
if auth_user and auth_user.is_authenticated():
auth_kwargs['created_user'] = self.get_authorization_user()
self.authorization = auth_class.objects.get_by_token_or_404(
**auth_kwargs
)
return self.authorization | python | def get_authorization(self, **kwargs):
"""Gets the authorization object for the view."""
if self.authorization is not None:
return self.authorization
auth_class = self.get_authorization_class()
auth_user = self.get_authorization_user()
auth_kwargs = {
'token': self.get_authorization_token(**kwargs)
}
if auth_user and auth_user.is_authenticated():
auth_kwargs['created_user'] = self.get_authorization_user()
self.authorization = auth_class.objects.get_by_token_or_404(
**auth_kwargs
)
return self.authorization | [
"def",
"get_authorization",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"authorization",
"is",
"not",
"None",
":",
"return",
"self",
".",
"authorization",
"auth_class",
"=",
"self",
".",
"get_authorization_class",
"(",
")",
"auth_user"... | Gets the authorization object for the view. | [
"Gets",
"the",
"authorization",
"object",
"for",
"the",
"view",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/auth/views.py#L31-L48 | train | 49,984 |
InfoAgeTech/django-core | django_core/auth/views.py | AuthorizationTokenRequiredViewMixin.get_authorization_user | def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorization_user
self.authorization_user = self.request.user
return self.request.user | python | def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorization_user
self.authorization_user = self.request.user
return self.request.user | [
"def",
"get_authorization_user",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"authorization_user",
"is",
"not",
"None",
":",
"return",
"self",
".",
"authorization_user",
"self",
".",
"authorization_user",
"=",
"self",
".",
"request",
"... | Gets the user the authorization object is for. | [
"Gets",
"the",
"user",
"the",
"authorization",
"object",
"is",
"for",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/auth/views.py#L54-L60 | train | 49,985 |
InfoAgeTech/django-core | django_core/utils/urls.py | safe_redirect | def safe_redirect(next_url, default=None):
"""Makes sure it's a legit site to redirect to.
:param default: this is the default url or named url to redirect to in the
event where next_url is not legit.
"""
if is_legit_next_url(next_url):
return redirect(next_url)
if default:
return redirect(default)
return redirect('/') | python | def safe_redirect(next_url, default=None):
"""Makes sure it's a legit site to redirect to.
:param default: this is the default url or named url to redirect to in the
event where next_url is not legit.
"""
if is_legit_next_url(next_url):
return redirect(next_url)
if default:
return redirect(default)
return redirect('/') | [
"def",
"safe_redirect",
"(",
"next_url",
",",
"default",
"=",
"None",
")",
":",
"if",
"is_legit_next_url",
"(",
"next_url",
")",
":",
"return",
"redirect",
"(",
"next_url",
")",
"if",
"default",
":",
"return",
"redirect",
"(",
"default",
")",
"return",
"re... | Makes sure it's a legit site to redirect to.
:param default: this is the default url or named url to redirect to in the
event where next_url is not legit. | [
"Makes",
"sure",
"it",
"s",
"a",
"legit",
"site",
"to",
"redirect",
"to",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/urls.py#L53-L66 | train | 49,986 |
InfoAgeTech/django-core | django_core/utils/urls.py | replace_url_query_values | def replace_url_query_values(url, replace_vals):
"""Replace querystring values in a url string.
>>> url = 'http://helloworld.com/some/path?test=5'
>>> replace_vals = {'test': 10}
>>> replace_url_query_values(url=url, replace_vals=replace_vals)
'http://helloworld.com/some/path?test=10'
"""
if '?' not in url:
return url
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
query.update(replace_vals)
return '{0}?{1}'.format(url.split('?')[0], urlencode(query)) | python | def replace_url_query_values(url, replace_vals):
"""Replace querystring values in a url string.
>>> url = 'http://helloworld.com/some/path?test=5'
>>> replace_vals = {'test': 10}
>>> replace_url_query_values(url=url, replace_vals=replace_vals)
'http://helloworld.com/some/path?test=10'
"""
if '?' not in url:
return url
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
query.update(replace_vals)
return '{0}?{1}'.format(url.split('?')[0], urlencode(query)) | [
"def",
"replace_url_query_values",
"(",
"url",
",",
"replace_vals",
")",
":",
"if",
"'?'",
"not",
"in",
"url",
":",
"return",
"url",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"query",
"=",
"dict",
"(",
"parse_qsl",
"(",
"parsed_url",
".",
"query",
... | Replace querystring values in a url string.
>>> url = 'http://helloworld.com/some/path?test=5'
>>> replace_vals = {'test': 10}
>>> replace_url_query_values(url=url, replace_vals=replace_vals)
'http://helloworld.com/some/path?test=10' | [
"Replace",
"querystring",
"values",
"in",
"a",
"url",
"string",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/urls.py#L82-L96 | train | 49,987 |
InfoAgeTech/django-core | django_core/utils/urls.py | get_query_values_from_url | def get_query_values_from_url(url, keys=None):
"""Gets query string values from a url.
if a list of keys are provided, then a dict will be returned. If only a
single string key is provided, then only a single value will be returned.
>>> url = 'http://helloworld.com/some/path?test=5&hello=world&john=doe'
>>> get_query_values_from_url(url=url, keys='test')
"5"
>>> get_query_values_from_url(url=url, keys=['test'])
{'test': '5'}
>>> get_query_values_from_url(url=url, keys=['test', 'john'])
{'test': '5', 'john': 'doe'}
>>> get_query_values_from_url(url=url, keys=['test', 'john', 'blah'])
{'test': '5', 'john': 'doe', 'blah': None}
"""
if not url or '?' not in url:
# no query params
return None
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
if keys is None:
return query
if isinstance(keys, string_types):
return query.get(keys)
return {k: query.get(k) for k in keys} | python | def get_query_values_from_url(url, keys=None):
"""Gets query string values from a url.
if a list of keys are provided, then a dict will be returned. If only a
single string key is provided, then only a single value will be returned.
>>> url = 'http://helloworld.com/some/path?test=5&hello=world&john=doe'
>>> get_query_values_from_url(url=url, keys='test')
"5"
>>> get_query_values_from_url(url=url, keys=['test'])
{'test': '5'}
>>> get_query_values_from_url(url=url, keys=['test', 'john'])
{'test': '5', 'john': 'doe'}
>>> get_query_values_from_url(url=url, keys=['test', 'john', 'blah'])
{'test': '5', 'john': 'doe', 'blah': None}
"""
if not url or '?' not in url:
# no query params
return None
parsed_url = urlparse(url)
query = dict(parse_qsl(parsed_url.query))
if keys is None:
return query
if isinstance(keys, string_types):
return query.get(keys)
return {k: query.get(k) for k in keys} | [
"def",
"get_query_values_from_url",
"(",
"url",
",",
"keys",
"=",
"None",
")",
":",
"if",
"not",
"url",
"or",
"'?'",
"not",
"in",
"url",
":",
"# no query params",
"return",
"None",
"parsed_url",
"=",
"urlparse",
"(",
"url",
")",
"query",
"=",
"dict",
"("... | Gets query string values from a url.
if a list of keys are provided, then a dict will be returned. If only a
single string key is provided, then only a single value will be returned.
>>> url = 'http://helloworld.com/some/path?test=5&hello=world&john=doe'
>>> get_query_values_from_url(url=url, keys='test')
"5"
>>> get_query_values_from_url(url=url, keys=['test'])
{'test': '5'}
>>> get_query_values_from_url(url=url, keys=['test', 'john'])
{'test': '5', 'john': 'doe'}
>>> get_query_values_from_url(url=url, keys=['test', 'john', 'blah'])
{'test': '5', 'john': 'doe', 'blah': None} | [
"Gets",
"query",
"string",
"values",
"from",
"a",
"url",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/urls.py#L99-L128 | train | 49,988 |
InfoAgeTech/django-core | django_core/views/response.py | JSONResponseMixin.get_json_response | def get_json_response(self, content, **kwargs):
"""Returns a json response object."""
# Don't care to return a django form or view in the response here.
# Remove those from the context.
if isinstance(content, dict):
response_content = {k: deepcopy(v) for k, v in content.items()
if k not in ('form', 'view') or k in ('form', 'view')
and not isinstance(v, (Form, View))}
else:
response_content = content
return HttpResponse(content=json.dumps(response_content),
content_type='application/json; charset=utf-8',
**kwargs) | python | def get_json_response(self, content, **kwargs):
"""Returns a json response object."""
# Don't care to return a django form or view in the response here.
# Remove those from the context.
if isinstance(content, dict):
response_content = {k: deepcopy(v) for k, v in content.items()
if k not in ('form', 'view') or k in ('form', 'view')
and not isinstance(v, (Form, View))}
else:
response_content = content
return HttpResponse(content=json.dumps(response_content),
content_type='application/json; charset=utf-8',
**kwargs) | [
"def",
"get_json_response",
"(",
"self",
",",
"content",
",",
"*",
"*",
"kwargs",
")",
":",
"# Don't care to return a django form or view in the response here.",
"# Remove those from the context.",
"if",
"isinstance",
"(",
"content",
",",
"dict",
")",
":",
"response_conte... | Returns a json response object. | [
"Returns",
"a",
"json",
"response",
"object",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/views/response.py#L23-L37 | train | 49,989 |
MarcoFavorito/flloat | flloat/flloat.py | find_atomics | def find_atomics(formula: Formula) -> Set[PLAtomic]:
"""Finds all the atomic formulas"""
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
# elif isinstance(f, PLNot):
# res = res.union(find_atomics(f.f))
# elif isinstance(f, PLBinaryOperator):
# for subf in f.formulas:
# res = res.union(find_atomics(subf))
else:
res.add(f)
return res | python | def find_atomics(formula: Formula) -> Set[PLAtomic]:
"""Finds all the atomic formulas"""
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
# elif isinstance(f, PLNot):
# res = res.union(find_atomics(f.f))
# elif isinstance(f, PLBinaryOperator):
# for subf in f.formulas:
# res = res.union(find_atomics(subf))
else:
res.add(f)
return res | [
"def",
"find_atomics",
"(",
"formula",
":",
"Formula",
")",
"->",
"Set",
"[",
"PLAtomic",
"]",
":",
"f",
"=",
"formula",
"res",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"formula",
",",
"PLFormula",
")",
":",
"res",
"=",
"formula",
".",
"find_at... | Finds all the atomic formulas | [
"Finds",
"all",
"the",
"atomic",
"formulas"
] | 5e6de1bea444b68d46d288834031860a8b2f8c2d | https://github.com/MarcoFavorito/flloat/blob/5e6de1bea444b68d46d288834031860a8b2f8c2d/flloat/flloat.py#L18-L31 | train | 49,990 |
MarcoFavorito/flloat | flloat/flloat.py | _transform_delta | def _transform_delta(f:Formula, formula2AtomicFormula):
"""From a Propositional Formula to a Propositional Formula
with non-propositional subformulas replaced with a "freezed" atomic formula."""
t = type(f)
if t == PLNot:
return PLNot(_transform_delta(f, formula2AtomicFormula))
# elif isinstance(f, PLBinaryOperator): #PLAnd, PLOr, PLImplies, PLEquivalence
elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence:
return t([_transform_delta(subf, formula2AtomicFormula) for subf in f.formulas])
elif t == PLTrue or t == PLFalse:
return f
else:
return formula2AtomicFormula[f] | python | def _transform_delta(f:Formula, formula2AtomicFormula):
"""From a Propositional Formula to a Propositional Formula
with non-propositional subformulas replaced with a "freezed" atomic formula."""
t = type(f)
if t == PLNot:
return PLNot(_transform_delta(f, formula2AtomicFormula))
# elif isinstance(f, PLBinaryOperator): #PLAnd, PLOr, PLImplies, PLEquivalence
elif t == PLAnd or t == PLOr or t == PLImplies or t == PLEquivalence:
return t([_transform_delta(subf, formula2AtomicFormula) for subf in f.formulas])
elif t == PLTrue or t == PLFalse:
return f
else:
return formula2AtomicFormula[f] | [
"def",
"_transform_delta",
"(",
"f",
":",
"Formula",
",",
"formula2AtomicFormula",
")",
":",
"t",
"=",
"type",
"(",
"f",
")",
"if",
"t",
"==",
"PLNot",
":",
"return",
"PLNot",
"(",
"_transform_delta",
"(",
"f",
",",
"formula2AtomicFormula",
")",
")",
"# ... | From a Propositional Formula to a Propositional Formula
with non-propositional subformulas replaced with a "freezed" atomic formula. | [
"From",
"a",
"Propositional",
"Formula",
"to",
"a",
"Propositional",
"Formula",
"with",
"non",
"-",
"propositional",
"subformulas",
"replaced",
"with",
"a",
"freezed",
"atomic",
"formula",
"."
] | 5e6de1bea444b68d46d288834031860a8b2f8c2d | https://github.com/MarcoFavorito/flloat/blob/5e6de1bea444b68d46d288834031860a8b2f8c2d/flloat/flloat.py#L33-L45 | train | 49,991 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_setting | def get_setting(key, **kwargs):
"""Gets a settings key or raises an improperly configured error.
:param key: the settings key to get.
:param default: the default value to return if no value is found
"""
has_default = 'default' in kwargs
default_val = kwargs.get('default')
try:
if has_default:
return getattr(settings, key, default_val)
else:
return getattr(settings, key)
except Exception as e:
raise ImproperlyConfigured(
_('"{0}" setting has not been properly set. {1}').format(key, e)
) | python | def get_setting(key, **kwargs):
"""Gets a settings key or raises an improperly configured error.
:param key: the settings key to get.
:param default: the default value to return if no value is found
"""
has_default = 'default' in kwargs
default_val = kwargs.get('default')
try:
if has_default:
return getattr(settings, key, default_val)
else:
return getattr(settings, key)
except Exception as e:
raise ImproperlyConfigured(
_('"{0}" setting has not been properly set. {1}').format(key, e)
) | [
"def",
"get_setting",
"(",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"has_default",
"=",
"'default'",
"in",
"kwargs",
"default_val",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
")",
"try",
":",
"if",
"has_default",
":",
"return",
"getattr",
"(",
"settin... | Gets a settings key or raises an improperly configured error.
:param key: the settings key to get.
:param default: the default value to return if no value is found | [
"Gets",
"a",
"settings",
"key",
"or",
"raises",
"an",
"improperly",
"configured",
"error",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L12-L29 | train | 49,992 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_class_from_settings | def get_class_from_settings(settings_key):
"""Gets a class from a setting key. This will first check loaded models,
then look in installed apps, then fallback to import from lib.
:param settings_key: the key defined in settings to the value for
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
# First check to see if it's an installed model
return get_model_from_settings(settings_key=settings_key)
except:
try:
# Next, check from installed apps
return get_class_from_settings_from_apps(settings_key=settings_key)
except:
# Last, try to load from the full path
return get_class_from_settings_full_path(settings_key) | python | def get_class_from_settings(settings_key):
"""Gets a class from a setting key. This will first check loaded models,
then look in installed apps, then fallback to import from lib.
:param settings_key: the key defined in settings to the value for
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
# First check to see if it's an installed model
return get_model_from_settings(settings_key=settings_key)
except:
try:
# Next, check from installed apps
return get_class_from_settings_from_apps(settings_key=settings_key)
except:
# Last, try to load from the full path
return get_class_from_settings_full_path(settings_key) | [
"def",
"get_class_from_settings",
"(",
"settings_key",
")",
":",
"cls_path",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"cls_path",
":",
"raise",
"NotImplementedError",
"(",
")",
"try",
":",
"# First check to see if it's a... | Gets a class from a setting key. This will first check loaded models,
then look in installed apps, then fallback to import from lib.
:param settings_key: the key defined in settings to the value for | [
"Gets",
"a",
"class",
"from",
"a",
"setting",
"key",
".",
"This",
"will",
"first",
"check",
"loaded",
"models",
"then",
"look",
"in",
"installed",
"apps",
"then",
"fallback",
"to",
"import",
"from",
"lib",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L32-L51 | train | 49,993 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_model_from_settings | def get_model_from_settings(settings_key):
"""Return the django model from a settings key.
This is the same pattern user for django's "get_user_model()" method. To
allow you to set the model instance to a different model subclass.
:param settings_key: the key defined in settings to the value for
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label, model_name = cls_path.split('.')
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'app_label.model_name'".format(settings_key))
model = apps.get_model(app_label, model_name)
if model is None:
raise ImproperlyConfigured("{0} refers to model '%s' that has not "
"been installed".format(settings_key))
return model | python | def get_model_from_settings(settings_key):
"""Return the django model from a settings key.
This is the same pattern user for django's "get_user_model()" method. To
allow you to set the model instance to a different model subclass.
:param settings_key: the key defined in settings to the value for
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label, model_name = cls_path.split('.')
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'app_label.model_name'".format(settings_key))
model = apps.get_model(app_label, model_name)
if model is None:
raise ImproperlyConfigured("{0} refers to model '%s' that has not "
"been installed".format(settings_key))
return model | [
"def",
"get_model_from_settings",
"(",
"settings_key",
")",
":",
"cls_path",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"cls_path",
":",
"raise",
"NotImplementedError",
"(",
")",
"try",
":",
"app_label",
",",
"model_na... | Return the django model from a settings key.
This is the same pattern user for django's "get_user_model()" method. To
allow you to set the model instance to a different model subclass.
:param settings_key: the key defined in settings to the value for | [
"Return",
"the",
"django",
"model",
"from",
"a",
"settings",
"key",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L54-L79 | train | 49,994 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_class_from_settings_from_apps | def get_class_from_settings_from_apps(settings_key):
"""Try and get a class from a settings path by lookin in installed apps.
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label = cls_path.split('.')[-2]
model_name = cls_path.split('.')[-1]
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'app_label.model_name'".format(
settings_key))
app = apps.get_app_config(app_label).models_module
if not app:
raise ImproperlyConfigured("{0} setting refers to an app that has not "
"been installed".format(settings_key))
return getattr(app, model_name) | python | def get_class_from_settings_from_apps(settings_key):
"""Try and get a class from a settings path by lookin in installed apps.
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
app_label = cls_path.split('.')[-2]
model_name = cls_path.split('.')[-1]
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'app_label.model_name'".format(
settings_key))
app = apps.get_app_config(app_label).models_module
if not app:
raise ImproperlyConfigured("{0} setting refers to an app that has not "
"been installed".format(settings_key))
return getattr(app, model_name) | [
"def",
"get_class_from_settings_from_apps",
"(",
"settings_key",
")",
":",
"cls_path",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"cls_path",
":",
"raise",
"NotImplementedError",
"(",
")",
"try",
":",
"app_label",
"=",
... | Try and get a class from a settings path by lookin in installed apps. | [
"Try",
"and",
"get",
"a",
"class",
"from",
"a",
"settings",
"path",
"by",
"lookin",
"in",
"installed",
"apps",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L82-L104 | train | 49,995 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_class_from_settings_full_path | def get_class_from_settings_full_path(settings_key):
"""Get a class from it's full path.
Example:
some.path.module.MyClass
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
module_name, class_name = cls_path.rsplit('.', 1)
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'some.path.module.MyClass'".format(
settings_key))
manager_module = importlib.import_module(module_name)
if not manager_module:
raise ImproperlyConfigured("{0} refers to a module that has not been "
"installed".format(settings_key))
return getattr(manager_module, class_name) | python | def get_class_from_settings_full_path(settings_key):
"""Get a class from it's full path.
Example:
some.path.module.MyClass
"""
cls_path = getattr(settings, settings_key, None)
if not cls_path:
raise NotImplementedError()
try:
module_name, class_name = cls_path.rsplit('.', 1)
except ValueError:
raise ImproperlyConfigured("{0} must be of the form "
"'some.path.module.MyClass'".format(
settings_key))
manager_module = importlib.import_module(module_name)
if not manager_module:
raise ImproperlyConfigured("{0} refers to a module that has not been "
"installed".format(settings_key))
return getattr(manager_module, class_name) | [
"def",
"get_class_from_settings_full_path",
"(",
"settings_key",
")",
":",
"cls_path",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"cls_path",
":",
"raise",
"NotImplementedError",
"(",
")",
"try",
":",
"module_name",
",",... | Get a class from it's full path.
Example:
some.path.module.MyClass | [
"Get",
"a",
"class",
"from",
"it",
"s",
"full",
"path",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L107-L132 | train | 49,996 |
InfoAgeTech/django-core | django_core/utils/loading.py | get_function_from_settings | def get_function_from_settings(settings_key):
"""Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_settings('SOME_FUNCTION')
<function my_app.my_file.some_function>
"""
renderer_func_str = getattr(settings, settings_key, None)
if not renderer_func_str:
return None
module_str, renderer_func_name = renderer_func_str.rsplit('.', 1)
try:
mod = importlib.import_module(module_str)
return getattr(mod, renderer_func_name)
except Exception:
return None | python | def get_function_from_settings(settings_key):
"""Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_settings('SOME_FUNCTION')
<function my_app.my_file.some_function>
"""
renderer_func_str = getattr(settings, settings_key, None)
if not renderer_func_str:
return None
module_str, renderer_func_name = renderer_func_str.rsplit('.', 1)
try:
mod = importlib.import_module(module_str)
return getattr(mod, renderer_func_name)
except Exception:
return None | [
"def",
"get_function_from_settings",
"(",
"settings_key",
")",
":",
"renderer_func_str",
"=",
"getattr",
"(",
"settings",
",",
"settings_key",
",",
"None",
")",
"if",
"not",
"renderer_func_str",
":",
"return",
"None",
"module_str",
",",
"renderer_func_name",
"=",
... | Gets a function from the string path defined in a settings file.
Example:
# my_app/my_file.py
def some_function():
# do something
pass
# settings.py
SOME_FUNCTION = 'my_app.my_file.some_function'
> get_function_from_settings('SOME_FUNCTION')
<function my_app.my_file.some_function> | [
"Gets",
"a",
"function",
"from",
"the",
"string",
"path",
"defined",
"in",
"a",
"settings",
"file",
"."
] | 9664a145473b75120bf71e1644e9c8086e7e8955 | https://github.com/InfoAgeTech/django-core/blob/9664a145473b75120bf71e1644e9c8086e7e8955/django_core/utils/loading.py#L135-L162 | train | 49,997 |
dls-controls/annotypes | annotypes/_anno.py | caller_locals | def caller_locals():
# type: () -> Dict
"""Return the frame object for the caller's stack frame."""
try:
raise ValueError
except ValueError:
_, _, tb = sys.exc_info()
assert tb, "Can't get traceback, this shouldn't happen"
caller_frame = tb.tb_frame.f_back.f_back
return caller_frame.f_locals | python | def caller_locals():
# type: () -> Dict
"""Return the frame object for the caller's stack frame."""
try:
raise ValueError
except ValueError:
_, _, tb = sys.exc_info()
assert tb, "Can't get traceback, this shouldn't happen"
caller_frame = tb.tb_frame.f_back.f_back
return caller_frame.f_locals | [
"def",
"caller_locals",
"(",
")",
":",
"# type: () -> Dict",
"try",
":",
"raise",
"ValueError",
"except",
"ValueError",
":",
"_",
",",
"_",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"assert",
"tb",
",",
"\"Can't get traceback, this shouldn't happen\"",
... | Return the frame object for the caller's stack frame. | [
"Return",
"the",
"frame",
"object",
"for",
"the",
"caller",
"s",
"stack",
"frame",
"."
] | 31ab68a0367bb70ebd9898e8b9fa9405423465bd | https://github.com/dls-controls/annotypes/blob/31ab68a0367bb70ebd9898e8b9fa9405423465bd/annotypes/_anno.py#L43-L52 | train | 49,998 |
dls-controls/annotypes | annotypes/_anno.py | make_repr | def make_repr(inst, attrs):
# type: (object, Sequence[str]) -> str
"""Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr
"""
arg_str = ", ".join(
"%s=%r" % (a, getattr(inst, a)) for a in attrs if hasattr(inst, a))
repr_str = "%s(%s)" % (inst.__class__.__name__, arg_str)
return repr_str | python | def make_repr(inst, attrs):
# type: (object, Sequence[str]) -> str
"""Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr
"""
arg_str = ", ".join(
"%s=%r" % (a, getattr(inst, a)) for a in attrs if hasattr(inst, a))
repr_str = "%s(%s)" % (inst.__class__.__name__, arg_str)
return repr_str | [
"def",
"make_repr",
"(",
"inst",
",",
"attrs",
")",
":",
"# type: (object, Sequence[str]) -> str",
"arg_str",
"=",
"\", \"",
".",
"join",
"(",
"\"%s=%r\"",
"%",
"(",
"a",
",",
"getattr",
"(",
"inst",
",",
"a",
")",
")",
"for",
"a",
"in",
"attrs",
"if",
... | Create a repr from an instance of a class
Args:
inst: The class instance we are generating a repr of
attrs: The attributes that should appear in the repr | [
"Create",
"a",
"repr",
"from",
"an",
"instance",
"of",
"a",
"class"
] | 31ab68a0367bb70ebd9898e8b9fa9405423465bd | https://github.com/dls-controls/annotypes/blob/31ab68a0367bb70ebd9898e8b9fa9405423465bd/annotypes/_anno.py#L55-L66 | train | 49,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.