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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ocaballeror/LyricFetch | lyricfetch/scraping.py | id_source | def id_source(source, full=False):
"""
Returns the name of a website-scrapping function.
"""
if source not in source_ids:
return ''
if full:
return source_ids[source][1]
else:
return source_ids[source][0] | python | def id_source(source, full=False):
"""
Returns the name of a website-scrapping function.
"""
if source not in source_ids:
return ''
if full:
return source_ids[source][1]
else:
return source_ids[source][0] | [
"def",
"id_source",
"(",
"source",
",",
"full",
"=",
"False",
")",
":",
"if",
"source",
"not",
"in",
"source_ids",
":",
"return",
"''",
"if",
"full",
":",
"return",
"source_ids",
"[",
"source",
"]",
"[",
"1",
"]",
"else",
":",
"return",
"source_ids",
... | Returns the name of a website-scrapping function. | [
"Returns",
"the",
"name",
"of",
"a",
"website",
"-",
"scrapping",
"function",
"."
] | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/scraping.py#L501-L511 | train | 52,500 |
nion-software/nionswift-instrumentation-kit | nion/instrumentation/stem_controller.py | STEMController.set_probe_position | def set_probe_position(self, new_probe_position):
""" Set the probe position, in normalized coordinates with origin at top left. """
if new_probe_position is not None:
# convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes.
new_probe_position = Geometry.FloatPoint.make(new_probe_position)
new_probe_position = Geometry.FloatPoint(y=max(min(new_probe_position.y, 1.0), 0.0),
x=max(min(new_probe_position.x, 1.0), 0.0))
old_probe_position = self.__probe_position_value.value
if ((old_probe_position is None) != (new_probe_position is None)) or (old_probe_position != new_probe_position):
# this path is only taken if set_probe_position is not called as a result of the probe_position model
# value changing.
self.__probe_position_value.value = new_probe_position
# update the probe position for listeners and also explicitly update for probe_graphic_connections.
self.probe_state_changed_event.fire(self.probe_state, self.probe_position) | python | def set_probe_position(self, new_probe_position):
""" Set the probe position, in normalized coordinates with origin at top left. """
if new_probe_position is not None:
# convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes.
new_probe_position = Geometry.FloatPoint.make(new_probe_position)
new_probe_position = Geometry.FloatPoint(y=max(min(new_probe_position.y, 1.0), 0.0),
x=max(min(new_probe_position.x, 1.0), 0.0))
old_probe_position = self.__probe_position_value.value
if ((old_probe_position is None) != (new_probe_position is None)) or (old_probe_position != new_probe_position):
# this path is only taken if set_probe_position is not called as a result of the probe_position model
# value changing.
self.__probe_position_value.value = new_probe_position
# update the probe position for listeners and also explicitly update for probe_graphic_connections.
self.probe_state_changed_event.fire(self.probe_state, self.probe_position) | [
"def",
"set_probe_position",
"(",
"self",
",",
"new_probe_position",
")",
":",
"if",
"new_probe_position",
"is",
"not",
"None",
":",
"# convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes.",
"new_probe_position",
"=",
"Geometry",
".",
"F... | Set the probe position, in normalized coordinates with origin at top left. | [
"Set",
"the",
"probe",
"position",
"in",
"normalized",
"coordinates",
"with",
"origin",
"at",
"top",
"left",
"."
] | b20c4fff17e840e8cb3d544705faf5bd05f1cbf7 | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nion/instrumentation/stem_controller.py#L157-L170 | train | 52,501 |
nion-software/nionswift-instrumentation-kit | nion/instrumentation/stem_controller.py | STEMController.apply_metadata_groups | def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None:
"""Apply metadata groups to properties.
Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which
to add the controls. The second is a control group from which to read a list of controls to be added as name
value pairs to the dict-path.
"""
pass | python | def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None:
"""Apply metadata groups to properties.
Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which
to add the controls. The second is a control group from which to read a list of controls to be added as name
value pairs to the dict-path.
"""
pass | [
"def",
"apply_metadata_groups",
"(",
"self",
",",
"properties",
":",
"typing",
".",
"Dict",
",",
"metatdata_groups",
":",
"typing",
".",
"Tuple",
"[",
"typing",
".",
"List",
"[",
"str",
"]",
",",
"str",
"]",
")",
"->",
"None",
":",
"pass"
] | Apply metadata groups to properties.
Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which
to add the controls. The second is a control group from which to read a list of controls to be added as name
value pairs to the dict-path. | [
"Apply",
"metadata",
"groups",
"to",
"properties",
"."
] | b20c4fff17e840e8cb3d544705faf5bd05f1cbf7 | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nion/instrumentation/stem_controller.py#L222-L229 | train | 52,502 |
numan/py-analytics | analytics/__init__.py | create_analytic_backend | def create_analytic_backend(settings):
"""
Creates a new Analytics backend from the settings
:param settings: Dictionary of settings for the analytics backend
:returns: A backend object implementing the analytics api
>>>
>>> analytics = create_analytic({
>>> 'backend': 'analytics.backends.redis.Redis',
>>> 'settings': {
>>> 'defaults': {
>>> 'host': 'localhost',
>>> 'port': 6379,
>>> 'db': 0,
>>> },
>>> 'hosts': [{'db': 0}, {'db': 1}, {'host': 'redis.example.org'}]
>>> },
>>> })
"""
backend = settings.get('backend')
if isinstance(backend, basestring):
backend = import_string(backend)
elif backend:
backend = backend
else:
raise KeyError('backend')
return backend(settings.get("settings", {})) | python | def create_analytic_backend(settings):
"""
Creates a new Analytics backend from the settings
:param settings: Dictionary of settings for the analytics backend
:returns: A backend object implementing the analytics api
>>>
>>> analytics = create_analytic({
>>> 'backend': 'analytics.backends.redis.Redis',
>>> 'settings': {
>>> 'defaults': {
>>> 'host': 'localhost',
>>> 'port': 6379,
>>> 'db': 0,
>>> },
>>> 'hosts': [{'db': 0}, {'db': 1}, {'host': 'redis.example.org'}]
>>> },
>>> })
"""
backend = settings.get('backend')
if isinstance(backend, basestring):
backend = import_string(backend)
elif backend:
backend = backend
else:
raise KeyError('backend')
return backend(settings.get("settings", {})) | [
"def",
"create_analytic_backend",
"(",
"settings",
")",
":",
"backend",
"=",
"settings",
".",
"get",
"(",
"'backend'",
")",
"if",
"isinstance",
"(",
"backend",
",",
"basestring",
")",
":",
"backend",
"=",
"import_string",
"(",
"backend",
")",
"elif",
"backen... | Creates a new Analytics backend from the settings
:param settings: Dictionary of settings for the analytics backend
:returns: A backend object implementing the analytics api
>>>
>>> analytics = create_analytic({
>>> 'backend': 'analytics.backends.redis.Redis',
>>> 'settings': {
>>> 'defaults': {
>>> 'host': 'localhost',
>>> 'port': 6379,
>>> 'db': 0,
>>> },
>>> 'hosts': [{'db': 0}, {'db': 1}, {'host': 'redis.example.org'}]
>>> },
>>> }) | [
"Creates",
"a",
"new",
"Analytics",
"backend",
"from",
"the",
"settings"
] | abbc814925c6cc200b3329c7de9f1868e1cb8c01 | https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/__init__.py#L27-L55 | train | 52,503 |
nion-software/nionswift-instrumentation-kit | nionswift_plugin/nion_instrumentation_ui/ScanControlPanel.py | IconCanvasItem.size_to_content | def size_to_content(self, horizontal_padding=None, vertical_padding=None):
""" Size the canvas item to the text content. """
if horizontal_padding is None:
horizontal_padding = 0
if vertical_padding is None:
vertical_padding = 0
self.sizing.set_fixed_size(Geometry.IntSize(18 + 2 * horizontal_padding, 18 + 2 * vertical_padding)) | python | def size_to_content(self, horizontal_padding=None, vertical_padding=None):
""" Size the canvas item to the text content. """
if horizontal_padding is None:
horizontal_padding = 0
if vertical_padding is None:
vertical_padding = 0
self.sizing.set_fixed_size(Geometry.IntSize(18 + 2 * horizontal_padding, 18 + 2 * vertical_padding)) | [
"def",
"size_to_content",
"(",
"self",
",",
"horizontal_padding",
"=",
"None",
",",
"vertical_padding",
"=",
"None",
")",
":",
"if",
"horizontal_padding",
"is",
"None",
":",
"horizontal_padding",
"=",
"0",
"if",
"vertical_padding",
"is",
"None",
":",
"vertical_p... | Size the canvas item to the text content. | [
"Size",
"the",
"canvas",
"item",
"to",
"the",
"text",
"content",
"."
] | b20c4fff17e840e8cb3d544705faf5bd05f1cbf7 | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nionswift_plugin/nion_instrumentation_ui/ScanControlPanel.py#L581-L590 | train | 52,504 |
ocaballeror/LyricFetch | lyricfetch/stats.py | Record.success_rate | def success_rate(self):
"""
Returns a float with the rate of success from all the logged results.
"""
if self.successes + self.fails == 0:
success_rate = 0
else:
total_attempts = self.successes + self.fails
success_rate = (self.successes * 100 / total_attempts)
return success_rate | python | def success_rate(self):
"""
Returns a float with the rate of success from all the logged results.
"""
if self.successes + self.fails == 0:
success_rate = 0
else:
total_attempts = self.successes + self.fails
success_rate = (self.successes * 100 / total_attempts)
return success_rate | [
"def",
"success_rate",
"(",
"self",
")",
":",
"if",
"self",
".",
"successes",
"+",
"self",
".",
"fails",
"==",
"0",
":",
"success_rate",
"=",
"0",
"else",
":",
"total_attempts",
"=",
"self",
".",
"successes",
"+",
"self",
".",
"fails",
"success_rate",
... | Returns a float with the rate of success from all the logged results. | [
"Returns",
"a",
"float",
"with",
"the",
"rate",
"of",
"success",
"from",
"all",
"the",
"logged",
"results",
"."
] | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/stats.py#L46-L56 | train | 52,505 |
ocaballeror/LyricFetch | lyricfetch/stats.py | Stats.add_result | def add_result(self, source, found, runtime):
"""
Adds a new record to the statistics 'database'. This function is
intended to be called after a website has been scraped. The arguments
indicate the function that was called, the time taken to scrap the
website and a boolean indicating if the lyrics were found or not.
"""
self.source_stats[source.__name__].add_runtime(runtime)
if found:
self.source_stats[source.__name__].successes += 1
else:
self.source_stats[source.__name__].fails += 1 | python | def add_result(self, source, found, runtime):
"""
Adds a new record to the statistics 'database'. This function is
intended to be called after a website has been scraped. The arguments
indicate the function that was called, the time taken to scrap the
website and a boolean indicating if the lyrics were found or not.
"""
self.source_stats[source.__name__].add_runtime(runtime)
if found:
self.source_stats[source.__name__].successes += 1
else:
self.source_stats[source.__name__].fails += 1 | [
"def",
"add_result",
"(",
"self",
",",
"source",
",",
"found",
",",
"runtime",
")",
":",
"self",
".",
"source_stats",
"[",
"source",
".",
"__name__",
"]",
".",
"add_runtime",
"(",
"runtime",
")",
"if",
"found",
":",
"self",
".",
"source_stats",
"[",
"s... | Adds a new record to the statistics 'database'. This function is
intended to be called after a website has been scraped. The arguments
indicate the function that was called, the time taken to scrap the
website and a boolean indicating if the lyrics were found or not. | [
"Adds",
"a",
"new",
"record",
"to",
"the",
"statistics",
"database",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"called",
"after",
"a",
"website",
"has",
"been",
"scraped",
".",
"The",
"arguments",
"indicate",
"the",
"function",
"that",
"was",
... | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/stats.py#L67-L78 | train | 52,506 |
ocaballeror/LyricFetch | lyricfetch/stats.py | Stats.avg_time | def avg_time(self, source=None):
"""
Returns the average time taken to scrape lyrics. If a string or a
function is passed as source, return the average time taken to scrape
lyrics from that source, otherwise return the total average.
"""
if source is None:
runtimes = []
for rec in self.source_stats.values():
runtimes.extend([r for r in rec.runtimes if r != 0])
return avg(runtimes)
else:
if callable(source):
return avg(self.source_stats[source.__name__].runtimes)
else:
return avg(self.source_stats[source].runtimes) | python | def avg_time(self, source=None):
"""
Returns the average time taken to scrape lyrics. If a string or a
function is passed as source, return the average time taken to scrape
lyrics from that source, otherwise return the total average.
"""
if source is None:
runtimes = []
for rec in self.source_stats.values():
runtimes.extend([r for r in rec.runtimes if r != 0])
return avg(runtimes)
else:
if callable(source):
return avg(self.source_stats[source.__name__].runtimes)
else:
return avg(self.source_stats[source].runtimes) | [
"def",
"avg_time",
"(",
"self",
",",
"source",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"runtimes",
"=",
"[",
"]",
"for",
"rec",
"in",
"self",
".",
"source_stats",
".",
"values",
"(",
")",
":",
"runtimes",
".",
"extend",
"(",
"[",
... | Returns the average time taken to scrape lyrics. If a string or a
function is passed as source, return the average time taken to scrape
lyrics from that source, otherwise return the total average. | [
"Returns",
"the",
"average",
"time",
"taken",
"to",
"scrape",
"lyrics",
".",
"If",
"a",
"string",
"or",
"a",
"function",
"is",
"passed",
"as",
"source",
"return",
"the",
"average",
"time",
"taken",
"to",
"scrape",
"lyrics",
"from",
"that",
"source",
"other... | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/stats.py#L80-L95 | train | 52,507 |
ocaballeror/LyricFetch | lyricfetch/stats.py | Stats.calculate | def calculate(self):
"""
Calculate the overall counts of best, worst, fastest, slowest, total
found, total not found and total runtime
Results are returned in a dictionary with the above parameters as keys.
"""
best, worst, fastest, slowest = (), (), (), ()
found = notfound = total_time = 0
for source, rec in self.source_stats.items():
if not best or rec.successes > best[1]:
best = (source, rec.successes, rec.success_rate())
if not worst or rec.successes < worst[1]:
worst = (source, rec.successes, rec.success_rate())
avg_time = self.avg_time(source)
if not fastest or (avg_time != 0 and avg_time < fastest[1]):
fastest = (source, avg_time)
if not slowest or (avg_time != 0 and avg_time > slowest[1]):
slowest = (source, avg_time)
found += rec.successes
notfound += rec.fails
total_time += sum(rec.runtimes)
return {
'best': best,
'worst': worst,
'fastest': fastest,
'slowest': slowest,
'found': found,
'notfound': notfound,
'total_time': total_time
} | python | def calculate(self):
"""
Calculate the overall counts of best, worst, fastest, slowest, total
found, total not found and total runtime
Results are returned in a dictionary with the above parameters as keys.
"""
best, worst, fastest, slowest = (), (), (), ()
found = notfound = total_time = 0
for source, rec in self.source_stats.items():
if not best or rec.successes > best[1]:
best = (source, rec.successes, rec.success_rate())
if not worst or rec.successes < worst[1]:
worst = (source, rec.successes, rec.success_rate())
avg_time = self.avg_time(source)
if not fastest or (avg_time != 0 and avg_time < fastest[1]):
fastest = (source, avg_time)
if not slowest or (avg_time != 0 and avg_time > slowest[1]):
slowest = (source, avg_time)
found += rec.successes
notfound += rec.fails
total_time += sum(rec.runtimes)
return {
'best': best,
'worst': worst,
'fastest': fastest,
'slowest': slowest,
'found': found,
'notfound': notfound,
'total_time': total_time
} | [
"def",
"calculate",
"(",
"self",
")",
":",
"best",
",",
"worst",
",",
"fastest",
",",
"slowest",
"=",
"(",
")",
",",
"(",
")",
",",
"(",
")",
",",
"(",
")",
"found",
"=",
"notfound",
"=",
"total_time",
"=",
"0",
"for",
"source",
",",
"rec",
"in... | Calculate the overall counts of best, worst, fastest, slowest, total
found, total not found and total runtime
Results are returned in a dictionary with the above parameters as keys. | [
"Calculate",
"the",
"overall",
"counts",
"of",
"best",
"worst",
"fastest",
"slowest",
"total",
"found",
"total",
"not",
"found",
"and",
"total",
"runtime"
] | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/stats.py#L97-L130 | train | 52,508 |
ocaballeror/LyricFetch | lyricfetch/stats.py | Stats.print_stats | def print_stats(self):
"""
Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program.
"""
stats = self.calculate()
total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600,
(stats['total_time'] / 3600) / 60,
(stats['total_time'] % 3600) % 60)
output = """\
Total runtime: {total_time}
Lyrics found: {found}
Lyrics not found:{notfound}
Most useful source:\
{best} ({best_count} lyrics found) ({best_rate:.2f}% success rate)
Least useful source:\
{worst} ({worst_count} lyrics found) ({worst_rate:.2f}% success rate)
Fastest website to scrape: {fastest} (Avg: {fastest_time:.2f}s per search)
Slowest website to scrape: {slowest} (Avg: {slowest_time:.2f}s per search)
Average time per website: {avg_time:.2f}s
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxx PER WEBSITE STATS: xxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
"""
output = output.format(total_time=total_time,
found=stats['found'],
notfound=stats['notfound'],
best=stats['best'][0].capitalize(),
best_count=stats['best'][1],
best_rate=stats['best'][2],
worst=stats['worst'][0].capitalize(),
worst_count=stats['worst'][1],
worst_rate=stats['worst'][2],
fastest=stats['fastest'][0].capitalize(),
fastest_time=stats['fastest'][1],
slowest=stats['slowest'][0].capitalize(),
slowest_time=stats['slowest'][1],
avg_time=self.avg_time())
for source in sources:
stat = str(self.source_stats[source.__name__])
output += f'\n{source.__name__.upper()}\n{stat}\n'
print(output) | python | def print_stats(self):
"""
Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program.
"""
stats = self.calculate()
total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600,
(stats['total_time'] / 3600) / 60,
(stats['total_time'] % 3600) % 60)
output = """\
Total runtime: {total_time}
Lyrics found: {found}
Lyrics not found:{notfound}
Most useful source:\
{best} ({best_count} lyrics found) ({best_rate:.2f}% success rate)
Least useful source:\
{worst} ({worst_count} lyrics found) ({worst_rate:.2f}% success rate)
Fastest website to scrape: {fastest} (Avg: {fastest_time:.2f}s per search)
Slowest website to scrape: {slowest} (Avg: {slowest_time:.2f}s per search)
Average time per website: {avg_time:.2f}s
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxx PER WEBSITE STATS: xxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
"""
output = output.format(total_time=total_time,
found=stats['found'],
notfound=stats['notfound'],
best=stats['best'][0].capitalize(),
best_count=stats['best'][1],
best_rate=stats['best'][2],
worst=stats['worst'][0].capitalize(),
worst_count=stats['worst'][1],
worst_rate=stats['worst'][2],
fastest=stats['fastest'][0].capitalize(),
fastest_time=stats['fastest'][1],
slowest=stats['slowest'][0].capitalize(),
slowest_time=stats['slowest'][1],
avg_time=self.avg_time())
for source in sources:
stat = str(self.source_stats[source.__name__])
output += f'\n{source.__name__.upper()}\n{stat}\n'
print(output) | [
"def",
"print_stats",
"(",
"self",
")",
":",
"stats",
"=",
"self",
".",
"calculate",
"(",
")",
"total_time",
"=",
"'%d:%02d:%02d'",
"%",
"(",
"stats",
"[",
"'total_time'",
"]",
"/",
"3600",
",",
"(",
"stats",
"[",
"'total_time'",
"]",
"/",
"3600",
")",... | Print a series of relevant stats about a full execution. This function
is meant to be called at the end of the program. | [
"Print",
"a",
"series",
"of",
"relevant",
"stats",
"about",
"a",
"full",
"execution",
".",
"This",
"function",
"is",
"meant",
"to",
"be",
"called",
"at",
"the",
"end",
"of",
"the",
"program",
"."
] | 86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb | https://github.com/ocaballeror/LyricFetch/blob/86e62fb39c4c413ad7e1acf5bf0d28c9ed7c8fcb/lyricfetch/stats.py#L132-L175 | train | 52,509 |
thiagopbueno/rddl2tf | rddl2tf/fluentscope.py | TensorFluentScope.broadcast | def broadcast(cls, s1: ParamsList, s2: ParamsList) -> BroadcastTuple:
'''It broadcasts the smaller scope over the larger scope.
It handles scope intersection as well as differences in scopes
in order to output a resulting scope so that input scopes are
contained within it (i.e., input scopes are subscopes of the
output scope). Also, if necessary, it outputs permutations of
the input scopes so that tensor broadcasting invariants are
not violated.
Note:
For more information on broadcasting, please report to
NumPy's official documentation available at the following URLs:
1. https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
2. https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html
Args:
s1: A fluent's scope.
s2: A fluent's scope.
Returns:
A tuple with the output scope and permutations of the input scopes.
'''
if len(s1) == 0:
return s2, [], []
if len(s2) == 0:
return s1, [], []
subscope = list(set(s1) & set(s2))
if len(subscope) == len(s1):
subscope = s1
elif len(subscope) == len(s2):
subscope = s2
perm1 = []
if s1[-len(subscope):] != subscope:
i = 0
for var in s1:
if var not in subscope:
perm1.append(i)
i += 1
else:
j = subscope.index(var)
perm1.append(len(s1) - len(subscope) + j)
perm2 = []
if s2[-len(subscope):] != subscope:
i = 0
for var in s2:
if var not in subscope:
perm2.append(i)
i += 1
else:
j = subscope.index(var)
perm2.append(len(s2) - len(subscope) + j)
scope = [] # type: ParamsList
if len(s1) >= len(s2):
if perm1 == []:
scope = s1
else:
for i in range(len(s1)):
scope.append(s1[perm1.index(i)])
else:
if perm2 == []:
scope = s2
else:
for i in range(len(s2)):
scope.append(s2[perm2.index(i)])
return (scope, perm1, perm2) | python | def broadcast(cls, s1: ParamsList, s2: ParamsList) -> BroadcastTuple:
'''It broadcasts the smaller scope over the larger scope.
It handles scope intersection as well as differences in scopes
in order to output a resulting scope so that input scopes are
contained within it (i.e., input scopes are subscopes of the
output scope). Also, if necessary, it outputs permutations of
the input scopes so that tensor broadcasting invariants are
not violated.
Note:
For more information on broadcasting, please report to
NumPy's official documentation available at the following URLs:
1. https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
2. https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html
Args:
s1: A fluent's scope.
s2: A fluent's scope.
Returns:
A tuple with the output scope and permutations of the input scopes.
'''
if len(s1) == 0:
return s2, [], []
if len(s2) == 0:
return s1, [], []
subscope = list(set(s1) & set(s2))
if len(subscope) == len(s1):
subscope = s1
elif len(subscope) == len(s2):
subscope = s2
perm1 = []
if s1[-len(subscope):] != subscope:
i = 0
for var in s1:
if var not in subscope:
perm1.append(i)
i += 1
else:
j = subscope.index(var)
perm1.append(len(s1) - len(subscope) + j)
perm2 = []
if s2[-len(subscope):] != subscope:
i = 0
for var in s2:
if var not in subscope:
perm2.append(i)
i += 1
else:
j = subscope.index(var)
perm2.append(len(s2) - len(subscope) + j)
scope = [] # type: ParamsList
if len(s1) >= len(s2):
if perm1 == []:
scope = s1
else:
for i in range(len(s1)):
scope.append(s1[perm1.index(i)])
else:
if perm2 == []:
scope = s2
else:
for i in range(len(s2)):
scope.append(s2[perm2.index(i)])
return (scope, perm1, perm2) | [
"def",
"broadcast",
"(",
"cls",
",",
"s1",
":",
"ParamsList",
",",
"s2",
":",
"ParamsList",
")",
"->",
"BroadcastTuple",
":",
"if",
"len",
"(",
"s1",
")",
"==",
"0",
":",
"return",
"s2",
",",
"[",
"]",
",",
"[",
"]",
"if",
"len",
"(",
"s2",
")"... | It broadcasts the smaller scope over the larger scope.
It handles scope intersection as well as differences in scopes
in order to output a resulting scope so that input scopes are
contained within it (i.e., input scopes are subscopes of the
output scope). Also, if necessary, it outputs permutations of
the input scopes so that tensor broadcasting invariants are
not violated.
Note:
For more information on broadcasting, please report to
NumPy's official documentation available at the following URLs:
1. https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
2. https://docs.scipy.org/doc/numpy/reference/generated/numpy.broadcast.html
Args:
s1: A fluent's scope.
s2: A fluent's scope.
Returns:
A tuple with the output scope and permutations of the input scopes. | [
"It",
"broadcasts",
"the",
"smaller",
"scope",
"over",
"the",
"larger",
"scope",
"."
] | f7c03d3a74d2663807c1e23e04eeed2e85166b71 | https://github.com/thiagopbueno/rddl2tf/blob/f7c03d3a74d2663807c1e23e04eeed2e85166b71/rddl2tf/fluentscope.py#L68-L137 | train | 52,510 |
inodb/sufam | sufam/__main__.py | get_baseparser_extended_df | def get_baseparser_extended_df(sample, bp_lines, ref, alt):
"""Turn baseParser results into a dataframe"""
columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split()
if bp_lines is None:
return None
# change baseparser output to get most common maf per indel
bpdf = pd.DataFrame([[sample] + l.rstrip('\n').split("\t") for l in bp_lines if len(l) > 0],
columns=["sample"] + columns, dtype=np.object)
bpdf[bpdf == ""] = None
# remove zero coverage rows
bpdf = bpdf[bpdf["cov"].astype(int) > 0]
if len(bpdf) == 0:
return None
if ref and alt:
# add columns for validation allele
bpdf = pd.concat([bpdf, pd.DataFrame({"val_ref": pd.Series(ref), "val_alt": pd.Series(alt)})], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_val_al, axis=1)], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_most_common_indel, axis=1)], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_most_common_al, axis=1)], axis=1)
bpdf["most_common_count"] = bpdf.apply(lambda x: max([x.most_common_al_count, x.most_common_indel_count]), axis=1)
bpdf["most_common_maf"] = bpdf.apply(lambda x: max([x.most_common_al_maf, x.most_common_indel_maf]), axis=1)
return bpdf | python | def get_baseparser_extended_df(sample, bp_lines, ref, alt):
"""Turn baseParser results into a dataframe"""
columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split()
if bp_lines is None:
return None
# change baseparser output to get most common maf per indel
bpdf = pd.DataFrame([[sample] + l.rstrip('\n').split("\t") for l in bp_lines if len(l) > 0],
columns=["sample"] + columns, dtype=np.object)
bpdf[bpdf == ""] = None
# remove zero coverage rows
bpdf = bpdf[bpdf["cov"].astype(int) > 0]
if len(bpdf) == 0:
return None
if ref and alt:
# add columns for validation allele
bpdf = pd.concat([bpdf, pd.DataFrame({"val_ref": pd.Series(ref), "val_alt": pd.Series(alt)})], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_val_al, axis=1)], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_most_common_indel, axis=1)], axis=1)
bpdf = pd.concat([bpdf, bpdf.apply(_most_common_al, axis=1)], axis=1)
bpdf["most_common_count"] = bpdf.apply(lambda x: max([x.most_common_al_count, x.most_common_indel_count]), axis=1)
bpdf["most_common_maf"] = bpdf.apply(lambda x: max([x.most_common_al_maf, x.most_common_indel_maf]), axis=1)
return bpdf | [
"def",
"get_baseparser_extended_df",
"(",
"sample",
",",
"bp_lines",
",",
"ref",
",",
"alt",
")",
":",
"columns",
"=",
"\"chrom\\tpos\\tref\\tcov\\tA\\tC\\tG\\tT\\t*\\t-\\t+\"",
".",
"split",
"(",
")",
"if",
"bp_lines",
"is",
"None",
":",
"return",
"None",
"# chan... | Turn baseParser results into a dataframe | [
"Turn",
"baseParser",
"results",
"into",
"a",
"dataframe"
] | d4e41c5478ca9ba58be44d95106885c096c90a74 | https://github.com/inodb/sufam/blob/d4e41c5478ca9ba58be44d95106885c096c90a74/sufam/__main__.py#L92-L119 | train | 52,511 |
inodb/sufam | sufam/__main__.py | filter_out_mutations_in_normal | def filter_out_mutations_in_normal(tumordf, normaldf, most_common_maf_min=0.2,
most_common_count_maf_threshold=20,
most_common_count_min=1):
"""Remove mutations that are in normal"""
df = tumordf.merge(normaldf, on=["chrom", "pos"], suffixes=("_T", "_N"))
# filters
common_al = (df.most_common_al_count_T == df.most_common_count_T) & (df.most_common_al_T == df.most_common_al_N)
common_indel = (df.most_common_indel_count_T == df.most_common_count_T) & \
(df.most_common_indel_T == df.imost_common_indel_N)
normal_criteria = ((df.most_common_count_N >= most_common_count_maf_threshold) &
(df.most_common_maf_N > most_common_maf_min)) | \
((df.most_common_count_N < most_common_count_maf_threshold) &
(df.most_common_count_N > most_common_count_min))
df = df[~(common_al | common_indel) & normal_criteria]
# restore column names of tumor
for c in df.columns:
if c.endswith("_N"):
del df[c]
df.columns = [c[:-2] if c.endswith("_T") else c for c in df.columns]
return df | python | def filter_out_mutations_in_normal(tumordf, normaldf, most_common_maf_min=0.2,
most_common_count_maf_threshold=20,
most_common_count_min=1):
"""Remove mutations that are in normal"""
df = tumordf.merge(normaldf, on=["chrom", "pos"], suffixes=("_T", "_N"))
# filters
common_al = (df.most_common_al_count_T == df.most_common_count_T) & (df.most_common_al_T == df.most_common_al_N)
common_indel = (df.most_common_indel_count_T == df.most_common_count_T) & \
(df.most_common_indel_T == df.imost_common_indel_N)
normal_criteria = ((df.most_common_count_N >= most_common_count_maf_threshold) &
(df.most_common_maf_N > most_common_maf_min)) | \
((df.most_common_count_N < most_common_count_maf_threshold) &
(df.most_common_count_N > most_common_count_min))
df = df[~(common_al | common_indel) & normal_criteria]
# restore column names of tumor
for c in df.columns:
if c.endswith("_N"):
del df[c]
df.columns = [c[:-2] if c.endswith("_T") else c for c in df.columns]
return df | [
"def",
"filter_out_mutations_in_normal",
"(",
"tumordf",
",",
"normaldf",
",",
"most_common_maf_min",
"=",
"0.2",
",",
"most_common_count_maf_threshold",
"=",
"20",
",",
"most_common_count_min",
"=",
"1",
")",
":",
"df",
"=",
"tumordf",
".",
"merge",
"(",
"normald... | Remove mutations that are in normal | [
"Remove",
"mutations",
"that",
"are",
"in",
"normal"
] | d4e41c5478ca9ba58be44d95106885c096c90a74 | https://github.com/inodb/sufam/blob/d4e41c5478ca9ba58be44d95106885c096c90a74/sufam/__main__.py#L122-L144 | train | 52,512 |
inodb/sufam | sufam/__main__.py | select_only_revertant_mutations | def select_only_revertant_mutations(bpdf, snv=None, ins=None, dlt=None):
"""
Selects only mutations that revert the given mutations in a single event.
"""
if sum([bool(snv), bool(ins), bool(dlt)]) != 1:
raise(Exception("Should be either snv, ins or del".format(snv)))
if snv:
if snv not in ["A", "C", "G", "T"]:
raise(Exception("snv {} should be A, C, G or T".format(snv)))
return bpdf[(bpdf.most_common_al == snv) & (bpdf.most_common_al_count == bpdf.most_common_count)]
elif bool(ins):
return \
bpdf[((bpdf.most_common_indel.apply(lambda x: len(x) + len(ins) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "+") & (bpdf.most_common_count == bpdf.most_common_indel_count)) |
((bpdf.most_common_indel.apply(lambda x: len(ins) - len(x) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "-") & (bpdf.most_common_count == bpdf.most_common_indel_count))]
elif bool(dlt):
return \
bpdf[((bpdf.most_common_indel.apply(lambda x: len(x) - len(dlt) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "+") & (bpdf.most_common_count == bpdf.most_common_indel_count)) |
((bpdf.most_common_indel.apply(lambda x: -len(dlt) - len(x) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "-") & (bpdf.most_common_count == bpdf.most_common_indel_count))]
else:
# should never happen
raise(Exception("No mutation given?")) | python | def select_only_revertant_mutations(bpdf, snv=None, ins=None, dlt=None):
"""
Selects only mutations that revert the given mutations in a single event.
"""
if sum([bool(snv), bool(ins), bool(dlt)]) != 1:
raise(Exception("Should be either snv, ins or del".format(snv)))
if snv:
if snv not in ["A", "C", "G", "T"]:
raise(Exception("snv {} should be A, C, G or T".format(snv)))
return bpdf[(bpdf.most_common_al == snv) & (bpdf.most_common_al_count == bpdf.most_common_count)]
elif bool(ins):
return \
bpdf[((bpdf.most_common_indel.apply(lambda x: len(x) + len(ins) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "+") & (bpdf.most_common_count == bpdf.most_common_indel_count)) |
((bpdf.most_common_indel.apply(lambda x: len(ins) - len(x) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "-") & (bpdf.most_common_count == bpdf.most_common_indel_count))]
elif bool(dlt):
return \
bpdf[((bpdf.most_common_indel.apply(lambda x: len(x) - len(dlt) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "+") & (bpdf.most_common_count == bpdf.most_common_indel_count)) |
((bpdf.most_common_indel.apply(lambda x: -len(dlt) - len(x) % 3 if x else None) == 0) &
(bpdf.most_common_indel_type == "-") & (bpdf.most_common_count == bpdf.most_common_indel_count))]
else:
# should never happen
raise(Exception("No mutation given?")) | [
"def",
"select_only_revertant_mutations",
"(",
"bpdf",
",",
"snv",
"=",
"None",
",",
"ins",
"=",
"None",
",",
"dlt",
"=",
"None",
")",
":",
"if",
"sum",
"(",
"[",
"bool",
"(",
"snv",
")",
",",
"bool",
"(",
"ins",
")",
",",
"bool",
"(",
"dlt",
")"... | Selects only mutations that revert the given mutations in a single event. | [
"Selects",
"only",
"mutations",
"that",
"revert",
"the",
"given",
"mutations",
"in",
"a",
"single",
"event",
"."
] | d4e41c5478ca9ba58be44d95106885c096c90a74 | https://github.com/inodb/sufam/blob/d4e41c5478ca9ba58be44d95106885c096c90a74/sufam/__main__.py#L147-L172 | train | 52,513 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster._prep_clients | def _prep_clients(self, clients):
"""Prep a client by tagging it with and id and wrapping methods.
Methods are wrapper to catch ConnectionError so that we can remove
it from the pool until the instance comes back up.
:returns: patched clients
"""
for pool_id, client in enumerate(clients):
# Tag it with an id we'll use to identify it in the pool
if hasattr(client, "pool_id"):
raise ValueError("%r is already part of a pool.", client)
setattr(client, "pool_id", pool_id)
# Wrap all public functions
self._wrap_functions(client)
return clients | python | def _prep_clients(self, clients):
"""Prep a client by tagging it with and id and wrapping methods.
Methods are wrapper to catch ConnectionError so that we can remove
it from the pool until the instance comes back up.
:returns: patched clients
"""
for pool_id, client in enumerate(clients):
# Tag it with an id we'll use to identify it in the pool
if hasattr(client, "pool_id"):
raise ValueError("%r is already part of a pool.", client)
setattr(client, "pool_id", pool_id)
# Wrap all public functions
self._wrap_functions(client)
return clients | [
"def",
"_prep_clients",
"(",
"self",
",",
"clients",
")",
":",
"for",
"pool_id",
",",
"client",
"in",
"enumerate",
"(",
"clients",
")",
":",
"# Tag it with an id we'll use to identify it in the pool",
"if",
"hasattr",
"(",
"client",
",",
"\"pool_id\"",
")",
":",
... | Prep a client by tagging it with and id and wrapping methods.
Methods are wrapper to catch ConnectionError so that we can remove
it from the pool until the instance comes back up.
:returns: patched clients | [
"Prep",
"a",
"client",
"by",
"tagging",
"it",
"with",
"and",
"id",
"and",
"wrapping",
"methods",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L79-L94 | train | 52,514 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster._wrap_functions | def _wrap_functions(self, client):
"""Wrap public functions to catch ConnectionError.
When an error happens, it puts the client in the penalty box
so that it won't be retried again for a little while.
"""
def wrap(fn):
def wrapper(*args, **kwargs):
"""Simple wrapper for to catch dead clients."""
try:
return fn(*args, **kwargs)
except (ConnectionError, TimeoutError): # TO THE PENALTY BOX!
self._penalize_client(client)
raise
return functools.update_wrapper(wrapper, fn)
for name in dir(client):
if name.startswith("_"):
continue
# Some things aren't wrapped
if name in ("echo", "execute_command", "parse_response"):
continue
obj = getattr(client, name)
if not callable(obj):
continue
log.debug("Wrapping %s", name)
setattr(client, name, wrap(obj)) | python | def _wrap_functions(self, client):
"""Wrap public functions to catch ConnectionError.
When an error happens, it puts the client in the penalty box
so that it won't be retried again for a little while.
"""
def wrap(fn):
def wrapper(*args, **kwargs):
"""Simple wrapper for to catch dead clients."""
try:
return fn(*args, **kwargs)
except (ConnectionError, TimeoutError): # TO THE PENALTY BOX!
self._penalize_client(client)
raise
return functools.update_wrapper(wrapper, fn)
for name in dir(client):
if name.startswith("_"):
continue
# Some things aren't wrapped
if name in ("echo", "execute_command", "parse_response"):
continue
obj = getattr(client, name)
if not callable(obj):
continue
log.debug("Wrapping %s", name)
setattr(client, name, wrap(obj)) | [
"def",
"_wrap_functions",
"(",
"self",
",",
"client",
")",
":",
"def",
"wrap",
"(",
"fn",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Simple wrapper for to catch dead clients.\"\"\"",
"try",
":",
"return",
"fn",
... | Wrap public functions to catch ConnectionError.
When an error happens, it puts the client in the penalty box
so that it won't be retried again for a little while. | [
"Wrap",
"public",
"functions",
"to",
"catch",
"ConnectionError",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L96-L124 | train | 52,515 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster._prune_penalty_box | def _prune_penalty_box(self):
"""Restores clients that have reconnected.
This function should be called first for every public method.
"""
added = False
for client in self.penalty_box.get():
log.info("Client %r is back up.", client)
self.active_clients.append(client)
added = True
if added:
self._sort_clients() | python | def _prune_penalty_box(self):
"""Restores clients that have reconnected.
This function should be called first for every public method.
"""
added = False
for client in self.penalty_box.get():
log.info("Client %r is back up.", client)
self.active_clients.append(client)
added = True
if added:
self._sort_clients() | [
"def",
"_prune_penalty_box",
"(",
"self",
")",
":",
"added",
"=",
"False",
"for",
"client",
"in",
"self",
".",
"penalty_box",
".",
"get",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Client %r is back up.\"",
",",
"client",
")",
"self",
".",
"active_clients"... | Restores clients that have reconnected.
This function should be called first for every public method. | [
"Restores",
"clients",
"that",
"have",
"reconnected",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L126-L137 | train | 52,516 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster.get_client | def get_client(self, shard_key):
"""Get the client for a given shard, based on what's available.
If the proper client isn't available, the next available client
is returned. If no clients are available, an exception is raised.
"""
self._prune_penalty_box()
if len(self.active_clients) == 0:
raise ClusterEmptyError("All clients are down.")
# So that hashing is consistent when a node is down, check against
# the initial client list. Only use the active client list when
# the desired node is down.
# N.B.: I know this is not technically "consistent hashing" as
# academically defined. It's a hack so that keys which need to
# go elsewhere do, while the rest stay on the same instance.
if not isinstance(shard_key, bytes):
shard_key = shard_key.encode("utf-8")
hashed = mmh3.hash(shard_key)
pos = hashed % len(self.initial_clients)
if self.initial_clients[pos] in self.active_clients:
return self.initial_clients[pos]
else:
pos = hashed % len(self.active_clients)
return self.active_clients[pos] | python | def get_client(self, shard_key):
"""Get the client for a given shard, based on what's available.
If the proper client isn't available, the next available client
is returned. If no clients are available, an exception is raised.
"""
self._prune_penalty_box()
if len(self.active_clients) == 0:
raise ClusterEmptyError("All clients are down.")
# So that hashing is consistent when a node is down, check against
# the initial client list. Only use the active client list when
# the desired node is down.
# N.B.: I know this is not technically "consistent hashing" as
# academically defined. It's a hack so that keys which need to
# go elsewhere do, while the rest stay on the same instance.
if not isinstance(shard_key, bytes):
shard_key = shard_key.encode("utf-8")
hashed = mmh3.hash(shard_key)
pos = hashed % len(self.initial_clients)
if self.initial_clients[pos] in self.active_clients:
return self.initial_clients[pos]
else:
pos = hashed % len(self.active_clients)
return self.active_clients[pos] | [
"def",
"get_client",
"(",
"self",
",",
"shard_key",
")",
":",
"self",
".",
"_prune_penalty_box",
"(",
")",
"if",
"len",
"(",
"self",
".",
"active_clients",
")",
"==",
"0",
":",
"raise",
"ClusterEmptyError",
"(",
"\"All clients are down.\"",
")",
"# So that has... | Get the client for a given shard, based on what's available.
If the proper client isn't available, the next available client
is returned. If no clients are available, an exception is raised. | [
"Get",
"the",
"client",
"for",
"a",
"given",
"shard",
"based",
"on",
"what",
"s",
"available",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L139-L164 | train | 52,517 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster._penalize_client | def _penalize_client(self, client):
"""Place client in the penalty box.
:param client: Client object
"""
if client in self.active_clients: # hasn't been removed yet
log.warning("%r marked down.", client)
self.active_clients.remove(client)
self.penalty_box.add(client)
else:
log.info("%r not in active client list.") | python | def _penalize_client(self, client):
"""Place client in the penalty box.
:param client: Client object
"""
if client in self.active_clients: # hasn't been removed yet
log.warning("%r marked down.", client)
self.active_clients.remove(client)
self.penalty_box.add(client)
else:
log.info("%r not in active client list.") | [
"def",
"_penalize_client",
"(",
"self",
",",
"client",
")",
":",
"if",
"client",
"in",
"self",
".",
"active_clients",
":",
"# hasn't been removed yet",
"log",
".",
"warning",
"(",
"\"%r marked down.\"",
",",
"client",
")",
"self",
".",
"active_clients",
".",
"... | Place client in the penalty box.
:param client: Client object | [
"Place",
"client",
"in",
"the",
"penalty",
"box",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L166-L176 | train | 52,518 |
Parsely/redis-fluster | fluster/cluster.py | FlusterCluster.zrevrange_with_int_score | def zrevrange_with_int_score(self, key, max_score, min_score):
"""Get the zrevrangebyscore across the cluster.
Highest score for duplicate element is returned.
A faster method should be written if scores are not needed.
"""
self._prune_penalty_box()
if len(self.active_clients) == 0:
raise ClusterEmptyError("All clients are down.")
element__score = defaultdict(int)
for client in self.active_clients:
revrange = client.zrevrangebyscore(
key, max_score, min_score, withscores=True, score_cast_func=int
)
for element, count in revrange:
element__score[element] = max(element__score[element], int(count))
return element__score | python | def zrevrange_with_int_score(self, key, max_score, min_score):
"""Get the zrevrangebyscore across the cluster.
Highest score for duplicate element is returned.
A faster method should be written if scores are not needed.
"""
self._prune_penalty_box()
if len(self.active_clients) == 0:
raise ClusterEmptyError("All clients are down.")
element__score = defaultdict(int)
for client in self.active_clients:
revrange = client.zrevrangebyscore(
key, max_score, min_score, withscores=True, score_cast_func=int
)
for element, count in revrange:
element__score[element] = max(element__score[element], int(count))
return element__score | [
"def",
"zrevrange_with_int_score",
"(",
"self",
",",
"key",
",",
"max_score",
",",
"min_score",
")",
":",
"self",
".",
"_prune_penalty_box",
"(",
")",
"if",
"len",
"(",
"self",
".",
"active_clients",
")",
"==",
"0",
":",
"raise",
"ClusterEmptyError",
"(",
... | Get the zrevrangebyscore across the cluster.
Highest score for duplicate element is returned.
A faster method should be written if scores are not needed. | [
"Get",
"the",
"zrevrangebyscore",
"across",
"the",
"cluster",
".",
"Highest",
"score",
"for",
"duplicate",
"element",
"is",
"returned",
".",
"A",
"faster",
"method",
"should",
"be",
"written",
"if",
"scores",
"are",
"not",
"needed",
"."
] | 9fb3ccdc3e0b24906520cac1e933a775e8dfbd99 | https://github.com/Parsely/redis-fluster/blob/9fb3ccdc3e0b24906520cac1e933a775e8dfbd99/fluster/cluster.py#L178-L197 | train | 52,519 |
alfredodeza/notario | notario/regex.py | chain | def chain(*regexes, **kwargs):
"""
A helper function to interact with the regular expression engine
that compiles and applies partial matches to a string.
It expects key value tuples as arguments (any number of them) where the
first pair is the regex to compile and the latter is the message to display
when the regular expression does not match.
The engine constructs partial regular expressions from the input and
applies them sequentially to find the exact point of failure and allowing
the ability to return a meaningful message.
Because adding negation statements like "does not..." can become
repetitive, the function defaults to ``True`` to include the option to
prepend the negative.
For example, this is what would happen with a failing regex::
>>> rx = chain((r'^\d+', 'start with a digit'))
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: does not start with a digit
If there is no need for prepending the negation, the keyword argument will
need to set it as ``False``::
>>> rx = chain((r'^\d+', 'it should start with a digit'),
... prepend_negation=False)
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: it should start with a digit
"""
prepend_negation = kwargs.get('prepend_negation', True)
return Linker(regexes, prepend_negation=prepend_negation) | python | def chain(*regexes, **kwargs):
"""
A helper function to interact with the regular expression engine
that compiles and applies partial matches to a string.
It expects key value tuples as arguments (any number of them) where the
first pair is the regex to compile and the latter is the message to display
when the regular expression does not match.
The engine constructs partial regular expressions from the input and
applies them sequentially to find the exact point of failure and allowing
the ability to return a meaningful message.
Because adding negation statements like "does not..." can become
repetitive, the function defaults to ``True`` to include the option to
prepend the negative.
For example, this is what would happen with a failing regex::
>>> rx = chain((r'^\d+', 'start with a digit'))
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: does not start with a digit
If there is no need for prepending the negation, the keyword argument will
need to set it as ``False``::
>>> rx = chain((r'^\d+', 'it should start with a digit'),
... prepend_negation=False)
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: it should start with a digit
"""
prepend_negation = kwargs.get('prepend_negation', True)
return Linker(regexes, prepend_negation=prepend_negation) | [
"def",
"chain",
"(",
"*",
"regexes",
",",
"*",
"*",
"kwargs",
")",
":",
"prepend_negation",
"=",
"kwargs",
".",
"get",
"(",
"'prepend_negation'",
",",
"True",
")",
"return",
"Linker",
"(",
"regexes",
",",
"prepend_negation",
"=",
"prepend_negation",
")"
] | A helper function to interact with the regular expression engine
that compiles and applies partial matches to a string.
It expects key value tuples as arguments (any number of them) where the
first pair is the regex to compile and the latter is the message to display
when the regular expression does not match.
The engine constructs partial regular expressions from the input and
applies them sequentially to find the exact point of failure and allowing
the ability to return a meaningful message.
Because adding negation statements like "does not..." can become
repetitive, the function defaults to ``True`` to include the option to
prepend the negative.
For example, this is what would happen with a failing regex::
>>> rx = chain((r'^\d+', 'start with a digit'))
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: does not start with a digit
If there is no need for prepending the negation, the keyword argument will
need to set it as ``False``::
>>> rx = chain((r'^\d+', 'it should start with a digit'),
... prepend_negation=False)
>>> rx('foo')
Traceback (most recent call last):
...
AssertionError: it should start with a digit | [
"A",
"helper",
"function",
"to",
"interact",
"with",
"the",
"regular",
"expression",
"engine",
"that",
"compiles",
"and",
"applies",
"partial",
"matches",
"to",
"a",
"string",
"."
] | d5dc2edfcb75d9291ced3f2551f368c35dd31475 | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/regex.py#L57-L94 | train | 52,520 |
solvebio/solvebio-dash-components | examples/s3_uploader.py | generate_s3_url | def generate_s3_url(files):
"""Takes files from React side, creates
SolveBio Object containing signed S3 URL."""
if files:
vault = g.client.Vault.get_personal_vault()
files = json.loads(files)
objects = []
for i in xrange(len(files)):
obj = g.client.Object.create(
vault_id=vault.id,
object_type='file',
filename=files[i].get('filename'),
mimetype=files[i].get('mimetype'),
size=files[i].get('size')
)
objects.append({
'id': obj.id,
'filename': obj.filename,
'upload_url': obj.upload_url
})
return json.dumps(objects) | python | def generate_s3_url(files):
"""Takes files from React side, creates
SolveBio Object containing signed S3 URL."""
if files:
vault = g.client.Vault.get_personal_vault()
files = json.loads(files)
objects = []
for i in xrange(len(files)):
obj = g.client.Object.create(
vault_id=vault.id,
object_type='file',
filename=files[i].get('filename'),
mimetype=files[i].get('mimetype'),
size=files[i].get('size')
)
objects.append({
'id': obj.id,
'filename': obj.filename,
'upload_url': obj.upload_url
})
return json.dumps(objects) | [
"def",
"generate_s3_url",
"(",
"files",
")",
":",
"if",
"files",
":",
"vault",
"=",
"g",
".",
"client",
".",
"Vault",
".",
"get_personal_vault",
"(",
")",
"files",
"=",
"json",
".",
"loads",
"(",
"files",
")",
"objects",
"=",
"[",
"]",
"for",
"i",
... | Takes files from React side, creates
SolveBio Object containing signed S3 URL. | [
"Takes",
"files",
"from",
"React",
"side",
"creates",
"SolveBio",
"Object",
"containing",
"signed",
"S3",
"URL",
"."
] | 07f786379f9bb1bb003cc5727baf85f5ce54ae23 | https://github.com/solvebio/solvebio-dash-components/blob/07f786379f9bb1bb003cc5727baf85f5ce54ae23/examples/s3_uploader.py#L36-L56 | train | 52,521 |
solvebio/solvebio-dash-components | examples/s3_uploader.py | handle_uploaded_files | def handle_uploaded_files(uploaded_files):
"""Handles downstream processes using metadata
about the uploaded files from React side."""
if uploaded_files:
uploaded_files = json.loads(uploaded_files)[0]
_id = uploaded_files.get('id')
# Strip extension from filename
_filename = os.path.splitext(uploaded_files.get('filename'))[0]
# Create a dataset
dataset = g.client.Dataset.get_or_create_by_full_path('~/' + _filename)
# Import the file into the dataset
g.client.DatasetImport.create(
dataset_id=dataset.id,
object_id=_id
)
# Wait until activity is completed
dataset.activity(follow=True)
SELECTED_COLS = ['col_a', 'col_b', 'col_c']
query = dataset.query(fields=SELECTED_COLS)
return html.Div(
dt.DataTable(
id='data-table',
rows=list(query),
columns=SELECTED_COLS
)
) | python | def handle_uploaded_files(uploaded_files):
"""Handles downstream processes using metadata
about the uploaded files from React side."""
if uploaded_files:
uploaded_files = json.loads(uploaded_files)[0]
_id = uploaded_files.get('id')
# Strip extension from filename
_filename = os.path.splitext(uploaded_files.get('filename'))[0]
# Create a dataset
dataset = g.client.Dataset.get_or_create_by_full_path('~/' + _filename)
# Import the file into the dataset
g.client.DatasetImport.create(
dataset_id=dataset.id,
object_id=_id
)
# Wait until activity is completed
dataset.activity(follow=True)
SELECTED_COLS = ['col_a', 'col_b', 'col_c']
query = dataset.query(fields=SELECTED_COLS)
return html.Div(
dt.DataTable(
id='data-table',
rows=list(query),
columns=SELECTED_COLS
)
) | [
"def",
"handle_uploaded_files",
"(",
"uploaded_files",
")",
":",
"if",
"uploaded_files",
":",
"uploaded_files",
"=",
"json",
".",
"loads",
"(",
"uploaded_files",
")",
"[",
"0",
"]",
"_id",
"=",
"uploaded_files",
".",
"get",
"(",
"'id'",
")",
"# Strip extension... | Handles downstream processes using metadata
about the uploaded files from React side. | [
"Handles",
"downstream",
"processes",
"using",
"metadata",
"about",
"the",
"uploaded",
"files",
"from",
"React",
"side",
"."
] | 07f786379f9bb1bb003cc5727baf85f5ce54ae23 | https://github.com/solvebio/solvebio-dash-components/blob/07f786379f9bb1bb003cc5727baf85f5ce54ae23/examples/s3_uploader.py#L62-L92 | train | 52,522 |
nion-software/nionswift-instrumentation-kit | nionswift_plugin/nion_instrumentation_ui/CameraControlPanel.py | create_camera_panel | def create_camera_panel(document_controller, panel_id, properties):
"""Create a custom camera panel.
The camera panel type is specified in the 'camera_panel_type' key in the properties dict.
The camera panel type must match a the 'camera_panel_type' of a camera panel factory in the Registry.
The matching camera panel factory must return a ui_handler for the panel which is used to produce the UI.
"""
camera_panel_type = properties.get("camera_panel_type")
for component in Registry.get_components_by_type("camera_panel"):
if component.camera_panel_type == camera_panel_type:
hardware_source_id = properties["hardware_source_id"]
hardware_source = HardwareSource.HardwareSourceManager().get_hardware_source_for_hardware_source_id(hardware_source_id)
camera_device = getattr(hardware_source, "camera", None)
camera_settings = getattr(hardware_source, "camera_settings", None)
ui_handler = component.get_ui_handler(api_broker=PlugInManager.APIBroker(), event_loop=document_controller.event_loop, hardware_source_id=hardware_source_id, camera_device=camera_device, camera_settings=camera_settings)
panel = Panel.Panel(document_controller, panel_id, properties)
panel.widget = Declarative.DeclarativeWidget(document_controller.ui, document_controller.event_loop, ui_handler)
return panel
return None | python | def create_camera_panel(document_controller, panel_id, properties):
"""Create a custom camera panel.
The camera panel type is specified in the 'camera_panel_type' key in the properties dict.
The camera panel type must match a the 'camera_panel_type' of a camera panel factory in the Registry.
The matching camera panel factory must return a ui_handler for the panel which is used to produce the UI.
"""
camera_panel_type = properties.get("camera_panel_type")
for component in Registry.get_components_by_type("camera_panel"):
if component.camera_panel_type == camera_panel_type:
hardware_source_id = properties["hardware_source_id"]
hardware_source = HardwareSource.HardwareSourceManager().get_hardware_source_for_hardware_source_id(hardware_source_id)
camera_device = getattr(hardware_source, "camera", None)
camera_settings = getattr(hardware_source, "camera_settings", None)
ui_handler = component.get_ui_handler(api_broker=PlugInManager.APIBroker(), event_loop=document_controller.event_loop, hardware_source_id=hardware_source_id, camera_device=camera_device, camera_settings=camera_settings)
panel = Panel.Panel(document_controller, panel_id, properties)
panel.widget = Declarative.DeclarativeWidget(document_controller.ui, document_controller.event_loop, ui_handler)
return panel
return None | [
"def",
"create_camera_panel",
"(",
"document_controller",
",",
"panel_id",
",",
"properties",
")",
":",
"camera_panel_type",
"=",
"properties",
".",
"get",
"(",
"\"camera_panel_type\"",
")",
"for",
"component",
"in",
"Registry",
".",
"get_components_by_type",
"(",
"... | Create a custom camera panel.
The camera panel type is specified in the 'camera_panel_type' key in the properties dict.
The camera panel type must match a the 'camera_panel_type' of a camera panel factory in the Registry.
The matching camera panel factory must return a ui_handler for the panel which is used to produce the UI. | [
"Create",
"a",
"custom",
"camera",
"panel",
"."
] | b20c4fff17e840e8cb3d544705faf5bd05f1cbf7 | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nionswift_plugin/nion_instrumentation_ui/CameraControlPanel.py#L849-L869 | train | 52,523 |
jneight/django-earthdistance | django_earthdistance/models.py | LlToEarth.resolve_expression | def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
"""Setup any data here, this method will be called before final SQL is generated"""
c = self.copy()
c.is_summary = summarize
c.for_save = for_save
final_points = []
for i, p in enumerate(self.params):
try:
float(p)
except:
_, source, _, join_list, last = query.setup_joins(
six.text_type(p).split('__'), query.model._meta, query.get_initial_alias())[:5]
target, alias, _ = query.trim_joins(source, join_list, last)
final_points.append("%s.%s" % (alias, target[0].get_attname_column()[1]))
else:
final_points.append(six.text_type(p))
c.params = final_points
return c | python | def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
"""Setup any data here, this method will be called before final SQL is generated"""
c = self.copy()
c.is_summary = summarize
c.for_save = for_save
final_points = []
for i, p in enumerate(self.params):
try:
float(p)
except:
_, source, _, join_list, last = query.setup_joins(
six.text_type(p).split('__'), query.model._meta, query.get_initial_alias())[:5]
target, alias, _ = query.trim_joins(source, join_list, last)
final_points.append("%s.%s" % (alias, target[0].get_attname_column()[1]))
else:
final_points.append(six.text_type(p))
c.params = final_points
return c | [
"def",
"resolve_expression",
"(",
"self",
",",
"query",
"=",
"None",
",",
"allow_joins",
"=",
"True",
",",
"reuse",
"=",
"None",
",",
"summarize",
"=",
"False",
",",
"for_save",
"=",
"False",
")",
":",
"c",
"=",
"self",
".",
"copy",
"(",
")",
"c",
... | Setup any data here, this method will be called before final SQL is generated | [
"Setup",
"any",
"data",
"here",
"this",
"method",
"will",
"be",
"called",
"before",
"final",
"SQL",
"is",
"generated"
] | d9e620778a8bb49ae8e73ea161fee3e832f1af77 | https://github.com/jneight/django-earthdistance/blob/d9e620778a8bb49ae8e73ea161fee3e832f1af77/django_earthdistance/models.py#L20-L37 | train | 52,524 |
jneight/django-earthdistance | django_earthdistance/models.py | EarthDistanceQuerySet.in_distance | def in_distance(self, distance, fields, points, annotate='_ed_distance'):
"""Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center of the circunference (latitude, longitude)
:param annotate: name where the distance will be annotated
"""
clone = self._clone()
return clone.annotate(
**{annotate: EarthDistance([
LlToEarth(fields), LlToEarth(points)])
}).filter(**{'{0}__lte'.format(annotate): distance}) | python | def in_distance(self, distance, fields, points, annotate='_ed_distance'):
"""Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center of the circunference (latitude, longitude)
:param annotate: name where the distance will be annotated
"""
clone = self._clone()
return clone.annotate(
**{annotate: EarthDistance([
LlToEarth(fields), LlToEarth(points)])
}).filter(**{'{0}__lte'.format(annotate): distance}) | [
"def",
"in_distance",
"(",
"self",
",",
"distance",
",",
"fields",
",",
"points",
",",
"annotate",
"=",
"'_ed_distance'",
")",
":",
"clone",
"=",
"self",
".",
"_clone",
"(",
")",
"return",
"clone",
".",
"annotate",
"(",
"*",
"*",
"{",
"annotate",
":",
... | Filter rows inside a circunference of radius distance `distance`
:param distance: max distance to allow
:param fields: `tuple` with the fields to filter (latitude, longitude)
:param points: center of the circunference (latitude, longitude)
:param annotate: name where the distance will be annotated | [
"Filter",
"rows",
"inside",
"a",
"circunference",
"of",
"radius",
"distance",
"distance"
] | d9e620778a8bb49ae8e73ea161fee3e832f1af77 | https://github.com/jneight/django-earthdistance/blob/d9e620778a8bb49ae8e73ea161fee3e832f1af77/django_earthdistance/models.py#L76-L89 | train | 52,525 |
HolmesNL/confidence | confidence/models.py | Configuration.get | def get(self, path, default=_NoDefault, as_type=None, resolve_references=True):
"""
Gets a value for the specified path.
:param path: the configuration key to fetch a value for, steps
separated by the separator supplied to the constructor (default
``.``)
:param default: a value to return if no value is found for the
supplied path (``None`` is allowed)
:param as_type: an optional callable to apply to the value found for
the supplied path (possibly raising exceptions of its own if the
value can not be coerced to the expected type)
:param resolve_references: whether to resolve references in values
:return: the value associated with the supplied configuration key, if
available, or a supplied default value if the key was not found
:raises ConfigurationError: when no value was found for *path* and
*default* was not provided or a reference could not be resolved
"""
value = self._source
steps_taken = []
try:
# walk through the values dictionary
for step in path.split(self._separator):
steps_taken.append(step)
value = value[step]
if as_type:
return as_type(value)
elif isinstance(value, Mapping):
# create an instance of our current type, copying 'configured' properties / policies
namespace = type(self)(separator=self._separator, missing=self._missing)
namespace._source = value
# carry the root object from namespace to namespace, references are always resolved from root
namespace._root = self._root
return namespace
elif resolve_references and isinstance(value, str):
# only resolve references in str-type values (the only way they can be expressed)
return self._resolve(value)
else:
return value
except ConfiguredReferenceError:
# also a KeyError, but this one should bubble to caller
raise
except KeyError as e:
if default is not _NoDefault:
return default
else:
missing_key = self._separator.join(steps_taken)
raise NotConfiguredError('no configuration for key {}'.format(missing_key), key=missing_key) from e | python | def get(self, path, default=_NoDefault, as_type=None, resolve_references=True):
"""
Gets a value for the specified path.
:param path: the configuration key to fetch a value for, steps
separated by the separator supplied to the constructor (default
``.``)
:param default: a value to return if no value is found for the
supplied path (``None`` is allowed)
:param as_type: an optional callable to apply to the value found for
the supplied path (possibly raising exceptions of its own if the
value can not be coerced to the expected type)
:param resolve_references: whether to resolve references in values
:return: the value associated with the supplied configuration key, if
available, or a supplied default value if the key was not found
:raises ConfigurationError: when no value was found for *path* and
*default* was not provided or a reference could not be resolved
"""
value = self._source
steps_taken = []
try:
# walk through the values dictionary
for step in path.split(self._separator):
steps_taken.append(step)
value = value[step]
if as_type:
return as_type(value)
elif isinstance(value, Mapping):
# create an instance of our current type, copying 'configured' properties / policies
namespace = type(self)(separator=self._separator, missing=self._missing)
namespace._source = value
# carry the root object from namespace to namespace, references are always resolved from root
namespace._root = self._root
return namespace
elif resolve_references and isinstance(value, str):
# only resolve references in str-type values (the only way they can be expressed)
return self._resolve(value)
else:
return value
except ConfiguredReferenceError:
# also a KeyError, but this one should bubble to caller
raise
except KeyError as e:
if default is not _NoDefault:
return default
else:
missing_key = self._separator.join(steps_taken)
raise NotConfiguredError('no configuration for key {}'.format(missing_key), key=missing_key) from e | [
"def",
"get",
"(",
"self",
",",
"path",
",",
"default",
"=",
"_NoDefault",
",",
"as_type",
"=",
"None",
",",
"resolve_references",
"=",
"True",
")",
":",
"value",
"=",
"self",
".",
"_source",
"steps_taken",
"=",
"[",
"]",
"try",
":",
"# walk through the ... | Gets a value for the specified path.
:param path: the configuration key to fetch a value for, steps
separated by the separator supplied to the constructor (default
``.``)
:param default: a value to return if no value is found for the
supplied path (``None`` is allowed)
:param as_type: an optional callable to apply to the value found for
the supplied path (possibly raising exceptions of its own if the
value can not be coerced to the expected type)
:param resolve_references: whether to resolve references in values
:return: the value associated with the supplied configuration key, if
available, or a supplied default value if the key was not found
:raises ConfigurationError: when no value was found for *path* and
*default* was not provided or a reference could not be resolved | [
"Gets",
"a",
"value",
"for",
"the",
"specified",
"path",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/models.py#L113-L161 | train | 52,526 |
craigahobbs/chisel | src/chisel/action.py | action | def action(action_callback=None, **kwargs):
"""
Chisel action decorator
"""
if action_callback is None:
return lambda fn: action(fn, **kwargs)
else:
return Action(action_callback, **kwargs).decorate_module(action_callback) | python | def action(action_callback=None, **kwargs):
"""
Chisel action decorator
"""
if action_callback is None:
return lambda fn: action(fn, **kwargs)
else:
return Action(action_callback, **kwargs).decorate_module(action_callback) | [
"def",
"action",
"(",
"action_callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"action_callback",
"is",
"None",
":",
"return",
"lambda",
"fn",
":",
"action",
"(",
"fn",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"return",
"Action",
"(... | Chisel action decorator | [
"Chisel",
"action",
"decorator"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/action.py#L15-L23 | train | 52,527 |
tipsi/tipsi_tools | tipsi_tools/tipsi_logging.py | get_plain_logname | def get_plain_logname(base_name, root_dir, enable_json):
"""
we nest all plain logs to prevent double log shipping
"""
if enable_json:
nested_dir = os.path.join(root_dir, 'plain')
if os.path.exists(root_dir) and not os.path.exists(nested_dir):
os.mkdir(nested_dir)
root_dir = nested_dir
return os.path.join(root_dir, '{}.log'.format(base_name)) | python | def get_plain_logname(base_name, root_dir, enable_json):
"""
we nest all plain logs to prevent double log shipping
"""
if enable_json:
nested_dir = os.path.join(root_dir, 'plain')
if os.path.exists(root_dir) and not os.path.exists(nested_dir):
os.mkdir(nested_dir)
root_dir = nested_dir
return os.path.join(root_dir, '{}.log'.format(base_name)) | [
"def",
"get_plain_logname",
"(",
"base_name",
",",
"root_dir",
",",
"enable_json",
")",
":",
"if",
"enable_json",
":",
"nested_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'plain'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
... | we nest all plain logs to prevent double log shipping | [
"we",
"nest",
"all",
"plain",
"logs",
"to",
"prevent",
"double",
"log",
"shipping"
] | 1aba960c9890ceef2fb5e215b98b1646056ee58e | https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/tipsi_logging.py#L50-L59 | train | 52,528 |
tipsi/tipsi_tools | tipsi_tools/unix.py | succ | def succ(cmd, check_stderr=True, stdout=None, stderr=None):
'''
Alias to run with check return code and stderr
'''
code, out, err = run(cmd)
# Because we're raising error, sometimes we want to process stdout/stderr after catching error
# so we're copying these outputs if required
if stdout is not None:
stdout[:] = out
if stderr is not None:
stderr[:] = err
if code != 0:
for l in out:
print(l)
assert code == 0, 'Return: {} {}\nStderr: {}'.format(code, cmd, err)
if check_stderr:
assert err == [], 'Error: {} {}'.format(err, code)
return code, out, err | python | def succ(cmd, check_stderr=True, stdout=None, stderr=None):
'''
Alias to run with check return code and stderr
'''
code, out, err = run(cmd)
# Because we're raising error, sometimes we want to process stdout/stderr after catching error
# so we're copying these outputs if required
if stdout is not None:
stdout[:] = out
if stderr is not None:
stderr[:] = err
if code != 0:
for l in out:
print(l)
assert code == 0, 'Return: {} {}\nStderr: {}'.format(code, cmd, err)
if check_stderr:
assert err == [], 'Error: {} {}'.format(err, code)
return code, out, err | [
"def",
"succ",
"(",
"cmd",
",",
"check_stderr",
"=",
"True",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"code",
",",
"out",
",",
"err",
"=",
"run",
"(",
"cmd",
")",
"# Because we're raising error, sometimes we want to process stdout/stde... | Alias to run with check return code and stderr | [
"Alias",
"to",
"run",
"with",
"check",
"return",
"code",
"and",
"stderr"
] | 1aba960c9890ceef2fb5e215b98b1646056ee58e | https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/unix.py#L34-L53 | train | 52,529 |
tipsi/tipsi_tools | tipsi_tools/unix.py | wait_socket | def wait_socket(host, port, timeout=120):
'''
Wait for socket opened on remote side. Return False after timeout
'''
return wait_result(lambda: check_socket(host, port), True, timeout) | python | def wait_socket(host, port, timeout=120):
'''
Wait for socket opened on remote side. Return False after timeout
'''
return wait_result(lambda: check_socket(host, port), True, timeout) | [
"def",
"wait_socket",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"120",
")",
":",
"return",
"wait_result",
"(",
"lambda",
":",
"check_socket",
"(",
"host",
",",
"port",
")",
",",
"True",
",",
"timeout",
")"
] | Wait for socket opened on remote side. Return False after timeout | [
"Wait",
"for",
"socket",
"opened",
"on",
"remote",
"side",
".",
"Return",
"False",
"after",
"timeout"
] | 1aba960c9890ceef2fb5e215b98b1646056ee58e | https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/unix.py#L132-L136 | train | 52,530 |
tipsi/tipsi_tools | tipsi_tools/unix.py | interpolate_sysenv | def interpolate_sysenv(line, defaults={}):
'''
Format line system environment variables + defaults
'''
map = ChainMap(os.environ, defaults)
return line.format(**map) | python | def interpolate_sysenv(line, defaults={}):
'''
Format line system environment variables + defaults
'''
map = ChainMap(os.environ, defaults)
return line.format(**map) | [
"def",
"interpolate_sysenv",
"(",
"line",
",",
"defaults",
"=",
"{",
"}",
")",
":",
"map",
"=",
"ChainMap",
"(",
"os",
".",
"environ",
",",
"defaults",
")",
"return",
"line",
".",
"format",
"(",
"*",
"*",
"map",
")"
] | Format line system environment variables + defaults | [
"Format",
"line",
"system",
"environment",
"variables",
"+",
"defaults"
] | 1aba960c9890ceef2fb5e215b98b1646056ee58e | https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/unix.py#L143-L148 | train | 52,531 |
tipsi/tipsi_tools | tipsi_tools/unix.py | cd | def cd(dir_name):
"""
do something in other directory and return back after block ended
"""
old_path = os.path.abspath('.')
os.chdir(dir_name)
try:
yield
os.chdir(old_path)
except Exception:
os.chdir(old_path)
raise | python | def cd(dir_name):
"""
do something in other directory and return back after block ended
"""
old_path = os.path.abspath('.')
os.chdir(dir_name)
try:
yield
os.chdir(old_path)
except Exception:
os.chdir(old_path)
raise | [
"def",
"cd",
"(",
"dir_name",
")",
":",
"old_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"os",
".",
"chdir",
"(",
"dir_name",
")",
"try",
":",
"yield",
"os",
".",
"chdir",
"(",
"old_path",
")",
"except",
"Exception",
":",
"os",
... | do something in other directory and return back after block ended | [
"do",
"something",
"in",
"other",
"directory",
"and",
"return",
"back",
"after",
"block",
"ended"
] | 1aba960c9890ceef2fb5e215b98b1646056ee58e | https://github.com/tipsi/tipsi_tools/blob/1aba960c9890ceef2fb5e215b98b1646056ee58e/tipsi_tools/unix.py#L164-L175 | train | 52,532 |
non-Jedi/gyr | gyr/resources.py | Resource._is_new | def _is_new(self, identifier):
"""Returns True if identifier hasn't been seen before."""
if identifier in self.tracker:
return False
else:
self.tracker.append(identifier)
self.tracker.pop(0)
return True | python | def _is_new(self, identifier):
"""Returns True if identifier hasn't been seen before."""
if identifier in self.tracker:
return False
else:
self.tracker.append(identifier)
self.tracker.pop(0)
return True | [
"def",
"_is_new",
"(",
"self",
",",
"identifier",
")",
":",
"if",
"identifier",
"in",
"self",
".",
"tracker",
":",
"return",
"False",
"else",
":",
"self",
".",
"tracker",
".",
"append",
"(",
"identifier",
")",
"self",
".",
"tracker",
".",
"pop",
"(",
... | Returns True if identifier hasn't been seen before. | [
"Returns",
"True",
"if",
"identifier",
"hasn",
"t",
"been",
"seen",
"before",
"."
] | 9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e | https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/resources.py#L35-L42 | train | 52,533 |
non-Jedi/gyr | gyr/resources.py | Transaction.on_put | def on_put(self, request, response, txn_id=None):
"""Responds to PUT request containing events."""
response.body = "{}"
# Check whether repeat txn_id
if not self._is_new(txn_id):
response.status = falcon.HTTP_200
return
request.context["body"] = request.stream.read()
try:
events = json.loads(request.context["body"].decode("utf-8"))["events"]
except(KeyError, ValueError, UnicodeDecodeError):
response.status = falcon.HTTP_400
response.body = "Malformed request body"
return
if self.handler(EventStream(events, self.Api)):
response.status = falcon.HTTP_200
else:
response.status = falcon.HTTP_400 | python | def on_put(self, request, response, txn_id=None):
"""Responds to PUT request containing events."""
response.body = "{}"
# Check whether repeat txn_id
if not self._is_new(txn_id):
response.status = falcon.HTTP_200
return
request.context["body"] = request.stream.read()
try:
events = json.loads(request.context["body"].decode("utf-8"))["events"]
except(KeyError, ValueError, UnicodeDecodeError):
response.status = falcon.HTTP_400
response.body = "Malformed request body"
return
if self.handler(EventStream(events, self.Api)):
response.status = falcon.HTTP_200
else:
response.status = falcon.HTTP_400 | [
"def",
"on_put",
"(",
"self",
",",
"request",
",",
"response",
",",
"txn_id",
"=",
"None",
")",
":",
"response",
".",
"body",
"=",
"\"{}\"",
"# Check whether repeat txn_id",
"if",
"not",
"self",
".",
"_is_new",
"(",
"txn_id",
")",
":",
"response",
".",
"... | Responds to PUT request containing events. | [
"Responds",
"to",
"PUT",
"request",
"containing",
"events",
"."
] | 9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e | https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/resources.py#L61-L81 | train | 52,534 |
non-Jedi/gyr | gyr/resources.py | User.on_get | def on_get(self, request, response, user_id=None):
"""Responds to GET request for users."""
response.body = "{}"
if self.handler(user_id):
response.status = falcon.HTTP_200
self.api.register(utils.mxid2localpart(user_id))
else:
response.status = falcon.HTTP_404 | python | def on_get(self, request, response, user_id=None):
"""Responds to GET request for users."""
response.body = "{}"
if self.handler(user_id):
response.status = falcon.HTTP_200
self.api.register(utils.mxid2localpart(user_id))
else:
response.status = falcon.HTTP_404 | [
"def",
"on_get",
"(",
"self",
",",
"request",
",",
"response",
",",
"user_id",
"=",
"None",
")",
":",
"response",
".",
"body",
"=",
"\"{}\"",
"if",
"self",
".",
"handler",
"(",
"user_id",
")",
":",
"response",
".",
"status",
"=",
"falcon",
".",
"HTTP... | Responds to GET request for users. | [
"Responds",
"to",
"GET",
"request",
"for",
"users",
"."
] | 9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e | https://github.com/non-Jedi/gyr/blob/9f7bfe033b9d3bbfd3a9e8aea02e35526b53125e/gyr/resources.py#L87-L94 | train | 52,535 |
nion-software/nionswift-instrumentation-kit | nion/instrumentation/camera_base.py | CameraSettings.set_frame_parameters | def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
"""Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters.
"""
self.frame_parameters_changed_event.fire(profile_index, frame_parameters) | python | def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
"""Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters.
"""
self.frame_parameters_changed_event.fire(profile_index, frame_parameters) | [
"def",
"set_frame_parameters",
"(",
"self",
",",
"profile_index",
":",
"int",
",",
"frame_parameters",
")",
"->",
"None",
":",
"self",
".",
"frame_parameters_changed_event",
".",
"fire",
"(",
"profile_index",
",",
"frame_parameters",
")"
] | Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matches the record settings index, call set record frame parameters. | [
"Set",
"the",
"frame",
"parameters",
"with",
"the",
"settings",
"index",
"and",
"fire",
"the",
"frame",
"parameters",
"changed",
"event",
"."
] | b20c4fff17e840e8cb3d544705faf5bd05f1cbf7 | https://github.com/nion-software/nionswift-instrumentation-kit/blob/b20c4fff17e840e8cb3d544705faf5bd05f1cbf7/nion/instrumentation/camera_base.py#L504-L511 | train | 52,536 |
bierschenk/ode | ode/integrators.py | euler | def euler(dfun, xzero, timerange, timestep):
'''Euler method integration. This function wraps the Euler class.
:param dfun:
derivative function of the system.
The differential system arranged as a series of first-order
equations: \\dot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x:
as lists
'''
return zip(*list(Euler(dfun, xzero, timerange, timestep))) | python | def euler(dfun, xzero, timerange, timestep):
'''Euler method integration. This function wraps the Euler class.
:param dfun:
derivative function of the system.
The differential system arranged as a series of first-order
equations: \\dot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x:
as lists
'''
return zip(*list(Euler(dfun, xzero, timerange, timestep))) | [
"def",
"euler",
"(",
"dfun",
",",
"xzero",
",",
"timerange",
",",
"timestep",
")",
":",
"return",
"zip",
"(",
"*",
"list",
"(",
"Euler",
"(",
"dfun",
",",
"xzero",
",",
"timerange",
",",
"timestep",
")",
")",
")"
] | Euler method integration. This function wraps the Euler class.
:param dfun:
derivative function of the system.
The differential system arranged as a series of first-order
equations: \\dot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x:
as lists | [
"Euler",
"method",
"integration",
".",
"This",
"function",
"wraps",
"the",
"Euler",
"class",
"."
] | 01fb714874926f0988a4bb250d2a0c8a2429e4f0 | https://github.com/bierschenk/ode/blob/01fb714874926f0988a4bb250d2a0c8a2429e4f0/ode/integrators.py#L72-L88 | train | 52,537 |
bierschenk/ode | ode/integrators.py | verlet | def verlet(dfun, xzero, vzero, timerange, timestep):
'''Verlet method integration. This function wraps the Verlet class.
:param dfun:
second derivative function of the system.
The differential system arranged as a series of second-order
equations: \ddot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param vzero:
the initial condition of first derivative of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x, v:
as lists.
'''
return zip(*list(Verlet(dfun, xzero, vzero, timerange, timestep))) | python | def verlet(dfun, xzero, vzero, timerange, timestep):
'''Verlet method integration. This function wraps the Verlet class.
:param dfun:
second derivative function of the system.
The differential system arranged as a series of second-order
equations: \ddot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param vzero:
the initial condition of first derivative of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x, v:
as lists.
'''
return zip(*list(Verlet(dfun, xzero, vzero, timerange, timestep))) | [
"def",
"verlet",
"(",
"dfun",
",",
"xzero",
",",
"vzero",
",",
"timerange",
",",
"timestep",
")",
":",
"return",
"zip",
"(",
"*",
"list",
"(",
"Verlet",
"(",
"dfun",
",",
"xzero",
",",
"vzero",
",",
"timerange",
",",
"timestep",
")",
")",
")"
] | Verlet method integration. This function wraps the Verlet class.
:param dfun:
second derivative function of the system.
The differential system arranged as a series of second-order
equations: \ddot{X} = dfun(t, x)
:param xzero:
the initial condition of the system
:param vzero:
the initial condition of first derivative of the system
:param timerange:
the start and end times as (starttime, endtime)
:param timestep:
the timestep
:returns: t, x, v:
as lists. | [
"Verlet",
"method",
"integration",
".",
"This",
"function",
"wraps",
"the",
"Verlet",
"class",
"."
] | 01fb714874926f0988a4bb250d2a0c8a2429e4f0 | https://github.com/bierschenk/ode/blob/01fb714874926f0988a4bb250d2a0c8a2429e4f0/ode/integrators.py#L145-L163 | train | 52,538 |
bierschenk/ode | ode/integrators.py | backwardeuler | def backwardeuler(dfun, xzero, timerange, timestep):
'''Backward Euler method integration. This function wraps BackwardEuler.
:param dfun:
Derivative function of the system.
The differential system arranged as a series of first-order
equations: \dot{X} = dfun(t, x)
:param xzero:
The initial condition of the system.
:param vzero:
The initial condition of first derivative of the system.
:param timerange:
The start and end times as (starttime, endtime).
:param timestep:
The timestep.
:param convergencethreshold:
Each step requires an iterative solution of an implicit equation.
This is the threshold of convergence.
:param maxiterations:
Maximum iterations of the implicit equation before raising
an exception.
:returns: t, x:
as lists.
'''
return zip(*list(BackwardEuler(dfun, xzero, timerange, timestep))) | python | def backwardeuler(dfun, xzero, timerange, timestep):
'''Backward Euler method integration. This function wraps BackwardEuler.
:param dfun:
Derivative function of the system.
The differential system arranged as a series of first-order
equations: \dot{X} = dfun(t, x)
:param xzero:
The initial condition of the system.
:param vzero:
The initial condition of first derivative of the system.
:param timerange:
The start and end times as (starttime, endtime).
:param timestep:
The timestep.
:param convergencethreshold:
Each step requires an iterative solution of an implicit equation.
This is the threshold of convergence.
:param maxiterations:
Maximum iterations of the implicit equation before raising
an exception.
:returns: t, x:
as lists.
'''
return zip(*list(BackwardEuler(dfun, xzero, timerange, timestep))) | [
"def",
"backwardeuler",
"(",
"dfun",
",",
"xzero",
",",
"timerange",
",",
"timestep",
")",
":",
"return",
"zip",
"(",
"*",
"list",
"(",
"BackwardEuler",
"(",
"dfun",
",",
"xzero",
",",
"timerange",
",",
"timestep",
")",
")",
")"
] | Backward Euler method integration. This function wraps BackwardEuler.
:param dfun:
Derivative function of the system.
The differential system arranged as a series of first-order
equations: \dot{X} = dfun(t, x)
:param xzero:
The initial condition of the system.
:param vzero:
The initial condition of first derivative of the system.
:param timerange:
The start and end times as (starttime, endtime).
:param timestep:
The timestep.
:param convergencethreshold:
Each step requires an iterative solution of an implicit equation.
This is the threshold of convergence.
:param maxiterations:
Maximum iterations of the implicit equation before raising
an exception.
:returns: t, x:
as lists. | [
"Backward",
"Euler",
"method",
"integration",
".",
"This",
"function",
"wraps",
"BackwardEuler",
"."
] | 01fb714874926f0988a4bb250d2a0c8a2429e4f0 | https://github.com/bierschenk/ode/blob/01fb714874926f0988a4bb250d2a0c8a2429e4f0/ode/integrators.py#L228-L252 | train | 52,539 |
craigahobbs/chisel | src/chisel/app.py | Application.add_request | def add_request(self, request):
"""
Add a request object
"""
# Duplicate request name?
if request.name in self.requests:
raise ValueError('redefinition of request "{0}"'.format(request.name))
self.requests[request.name] = request
# Add the request URLs
for method, url in request.urls:
# URL with arguments?
if RE_URL_ARG.search(url):
request_regex = '^' + RE_URL_ARG_ESC.sub(r'/(?P<\1>[^/]+)', re.escape(url)) + '$'
self.__request_regex.append((method, re.compile(request_regex), request))
else:
request_key = (method, url)
if request_key in self.__request_urls:
raise ValueError('redefinition of request URL "{0}"'.format(url))
self.__request_urls[request_key] = request | python | def add_request(self, request):
"""
Add a request object
"""
# Duplicate request name?
if request.name in self.requests:
raise ValueError('redefinition of request "{0}"'.format(request.name))
self.requests[request.name] = request
# Add the request URLs
for method, url in request.urls:
# URL with arguments?
if RE_URL_ARG.search(url):
request_regex = '^' + RE_URL_ARG_ESC.sub(r'/(?P<\1>[^/]+)', re.escape(url)) + '$'
self.__request_regex.append((method, re.compile(request_regex), request))
else:
request_key = (method, url)
if request_key in self.__request_urls:
raise ValueError('redefinition of request URL "{0}"'.format(url))
self.__request_urls[request_key] = request | [
"def",
"add_request",
"(",
"self",
",",
"request",
")",
":",
"# Duplicate request name?",
"if",
"request",
".",
"name",
"in",
"self",
".",
"requests",
":",
"raise",
"ValueError",
"(",
"'redefinition of request \"{0}\"'",
".",
"format",
"(",
"request",
".",
"name... | Add a request object | [
"Add",
"a",
"request",
"object"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L44-L65 | train | 52,540 |
craigahobbs/chisel | src/chisel/app.py | Context.add_header | def add_header(self, key, value):
"""
Add a response header
"""
assert isinstance(key, str), 'header key must be of type str'
assert isinstance(value, str), 'header value must be of type str'
self.headers[key] = value | python | def add_header(self, key, value):
"""
Add a response header
"""
assert isinstance(key, str), 'header key must be of type str'
assert isinstance(value, str), 'header value must be of type str'
self.headers[key] = value | [
"def",
"add_header",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"key",
",",
"str",
")",
",",
"'header key must be of type str'",
"assert",
"isinstance",
"(",
"value",
",",
"str",
")",
",",
"'header value must be of type str'",
... | Add a response header | [
"Add",
"a",
"response",
"header"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L178-L185 | train | 52,541 |
craigahobbs/chisel | src/chisel/app.py | Context.response | def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
response_headers.extend(headers)
self.start_response(status, response_headers)
return content | python | def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
response_headers.extend(headers)
self.start_response(status, response_headers)
return content | [
"def",
"response",
"(",
"self",
",",
"status",
",",
"content_type",
",",
"content",
",",
"headers",
"=",
"None",
")",
":",
"assert",
"not",
"isinstance",
"(",
"content",
",",
"(",
"str",
",",
"bytes",
")",
")",
",",
"'response content cannot be of type str o... | Send an HTTP response | [
"Send",
"an",
"HTTP",
"response"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L200-L210 | train | 52,542 |
craigahobbs/chisel | src/chisel/app.py | Context.response_text | def response_text(self, status, text=None, content_type='text/plain', encoding='utf-8', headers=None):
"""
Send a plain-text response
"""
if text is None:
if isinstance(status, str):
text = status
else:
text = status.phrase
return self.response(status, content_type, [text.encode(encoding)], headers=headers) | python | def response_text(self, status, text=None, content_type='text/plain', encoding='utf-8', headers=None):
"""
Send a plain-text response
"""
if text is None:
if isinstance(status, str):
text = status
else:
text = status.phrase
return self.response(status, content_type, [text.encode(encoding)], headers=headers) | [
"def",
"response_text",
"(",
"self",
",",
"status",
",",
"text",
"=",
"None",
",",
"content_type",
"=",
"'text/plain'",
",",
"encoding",
"=",
"'utf-8'",
",",
"headers",
"=",
"None",
")",
":",
"if",
"text",
"is",
"None",
":",
"if",
"isinstance",
"(",
"s... | Send a plain-text response | [
"Send",
"a",
"plain",
"-",
"text",
"response"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L212-L222 | train | 52,543 |
craigahobbs/chisel | src/chisel/app.py | Context.response_json | def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
"""
Send a JSON response
"""
encoder = JSONEncoder(
check_circular=self.app.validate_output,
allow_nan=False,
sort_keys=True,
indent=2 if self.app.pretty_output else None,
separators=(',', ': ') if self.app.pretty_output else (',', ':')
)
content = encoder.encode(response)
if jsonp:
content_list = [jsonp.encode(encoding), b'(', content.encode(encoding), b');']
else:
content_list = [content.encode(encoding)]
return self.response(status, content_type, content_list, headers=headers) | python | def response_json(self, status, response, content_type='application/json', encoding='utf-8', headers=None, jsonp=None):
"""
Send a JSON response
"""
encoder = JSONEncoder(
check_circular=self.app.validate_output,
allow_nan=False,
sort_keys=True,
indent=2 if self.app.pretty_output else None,
separators=(',', ': ') if self.app.pretty_output else (',', ':')
)
content = encoder.encode(response)
if jsonp:
content_list = [jsonp.encode(encoding), b'(', content.encode(encoding), b');']
else:
content_list = [content.encode(encoding)]
return self.response(status, content_type, content_list, headers=headers) | [
"def",
"response_json",
"(",
"self",
",",
"status",
",",
"response",
",",
"content_type",
"=",
"'application/json'",
",",
"encoding",
"=",
"'utf-8'",
",",
"headers",
"=",
"None",
",",
"jsonp",
"=",
"None",
")",
":",
"encoder",
"=",
"JSONEncoder",
"(",
"che... | Send a JSON response | [
"Send",
"a",
"JSON",
"response"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L224-L241 | train | 52,544 |
craigahobbs/chisel | src/chisel/app.py | Context.reconstruct_url | def reconstruct_url(self, path_info=None, query_string=None, relative=False):
"""
Reconstructs the request URL using the algorithm provided by PEP3333
"""
environ = self.environ
if relative:
url = ''
else:
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if environ['wsgi.url_scheme'] == 'https':
if environ['SERVER_PORT'] != '443':
url += ':' + environ['SERVER_PORT']
else:
if environ['SERVER_PORT'] != '80':
url += ':' + environ['SERVER_PORT']
url += quote(environ.get('SCRIPT_NAME', ''))
if path_info is None:
url += quote(environ.get('PATH_INFO', ''))
else:
url += path_info
if query_string is None:
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
else:
if query_string:
if isinstance(query_string, str):
url += '?' + query_string
else:
url += '?' + encode_query_string(query_string)
return url | python | def reconstruct_url(self, path_info=None, query_string=None, relative=False):
"""
Reconstructs the request URL using the algorithm provided by PEP3333
"""
environ = self.environ
if relative:
url = ''
else:
url = environ['wsgi.url_scheme'] + '://'
if environ.get('HTTP_HOST'):
url += environ['HTTP_HOST']
else:
url += environ['SERVER_NAME']
if environ['wsgi.url_scheme'] == 'https':
if environ['SERVER_PORT'] != '443':
url += ':' + environ['SERVER_PORT']
else:
if environ['SERVER_PORT'] != '80':
url += ':' + environ['SERVER_PORT']
url += quote(environ.get('SCRIPT_NAME', ''))
if path_info is None:
url += quote(environ.get('PATH_INFO', ''))
else:
url += path_info
if query_string is None:
if environ.get('QUERY_STRING'):
url += '?' + environ['QUERY_STRING']
else:
if query_string:
if isinstance(query_string, str):
url += '?' + query_string
else:
url += '?' + encode_query_string(query_string)
return url | [
"def",
"reconstruct_url",
"(",
"self",
",",
"path_info",
"=",
"None",
",",
"query_string",
"=",
"None",
",",
"relative",
"=",
"False",
")",
":",
"environ",
"=",
"self",
".",
"environ",
"if",
"relative",
":",
"url",
"=",
"''",
"else",
":",
"url",
"=",
... | Reconstructs the request URL using the algorithm provided by PEP3333 | [
"Reconstructs",
"the",
"request",
"URL",
"using",
"the",
"algorithm",
"provided",
"by",
"PEP3333"
] | d306a9eae2ff757647c6ca1c933bc944efa5c326 | https://github.com/craigahobbs/chisel/blob/d306a9eae2ff757647c6ca1c933bc944efa5c326/src/chisel/app.py#L243-L281 | train | 52,545 |
HolmesNL/confidence | confidence/io.py | read_envvar_file | def read_envvar_file(name, extension):
"""
Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured`
"""
envvar_file = environ.get('{}_config_file'.format(name).upper())
if envvar_file:
# envvar set, load value as file
return loadf(envvar_file)
else:
# envvar not set, return an empty source
return NotConfigured | python | def read_envvar_file(name, extension):
"""
Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured`
"""
envvar_file = environ.get('{}_config_file'.format(name).upper())
if envvar_file:
# envvar set, load value as file
return loadf(envvar_file)
else:
# envvar not set, return an empty source
return NotConfigured | [
"def",
"read_envvar_file",
"(",
"name",
",",
"extension",
")",
":",
"envvar_file",
"=",
"environ",
".",
"get",
"(",
"'{}_config_file'",
".",
"format",
"(",
"name",
")",
".",
"upper",
"(",
")",
")",
"if",
"envvar_file",
":",
"# envvar set, load value as file",
... | Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured` | [
"Read",
"values",
"from",
"a",
"file",
"provided",
"as",
"a",
"environment",
"variable",
"NAME_CONFIG_FILE",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L99-L115 | train | 52,546 |
HolmesNL/confidence | confidence/io.py | loaders | def loaders(*specifiers):
"""
Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load order using predefined user-local locations,
# an explicit path, a template and a user-defined function
load_order = loaders(Locality.user,
'/etc/defaults/hard-coded.yaml',
'/path/to/{name}.{extension}',
my_loader)
# load configuration for name 'my-application' using the load order
# defined above
config = load_name('my-application', load_order=load_order)
:param specifiers:
:return: a `generator` of configuration loaders in the specified order
"""
for specifier in specifiers:
if isinstance(specifier, Locality):
# localities can carry multiple loaders, flatten this
yield from _LOADERS[specifier]
else:
# something not a locality, pass along verbatim
yield specifier | python | def loaders(*specifiers):
"""
Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load order using predefined user-local locations,
# an explicit path, a template and a user-defined function
load_order = loaders(Locality.user,
'/etc/defaults/hard-coded.yaml',
'/path/to/{name}.{extension}',
my_loader)
# load configuration for name 'my-application' using the load order
# defined above
config = load_name('my-application', load_order=load_order)
:param specifiers:
:return: a `generator` of configuration loaders in the specified order
"""
for specifier in specifiers:
if isinstance(specifier, Locality):
# localities can carry multiple loaders, flatten this
yield from _LOADERS[specifier]
else:
# something not a locality, pass along verbatim
yield specifier | [
"def",
"loaders",
"(",
"*",
"specifiers",
")",
":",
"for",
"specifier",
"in",
"specifiers",
":",
"if",
"isinstance",
"(",
"specifier",
",",
"Locality",
")",
":",
"# localities can carry multiple loaders, flatten this",
"yield",
"from",
"_LOADERS",
"[",
"specifier",
... | Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load order using predefined user-local locations,
# an explicit path, a template and a user-defined function
load_order = loaders(Locality.user,
'/etc/defaults/hard-coded.yaml',
'/path/to/{name}.{extension}',
my_loader)
# load configuration for name 'my-application' using the load order
# defined above
config = load_name('my-application', load_order=load_order)
:param specifiers:
:return: a `generator` of configuration loaders in the specified order | [
"Generates",
"loaders",
"in",
"the",
"specified",
"order",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L184-L214 | train | 52,547 |
HolmesNL/confidence | confidence/io.py | load | def load(*fps, missing=Missing.silent):
"""
Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fps*
:rtype: `.Configuration`
"""
return Configuration(*(yaml.safe_load(fp.read()) for fp in fps), missing=missing) | python | def load(*fps, missing=Missing.silent):
"""
Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fps*
:rtype: `.Configuration`
"""
return Configuration(*(yaml.safe_load(fp.read()) for fp in fps), missing=missing) | [
"def",
"load",
"(",
"*",
"fps",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"return",
"Configuration",
"(",
"*",
"(",
"yaml",
".",
"safe_load",
"(",
"fp",
".",
"read",
"(",
")",
")",
"for",
"fp",
"in",
"fps",
")",
",",
"missing",
"="... | Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fps*
:rtype: `.Configuration` | [
"Read",
"a",
".",
"Configuration",
"instance",
"from",
"file",
"-",
"like",
"objects",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L223-L233 | train | 52,548 |
HolmesNL/confidence | confidence/io.py | loadf | def loadf(*fnames, default=_NoDefault, missing=Missing.silent):
"""
Read a `.Configuration` instance from named files.
:param fnames: name of the files to ``open()``
:param default: `dict` or `.Configuration` to use when a file does not
exist (default is to raise a `FileNotFoundError`)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fnames*
:rtype: `.Configuration`
"""
def readf(fname):
if default is _NoDefault or path.exists(fname):
# (attempt to) open fname if it exists OR if we're expected to raise an error on a missing file
with open(fname, 'r') as fp:
# default to empty dict, yaml.safe_load will return None for an empty document
return yaml.safe_load(fp.read()) or {}
else:
return default
return Configuration(*(readf(path.expanduser(fname)) for fname in fnames), missing=missing) | python | def loadf(*fnames, default=_NoDefault, missing=Missing.silent):
"""
Read a `.Configuration` instance from named files.
:param fnames: name of the files to ``open()``
:param default: `dict` or `.Configuration` to use when a file does not
exist (default is to raise a `FileNotFoundError`)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fnames*
:rtype: `.Configuration`
"""
def readf(fname):
if default is _NoDefault or path.exists(fname):
# (attempt to) open fname if it exists OR if we're expected to raise an error on a missing file
with open(fname, 'r') as fp:
# default to empty dict, yaml.safe_load will return None for an empty document
return yaml.safe_load(fp.read()) or {}
else:
return default
return Configuration(*(readf(path.expanduser(fname)) for fname in fnames), missing=missing) | [
"def",
"loadf",
"(",
"*",
"fnames",
",",
"default",
"=",
"_NoDefault",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"def",
"readf",
"(",
"fname",
")",
":",
"if",
"default",
"is",
"_NoDefault",
"or",
"path",
".",
"exists",
"(",
"fname",
")... | Read a `.Configuration` instance from named files.
:param fnames: name of the files to ``open()``
:param default: `dict` or `.Configuration` to use when a file does not
exist (default is to raise a `FileNotFoundError`)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *fnames*
:rtype: `.Configuration` | [
"Read",
"a",
".",
"Configuration",
"instance",
"from",
"named",
"files",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L236-L257 | train | 52,549 |
HolmesNL/confidence | confidence/io.py | loads | def loads(*strings, missing=Missing.silent):
"""
Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *strings*
:rtype: `.Configuration`
"""
return Configuration(*(yaml.safe_load(string) for string in strings), missing=missing) | python | def loads(*strings, missing=Missing.silent):
"""
Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *strings*
:rtype: `.Configuration`
"""
return Configuration(*(yaml.safe_load(string) for string in strings), missing=missing) | [
"def",
"loads",
"(",
"*",
"strings",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"return",
"Configuration",
"(",
"*",
"(",
"yaml",
".",
"safe_load",
"(",
"string",
")",
"for",
"string",
"in",
"strings",
")",
",",
"missing",
"=",
"missing",... | Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance providing values from *strings*
:rtype: `.Configuration` | [
"Read",
"a",
".",
"Configuration",
"instance",
"from",
"strings",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L260-L270 | train | 52,550 |
HolmesNL/confidence | confidence/io.py | load_name | def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent):
"""
Read a `.Configuration` instance by name, trying to read from files in
increasing significance. The default load order is `.system`, `.user`,
`.application`, `.environment`.
Multiple names are combined with multiple loaders using names as the 'inner
loop / selector', loading ``/etc/name1.yaml`` and ``/etc/name2.yaml``
before ``./name1.yaml`` and ``./name2.yaml``.
:param names: application or configuration set names, in increasing
significance
:param load_order: ordered list of name templates or `callable`s, in
increasing order of significance
:param extension: file extension to be used
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instances providing values loaded from *names*
in *load_order* ordering
"""
def generate_sources():
# argument order for product matters, for names "foo" and "bar":
# /etc/foo.yaml before /etc/bar.yaml, but both of them before ~/.foo.yaml and ~/.bar.yaml
for source, name in product(load_order, names):
if callable(source):
yield source(name, extension)
else:
# expand user to turn ~/.name.yaml into /home/user/.name.yaml
candidate = path.expanduser(source.format(name=name, extension=extension))
yield loadf(candidate, default=NotConfigured)
return Configuration(*generate_sources(), missing=missing) | python | def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent):
"""
Read a `.Configuration` instance by name, trying to read from files in
increasing significance. The default load order is `.system`, `.user`,
`.application`, `.environment`.
Multiple names are combined with multiple loaders using names as the 'inner
loop / selector', loading ``/etc/name1.yaml`` and ``/etc/name2.yaml``
before ``./name1.yaml`` and ``./name2.yaml``.
:param names: application or configuration set names, in increasing
significance
:param load_order: ordered list of name templates or `callable`s, in
increasing order of significance
:param extension: file extension to be used
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instances providing values loaded from *names*
in *load_order* ordering
"""
def generate_sources():
# argument order for product matters, for names "foo" and "bar":
# /etc/foo.yaml before /etc/bar.yaml, but both of them before ~/.foo.yaml and ~/.bar.yaml
for source, name in product(load_order, names):
if callable(source):
yield source(name, extension)
else:
# expand user to turn ~/.name.yaml into /home/user/.name.yaml
candidate = path.expanduser(source.format(name=name, extension=extension))
yield loadf(candidate, default=NotConfigured)
return Configuration(*generate_sources(), missing=missing) | [
"def",
"load_name",
"(",
"*",
"names",
",",
"load_order",
"=",
"DEFAULT_LOAD_ORDER",
",",
"extension",
"=",
"'yaml'",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"def",
"generate_sources",
"(",
")",
":",
"# argument order for product matters, for name... | Read a `.Configuration` instance by name, trying to read from files in
increasing significance. The default load order is `.system`, `.user`,
`.application`, `.environment`.
Multiple names are combined with multiple loaders using names as the 'inner
loop / selector', loading ``/etc/name1.yaml`` and ``/etc/name2.yaml``
before ``./name1.yaml`` and ``./name2.yaml``.
:param names: application or configuration set names, in increasing
significance
:param load_order: ordered list of name templates or `callable`s, in
increasing order of significance
:param extension: file extension to be used
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instances providing values loaded from *names*
in *load_order* ordering | [
"Read",
"a",
".",
"Configuration",
"instance",
"by",
"name",
"trying",
"to",
"read",
"from",
"files",
"in",
"increasing",
"significance",
".",
"The",
"default",
"load",
"order",
"is",
".",
"system",
".",
"user",
".",
"application",
".",
"environment",
"."
] | e14d2d8769a01fa55676716f7a2f22714c2616d3 | https://github.com/HolmesNL/confidence/blob/e14d2d8769a01fa55676716f7a2f22714c2616d3/confidence/io.py#L273-L304 | train | 52,551 |
hassa/BeatCop | beatcop.py | Lock.acquire | def acquire(self, block=True):
"""Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired."""
while True:
# Try to set the lock
if self.redis.set(self.name, self.value, px=self.timeout, nx=True):
# It's ours until the timeout now
return True
# Lock is taken
if not block:
return False
# If blocking, try again in a bit
time.sleep(self.sleep) | python | def acquire(self, block=True):
"""Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired."""
while True:
# Try to set the lock
if self.redis.set(self.name, self.value, px=self.timeout, nx=True):
# It's ours until the timeout now
return True
# Lock is taken
if not block:
return False
# If blocking, try again in a bit
time.sleep(self.sleep) | [
"def",
"acquire",
"(",
"self",
",",
"block",
"=",
"True",
")",
":",
"while",
"True",
":",
"# Try to set the lock",
"if",
"self",
".",
"redis",
".",
"set",
"(",
"self",
".",
"name",
",",
"self",
".",
"value",
",",
"px",
"=",
"self",
".",
"timeout",
... | Acquire lock. Blocks until acquired if `block` is `True`, otherwise returns `False` if the lock could not be acquired. | [
"Acquire",
"lock",
".",
"Blocks",
"until",
"acquired",
"if",
"block",
"is",
"True",
"otherwise",
"returns",
"False",
"if",
"the",
"lock",
"could",
"not",
"be",
"acquired",
"."
] | bf7721e17a7828728b15c5833f047d858111197c | https://github.com/hassa/BeatCop/blob/bf7721e17a7828728b15c5833f047d858111197c/beatcop.py#L59-L70 | train | 52,552 |
hassa/BeatCop | beatcop.py | BeatCop.run | def run(self):
"""Run process if nobody else is, otherwise wait until we're needed. Never returns."""
log.info("Waiting for lock, currently held by %s", self.lock.who())
if self.lock.acquire():
log.info("Lock '%s' acquired", self.lockname)
# We got the lock, so we make sure the process is running and keep refreshing the lock - if we ever stop for any reason, for example because our host died, the lock will soon expire.
while True:
if self.process is None: # Process not spawned yet
self.process = self.spawn(self.command)
log.info("Spawned PID %d", self.process.pid)
child_status = self.process.poll()
if child_status is not None:
# Oops, process died on us.
log.error("Child died with exit code %d", child_status)
sys.exit(1)
# Refresh lock and sleep
if not self.lock.refresh():
who = self.lock.who()
if who is None:
if self.lock.acquire(block=False):
log.warning("Lock refresh failed, but successfully re-acquired unclaimed lock")
else:
log.error("Lock refresh and subsequent re-acquire failed, giving up (Lock now held by %s)", self.lock.who())
self.cleanup()
sys.exit(os.EX_UNAVAILABLE)
else:
log.error("Lock refresh failed, %s stole it - bailing out", self.lock.who())
self.cleanup()
sys.exit(os.EX_UNAVAILABLE)
time.sleep(self.sleep) | python | def run(self):
"""Run process if nobody else is, otherwise wait until we're needed. Never returns."""
log.info("Waiting for lock, currently held by %s", self.lock.who())
if self.lock.acquire():
log.info("Lock '%s' acquired", self.lockname)
# We got the lock, so we make sure the process is running and keep refreshing the lock - if we ever stop for any reason, for example because our host died, the lock will soon expire.
while True:
if self.process is None: # Process not spawned yet
self.process = self.spawn(self.command)
log.info("Spawned PID %d", self.process.pid)
child_status = self.process.poll()
if child_status is not None:
# Oops, process died on us.
log.error("Child died with exit code %d", child_status)
sys.exit(1)
# Refresh lock and sleep
if not self.lock.refresh():
who = self.lock.who()
if who is None:
if self.lock.acquire(block=False):
log.warning("Lock refresh failed, but successfully re-acquired unclaimed lock")
else:
log.error("Lock refresh and subsequent re-acquire failed, giving up (Lock now held by %s)", self.lock.who())
self.cleanup()
sys.exit(os.EX_UNAVAILABLE)
else:
log.error("Lock refresh failed, %s stole it - bailing out", self.lock.who())
self.cleanup()
sys.exit(os.EX_UNAVAILABLE)
time.sleep(self.sleep) | [
"def",
"run",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Waiting for lock, currently held by %s\"",
",",
"self",
".",
"lock",
".",
"who",
"(",
")",
")",
"if",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"Loc... | Run process if nobody else is, otherwise wait until we're needed. Never returns. | [
"Run",
"process",
"if",
"nobody",
"else",
"is",
"otherwise",
"wait",
"until",
"we",
"re",
"needed",
".",
"Never",
"returns",
"."
] | bf7721e17a7828728b15c5833f047d858111197c | https://github.com/hassa/BeatCop/blob/bf7721e17a7828728b15c5833f047d858111197c/beatcop.py#L140-L170 | train | 52,553 |
hassa/BeatCop | beatcop.py | BeatCop.spawn | def spawn(self, command):
"""Spawn process."""
if self.shell:
args = command
else:
args = shlex.split(command)
return subprocess.Popen(args, shell=self.shell) | python | def spawn(self, command):
"""Spawn process."""
if self.shell:
args = command
else:
args = shlex.split(command)
return subprocess.Popen(args, shell=self.shell) | [
"def",
"spawn",
"(",
"self",
",",
"command",
")",
":",
"if",
"self",
".",
"shell",
":",
"args",
"=",
"command",
"else",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"command",
")",
"return",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"shell",
"... | Spawn process. | [
"Spawn",
"process",
"."
] | bf7721e17a7828728b15c5833f047d858111197c | https://github.com/hassa/BeatCop/blob/bf7721e17a7828728b15c5833f047d858111197c/beatcop.py#L172-L178 | train | 52,554 |
hassa/BeatCop | beatcop.py | BeatCop.cleanup | def cleanup(self):
"""Clean up, making sure the process is stopped before we pack up and go home."""
if self.process is None: # Process wasn't running yet, so nothing to worry about
return
if self.process.poll() is None:
log.info("Sending TERM to %d", self.process.pid)
self.process.terminate()
# Give process a second to terminate, if it didn't, kill it.
start = time.clock()
while time.clock() - start < 1.0:
time.sleep(0.05)
if self.process.poll() is not None:
break
else:
log.info("Sending KILL to %d", self.process.pid)
self.process.kill()
assert self.process.poll() is not None | python | def cleanup(self):
"""Clean up, making sure the process is stopped before we pack up and go home."""
if self.process is None: # Process wasn't running yet, so nothing to worry about
return
if self.process.poll() is None:
log.info("Sending TERM to %d", self.process.pid)
self.process.terminate()
# Give process a second to terminate, if it didn't, kill it.
start = time.clock()
while time.clock() - start < 1.0:
time.sleep(0.05)
if self.process.poll() is not None:
break
else:
log.info("Sending KILL to %d", self.process.pid)
self.process.kill()
assert self.process.poll() is not None | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"process",
"is",
"None",
":",
"# Process wasn't running yet, so nothing to worry about",
"return",
"if",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"log",
".",
"info",
"(",
... | Clean up, making sure the process is stopped before we pack up and go home. | [
"Clean",
"up",
"making",
"sure",
"the",
"process",
"is",
"stopped",
"before",
"we",
"pack",
"up",
"and",
"go",
"home",
"."
] | bf7721e17a7828728b15c5833f047d858111197c | https://github.com/hassa/BeatCop/blob/bf7721e17a7828728b15c5833f047d858111197c/beatcop.py#L180-L196 | train | 52,555 |
hassa/BeatCop | beatcop.py | BeatCop.handle_signal | def handle_signal(self, sig, frame):
"""Handles signals, surprisingly."""
if sig in [signal.SIGINT]:
log.warning("Ctrl-C pressed, shutting down...")
if sig in [signal.SIGTERM]:
log.warning("SIGTERM received, shutting down...")
self.cleanup()
sys.exit(-sig) | python | def handle_signal(self, sig, frame):
"""Handles signals, surprisingly."""
if sig in [signal.SIGINT]:
log.warning("Ctrl-C pressed, shutting down...")
if sig in [signal.SIGTERM]:
log.warning("SIGTERM received, shutting down...")
self.cleanup()
sys.exit(-sig) | [
"def",
"handle_signal",
"(",
"self",
",",
"sig",
",",
"frame",
")",
":",
"if",
"sig",
"in",
"[",
"signal",
".",
"SIGINT",
"]",
":",
"log",
".",
"warning",
"(",
"\"Ctrl-C pressed, shutting down...\"",
")",
"if",
"sig",
"in",
"[",
"signal",
".",
"SIGTERM",... | Handles signals, surprisingly. | [
"Handles",
"signals",
"surprisingly",
"."
] | bf7721e17a7828728b15c5833f047d858111197c | https://github.com/hassa/BeatCop/blob/bf7721e17a7828728b15c5833f047d858111197c/beatcop.py#L198-L205 | train | 52,556 |
alfredodeza/notario | notario/engine.py | validate | def validate(data, schema, defined_keys=False):
"""
Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against
"""
if isinstance(data, dict):
validator = Validator(data, schema, defined_keys=defined_keys)
validator.validate()
else:
raise TypeError('expected data to be of type dict, but got: %s' % type(data)) | python | def validate(data, schema, defined_keys=False):
"""
Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against
"""
if isinstance(data, dict):
validator = Validator(data, schema, defined_keys=defined_keys)
validator.validate()
else:
raise TypeError('expected data to be of type dict, but got: %s' % type(data)) | [
"def",
"validate",
"(",
"data",
",",
"schema",
",",
"defined_keys",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"validator",
"=",
"Validator",
"(",
"data",
",",
"schema",
",",
"defined_keys",
"=",
"defined_keys",
")",
... | Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against | [
"Main",
"entry",
"point",
"for",
"the",
"validation",
"engine",
"."
] | d5dc2edfcb75d9291ced3f2551f368c35dd31475 | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L343-L354 | train | 52,557 |
RowleyGroup/pyqueue | pyqueue/utils.py | strfdelta | def strfdelta(tdelta, fmt):
"""
Used to format `datetime.timedelta` objects. Works just like `strftime`
>>> strfdelta(duration, '%H:%M:%S')
param tdelta: Time duration which is an instance of datetime.timedelta
param fmt: The pattern to format the timedelta with
rtype: str
"""
substitutes = dict()
hours, rem = divmod(tdelta.total_seconds(), 3600)
minutes, seconds = divmod(rem, 60)
substitutes["H"] = '{:02d}'.format(int(hours))
substitutes["M"] = '{:02d}'.format(int(minutes))
substitutes["S"] = '{:02d}'.format(int(seconds))
return DeltaTemplate(fmt).substitute(**substitutes) | python | def strfdelta(tdelta, fmt):
"""
Used to format `datetime.timedelta` objects. Works just like `strftime`
>>> strfdelta(duration, '%H:%M:%S')
param tdelta: Time duration which is an instance of datetime.timedelta
param fmt: The pattern to format the timedelta with
rtype: str
"""
substitutes = dict()
hours, rem = divmod(tdelta.total_seconds(), 3600)
minutes, seconds = divmod(rem, 60)
substitutes["H"] = '{:02d}'.format(int(hours))
substitutes["M"] = '{:02d}'.format(int(minutes))
substitutes["S"] = '{:02d}'.format(int(seconds))
return DeltaTemplate(fmt).substitute(**substitutes) | [
"def",
"strfdelta",
"(",
"tdelta",
",",
"fmt",
")",
":",
"substitutes",
"=",
"dict",
"(",
")",
"hours",
",",
"rem",
"=",
"divmod",
"(",
"tdelta",
".",
"total_seconds",
"(",
")",
",",
"3600",
")",
"minutes",
",",
"seconds",
"=",
"divmod",
"(",
"rem",
... | Used to format `datetime.timedelta` objects. Works just like `strftime`
>>> strfdelta(duration, '%H:%M:%S')
param tdelta: Time duration which is an instance of datetime.timedelta
param fmt: The pattern to format the timedelta with
rtype: str | [
"Used",
"to",
"format",
"datetime",
".",
"timedelta",
"objects",
".",
"Works",
"just",
"like",
"strftime"
] | 24de6e1b06b9626ed94d0d5a859bc71bd3afbb4f | https://github.com/RowleyGroup/pyqueue/blob/24de6e1b06b9626ed94d0d5a859bc71bd3afbb4f/pyqueue/utils.py#L15-L32 | train | 52,558 |
RowleyGroup/pyqueue | pyqueue/utils.py | get_user_information | def get_user_information():
"""
Returns the user's information
:rtype: (str, int, str)
"""
try:
import pwd
_username = pwd.getpwuid(os.getuid())[0]
_userid = os.getuid()
_uname = os.uname()[1]
except ImportError:
import getpass
_username = getpass.getuser()
_userid = 0
import platform
_uname = platform.node()
return _username, _userid, _uname | python | def get_user_information():
"""
Returns the user's information
:rtype: (str, int, str)
"""
try:
import pwd
_username = pwd.getpwuid(os.getuid())[0]
_userid = os.getuid()
_uname = os.uname()[1]
except ImportError:
import getpass
_username = getpass.getuser()
_userid = 0
import platform
_uname = platform.node()
return _username, _userid, _uname | [
"def",
"get_user_information",
"(",
")",
":",
"try",
":",
"import",
"pwd",
"_username",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
"[",
"0",
"]",
"_userid",
"=",
"os",
".",
"getuid",
"(",
")",
"_uname",
"=",
"os",
".",
... | Returns the user's information
:rtype: (str, int, str) | [
"Returns",
"the",
"user",
"s",
"information"
] | 24de6e1b06b9626ed94d0d5a859bc71bd3afbb4f | https://github.com/RowleyGroup/pyqueue/blob/24de6e1b06b9626ed94d0d5a859bc71bd3afbb4f/pyqueue/utils.py#L35-L53 | train | 52,559 |
oceanprotocol/osmosis-azure-driver | osmosis_azure_driver/computing_plugin.py | Plugin.list_container_groups | def list_container_groups(self, resource_group_name):
"""Lists the container groups in the specified resource group.
Arguments:
aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
-- An authenticated container instance management client.
resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
-- The resource group containing the container group(s).
"""
print("Listing container groups in resource group '{0}'...".format(resource_group_name))
container_groups = self.client.container_groups.list_by_resource_group(resource_group_name)
for container_group in container_groups:
print(" {0}".format(container_group.name)) | python | def list_container_groups(self, resource_group_name):
"""Lists the container groups in the specified resource group.
Arguments:
aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
-- An authenticated container instance management client.
resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
-- The resource group containing the container group(s).
"""
print("Listing container groups in resource group '{0}'...".format(resource_group_name))
container_groups = self.client.container_groups.list_by_resource_group(resource_group_name)
for container_group in container_groups:
print(" {0}".format(container_group.name)) | [
"def",
"list_container_groups",
"(",
"self",
",",
"resource_group_name",
")",
":",
"print",
"(",
"\"Listing container groups in resource group '{0}'...\"",
".",
"format",
"(",
"resource_group_name",
")",
")",
"container_groups",
"=",
"self",
".",
"client",
".",
"contain... | Lists the container groups in the specified resource group.
Arguments:
aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
-- An authenticated container instance management client.
resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
-- The resource group containing the container group(s). | [
"Lists",
"the",
"container",
"groups",
"in",
"the",
"specified",
"resource",
"group",
"."
] | 36bcfa96547fb6117346b02b0ac6a74345c59695 | https://github.com/oceanprotocol/osmosis-azure-driver/blob/36bcfa96547fb6117346b02b0ac6a74345c59695/osmosis_azure_driver/computing_plugin.py#L210-L224 | train | 52,560 |
juiceinc/recipe | recipe/ingredients.py | Dimension.cauldron_extras | def cauldron_extras(self):
""" Yield extra tuples containing a field name and a callable that takes
a row
"""
for extra in super(Dimension, self).cauldron_extras:
yield extra
if self.formatters:
prop = self.id + '_raw'
else:
prop = self.id_prop
yield self.id + '_id', lambda row: getattr(row, prop) | python | def cauldron_extras(self):
""" Yield extra tuples containing a field name and a callable that takes
a row
"""
for extra in super(Dimension, self).cauldron_extras:
yield extra
if self.formatters:
prop = self.id + '_raw'
else:
prop = self.id_prop
yield self.id + '_id', lambda row: getattr(row, prop) | [
"def",
"cauldron_extras",
"(",
"self",
")",
":",
"for",
"extra",
"in",
"super",
"(",
"Dimension",
",",
"self",
")",
".",
"cauldron_extras",
":",
"yield",
"extra",
"if",
"self",
".",
"formatters",
":",
"prop",
"=",
"self",
".",
"id",
"+",
"'_raw'",
"els... | Yield extra tuples containing a field name and a callable that takes
a row | [
"Yield",
"extra",
"tuples",
"containing",
"a",
"field",
"name",
"and",
"a",
"callable",
"that",
"takes",
"a",
"row"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/ingredients.py#L280-L292 | train | 52,561 |
juiceinc/recipe | recipe/ingredients.py | Dimension.make_column_suffixes | def make_column_suffixes(self):
""" Make sure we have the right column suffixes. These will be appended
to `id` when generating the query.
"""
if self.column_suffixes:
return self.column_suffixes
if len(self.columns) == 0:
return ()
elif len(self.columns) == 1:
if self.formatters:
return '_raw',
else:
return '',
elif len(self.columns) == 2:
if self.formatters:
return '_id', '_raw',
else:
return '_id', '',
else:
raise BadIngredient(
'column_suffixes must be supplied if there is '
'more than one column'
) | python | def make_column_suffixes(self):
""" Make sure we have the right column suffixes. These will be appended
to `id` when generating the query.
"""
if self.column_suffixes:
return self.column_suffixes
if len(self.columns) == 0:
return ()
elif len(self.columns) == 1:
if self.formatters:
return '_raw',
else:
return '',
elif len(self.columns) == 2:
if self.formatters:
return '_id', '_raw',
else:
return '_id', '',
else:
raise BadIngredient(
'column_suffixes must be supplied if there is '
'more than one column'
) | [
"def",
"make_column_suffixes",
"(",
"self",
")",
":",
"if",
"self",
".",
"column_suffixes",
":",
"return",
"self",
".",
"column_suffixes",
"if",
"len",
"(",
"self",
".",
"columns",
")",
"==",
"0",
":",
"return",
"(",
")",
"elif",
"len",
"(",
"self",
".... | Make sure we have the right column suffixes. These will be appended
to `id` when generating the query. | [
"Make",
"sure",
"we",
"have",
"the",
"right",
"column",
"suffixes",
".",
"These",
"will",
"be",
"appended",
"to",
"id",
"when",
"generating",
"the",
"query",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/ingredients.py#L294-L319 | train | 52,562 |
juiceinc/recipe | recipe/shelf.py | parse_condition | def parse_condition(
cond, selectable, aggregated=False, default_aggregation='sum'
):
"""Create a SQLAlchemy clause from a condition."""
if cond is None:
return None
else:
if 'and' in cond:
conditions = [
parse_condition(
c, selectable, aggregated, default_aggregation
) for c in cond['and']
]
return and_(*conditions)
elif 'or' in cond:
conditions = [
parse_condition(
c, selectable, aggregated, default_aggregation
) for c in cond['or']
]
return or_(*conditions)
elif 'field' not in cond:
raise BadIngredient('field must be defined in condition')
field = parse_field(
cond['field'],
selectable,
aggregated=aggregated,
default_aggregation=default_aggregation
)
if 'in' in cond:
value = cond['in']
if isinstance(value, dict):
raise BadIngredient('value for in must be a list')
condition_expression = getattr(field, 'in_')(tuple(value))
elif 'gt' in cond:
value = cond['gt']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__gt__')(value)
elif 'gte' in cond:
value = cond['gte']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__ge__')(value)
elif 'lt' in cond:
value = cond['lt']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__lt__')(value)
elif 'lte' in cond:
value = cond['lte']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__le__')(value)
elif 'eq' in cond:
value = cond['eq']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__eq__')(value)
elif 'ne' in cond:
value = cond['ne']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__ne__')(value)
else:
raise BadIngredient('Bad condition')
return condition_expression | python | def parse_condition(
cond, selectable, aggregated=False, default_aggregation='sum'
):
"""Create a SQLAlchemy clause from a condition."""
if cond is None:
return None
else:
if 'and' in cond:
conditions = [
parse_condition(
c, selectable, aggregated, default_aggregation
) for c in cond['and']
]
return and_(*conditions)
elif 'or' in cond:
conditions = [
parse_condition(
c, selectable, aggregated, default_aggregation
) for c in cond['or']
]
return or_(*conditions)
elif 'field' not in cond:
raise BadIngredient('field must be defined in condition')
field = parse_field(
cond['field'],
selectable,
aggregated=aggregated,
default_aggregation=default_aggregation
)
if 'in' in cond:
value = cond['in']
if isinstance(value, dict):
raise BadIngredient('value for in must be a list')
condition_expression = getattr(field, 'in_')(tuple(value))
elif 'gt' in cond:
value = cond['gt']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__gt__')(value)
elif 'gte' in cond:
value = cond['gte']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__ge__')(value)
elif 'lt' in cond:
value = cond['lt']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__lt__')(value)
elif 'lte' in cond:
value = cond['lte']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__le__')(value)
elif 'eq' in cond:
value = cond['eq']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__eq__')(value)
elif 'ne' in cond:
value = cond['ne']
if isinstance(value, (list, dict)):
raise BadIngredient('conditional value must be a scalar')
condition_expression = getattr(field, '__ne__')(value)
else:
raise BadIngredient('Bad condition')
return condition_expression | [
"def",
"parse_condition",
"(",
"cond",
",",
"selectable",
",",
"aggregated",
"=",
"False",
",",
"default_aggregation",
"=",
"'sum'",
")",
":",
"if",
"cond",
"is",
"None",
":",
"return",
"None",
"else",
":",
"if",
"'and'",
"in",
"cond",
":",
"conditions",
... | Create a SQLAlchemy clause from a condition. | [
"Create",
"a",
"SQLAlchemy",
"clause",
"from",
"a",
"condition",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L32-L100 | train | 52,563 |
juiceinc/recipe | recipe/shelf.py | tokenize | def tokenize(s):
""" Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', 'PLUS', 'that']
>>> tokenize('this+that')
['this', 'PLUS', 'that']
>>> tokenize('this+that-other')
['this', 'PLUS', 'that', 'MINUS', 'other']
"""
# Crude tokenization
s = s.replace('+', ' PLUS ').replace('-', ' MINUS ') \
.replace('/', ' DIVIDE ').replace('*', ' MULTIPLY ')
words = [w for w in s.split(' ') if w]
return words | python | def tokenize(s):
""" Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', 'PLUS', 'that']
>>> tokenize('this+that')
['this', 'PLUS', 'that']
>>> tokenize('this+that-other')
['this', 'PLUS', 'that', 'MINUS', 'other']
"""
# Crude tokenization
s = s.replace('+', ' PLUS ').replace('-', ' MINUS ') \
.replace('/', ' DIVIDE ').replace('*', ' MULTIPLY ')
words = [w for w in s.split(' ') if w]
return words | [
"def",
"tokenize",
"(",
"s",
")",
":",
"# Crude tokenization",
"s",
"=",
"s",
".",
"replace",
"(",
"'+'",
",",
"' PLUS '",
")",
".",
"replace",
"(",
"'-'",
",",
"' MINUS '",
")",
".",
"replace",
"(",
"'/'",
",",
"' DIVIDE '",
")",
".",
"replace",
"("... | Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', 'PLUS', 'that']
>>> tokenize('this+that')
['this', 'PLUS', 'that']
>>> tokenize('this+that-other')
['this', 'PLUS', 'that', 'MINUS', 'other'] | [
"Tokenize",
"a",
"string",
"by",
"splitting",
"it",
"by",
"+",
"and",
"-"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L103-L120 | train | 52,564 |
juiceinc/recipe | recipe/shelf.py | _find_in_columncollection | def _find_in_columncollection(columns, name):
""" Find a column in a column collection by name or _label"""
for col in columns:
if col.name == name or getattr(col, '_label', None) == name:
return col
return None | python | def _find_in_columncollection(columns, name):
""" Find a column in a column collection by name or _label"""
for col in columns:
if col.name == name or getattr(col, '_label', None) == name:
return col
return None | [
"def",
"_find_in_columncollection",
"(",
"columns",
",",
"name",
")",
":",
"for",
"col",
"in",
"columns",
":",
"if",
"col",
".",
"name",
"==",
"name",
"or",
"getattr",
"(",
"col",
",",
"'_label'",
",",
"None",
")",
"==",
"name",
":",
"return",
"col",
... | Find a column in a column collection by name or _label | [
"Find",
"a",
"column",
"in",
"a",
"column",
"collection",
"by",
"name",
"or",
"_label"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L123-L128 | train | 52,565 |
juiceinc/recipe | recipe/shelf.py | find_column | def find_column(selectable, name):
"""
Find a column named `name` in selectable
:param selectable:
:param name:
:return: A column object
"""
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
# Selectable is a table
if isinstance(selectable, DeclarativeMeta):
col = getattr(selectable, name, None)
if col is not None:
return col
col = _find_in_columncollection(selectable.__table__.columns, name)
if col is not None:
return col
# Selectable is a sqlalchemy subquery
elif hasattr(selectable, 'c'
) and isinstance(selectable.c, ImmutableColumnCollection):
col = getattr(selectable.c, name, None)
if col is not None:
return col
col = _find_in_columncollection(selectable.c, name)
if col is not None:
return col
raise BadIngredient('Can not find {} in {}'.format(name, selectable)) | python | def find_column(selectable, name):
"""
Find a column named `name` in selectable
:param selectable:
:param name:
:return: A column object
"""
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
# Selectable is a table
if isinstance(selectable, DeclarativeMeta):
col = getattr(selectable, name, None)
if col is not None:
return col
col = _find_in_columncollection(selectable.__table__.columns, name)
if col is not None:
return col
# Selectable is a sqlalchemy subquery
elif hasattr(selectable, 'c'
) and isinstance(selectable.c, ImmutableColumnCollection):
col = getattr(selectable.c, name, None)
if col is not None:
return col
col = _find_in_columncollection(selectable.c, name)
if col is not None:
return col
raise BadIngredient('Can not find {} in {}'.format(name, selectable)) | [
"def",
"find_column",
"(",
"selectable",
",",
"name",
")",
":",
"from",
"recipe",
"import",
"Recipe",
"if",
"isinstance",
"(",
"selectable",
",",
"Recipe",
")",
":",
"selectable",
"=",
"selectable",
".",
"subquery",
"(",
")",
"# Selectable is a table",
"if",
... | Find a column named `name` in selectable
:param selectable:
:param name:
:return: A column object | [
"Find",
"a",
"column",
"named",
"name",
"in",
"selectable"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L131-L165 | train | 52,566 |
juiceinc/recipe | recipe/shelf.py | parse_validated_field | def parse_validated_field(fld, selectable):
""" Converts a validated field to sqlalchemy. Field references are
looked up in selectable """
aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']]
field = find_column(selectable, fld['value'])
for operator in fld.get('operators', []):
op = operator['operator']
other_field = parse_validated_field(operator['field'], selectable)
field = IngredientValidator.operator_lookup[op](field)(other_field)
condition = fld.get('condition', None)
if condition:
condition = parse_condition(condition, selectable)
field = case([(condition, field)])
field = aggr_fn(field)
return field | python | def parse_validated_field(fld, selectable):
""" Converts a validated field to sqlalchemy. Field references are
looked up in selectable """
aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']]
field = find_column(selectable, fld['value'])
for operator in fld.get('operators', []):
op = operator['operator']
other_field = parse_validated_field(operator['field'], selectable)
field = IngredientValidator.operator_lookup[op](field)(other_field)
condition = fld.get('condition', None)
if condition:
condition = parse_condition(condition, selectable)
field = case([(condition, field)])
field = aggr_fn(field)
return field | [
"def",
"parse_validated_field",
"(",
"fld",
",",
"selectable",
")",
":",
"aggr_fn",
"=",
"IngredientValidator",
".",
"aggregation_lookup",
"[",
"fld",
"[",
"'aggregation'",
"]",
"]",
"field",
"=",
"find_column",
"(",
"selectable",
",",
"fld",
"[",
"'value'",
"... | Converts a validated field to sqlalchemy. Field references are
looked up in selectable | [
"Converts",
"a",
"validated",
"field",
"to",
"sqlalchemy",
".",
"Field",
"references",
"are",
"looked",
"up",
"in",
"selectable"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L371-L389 | train | 52,567 |
juiceinc/recipe | recipe/shelf.py | AutomaticShelf | def AutomaticShelf(table):
"""Given a SQLAlchemy Table, automatically generate a Shelf with metrics
and dimensions based on its schema.
"""
if hasattr(table, '__table__'):
table = table.__table__
config = introspect_table(table)
return Shelf.from_config(config, table) | python | def AutomaticShelf(table):
"""Given a SQLAlchemy Table, automatically generate a Shelf with metrics
and dimensions based on its schema.
"""
if hasattr(table, '__table__'):
table = table.__table__
config = introspect_table(table)
return Shelf.from_config(config, table) | [
"def",
"AutomaticShelf",
"(",
"table",
")",
":",
"if",
"hasattr",
"(",
"table",
",",
"'__table__'",
")",
":",
"table",
"=",
"table",
".",
"__table__",
"config",
"=",
"introspect_table",
"(",
"table",
")",
"return",
"Shelf",
".",
"from_config",
"(",
"config... | Given a SQLAlchemy Table, automatically generate a Shelf with metrics
and dimensions based on its schema. | [
"Given",
"a",
"SQLAlchemy",
"Table",
"automatically",
"generate",
"a",
"Shelf",
"with",
"metrics",
"and",
"dimensions",
"based",
"on",
"its",
"schema",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L764-L771 | train | 52,568 |
juiceinc/recipe | recipe/shelf.py | introspect_table | def introspect_table(table):
"""Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config.
"""
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type, (Integer, Float)):
d[c.name] = {'kind': 'Metric', 'field': c.name}
return d | python | def introspect_table(table):
"""Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config.
"""
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type, (Integer, Float)):
d[c.name] = {'kind': 'Metric', 'field': c.name}
return d | [
"def",
"introspect_table",
"(",
"table",
")",
":",
"d",
"=",
"{",
"}",
"for",
"c",
"in",
"table",
".",
"columns",
":",
"if",
"isinstance",
"(",
"c",
".",
"type",
",",
"String",
")",
":",
"d",
"[",
"c",
".",
"name",
"]",
"=",
"{",
"'kind'",
":",... | Given a SQLAlchemy Table object, return a Shelf description suitable
for passing to Shelf.from_config. | [
"Given",
"a",
"SQLAlchemy",
"Table",
"object",
"return",
"a",
"Shelf",
"description",
"suitable",
"for",
"passing",
"to",
"Shelf",
".",
"from_config",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L774-L784 | train | 52,569 |
juiceinc/recipe | recipe/shelf.py | Shelf.pop | def pop(self, k, d=_POP_DEFAULT):
"""Pop an ingredient off of this shelf."""
if d is _POP_DEFAULT:
return self._ingredients.pop(k)
else:
return self._ingredients.pop(k, d) | python | def pop(self, k, d=_POP_DEFAULT):
"""Pop an ingredient off of this shelf."""
if d is _POP_DEFAULT:
return self._ingredients.pop(k)
else:
return self._ingredients.pop(k, d) | [
"def",
"pop",
"(",
"self",
",",
"k",
",",
"d",
"=",
"_POP_DEFAULT",
")",
":",
"if",
"d",
"is",
"_POP_DEFAULT",
":",
"return",
"self",
".",
"_ingredients",
".",
"pop",
"(",
"k",
")",
"else",
":",
"return",
"self",
".",
"_ingredients",
".",
"pop",
"(... | Pop an ingredient off of this shelf. | [
"Pop",
"an",
"ingredient",
"off",
"of",
"this",
"shelf",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L531-L536 | train | 52,570 |
juiceinc/recipe | recipe/shelf.py | Shelf.dimension_ids | def dimension_ids(self):
""" Return the Dimensions on this shelf in the order in which
they were used."""
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Dimension)
]) | python | def dimension_ids(self):
""" Return the Dimensions on this shelf in the order in which
they were used."""
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Dimension)
]) | [
"def",
"dimension_ids",
"(",
"self",
")",
":",
"return",
"self",
".",
"_sorted_ingredients",
"(",
"[",
"d",
".",
"id",
"for",
"d",
"in",
"self",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"d",
",",
"Dimension",
")",
"]",
")"
] | Return the Dimensions on this shelf in the order in which
they were used. | [
"Return",
"the",
"Dimensions",
"on",
"this",
"shelf",
"in",
"the",
"order",
"in",
"which",
"they",
"were",
"used",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L545-L550 | train | 52,571 |
juiceinc/recipe | recipe/shelf.py | Shelf.from_config | def from_config(
cls,
obj,
selectable,
ingredient_constructor=ingredient_from_validated_dict,
metadata=None
):
"""Create a shelf using a dict shelf definition.
:param obj: A Python dictionary describing a Shelf.
:param selectable: A SQLAlchemy Table, a Recipe, a table name, or a
SQLAlchemy join to select from.
:param metadata: If `selectable` is passed as a table name, then in
order to introspect its schema, we must have the SQLAlchemy
MetaData object to associate it with.
:return: A shelf that contains the ingredients defined in obj.
"""
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
elif isinstance(selectable, basestring):
if '.' in selectable:
schema, tablename = selectable.split('.')
else:
schema, tablename = None, selectable
selectable = Table(
tablename,
metadata,
schema=schema,
extend_existing=True,
autoload=True
)
d = {}
for k, v in iteritems(obj):
d[k] = ingredient_constructor(v, selectable)
shelf = cls(d, select_from=selectable)
return shelf | python | def from_config(
cls,
obj,
selectable,
ingredient_constructor=ingredient_from_validated_dict,
metadata=None
):
"""Create a shelf using a dict shelf definition.
:param obj: A Python dictionary describing a Shelf.
:param selectable: A SQLAlchemy Table, a Recipe, a table name, or a
SQLAlchemy join to select from.
:param metadata: If `selectable` is passed as a table name, then in
order to introspect its schema, we must have the SQLAlchemy
MetaData object to associate it with.
:return: A shelf that contains the ingredients defined in obj.
"""
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
elif isinstance(selectable, basestring):
if '.' in selectable:
schema, tablename = selectable.split('.')
else:
schema, tablename = None, selectable
selectable = Table(
tablename,
metadata,
schema=schema,
extend_existing=True,
autoload=True
)
d = {}
for k, v in iteritems(obj):
d[k] = ingredient_constructor(v, selectable)
shelf = cls(d, select_from=selectable)
return shelf | [
"def",
"from_config",
"(",
"cls",
",",
"obj",
",",
"selectable",
",",
"ingredient_constructor",
"=",
"ingredient_from_validated_dict",
",",
"metadata",
"=",
"None",
")",
":",
"from",
"recipe",
"import",
"Recipe",
"if",
"isinstance",
"(",
"selectable",
",",
"Reci... | Create a shelf using a dict shelf definition.
:param obj: A Python dictionary describing a Shelf.
:param selectable: A SQLAlchemy Table, a Recipe, a table name, or a
SQLAlchemy join to select from.
:param metadata: If `selectable` is passed as a table name, then in
order to introspect its schema, we must have the SQLAlchemy
MetaData object to associate it with.
:return: A shelf that contains the ingredients defined in obj. | [
"Create",
"a",
"shelf",
"using",
"a",
"dict",
"shelf",
"definition",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L600-L638 | train | 52,572 |
juiceinc/recipe | recipe/shelf.py | Shelf.find | def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subclass `filter_to_class`
"""
if callable(constructor):
obj = constructor(obj, shelf=self)
if isinstance(obj, basestring):
set_descending = obj.startswith('-')
if set_descending:
obj = obj[1:]
if obj not in self:
raise BadRecipe("{} doesn't exist on the shelf".format(obj))
ingredient = self[obj]
if not isinstance(ingredient, filter_to_class):
raise BadRecipe('{} is not a {}'.format(obj, filter_to_class))
if set_descending:
ingredient.ordering = 'desc'
return ingredient
elif isinstance(obj, filter_to_class):
return obj
else:
raise BadRecipe('{} is not a {}'.format(obj, filter_to_class)) | python | def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subclass `filter_to_class`
"""
if callable(constructor):
obj = constructor(obj, shelf=self)
if isinstance(obj, basestring):
set_descending = obj.startswith('-')
if set_descending:
obj = obj[1:]
if obj not in self:
raise BadRecipe("{} doesn't exist on the shelf".format(obj))
ingredient = self[obj]
if not isinstance(ingredient, filter_to_class):
raise BadRecipe('{} is not a {}'.format(obj, filter_to_class))
if set_descending:
ingredient.ordering = 'desc'
return ingredient
elif isinstance(obj, filter_to_class):
return obj
else:
raise BadRecipe('{} is not a {}'.format(obj, filter_to_class)) | [
"def",
"find",
"(",
"self",
",",
"obj",
",",
"filter_to_class",
"=",
"Ingredient",
",",
"constructor",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"constructor",
")",
":",
"obj",
"=",
"constructor",
"(",
"obj",
",",
"shelf",
"=",
"self",
")",
"if",
... | Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional callable for building Ingredients
from obj
:return: An Ingredient of subclass `filter_to_class` | [
"Find",
"an",
"Ingredient",
"optionally",
"using",
"the",
"shelf",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L669-L702 | train | 52,573 |
juiceinc/recipe | recipe/shelf.py | Shelf.brew_query_parts | def brew_query_parts(self):
""" Make columns, group_bys, filters, havings
"""
columns, group_bys, filters, havings = [], [], set(), set()
for ingredient in self.ingredients():
if ingredient.query_columns:
columns.extend(ingredient.query_columns)
if ingredient.group_by:
group_bys.extend(ingredient.group_by)
if ingredient.filters:
filters.update(ingredient.filters)
if ingredient.havings:
havings.update(ingredient.havings)
return {
'columns': columns,
'group_bys': group_bys,
'filters': filters,
'havings': havings,
} | python | def brew_query_parts(self):
""" Make columns, group_bys, filters, havings
"""
columns, group_bys, filters, havings = [], [], set(), set()
for ingredient in self.ingredients():
if ingredient.query_columns:
columns.extend(ingredient.query_columns)
if ingredient.group_by:
group_bys.extend(ingredient.group_by)
if ingredient.filters:
filters.update(ingredient.filters)
if ingredient.havings:
havings.update(ingredient.havings)
return {
'columns': columns,
'group_bys': group_bys,
'filters': filters,
'havings': havings,
} | [
"def",
"brew_query_parts",
"(",
"self",
")",
":",
"columns",
",",
"group_bys",
",",
"filters",
",",
"havings",
"=",
"[",
"]",
",",
"[",
"]",
",",
"set",
"(",
")",
",",
"set",
"(",
")",
"for",
"ingredient",
"in",
"self",
".",
"ingredients",
"(",
")"... | Make columns, group_bys, filters, havings | [
"Make",
"columns",
"group_bys",
"filters",
"havings"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L704-L723 | train | 52,574 |
juiceinc/recipe | recipe/shelf.py | Shelf.enchant | def enchant(self, list, cache_context=None):
""" Add any calculated values to each row of a resultset generating a
new namedtuple
:param list: a list of row results
:param cache_context: optional extra context for caching
:return: a list with ingredient.cauldron_extras added for all
ingredients
"""
enchantedlist = []
if list:
sample_item = list[0]
# Extra fields to add to each row
# With extra callables
extra_fields, extra_callables = [], []
for ingredient in self.values():
if not isinstance(ingredient, (Dimension, Metric)):
continue
if cache_context:
ingredient.cache_context += str(cache_context)
for extra_field, extra_callable in ingredient.cauldron_extras:
extra_fields.append(extra_field)
extra_callables.append(extra_callable)
# Mixin the extra fields
keyed_tuple = lightweight_named_tuple(
'result', sample_item._fields + tuple(extra_fields)
)
# Iterate over the results and build a new namedtuple for each row
for row in list:
values = row + tuple(fn(row) for fn in extra_callables)
enchantedlist.append(keyed_tuple(values))
return enchantedlist | python | def enchant(self, list, cache_context=None):
""" Add any calculated values to each row of a resultset generating a
new namedtuple
:param list: a list of row results
:param cache_context: optional extra context for caching
:return: a list with ingredient.cauldron_extras added for all
ingredients
"""
enchantedlist = []
if list:
sample_item = list[0]
# Extra fields to add to each row
# With extra callables
extra_fields, extra_callables = [], []
for ingredient in self.values():
if not isinstance(ingredient, (Dimension, Metric)):
continue
if cache_context:
ingredient.cache_context += str(cache_context)
for extra_field, extra_callable in ingredient.cauldron_extras:
extra_fields.append(extra_field)
extra_callables.append(extra_callable)
# Mixin the extra fields
keyed_tuple = lightweight_named_tuple(
'result', sample_item._fields + tuple(extra_fields)
)
# Iterate over the results and build a new namedtuple for each row
for row in list:
values = row + tuple(fn(row) for fn in extra_callables)
enchantedlist.append(keyed_tuple(values))
return enchantedlist | [
"def",
"enchant",
"(",
"self",
",",
"list",
",",
"cache_context",
"=",
"None",
")",
":",
"enchantedlist",
"=",
"[",
"]",
"if",
"list",
":",
"sample_item",
"=",
"list",
"[",
"0",
"]",
"# Extra fields to add to each row",
"# With extra callables",
"extra_fields",
... | Add any calculated values to each row of a resultset generating a
new namedtuple
:param list: a list of row results
:param cache_context: optional extra context for caching
:return: a list with ingredient.cauldron_extras added for all
ingredients | [
"Add",
"any",
"calculated",
"values",
"to",
"each",
"row",
"of",
"a",
"resultset",
"generating",
"a",
"new",
"namedtuple"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/shelf.py#L725-L761 | train | 52,575 |
juiceinc/recipe | recipe/extensions.py | SummarizeOver.modify_postquery_parts | def modify_postquery_parts(self, postquery_parts):
"""
Take a recipe that has dimensions
Resummarize it over one of the dimensions returning averages of the
metrics.
"""
if self._summarize_over is None:
return postquery_parts
assert self._summarize_over in self.recipe.dimension_ids
# Start with a subquery
subq = postquery_parts['query'].subquery(name='summarize')
summarize_over_dim = set((
self._summarize_over, self._summarize_over + '_id',
self._summarize_over + '_raw'
))
dim_column_names = set(dim for dim in self.recipe.dimension_ids).union(
set(dim + '_id' for dim in self.recipe.dimension_ids)
).union(set(dim + '_raw' for dim in self.recipe.dimension_ids))
used_dim_column_names = dim_column_names - summarize_over_dim
# Build a new query around the subquery
group_by_columns = [
col for col in subq.c if col.name in used_dim_column_names
]
# Generate columns for the metric, remapping the aggregation function
# count -> sum
# sum -> sum
# avg -> avg
# Metrics can override the summary aggregation by providing a
# metric.meta.summary_aggregation callable parameter
metric_columns = []
for col in subq.c:
if col.name not in dim_column_names:
met = self.recipe._cauldron.find(col.name, Metric)
summary_aggregation = met.meta.get('summary_aggregation', None)
if summary_aggregation is None:
if str(met.expression).startswith(u'avg'):
summary_aggregation = func.avg
elif str(met.expression).startswith(u'count'):
summary_aggregation = func.sum
elif str(met.expression).startswith(u'sum'):
summary_aggregation = func.sum
if summary_aggregation is None:
# We don't know how to aggregate this metric in a summary
raise BadRecipe(
u'Provide a summary_aggregation for metric'
u' {}'.format(col.name)
)
metric_columns.append(summary_aggregation(col).label(col.name))
# Find the ordering columns and apply them to the new query
order_by_columns = []
for col in postquery_parts['query']._order_by:
subq_col = getattr(
subq.c, col.name, getattr(subq.c, col.name + '_raw', None)
)
if subq_col is not None:
order_by_columns.append(subq_col)
postquery_parts['query'] = self.recipe._session.query(
*(group_by_columns + metric_columns)
).group_by(*group_by_columns).order_by(*order_by_columns)
# Remove the summarized dimension
self.recipe._cauldron.pop(self._summarize_over, None)
return postquery_parts | python | def modify_postquery_parts(self, postquery_parts):
"""
Take a recipe that has dimensions
Resummarize it over one of the dimensions returning averages of the
metrics.
"""
if self._summarize_over is None:
return postquery_parts
assert self._summarize_over in self.recipe.dimension_ids
# Start with a subquery
subq = postquery_parts['query'].subquery(name='summarize')
summarize_over_dim = set((
self._summarize_over, self._summarize_over + '_id',
self._summarize_over + '_raw'
))
dim_column_names = set(dim for dim in self.recipe.dimension_ids).union(
set(dim + '_id' for dim in self.recipe.dimension_ids)
).union(set(dim + '_raw' for dim in self.recipe.dimension_ids))
used_dim_column_names = dim_column_names - summarize_over_dim
# Build a new query around the subquery
group_by_columns = [
col for col in subq.c if col.name in used_dim_column_names
]
# Generate columns for the metric, remapping the aggregation function
# count -> sum
# sum -> sum
# avg -> avg
# Metrics can override the summary aggregation by providing a
# metric.meta.summary_aggregation callable parameter
metric_columns = []
for col in subq.c:
if col.name not in dim_column_names:
met = self.recipe._cauldron.find(col.name, Metric)
summary_aggregation = met.meta.get('summary_aggregation', None)
if summary_aggregation is None:
if str(met.expression).startswith(u'avg'):
summary_aggregation = func.avg
elif str(met.expression).startswith(u'count'):
summary_aggregation = func.sum
elif str(met.expression).startswith(u'sum'):
summary_aggregation = func.sum
if summary_aggregation is None:
# We don't know how to aggregate this metric in a summary
raise BadRecipe(
u'Provide a summary_aggregation for metric'
u' {}'.format(col.name)
)
metric_columns.append(summary_aggregation(col).label(col.name))
# Find the ordering columns and apply them to the new query
order_by_columns = []
for col in postquery_parts['query']._order_by:
subq_col = getattr(
subq.c, col.name, getattr(subq.c, col.name + '_raw', None)
)
if subq_col is not None:
order_by_columns.append(subq_col)
postquery_parts['query'] = self.recipe._session.query(
*(group_by_columns + metric_columns)
).group_by(*group_by_columns).order_by(*order_by_columns)
# Remove the summarized dimension
self.recipe._cauldron.pop(self._summarize_over, None)
return postquery_parts | [
"def",
"modify_postquery_parts",
"(",
"self",
",",
"postquery_parts",
")",
":",
"if",
"self",
".",
"_summarize_over",
"is",
"None",
":",
"return",
"postquery_parts",
"assert",
"self",
".",
"_summarize_over",
"in",
"self",
".",
"recipe",
".",
"dimension_ids",
"# ... | Take a recipe that has dimensions
Resummarize it over one of the dimensions returning averages of the
metrics. | [
"Take",
"a",
"recipe",
"that",
"has",
"dimensions",
"Resummarize",
"it",
"over",
"one",
"of",
"the",
"dimensions",
"returning",
"averages",
"of",
"the",
"metrics",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/extensions.py#L334-L403 | train | 52,576 |
juiceinc/recipe | recipe/extensions.py | Anonymize.anonymize | def anonymize(self, value):
""" Should this recipe be anonymized"""
assert isinstance(value, bool)
if self._anonymize != value:
self.dirty = True
self._anonymize = value
# Builder pattern must return the recipe
return self.recipe | python | def anonymize(self, value):
""" Should this recipe be anonymized"""
assert isinstance(value, bool)
if self._anonymize != value:
self.dirty = True
self._anonymize = value
# Builder pattern must return the recipe
return self.recipe | [
"def",
"anonymize",
"(",
"self",
",",
"value",
")",
":",
"assert",
"isinstance",
"(",
"value",
",",
"bool",
")",
"if",
"self",
".",
"_anonymize",
"!=",
"value",
":",
"self",
".",
"dirty",
"=",
"True",
"self",
".",
"_anonymize",
"=",
"value",
"# Builder... | Should this recipe be anonymized | [
"Should",
"this",
"recipe",
"be",
"anonymized"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/extensions.py#L430-L439 | train | 52,577 |
juiceinc/recipe | recipe/extensions.py | Anonymize.add_ingredients | def add_ingredients(self):
""" Put the anonymizers in the last position of formatters """
for ingredient in self.recipe._cauldron.values():
if hasattr(ingredient.meta, 'anonymizer'):
anonymizer = ingredient.meta.anonymizer
# Build a FakerAnonymizer if we have a string
if isinstance(anonymizer, basestring):
# Check for extra parameters
kwargs = {}
anonymizer_locale = getattr(
ingredient.meta, 'anonymizer_locale', None
)
anonymizer_postprocessor = getattr(
ingredient.meta, 'anonymizer_postprocessor', None
)
if anonymizer_postprocessor is not None:
kwargs['postprocessor'] = anonymizer_postprocessor
if anonymizer_locale is not None:
kwargs['locale'] = anonymizer_locale
anonymizer = FakerAnonymizer(anonymizer, **kwargs)
# Strip out all FakerAnonymizers
ingredient.formatters = [
f for f in ingredient.formatters
if not isinstance(f, FakerAnonymizer)
]
if self._anonymize:
if ingredient.meta.anonymizer not in ingredient.formatters:
ingredient.formatters.append(anonymizer)
else:
if ingredient.meta.anonymizer in ingredient.formatters:
ingredient.formatters.remove(anonymizer) | python | def add_ingredients(self):
""" Put the anonymizers in the last position of formatters """
for ingredient in self.recipe._cauldron.values():
if hasattr(ingredient.meta, 'anonymizer'):
anonymizer = ingredient.meta.anonymizer
# Build a FakerAnonymizer if we have a string
if isinstance(anonymizer, basestring):
# Check for extra parameters
kwargs = {}
anonymizer_locale = getattr(
ingredient.meta, 'anonymizer_locale', None
)
anonymizer_postprocessor = getattr(
ingredient.meta, 'anonymizer_postprocessor', None
)
if anonymizer_postprocessor is not None:
kwargs['postprocessor'] = anonymizer_postprocessor
if anonymizer_locale is not None:
kwargs['locale'] = anonymizer_locale
anonymizer = FakerAnonymizer(anonymizer, **kwargs)
# Strip out all FakerAnonymizers
ingredient.formatters = [
f for f in ingredient.formatters
if not isinstance(f, FakerAnonymizer)
]
if self._anonymize:
if ingredient.meta.anonymizer not in ingredient.formatters:
ingredient.formatters.append(anonymizer)
else:
if ingredient.meta.anonymizer in ingredient.formatters:
ingredient.formatters.remove(anonymizer) | [
"def",
"add_ingredients",
"(",
"self",
")",
":",
"for",
"ingredient",
"in",
"self",
".",
"recipe",
".",
"_cauldron",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"ingredient",
".",
"meta",
",",
"'anonymizer'",
")",
":",
"anonymizer",
"=",
"ingredi... | Put the anonymizers in the last position of formatters | [
"Put",
"the",
"anonymizers",
"in",
"the",
"last",
"position",
"of",
"formatters"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/extensions.py#L441-L475 | train | 52,578 |
juiceinc/recipe | recipe/extensions.py | BlendRecipe.blend | def blend(self, blend_recipe, join_base, join_blend):
"""Blend a recipe into the base recipe.
This performs an inner join of the blend_recipe to the
base recipe's SQL.
"""
assert isinstance(blend_recipe, Recipe)
self.blend_recipes.append(blend_recipe)
self.blend_types.append('inner')
self.blend_criteria.append((join_base, join_blend))
self.dirty = True
return self.recipe | python | def blend(self, blend_recipe, join_base, join_blend):
"""Blend a recipe into the base recipe.
This performs an inner join of the blend_recipe to the
base recipe's SQL.
"""
assert isinstance(blend_recipe, Recipe)
self.blend_recipes.append(blend_recipe)
self.blend_types.append('inner')
self.blend_criteria.append((join_base, join_blend))
self.dirty = True
return self.recipe | [
"def",
"blend",
"(",
"self",
",",
"blend_recipe",
",",
"join_base",
",",
"join_blend",
")",
":",
"assert",
"isinstance",
"(",
"blend_recipe",
",",
"Recipe",
")",
"self",
".",
"blend_recipes",
".",
"append",
"(",
"blend_recipe",
")",
"self",
".",
"blend_types... | Blend a recipe into the base recipe.
This performs an inner join of the blend_recipe to the
base recipe's SQL. | [
"Blend",
"a",
"recipe",
"into",
"the",
"base",
"recipe",
".",
"This",
"performs",
"an",
"inner",
"join",
"of",
"the",
"blend_recipe",
"to",
"the",
"base",
"recipe",
"s",
"SQL",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/extensions.py#L498-L509 | train | 52,579 |
juiceinc/recipe | recipe/extensions.py | CompareRecipe.compare | def compare(self, compare_recipe, suffix='_compare'):
"""Adds a comparison recipe to a base recipe."""
assert isinstance(compare_recipe, Recipe)
assert isinstance(suffix, basestring)
self.compare_recipe.append(compare_recipe)
self.suffix.append(suffix)
self.dirty = True
return self.recipe | python | def compare(self, compare_recipe, suffix='_compare'):
"""Adds a comparison recipe to a base recipe."""
assert isinstance(compare_recipe, Recipe)
assert isinstance(suffix, basestring)
self.compare_recipe.append(compare_recipe)
self.suffix.append(suffix)
self.dirty = True
return self.recipe | [
"def",
"compare",
"(",
"self",
",",
"compare_recipe",
",",
"suffix",
"=",
"'_compare'",
")",
":",
"assert",
"isinstance",
"(",
"compare_recipe",
",",
"Recipe",
")",
"assert",
"isinstance",
"(",
"suffix",
",",
"basestring",
")",
"self",
".",
"compare_recipe",
... | Adds a comparison recipe to a base recipe. | [
"Adds",
"a",
"comparison",
"recipe",
"to",
"a",
"base",
"recipe",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/extensions.py#L624-L631 | train | 52,580 |
juiceinc/recipe | recipe/utils.py | prettyprintable_sql | def prettyprintable_sql(statement, dialect=None, reindent=True):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement. The function can also receive a
`sqlalchemy.orm.Query` object instead of statement.
WARNING: Should only be used for debugging. Inlining parameters is not
safe when handling user created data.
"""
if isinstance(statement, sqlalchemy.orm.Query):
if dialect is None:
dialect = statement.session.get_bind().dialect
statement = statement.statement
# Generate a class that can handle encoding
if dialect:
DialectKlass = dialect.__class__
else:
DialectKlass = DefaultDialect
class LiteralDialect(DialectKlass):
colspecs = {
# prevent various encoding explosions
String: StringLiteral,
# teach SA about how to literalize a datetime
DateTime: StringLiteral,
Date: StringLiteral,
# don't format py2 long integers to NULL
NullType: StringLiteral,
}
compiled = statement.compile(
dialect=LiteralDialect(), compile_kwargs={
'literal_binds': True
}
)
return sqlparse.format(str(compiled), reindent=reindent) | python | def prettyprintable_sql(statement, dialect=None, reindent=True):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement. The function can also receive a
`sqlalchemy.orm.Query` object instead of statement.
WARNING: Should only be used for debugging. Inlining parameters is not
safe when handling user created data.
"""
if isinstance(statement, sqlalchemy.orm.Query):
if dialect is None:
dialect = statement.session.get_bind().dialect
statement = statement.statement
# Generate a class that can handle encoding
if dialect:
DialectKlass = dialect.__class__
else:
DialectKlass = DefaultDialect
class LiteralDialect(DialectKlass):
colspecs = {
# prevent various encoding explosions
String: StringLiteral,
# teach SA about how to literalize a datetime
DateTime: StringLiteral,
Date: StringLiteral,
# don't format py2 long integers to NULL
NullType: StringLiteral,
}
compiled = statement.compile(
dialect=LiteralDialect(), compile_kwargs={
'literal_binds': True
}
)
return sqlparse.format(str(compiled), reindent=reindent) | [
"def",
"prettyprintable_sql",
"(",
"statement",
",",
"dialect",
"=",
"None",
",",
"reindent",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"statement",
",",
"sqlalchemy",
".",
"orm",
".",
"Query",
")",
":",
"if",
"dialect",
"is",
"None",
":",
"dialect... | Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement. The function can also receive a
`sqlalchemy.orm.Query` object instead of statement.
WARNING: Should only be used for debugging. Inlining parameters is not
safe when handling user created data. | [
"Generate",
"an",
"SQL",
"expression",
"string",
"with",
"bound",
"parameters",
"rendered",
"inline",
"for",
"the",
"given",
"SQLAlchemy",
"statement",
".",
"The",
"function",
"can",
"also",
"receive",
"a",
"sqlalchemy",
".",
"orm",
".",
"Query",
"object",
"in... | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/utils.py#L42-L78 | train | 52,581 |
juiceinc/recipe | recipe/validators.py | IngredientValidator._normalize_coerce_to_format_with_lookup | def _normalize_coerce_to_format_with_lookup(self, v):
""" Replace a format with a default """
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | python | def _normalize_coerce_to_format_with_lookup(self, v):
""" Replace a format with a default """
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | [
"def",
"_normalize_coerce_to_format_with_lookup",
"(",
"self",
",",
"v",
")",
":",
"try",
":",
"return",
"self",
".",
"format_lookup",
".",
"get",
"(",
"v",
",",
"v",
")",
"except",
"TypeError",
":",
"# v is something we can't lookup (like a list)",
"return",
"v"
... | Replace a format with a default | [
"Replace",
"a",
"format",
"with",
"a",
"default"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/validators.py#L66-L72 | train | 52,582 |
juiceinc/recipe | recipe/validators.py | IngredientValidator._validate_type_scalar | def _validate_type_scalar(self, value):
""" Is not a list or a dict """
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True | python | def _validate_type_scalar(self, value):
""" Is not a list or a dict """
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True | [
"def",
"_validate_type_scalar",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"_int_types",
"+",
"(",
"_str_type",
",",
"float",
",",
"date",
",",
"datetime",
",",
"bool",
")",
")",
":",
"return",
"True"
] | Is not a list or a dict | [
"Is",
"not",
"a",
"list",
"or",
"a",
"dict"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/validators.py#L132-L137 | train | 52,583 |
juiceinc/recipe | recipe/core.py | Recipe.from_config | def from_config(cls, shelf, obj, **kwargs):
"""
Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each RecipeExtension can extract and handle data from the
configuration.
"""
def subdict(d, keys):
new = {}
for k in keys:
if k in d:
new[k] = d[k]
return new
core_kwargs = subdict(obj, recipe_schema['schema'].keys())
core_kwargs = normalize_schema(recipe_schema, core_kwargs)
core_kwargs['filters'] = [
parse_condition(filter, shelf.Meta.select_from)
if isinstance(filter, dict)
else filter
for filter in obj.get('filters', [])
]
core_kwargs.update(kwargs)
recipe = cls(shelf=shelf, **core_kwargs)
# Now let extensions handle their own stuff
for ext in recipe.recipe_extensions:
additional_schema = getattr(ext, 'recipe_schema', None)
if additional_schema is not None:
ext_data = subdict(obj, additional_schema.keys())
ext_data = normalize_dict(additional_schema, ext_data)
recipe = ext.from_config(ext_data)
return recipe | python | def from_config(cls, shelf, obj, **kwargs):
"""
Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each RecipeExtension can extract and handle data from the
configuration.
"""
def subdict(d, keys):
new = {}
for k in keys:
if k in d:
new[k] = d[k]
return new
core_kwargs = subdict(obj, recipe_schema['schema'].keys())
core_kwargs = normalize_schema(recipe_schema, core_kwargs)
core_kwargs['filters'] = [
parse_condition(filter, shelf.Meta.select_from)
if isinstance(filter, dict)
else filter
for filter in obj.get('filters', [])
]
core_kwargs.update(kwargs)
recipe = cls(shelf=shelf, **core_kwargs)
# Now let extensions handle their own stuff
for ext in recipe.recipe_extensions:
additional_schema = getattr(ext, 'recipe_schema', None)
if additional_schema is not None:
ext_data = subdict(obj, additional_schema.keys())
ext_data = normalize_dict(additional_schema, ext_data)
recipe = ext.from_config(ext_data)
return recipe | [
"def",
"from_config",
"(",
"cls",
",",
"shelf",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"subdict",
"(",
"d",
",",
"keys",
")",
":",
"new",
"=",
"{",
"}",
"for",
"k",
"in",
"keys",
":",
"if",
"k",
"in",
"d",
":",
"new",
"[",
"k... | Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each RecipeExtension can extract and handle data from the
configuration. | [
"Construct",
"a",
"Recipe",
"from",
"a",
"plain",
"Python",
"dictionary",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L145-L181 | train | 52,584 |
juiceinc/recipe | recipe/core.py | Recipe.shelf | def shelf(self, shelf=None):
""" Defines a shelf to use for this recipe """
if shelf is None:
self._shelf = Shelf({})
elif isinstance(shelf, Shelf):
self._shelf = shelf
elif isinstance(shelf, dict):
self._shelf = Shelf(shelf)
else:
raise BadRecipe('shelf must be a dict or recipe.shelf.Shelf')
if self._select_from is None and \
self._shelf.Meta.select_from is not None:
self._select_from = self._shelf.Meta.select_from
return self | python | def shelf(self, shelf=None):
""" Defines a shelf to use for this recipe """
if shelf is None:
self._shelf = Shelf({})
elif isinstance(shelf, Shelf):
self._shelf = shelf
elif isinstance(shelf, dict):
self._shelf = Shelf(shelf)
else:
raise BadRecipe('shelf must be a dict or recipe.shelf.Shelf')
if self._select_from is None and \
self._shelf.Meta.select_from is not None:
self._select_from = self._shelf.Meta.select_from
return self | [
"def",
"shelf",
"(",
"self",
",",
"shelf",
"=",
"None",
")",
":",
"if",
"shelf",
"is",
"None",
":",
"self",
".",
"_shelf",
"=",
"Shelf",
"(",
"{",
"}",
")",
"elif",
"isinstance",
"(",
"shelf",
",",
"Shelf",
")",
":",
"self",
".",
"_shelf",
"=",
... | Defines a shelf to use for this recipe | [
"Defines",
"a",
"shelf",
"to",
"use",
"for",
"this",
"recipe"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L217-L231 | train | 52,585 |
juiceinc/recipe | recipe/core.py | Recipe.metrics | def metrics(self, *metrics):
""" Add a list of Metric ingredients to the query. These can either be
Metric objects or strings representing metrics on the shelf.
The Metric expression will be added to the query's select statement.
The metric value is a property of each row of the result.
:param metrics: Metrics to add to the recipe. Metrics can
either be keys on the ``shelf`` or
Metric objects
:type metrics: list
"""
for m in metrics:
self._cauldron.use(self._shelf.find(m, Metric))
self.dirty = True
return self | python | def metrics(self, *metrics):
""" Add a list of Metric ingredients to the query. These can either be
Metric objects or strings representing metrics on the shelf.
The Metric expression will be added to the query's select statement.
The metric value is a property of each row of the result.
:param metrics: Metrics to add to the recipe. Metrics can
either be keys on the ``shelf`` or
Metric objects
:type metrics: list
"""
for m in metrics:
self._cauldron.use(self._shelf.find(m, Metric))
self.dirty = True
return self | [
"def",
"metrics",
"(",
"self",
",",
"*",
"metrics",
")",
":",
"for",
"m",
"in",
"metrics",
":",
"self",
".",
"_cauldron",
".",
"use",
"(",
"self",
".",
"_shelf",
".",
"find",
"(",
"m",
",",
"Metric",
")",
")",
"self",
".",
"dirty",
"=",
"True",
... | Add a list of Metric ingredients to the query. These can either be
Metric objects or strings representing metrics on the shelf.
The Metric expression will be added to the query's select statement.
The metric value is a property of each row of the result.
:param metrics: Metrics to add to the recipe. Metrics can
either be keys on the ``shelf`` or
Metric objects
:type metrics: list | [
"Add",
"a",
"list",
"of",
"Metric",
"ingredients",
"to",
"the",
"query",
".",
"These",
"can",
"either",
"be",
"Metric",
"objects",
"or",
"strings",
"representing",
"metrics",
"on",
"the",
"shelf",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L233-L248 | train | 52,586 |
juiceinc/recipe | recipe/core.py | Recipe.dimensions | def dimensions(self, *dimensions):
""" Add a list of Dimension ingredients to the query. These can either be
Dimension objects or strings representing dimensions on the shelf.
The Dimension expression will be added to the query's select statement
and to the group_by.
:param dimensions: Dimensions to add to the recipe. Dimensions can
either be keys on the ``shelf`` or
Dimension objects
:type dimensions: list
"""
for d in dimensions:
self._cauldron.use(self._shelf.find(d, Dimension))
self.dirty = True
return self | python | def dimensions(self, *dimensions):
""" Add a list of Dimension ingredients to the query. These can either be
Dimension objects or strings representing dimensions on the shelf.
The Dimension expression will be added to the query's select statement
and to the group_by.
:param dimensions: Dimensions to add to the recipe. Dimensions can
either be keys on the ``shelf`` or
Dimension objects
:type dimensions: list
"""
for d in dimensions:
self._cauldron.use(self._shelf.find(d, Dimension))
self.dirty = True
return self | [
"def",
"dimensions",
"(",
"self",
",",
"*",
"dimensions",
")",
":",
"for",
"d",
"in",
"dimensions",
":",
"self",
".",
"_cauldron",
".",
"use",
"(",
"self",
".",
"_shelf",
".",
"find",
"(",
"d",
",",
"Dimension",
")",
")",
"self",
".",
"dirty",
"=",... | Add a list of Dimension ingredients to the query. These can either be
Dimension objects or strings representing dimensions on the shelf.
The Dimension expression will be added to the query's select statement
and to the group_by.
:param dimensions: Dimensions to add to the recipe. Dimensions can
either be keys on the ``shelf`` or
Dimension objects
:type dimensions: list | [
"Add",
"a",
"list",
"of",
"Dimension",
"ingredients",
"to",
"the",
"query",
".",
"These",
"can",
"either",
"be",
"Dimension",
"objects",
"or",
"strings",
"representing",
"dimensions",
"on",
"the",
"shelf",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L254-L270 | train | 52,587 |
juiceinc/recipe | recipe/core.py | Recipe.order_by | def order_by(self, *order_bys):
""" Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Order_bys to add to the recipe. Order_bys can
either be keys on the ``shelf`` or
Dimension or Metric objects. If the
key is prefixed by "-" the ordering will be
descending.
:type order_bys: list
"""
# Order bys shouldn't be added to the _cauldron
self._order_bys = []
for ingr in order_bys:
order_by = self._shelf.find(ingr, (Dimension, Metric))
self._order_bys.append(order_by)
self.dirty = True
return self | python | def order_by(self, *order_bys):
""" Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Order_bys to add to the recipe. Order_bys can
either be keys on the ``shelf`` or
Dimension or Metric objects. If the
key is prefixed by "-" the ordering will be
descending.
:type order_bys: list
"""
# Order bys shouldn't be added to the _cauldron
self._order_bys = []
for ingr in order_bys:
order_by = self._shelf.find(ingr, (Dimension, Metric))
self._order_bys.append(order_by)
self.dirty = True
return self | [
"def",
"order_by",
"(",
"self",
",",
"*",
"order_bys",
")",
":",
"# Order bys shouldn't be added to the _cauldron",
"self",
".",
"_order_bys",
"=",
"[",
"]",
"for",
"ingr",
"in",
"order_bys",
":",
"order_by",
"=",
"self",
".",
"_shelf",
".",
"find",
"(",
"in... | Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Order_bys to add to the recipe. Order_bys can
either be keys on the ``shelf`` or
Dimension or Metric objects. If the
key is prefixed by "-" the ordering will be
descending.
:type order_bys: list | [
"Add",
"a",
"list",
"of",
"ingredients",
"to",
"order",
"by",
"to",
"the",
"query",
".",
"These",
"can",
"either",
"be",
"Dimension",
"or",
"Metric",
"objects",
"or",
"strings",
"representing",
"order_bys",
"on",
"the",
"shelf",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L311-L333 | train | 52,588 |
juiceinc/recipe | recipe/core.py | Recipe.limit | def limit(self, limit):
""" Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int
"""
if self._limit != limit:
self.dirty = True
self._limit = limit
return self | python | def limit(self, limit):
""" Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int
"""
if self._limit != limit:
self.dirty = True
self._limit = limit
return self | [
"def",
"limit",
"(",
"self",
",",
"limit",
")",
":",
"if",
"self",
".",
"_limit",
"!=",
"limit",
":",
"self",
".",
"dirty",
"=",
"True",
"self",
".",
"_limit",
"=",
"limit",
"return",
"self"
] | Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int | [
"Limit",
"the",
"number",
"of",
"rows",
"returned",
"from",
"the",
"database",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L345-L355 | train | 52,589 |
juiceinc/recipe | recipe/core.py | Recipe.offset | def offset(self, offset):
""" Offset a number of rows before returning rows from the database.
:param offset: The number of rows to offset in the recipe. 0 will
return from the first available row
:type offset: int
"""
if self._offset != offset:
self.dirty = True
self._offset = offset
return self | python | def offset(self, offset):
""" Offset a number of rows before returning rows from the database.
:param offset: The number of rows to offset in the recipe. 0 will
return from the first available row
:type offset: int
"""
if self._offset != offset:
self.dirty = True
self._offset = offset
return self | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"if",
"self",
".",
"_offset",
"!=",
"offset",
":",
"self",
".",
"dirty",
"=",
"True",
"self",
".",
"_offset",
"=",
"offset",
"return",
"self"
] | Offset a number of rows before returning rows from the database.
:param offset: The number of rows to offset in the recipe. 0 will
return from the first available row
:type offset: int | [
"Offset",
"a",
"number",
"of",
"rows",
"before",
"returning",
"rows",
"from",
"the",
"database",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L357-L367 | train | 52,590 |
juiceinc/recipe | recipe/core.py | Recipe._is_postgres | def _is_postgres(self):
""" Determine if the running engine is postgres """
if self._is_postgres_engine is None:
is_postgres_engine = False
try:
dialect = self.session.bind.engine.name
if 'redshift' in dialect or 'postg' in dialect or 'pg' in \
dialect:
is_postgres_engine = True
except:
pass
self._is_postgres_engine = is_postgres_engine
return self._is_postgres_engine | python | def _is_postgres(self):
""" Determine if the running engine is postgres """
if self._is_postgres_engine is None:
is_postgres_engine = False
try:
dialect = self.session.bind.engine.name
if 'redshift' in dialect or 'postg' in dialect or 'pg' in \
dialect:
is_postgres_engine = True
except:
pass
self._is_postgres_engine = is_postgres_engine
return self._is_postgres_engine | [
"def",
"_is_postgres",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_postgres_engine",
"is",
"None",
":",
"is_postgres_engine",
"=",
"False",
"try",
":",
"dialect",
"=",
"self",
".",
"session",
".",
"bind",
".",
"engine",
".",
"name",
"if",
"'redshift'",
... | Determine if the running engine is postgres | [
"Determine",
"if",
"the",
"running",
"engine",
"is",
"postgres"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L373-L385 | train | 52,591 |
juiceinc/recipe | recipe/core.py | Recipe._prepare_order_bys | def _prepare_order_bys(self):
""" Build a set of order by columns """
order_bys = OrderedSet()
if self._order_bys:
for ingredient in self._order_bys:
if isinstance(ingredient, Dimension):
# Reverse the ordering columns so that dimensions
# order by their label rather than their id
columns = reversed(ingredient.columns)
else:
columns = ingredient.columns
for c in columns:
order_by = c.desc() if ingredient.ordering == 'desc' else c
if str(order_by) not in [str(o) for o in order_bys]:
order_bys.add(order_by)
return list(order_bys) | python | def _prepare_order_bys(self):
""" Build a set of order by columns """
order_bys = OrderedSet()
if self._order_bys:
for ingredient in self._order_bys:
if isinstance(ingredient, Dimension):
# Reverse the ordering columns so that dimensions
# order by their label rather than their id
columns = reversed(ingredient.columns)
else:
columns = ingredient.columns
for c in columns:
order_by = c.desc() if ingredient.ordering == 'desc' else c
if str(order_by) not in [str(o) for o in order_bys]:
order_bys.add(order_by)
return list(order_bys) | [
"def",
"_prepare_order_bys",
"(",
"self",
")",
":",
"order_bys",
"=",
"OrderedSet",
"(",
")",
"if",
"self",
".",
"_order_bys",
":",
"for",
"ingredient",
"in",
"self",
".",
"_order_bys",
":",
"if",
"isinstance",
"(",
"ingredient",
",",
"Dimension",
")",
":"... | Build a set of order by columns | [
"Build",
"a",
"set",
"of",
"order",
"by",
"columns"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L387-L403 | train | 52,592 |
juiceinc/recipe | recipe/core.py | Recipe.query | def query(self):
"""
Generates a query using the ingredients supplied by the recipe.
:return: A SQLAlchemy query
"""
if len(self._cauldron.ingredients()) == 0:
raise BadRecipe('No ingredients have been added to this recipe')
if not self.dirty and self._query:
return self._query
# Step 1: Gather up global filters and user filters and
# apply them as if they had been added to recipe().filters(...)
for extension in self.recipe_extensions:
extension.add_ingredients()
# Step 2: Build the query (now that it has all the filters
# and apply any blend recipes
# Get the parts of the query from the cauldron
# We don't need to regather order_bys
recipe_parts = self._cauldron.brew_query_parts()
recipe_parts['order_bys'] = self._prepare_order_bys()
for extension in self.recipe_extensions:
recipe_parts = extension.modify_recipe_parts(recipe_parts)
# Start building the query
query = self._session.query(*recipe_parts['columns'])
if self._select_from is not None:
query = query.select_from(self._select_from)
recipe_parts['query'] = query \
.group_by(*recipe_parts['group_bys']) \
.order_by(*recipe_parts['order_bys']) \
.filter(*recipe_parts['filters'])
if recipe_parts['havings']:
for having in recipe_parts['havings']:
recipe_parts['query'] = recipe_parts['query'].having(having)
for extension in self.recipe_extensions:
recipe_parts = extension.modify_prequery_parts(recipe_parts)
if self._select_from is None and len(
recipe_parts['query'].selectable.froms
) != 1:
raise BadRecipe(
'Recipes must use ingredients that all come from '
'the same table. \nDetails on this recipe:\n{'
'}'.format(str(self._cauldron))
)
for extension in self.recipe_extensions:
recipe_parts = extension.modify_postquery_parts(recipe_parts)
recipe_parts = run_hooks(
recipe_parts, 'modify_query', self.dynamic_extensions
)
# Apply limit on the outermost query
# This happens after building the comparison recipe
if self._limit and self._limit > 0:
recipe_parts['query'] = recipe_parts['query'].limit(self._limit)
if self._offset and self._offset > 0:
recipe_parts['query'] = recipe_parts['query'].offset(self._offset)
# Step 5: Clear the dirty flag,
# Patch the query if there's a comparison query
# cache results
self._query = recipe_parts['query']
self.dirty = False
return self._query | python | def query(self):
"""
Generates a query using the ingredients supplied by the recipe.
:return: A SQLAlchemy query
"""
if len(self._cauldron.ingredients()) == 0:
raise BadRecipe('No ingredients have been added to this recipe')
if not self.dirty and self._query:
return self._query
# Step 1: Gather up global filters and user filters and
# apply them as if they had been added to recipe().filters(...)
for extension in self.recipe_extensions:
extension.add_ingredients()
# Step 2: Build the query (now that it has all the filters
# and apply any blend recipes
# Get the parts of the query from the cauldron
# We don't need to regather order_bys
recipe_parts = self._cauldron.brew_query_parts()
recipe_parts['order_bys'] = self._prepare_order_bys()
for extension in self.recipe_extensions:
recipe_parts = extension.modify_recipe_parts(recipe_parts)
# Start building the query
query = self._session.query(*recipe_parts['columns'])
if self._select_from is not None:
query = query.select_from(self._select_from)
recipe_parts['query'] = query \
.group_by(*recipe_parts['group_bys']) \
.order_by(*recipe_parts['order_bys']) \
.filter(*recipe_parts['filters'])
if recipe_parts['havings']:
for having in recipe_parts['havings']:
recipe_parts['query'] = recipe_parts['query'].having(having)
for extension in self.recipe_extensions:
recipe_parts = extension.modify_prequery_parts(recipe_parts)
if self._select_from is None and len(
recipe_parts['query'].selectable.froms
) != 1:
raise BadRecipe(
'Recipes must use ingredients that all come from '
'the same table. \nDetails on this recipe:\n{'
'}'.format(str(self._cauldron))
)
for extension in self.recipe_extensions:
recipe_parts = extension.modify_postquery_parts(recipe_parts)
recipe_parts = run_hooks(
recipe_parts, 'modify_query', self.dynamic_extensions
)
# Apply limit on the outermost query
# This happens after building the comparison recipe
if self._limit and self._limit > 0:
recipe_parts['query'] = recipe_parts['query'].limit(self._limit)
if self._offset and self._offset > 0:
recipe_parts['query'] = recipe_parts['query'].offset(self._offset)
# Step 5: Clear the dirty flag,
# Patch the query if there's a comparison query
# cache results
self._query = recipe_parts['query']
self.dirty = False
return self._query | [
"def",
"query",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_cauldron",
".",
"ingredients",
"(",
")",
")",
"==",
"0",
":",
"raise",
"BadRecipe",
"(",
"'No ingredients have been added to this recipe'",
")",
"if",
"not",
"self",
".",
"dirty",
"and... | Generates a query using the ingredients supplied by the recipe.
:return: A SQLAlchemy query | [
"Generates",
"a",
"query",
"using",
"the",
"ingredients",
"supplied",
"by",
"the",
"recipe",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L405-L479 | train | 52,593 |
juiceinc/recipe | recipe/core.py | Recipe.dirty | def dirty(self):
""" The recipe is dirty if it is flagged dirty or any extensions are
flagged dirty """
if self._dirty:
return True
else:
for extension in self.recipe_extensions:
if extension.dirty:
return True
return False | python | def dirty(self):
""" The recipe is dirty if it is flagged dirty or any extensions are
flagged dirty """
if self._dirty:
return True
else:
for extension in self.recipe_extensions:
if extension.dirty:
return True
return False | [
"def",
"dirty",
"(",
"self",
")",
":",
"if",
"self",
".",
"_dirty",
":",
"return",
"True",
"else",
":",
"for",
"extension",
"in",
"self",
".",
"recipe_extensions",
":",
"if",
"extension",
".",
"dirty",
":",
"return",
"True",
"return",
"False"
] | The recipe is dirty if it is flagged dirty or any extensions are
flagged dirty | [
"The",
"recipe",
"is",
"dirty",
"if",
"it",
"is",
"flagged",
"dirty",
"or",
"any",
"extensions",
"are",
"flagged",
"dirty"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L482-L491 | train | 52,594 |
juiceinc/recipe | recipe/core.py | Recipe.dirty | def dirty(self, value):
""" If dirty is true set the recipe to dirty flag. If false,
clear the recipe and all extension dirty flags """
if value:
self._dirty = True
else:
self._dirty = False
for extension in self.recipe_extensions:
extension.dirty = False | python | def dirty(self, value):
""" If dirty is true set the recipe to dirty flag. If false,
clear the recipe and all extension dirty flags """
if value:
self._dirty = True
else:
self._dirty = False
for extension in self.recipe_extensions:
extension.dirty = False | [
"def",
"dirty",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"self",
".",
"_dirty",
"=",
"True",
"else",
":",
"self",
".",
"_dirty",
"=",
"False",
"for",
"extension",
"in",
"self",
".",
"recipe_extensions",
":",
"extension",
".",
"dirty",
... | If dirty is true set the recipe to dirty flag. If false,
clear the recipe and all extension dirty flags | [
"If",
"dirty",
"is",
"true",
"set",
"the",
"recipe",
"to",
"dirty",
"flag",
".",
"If",
"false",
"clear",
"the",
"recipe",
"and",
"all",
"extension",
"dirty",
"flags"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L494-L502 | train | 52,595 |
juiceinc/recipe | recipe/core.py | Recipe.subquery | def subquery(self, name=None):
""" The recipe's query as a subquery suitable for use in joins or other
queries.
"""
query = self.query()
return query.subquery(name=name) | python | def subquery(self, name=None):
""" The recipe's query as a subquery suitable for use in joins or other
queries.
"""
query = self.query()
return query.subquery(name=name) | [
"def",
"subquery",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"query",
"(",
")",
"return",
"query",
".",
"subquery",
"(",
"name",
"=",
"name",
")"
] | The recipe's query as a subquery suitable for use in joins or other
queries. | [
"The",
"recipe",
"s",
"query",
"as",
"a",
"subquery",
"suitable",
"for",
"use",
"in",
"joins",
"or",
"other",
"queries",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L519-L524 | train | 52,596 |
juiceinc/recipe | recipe/core.py | Recipe.as_table | def as_table(self, name=None):
""" Return an alias to a table
"""
if name is None:
name = self._id
return alias(self.subquery(), name=name) | python | def as_table(self, name=None):
""" Return an alias to a table
"""
if name is None:
name = self._id
return alias(self.subquery(), name=name) | [
"def",
"as_table",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"_id",
"return",
"alias",
"(",
"self",
".",
"subquery",
"(",
")",
",",
"name",
"=",
"name",
")"
] | Return an alias to a table | [
"Return",
"an",
"alias",
"to",
"a",
"table"
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/core.py#L526-L531 | train | 52,597 |
juiceinc/recipe | recipe/schemas.py | RecipeSchemas._validate_condition_keys | def _validate_condition_keys(self, field, value, error):
"""
Validates that all of the keys in one of the sets of keys are defined
as keys of ``value``.
"""
if 'field' in value:
operators = self.nonscalar_conditions + self.scalar_conditions
matches = sum(1 for k in operators if k in value)
if matches == 0:
error(field, 'Must contain one of {}'.format(operators))
return False
elif matches > 1:
error(
field,
'Must contain no more than one of {}'.format(operators)
)
return False
return True
elif 'and' in value:
for condition in value['and']:
self._validate_condition_keys(field, condition, error)
elif 'or' in value:
for condition in value['or']:
self._validate_condition_keys(field, condition, error)
else:
error(field, "Must contain field + operator keys, 'and', or 'or'.")
return False | python | def _validate_condition_keys(self, field, value, error):
"""
Validates that all of the keys in one of the sets of keys are defined
as keys of ``value``.
"""
if 'field' in value:
operators = self.nonscalar_conditions + self.scalar_conditions
matches = sum(1 for k in operators if k in value)
if matches == 0:
error(field, 'Must contain one of {}'.format(operators))
return False
elif matches > 1:
error(
field,
'Must contain no more than one of {}'.format(operators)
)
return False
return True
elif 'and' in value:
for condition in value['and']:
self._validate_condition_keys(field, condition, error)
elif 'or' in value:
for condition in value['or']:
self._validate_condition_keys(field, condition, error)
else:
error(field, "Must contain field + operator keys, 'and', or 'or'.")
return False | [
"def",
"_validate_condition_keys",
"(",
"self",
",",
"field",
",",
"value",
",",
"error",
")",
":",
"if",
"'field'",
"in",
"value",
":",
"operators",
"=",
"self",
".",
"nonscalar_conditions",
"+",
"self",
".",
"scalar_conditions",
"matches",
"=",
"sum",
"(",... | Validates that all of the keys in one of the sets of keys are defined
as keys of ``value``. | [
"Validates",
"that",
"all",
"of",
"the",
"keys",
"in",
"one",
"of",
"the",
"sets",
"of",
"keys",
"are",
"defined",
"as",
"keys",
"of",
"value",
"."
] | 2e60c2242aeaea3029a2274b31bc3a937761e568 | https://github.com/juiceinc/recipe/blob/2e60c2242aeaea3029a2274b31bc3a937761e568/recipe/schemas.py#L123-L149 | train | 52,598 |
lacava/few | few/selection.py | SurvivalMixin.survival | def survival(self,parents,offspring,elite=None,elite_index=None,X=None,X_O=None,F=None,F_O=None):
"""routes to the survival method, returns survivors"""
if self.sel == 'tournament':
survivors, survivor_index = self.tournament(parents + offspring, self.tourn_size, num_selections = len(parents))
elif self.sel == 'lexicase':
survivor_index = self.lexicase(np.vstack((F,F_O)), num_selections = len(parents), survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
elif self.sel == 'epsilon_lexicase':
# survivors, survivor_index = self.epsilon_lexicase(parents + offspring, num_selections = len(parents), survival = True)
if self.lex_size:
sizes = [len(i.stack) for i in (parents + offspring)]
survivor_index = self.epsilon_lexicase(np.vstack((F,F_O)), sizes, num_selections = F.shape[0], survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
else:
survivor_index = self.epsilon_lexicase(np.vstack((F,F_O)), [], num_selections = F.shape[0], survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
elif self.sel == 'deterministic_crowding':
survivors, survivor_index = self.deterministic_crowding(parents,offspring,X,X_O)
elif self.sel == 'random':
# pdb.set_trace()
survivor_index = self.random_state.permutation(np.arange(2*len(parents)))[:len(parents)]
survivors = [(parents + offspring)[s] for s in survivor_index]
# elitism
if self.elitism:
if min([x.fitness for x in survivors]) > elite.fitness:
# if the elite individual did not survive and elitism is on, replace worst individual with elite
rep_index = np.argmax([x.fitness for x in survivors])
survivors[rep_index] = elite
survivor_index[rep_index] = elite_index
# return survivors
return survivors,survivor_index | python | def survival(self,parents,offspring,elite=None,elite_index=None,X=None,X_O=None,F=None,F_O=None):
"""routes to the survival method, returns survivors"""
if self.sel == 'tournament':
survivors, survivor_index = self.tournament(parents + offspring, self.tourn_size, num_selections = len(parents))
elif self.sel == 'lexicase':
survivor_index = self.lexicase(np.vstack((F,F_O)), num_selections = len(parents), survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
elif self.sel == 'epsilon_lexicase':
# survivors, survivor_index = self.epsilon_lexicase(parents + offspring, num_selections = len(parents), survival = True)
if self.lex_size:
sizes = [len(i.stack) for i in (parents + offspring)]
survivor_index = self.epsilon_lexicase(np.vstack((F,F_O)), sizes, num_selections = F.shape[0], survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
else:
survivor_index = self.epsilon_lexicase(np.vstack((F,F_O)), [], num_selections = F.shape[0], survival = True)
survivors = [(parents+ offspring)[s] for s in survivor_index]
elif self.sel == 'deterministic_crowding':
survivors, survivor_index = self.deterministic_crowding(parents,offspring,X,X_O)
elif self.sel == 'random':
# pdb.set_trace()
survivor_index = self.random_state.permutation(np.arange(2*len(parents)))[:len(parents)]
survivors = [(parents + offspring)[s] for s in survivor_index]
# elitism
if self.elitism:
if min([x.fitness for x in survivors]) > elite.fitness:
# if the elite individual did not survive and elitism is on, replace worst individual with elite
rep_index = np.argmax([x.fitness for x in survivors])
survivors[rep_index] = elite
survivor_index[rep_index] = elite_index
# return survivors
return survivors,survivor_index | [
"def",
"survival",
"(",
"self",
",",
"parents",
",",
"offspring",
",",
"elite",
"=",
"None",
",",
"elite_index",
"=",
"None",
",",
"X",
"=",
"None",
",",
"X_O",
"=",
"None",
",",
"F",
"=",
"None",
",",
"F_O",
"=",
"None",
")",
":",
"if",
"self",
... | routes to the survival method, returns survivors | [
"routes",
"to",
"the",
"survival",
"method",
"returns",
"survivors"
] | 5c72044425e9a5d73b8dc2cbb9b96e873dcb5b4a | https://github.com/lacava/few/blob/5c72044425e9a5d73b8dc2cbb9b96e873dcb5b4a/few/selection.py#L19-L50 | train | 52,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.