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
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Kortemme-Lab/klab
klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py
DBBenchmarkRun.get_experimental_ddg_values
def get_experimental_ddg_values(self, record, dataframe_record): '''Adds the mean experimental value associated with each analysis set to the dataframe row.''' new_idxs = [] for analysis_set in self.get_analysis_sets(record): ddg_details = record['DDG'][analysis_set] exp_...
python
def get_experimental_ddg_values(self, record, dataframe_record): '''Adds the mean experimental value associated with each analysis set to the dataframe row.''' new_idxs = [] for analysis_set in self.get_analysis_sets(record): ddg_details = record['DDG'][analysis_set] exp_...
[ "def", "get_experimental_ddg_values", "(", "self", ",", "record", ",", "dataframe_record", ")", ":", "new_idxs", "=", "[", "]", "for", "analysis_set", "in", "self", ".", "get_analysis_sets", "(", "record", ")", ":", "ddg_details", "=", "record", "[", "'DDG'", ...
Adds the mean experimental value associated with each analysis set to the dataframe row.
[ "Adds", "the", "mean", "experimental", "value", "associated", "with", "each", "analysis", "set", "to", "the", "dataframe", "row", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py#L2314-L2329
train
Kortemme-Lab/klab
klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py
DBBenchmarkRun.compute_stability_classification
def compute_stability_classification(self, predicted_data, record, dataframe_record): '''Calculate the stability classification for the analysis cases. Must be called after get_experimental_ddg_values.''' new_idxs = [] stability_classication_x_cutoff, stability_classication_y_cutoff = self.stab...
python
def compute_stability_classification(self, predicted_data, record, dataframe_record): '''Calculate the stability classification for the analysis cases. Must be called after get_experimental_ddg_values.''' new_idxs = [] stability_classication_x_cutoff, stability_classication_y_cutoff = self.stab...
[ "def", "compute_stability_classification", "(", "self", ",", "predicted_data", ",", "record", ",", "dataframe_record", ")", ":", "new_idxs", "=", "[", "]", "stability_classication_x_cutoff", ",", "stability_classication_y_cutoff", "=", "self", ".", "stability_classication...
Calculate the stability classification for the analysis cases. Must be called after get_experimental_ddg_values.
[ "Calculate", "the", "stability", "classification", "for", "the", "analysis", "cases", ".", "Must", "be", "called", "after", "get_experimental_ddg_values", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py#L2332-L2356
train
Kortemme-Lab/klab
klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py
DBBenchmarkRun.compute_absolute_error
def compute_absolute_error(self, predicted_data, record, dataframe_record): '''Calculate the absolute error for the analysis cases. Must be called after get_experimental_ddg_values.''' new_idxs = [] for analysis_set in self.get_analysis_sets(record): ddg_details = record['DDG'][anal...
python
def compute_absolute_error(self, predicted_data, record, dataframe_record): '''Calculate the absolute error for the analysis cases. Must be called after get_experimental_ddg_values.''' new_idxs = [] for analysis_set in self.get_analysis_sets(record): ddg_details = record['DDG'][anal...
[ "def", "compute_absolute_error", "(", "self", ",", "predicted_data", ",", "record", ",", "dataframe_record", ")", ":", "new_idxs", "=", "[", "]", "for", "analysis_set", "in", "self", ".", "get_analysis_sets", "(", "record", ")", ":", "ddg_details", "=", "recor...
Calculate the absolute error for the analysis cases. Must be called after get_experimental_ddg_values.
[ "Calculate", "the", "absolute", "error", "for", "the", "analysis", "cases", ".", "Must", "be", "called", "after", "get_experimental_ddg_values", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/benchmarking/analysis/ddg_monomeric_stability_analysis.py#L2359-L2378
train
brunato/lograptor
lograptor/application.py
AppRule.add_result
def add_result(self, values): """ Add a tuple or increment the value of an existing one in the rule results dictionary. """ idx = [values['host']] for gid in self.key_gids[1:]: idx.append(values[gid]) idx = tuple(idx) try: ...
python
def add_result(self, values): """ Add a tuple or increment the value of an existing one in the rule results dictionary. """ idx = [values['host']] for gid in self.key_gids[1:]: idx.append(values[gid]) idx = tuple(idx) try: ...
[ "def", "add_result", "(", "self", ",", "values", ")", ":", "idx", "=", "[", "values", "[", "'host'", "]", "]", "for", "gid", "in", "self", ".", "key_gids", "[", "1", ":", "]", ":", "idx", ".", "append", "(", "values", "[", "gid", "]", ")", "idx...
Add a tuple or increment the value of an existing one in the rule results dictionary.
[ "Add", "a", "tuple", "or", "increment", "the", "value", "of", "an", "existing", "one", "in", "the", "rule", "results", "dictionary", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/application.py#L103-L117
train
brunato/lograptor
lograptor/application.py
AppRule.increase_last
def increase_last(self, k): """ Increase the last result by k. """ idx = self._last_idx if idx is not None: self.results[idx] += k
python
def increase_last(self, k): """ Increase the last result by k. """ idx = self._last_idx if idx is not None: self.results[idx] += k
[ "def", "increase_last", "(", "self", ",", "k", ")", ":", "idx", "=", "self", ".", "_last_idx", "if", "idx", "is", "not", "None", ":", "self", ".", "results", "[", "idx", "]", "+=", "k" ]
Increase the last result by k.
[ "Increase", "the", "last", "result", "by", "k", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/application.py#L119-L125
train
brunato/lograptor
lograptor/application.py
AppLogParser.parse_rules
def parse_rules(self): """ Add a set of rules to the app, dividing between filter and other rule set """ # Load patterns: an app is removed when has no defined patterns. try: rule_options = self.config.items('rules') except configparser.NoSectionError: ...
python
def parse_rules(self): """ Add a set of rules to the app, dividing between filter and other rule set """ # Load patterns: an app is removed when has no defined patterns. try: rule_options = self.config.items('rules') except configparser.NoSectionError: ...
[ "def", "parse_rules", "(", "self", ")", ":", "try", ":", "rule_options", "=", "self", ".", "config", ".", "items", "(", "'rules'", ")", "except", "configparser", ".", "NoSectionError", ":", "raise", "LogRaptorConfigError", "(", "\"the app %r has no defined rules!\...
Add a set of rules to the app, dividing between filter and other rule set
[ "Add", "a", "set", "of", "rules", "to", "the", "app", "dividing", "between", "filter", "and", "other", "rule", "set" ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/application.py#L385-L411
train
brunato/lograptor
lograptor/application.py
AppLogParser.increase_last
def increase_last(self, k): """ Increase the counter of the last matched rule by k. """ rule = self._last_rule if rule is not None: rule.increase_last(k)
python
def increase_last(self, k): """ Increase the counter of the last matched rule by k. """ rule = self._last_rule if rule is not None: rule.increase_last(k)
[ "def", "increase_last", "(", "self", ",", "k", ")", ":", "rule", "=", "self", ".", "_last_rule", "if", "rule", "is", "not", "None", ":", "rule", ".", "increase_last", "(", "k", ")" ]
Increase the counter of the last matched rule by k.
[ "Increase", "the", "counter", "of", "the", "last", "matched", "rule", "by", "k", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/application.py#L413-L419
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_sections_by_delegate_and_term
def get_sections_by_delegate_and_term(person, term, future_terms=0, include_secondaries=True, transcriptable_course='yes', delete_...
python
def get_sections_by_delegate_and_term(person, term, future_terms=0, include_secondaries=True, transcriptable_course='yes', delete_...
[ "def", "get_sections_by_delegate_and_term", "(", "person", ",", "term", ",", "future_terms", "=", "0", ",", "include_secondaries", "=", "True", ",", "transcriptable_course", "=", "'yes'", ",", "delete_flag", "=", "[", "'active'", "]", ")", ":", "data", "=", "_...
Returns a list of uw_sws.models.SectionReference objects for the passed grade submission delegate and term. @param: future_terms: 0..400 @param: transcriptable_course: 'yes', 'no', 'all' @param: delete_flag: ['active', 'suspended', 'withdrawn']
[ "Returns", "a", "list", "of", "uw_sws", ".", "models", ".", "SectionReference", "objects", "for", "the", "passed", "grade", "submission", "delegate", "and", "term", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L65-L85
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_sections_by_curriculum_and_term
def get_sections_by_curriculum_and_term(curriculum, term): """ Returns a list of uw_sws.models.SectionReference objects for the passed curriculum and term. """ url = "{}?{}".format( section_res_url_prefix, urlencode([("curriculum_abbreviation", curriculum.label,), ...
python
def get_sections_by_curriculum_and_term(curriculum, term): """ Returns a list of uw_sws.models.SectionReference objects for the passed curriculum and term. """ url = "{}?{}".format( section_res_url_prefix, urlencode([("curriculum_abbreviation", curriculum.label,), ...
[ "def", "get_sections_by_curriculum_and_term", "(", "curriculum", ",", "term", ")", ":", "url", "=", "\"{}?{}\"", ".", "format", "(", "section_res_url_prefix", ",", "urlencode", "(", "[", "(", "\"curriculum_abbreviation\"", ",", "curriculum", ".", "label", ",", ")"...
Returns a list of uw_sws.models.SectionReference objects for the passed curriculum and term.
[ "Returns", "a", "list", "of", "uw_sws", ".", "models", ".", "SectionReference", "objects", "for", "the", "passed", "curriculum", "and", "term", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L88-L98
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_sections_by_building_and_term
def get_sections_by_building_and_term(building, term): """ Returns a list of uw_sws.models.SectionReference objects for the passed building and term. """ url = "{}?{}".format( section_res_url_prefix, urlencode([("quarter", term.quarter.lower(),), ("facility_code", ...
python
def get_sections_by_building_and_term(building, term): """ Returns a list of uw_sws.models.SectionReference objects for the passed building and term. """ url = "{}?{}".format( section_res_url_prefix, urlencode([("quarter", term.quarter.lower(),), ("facility_code", ...
[ "def", "get_sections_by_building_and_term", "(", "building", ",", "term", ")", ":", "url", "=", "\"{}?{}\"", ".", "format", "(", "section_res_url_prefix", ",", "urlencode", "(", "[", "(", "\"quarter\"", ",", "term", ".", "quarter", ".", "lower", "(", ")", ",...
Returns a list of uw_sws.models.SectionReference objects for the passed building and term.
[ "Returns", "a", "list", "of", "uw_sws", ".", "models", ".", "SectionReference", "objects", "for", "the", "passed", "building", "and", "term", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L101-L111
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
_json_to_sectionref
def _json_to_sectionref(data): """ Returns a list of SectionReference object created from the passed json data. """ section_term = None sections = [] for section_data in data.get("Sections", []): if (section_term is None or section_data["Year"] != section_term.year or...
python
def _json_to_sectionref(data): """ Returns a list of SectionReference object created from the passed json data. """ section_term = None sections = [] for section_data in data.get("Sections", []): if (section_term is None or section_data["Year"] != section_term.year or...
[ "def", "_json_to_sectionref", "(", "data", ")", ":", "section_term", "=", "None", "sections", "=", "[", "]", "for", "section_data", "in", "data", ".", "get", "(", "\"Sections\"", ",", "[", "]", ")", ":", "if", "(", "section_term", "is", "None", "or", "...
Returns a list of SectionReference object created from the passed json data.
[ "Returns", "a", "list", "of", "SectionReference", "object", "created", "from", "the", "passed", "json", "data", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L138-L158
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_section_by_url
def get_section_by_url(url, include_instructor_not_on_time_schedule=True): """ Returns a uw_sws.models.Section object for the passed section url. """ if not course_url_pattern.match(url): raise InvalidSectionURL(url) return _json_to_section( get_resource(u...
python
def get_section_by_url(url, include_instructor_not_on_time_schedule=True): """ Returns a uw_sws.models.Section object for the passed section url. """ if not course_url_pattern.match(url): raise InvalidSectionURL(url) return _json_to_section( get_resource(u...
[ "def", "get_section_by_url", "(", "url", ",", "include_instructor_not_on_time_schedule", "=", "True", ")", ":", "if", "not", "course_url_pattern", ".", "match", "(", "url", ")", ":", "raise", "InvalidSectionURL", "(", "url", ")", "return", "_json_to_section", "(",...
Returns a uw_sws.models.Section object for the passed section url.
[ "Returns", "a", "uw_sws", ".", "models", ".", "Section", "object", "for", "the", "passed", "section", "url", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L221-L233
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_section_by_label
def get_section_by_label(label, include_instructor_not_on_time_schedule=True): """ Returns a uw_sws.models.Section object for the passed section label. """ validate_section_label(label) url = "{}/{}.json".format(course_res_url_prefix, encod...
python
def get_section_by_label(label, include_instructor_not_on_time_schedule=True): """ Returns a uw_sws.models.Section object for the passed section label. """ validate_section_label(label) url = "{}/{}.json".format(course_res_url_prefix, encod...
[ "def", "get_section_by_label", "(", "label", ",", "include_instructor_not_on_time_schedule", "=", "True", ")", ":", "validate_section_label", "(", "label", ")", "url", "=", "\"{}/{}.json\"", ".", "format", "(", "course_res_url_prefix", ",", "encode_section_label", "(", ...
Returns a uw_sws.models.Section object for the passed section label.
[ "Returns", "a", "uw_sws", ".", "models", ".", "Section", "object", "for", "the", "passed", "section", "label", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L236-L248
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_linked_sections
def get_linked_sections(section, include_instructor_not_on_time_schedule=True): """ Returns a list of uw_sws.models.Section objects, representing linked sections for the passed section. """ linked_sections = [] for url in section.linked_section_urls: section = ge...
python
def get_linked_sections(section, include_instructor_not_on_time_schedule=True): """ Returns a list of uw_sws.models.Section objects, representing linked sections for the passed section. """ linked_sections = [] for url in section.linked_section_urls: section = ge...
[ "def", "get_linked_sections", "(", "section", ",", "include_instructor_not_on_time_schedule", "=", "True", ")", ":", "linked_sections", "=", "[", "]", "for", "url", "in", "section", ".", "linked_section_urls", ":", "section", "=", "get_section_by_url", "(", "url", ...
Returns a list of uw_sws.models.Section objects, representing linked sections for the passed section.
[ "Returns", "a", "list", "of", "uw_sws", ".", "models", ".", "Section", "objects", "representing", "linked", "sections", "for", "the", "passed", "section", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L251-L264
train
uw-it-aca/uw-restclients-sws
uw_sws/section.py
get_joint_sections
def get_joint_sections(section, include_instructor_not_on_time_schedule=True): """ Returns a list of uw_sws.models.Section objects, representing joint sections for the passed section. """ joint_sections = [] for url in section.joint_section_urls: section = get_sec...
python
def get_joint_sections(section, include_instructor_not_on_time_schedule=True): """ Returns a list of uw_sws.models.Section objects, representing joint sections for the passed section. """ joint_sections = [] for url in section.joint_section_urls: section = get_sec...
[ "def", "get_joint_sections", "(", "section", ",", "include_instructor_not_on_time_schedule", "=", "True", ")", ":", "joint_sections", "=", "[", "]", "for", "url", "in", "section", ".", "joint_section_urls", ":", "section", "=", "get_section_by_url", "(", "url", ",...
Returns a list of uw_sws.models.Section objects, representing joint sections for the passed section.
[ "Returns", "a", "list", "of", "uw_sws", ".", "models", ".", "Section", "objects", "representing", "joint", "sections", "for", "the", "passed", "section", "." ]
4d36776dcca36855fc15c1b8fe7650ae045194cf
https://github.com/uw-it-aca/uw-restclients-sws/blob/4d36776dcca36855fc15c1b8fe7650ae045194cf/uw_sws/section.py#L267-L280
train
Kortemme-Lab/klab
klab/bio/scop.py
SCOPeDatabase.get_chain_details_by_related_pdb_chains
def get_chain_details_by_related_pdb_chains(self, pdb_id, chain_id, pfam_accs): ''' Returns a dict of SCOPe details using info This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the assoc...
python
def get_chain_details_by_related_pdb_chains(self, pdb_id, chain_id, pfam_accs): ''' Returns a dict of SCOPe details using info This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the assoc...
[ "def", "get_chain_details_by_related_pdb_chains", "(", "self", ",", "pdb_id", ",", "chain_id", ",", "pfam_accs", ")", ":", "if", "not", "pfam_accs", ":", "return", "None", "associated_pdb_chains", "=", "set", "(", ")", "pfam_api", "=", "self", ".", "get_pfam_api...
Returns a dict of SCOPe details using info This returns Pfam-level information for a PDB chain i.e. no details on the protein, species, or domain will be returned. If there are SCOPe entries for the associated Pfam accession numbers which agree then this function returns pretty compl...
[ "Returns", "a", "dict", "of", "SCOPe", "details", "using", "info", "This", "returns", "Pfam", "-", "level", "information", "for", "a", "PDB", "chain", "i", ".", "e", ".", "no", "details", "on", "the", "protein", "species", "or", "domain", "will", "be", ...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/scop.py#L216-L275
train
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip.recall_service
def recall_service(self, service): """ This method assumes that its a roll back during a deployment. If not used during a deployment session This method should be extended later to be more useful. """ if not isinstance(service, Service): raise TypeError("service mus...
python
def recall_service(self, service): """ This method assumes that its a roll back during a deployment. If not used during a deployment session This method should be extended later to be more useful. """ if not isinstance(service, Service): raise TypeError("service mus...
[ "def", "recall_service", "(", "self", ",", "service", ")", ":", "if", "not", "isinstance", "(", "service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must be of type Service.\"", ")", "logger", ".", "warning", "(", "\"The deployment for {0} on...
This method assumes that its a roll back during a deployment. If not used during a deployment session This method should be extended later to be more useful.
[ "This", "method", "assumes", "that", "its", "a", "roll", "back", "during", "a", "deployment", ".", "If", "not", "used", "during", "a", "deployment", "session" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L88-L134
train
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip.clean_up_dangling_images
def clean_up_dangling_images(self): """ Clean up all dangling images. """ cargoes = Image.all(client=self._client_session, filters={'dangling': True}) for id, cargo in six.iteritems(cargoes): logger.info("Removing dangling image: {0}".format(id)) cargo.del...
python
def clean_up_dangling_images(self): """ Clean up all dangling images. """ cargoes = Image.all(client=self._client_session, filters={'dangling': True}) for id, cargo in six.iteritems(cargoes): logger.info("Removing dangling image: {0}".format(id)) cargo.del...
[ "def", "clean_up_dangling_images", "(", "self", ")", ":", "cargoes", "=", "Image", ".", "all", "(", "client", "=", "self", ".", "_client_session", ",", "filters", "=", "{", "'dangling'", ":", "True", "}", ")", "for", "id", ",", "cargo", "in", "six", "....
Clean up all dangling images.
[ "Clean", "up", "all", "dangling", "images", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L156-L163
train
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip.offload_all_service_containers
def offload_all_service_containers(self, service): """Deletes all containers related to the service. """ def anonymous(anonymous_service): if not isinstance(anonymous_service, Service): raise TypeError("service must be an instance of Service.") containers...
python
def offload_all_service_containers(self, service): """Deletes all containers related to the service. """ def anonymous(anonymous_service): if not isinstance(anonymous_service, Service): raise TypeError("service must be an instance of Service.") containers...
[ "def", "offload_all_service_containers", "(", "self", ",", "service", ")", ":", "def", "anonymous", "(", "anonymous_service", ")", ":", "if", "not", "isinstance", "(", "anonymous_service", ",", "Service", ")", ":", "raise", "TypeError", "(", "\"service must be an ...
Deletes all containers related to the service.
[ "Deletes", "all", "containers", "related", "to", "the", "service", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L326-L339
train
TUNE-Archive/freight_forwarder
freight_forwarder/container_ship.py
ContainerShip._container_registration
def _container_registration(self, alias): """ Check for an available name and return that to the caller. """ containers = Container.find_by_name(self._client_session, alias) def validate_name(name): valid = True if name in containers: vali...
python
def _container_registration(self, alias): """ Check for an available name and return that to the caller. """ containers = Container.find_by_name(self._client_session, alias) def validate_name(name): valid = True if name in containers: vali...
[ "def", "_container_registration", "(", "self", ",", "alias", ")", ":", "containers", "=", "Container", ".", "find_by_name", "(", "self", ".", "_client_session", ",", "alias", ")", "def", "validate_name", "(", "name", ")", ":", "valid", "=", "True", "if", "...
Check for an available name and return that to the caller.
[ "Check", "for", "an", "available", "name", "and", "return", "that", "to", "the", "caller", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/container_ship.py#L529-L549
train
jpulec/django-protractor
protractor/management/commands/protractor.py
Command.teardown_databases
def teardown_databases(self, old_config, options): """ Destroys all the non-mirror databases. """ if len(old_config) > 1: old_names, mirrors = old_config else: old_names = old_config for connection, old_name, destroy in old_names: if de...
python
def teardown_databases(self, old_config, options): """ Destroys all the non-mirror databases. """ if len(old_config) > 1: old_names, mirrors = old_config else: old_names = old_config for connection, old_name, destroy in old_names: if de...
[ "def", "teardown_databases", "(", "self", ",", "old_config", ",", "options", ")", ":", "if", "len", "(", "old_config", ")", ">", "1", ":", "old_names", ",", "mirrors", "=", "old_config", "else", ":", "old_names", "=", "old_config", "for", "connection", ","...
Destroys all the non-mirror databases.
[ "Destroys", "all", "the", "non", "-", "mirror", "databases", "." ]
3857d651612fd988ff0ab17264d367db5345664a
https://github.com/jpulec/django-protractor/blob/3857d651612fd988ff0ab17264d367db5345664a/protractor/management/commands/protractor.py#L114-L124
train
mardix/Mocha
mocha/extras/jinja_helpers.py
oembed
def oembed(url, class_=""): """ Create OEmbed link {{ url | oembed }} :param url: :param class_: :return: """ o = "<a href=\"{url}\" class=\"oembed {class_}\" ></a>".format(url=url, class_=class_) return Markup(o)
python
def oembed(url, class_=""): """ Create OEmbed link {{ url | oembed }} :param url: :param class_: :return: """ o = "<a href=\"{url}\" class=\"oembed {class_}\" ></a>".format(url=url, class_=class_) return Markup(o)
[ "def", "oembed", "(", "url", ",", "class_", "=", "\"\"", ")", ":", "o", "=", "\"<a href=\\\"{url}\\\" class=\\\"oembed {class_}\\\" ></a>\"", ".", "format", "(", "url", "=", "url", ",", "class_", "=", "class_", ")", "return", "Markup", "(", "o", ")" ]
Create OEmbed link {{ url | oembed }} :param url: :param class_: :return:
[ "Create", "OEmbed", "link" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/jinja_helpers.py#L31-L42
train
mardix/Mocha
mocha/extras/jinja_helpers.py
img_src
def img_src(url, class_="", responsive=False, lazy_load=False, id_=""): """ Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return: """ if not url.startswith("http://") and not url.startswith("https://...
python
def img_src(url, class_="", responsive=False, lazy_load=False, id_=""): """ Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return: """ if not url.startswith("http://") and not url.startswith("https://...
[ "def", "img_src", "(", "url", ",", "class_", "=", "\"\"", ",", "responsive", "=", "False", ",", "lazy_load", "=", "False", ",", "id_", "=", "\"\"", ")", ":", "if", "not", "url", ".", "startswith", "(", "\"http://\"", ")", "and", "not", "url", ".", ...
Create an image src {{ xyz.jpg | img_src }} :param url: :param class_: :param responsive: :param lazy_load: :param id_: :return:
[ "Create", "an", "image", "src" ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/jinja_helpers.py#L45-L72
train
assamite/creamas
creamas/examples/spiro/spiro.py
give_dots_yield
def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(theta) + r_*math.cos((R-r) / r * theta) def y(theta): return (R-r) * math.sin(theta) - r_*math.sin((R-r) / r * theta) thet...
python
def give_dots_yield(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots without numpy using yield. ''' def x(theta): return (R-r) * math.cos(theta) + r_*math.cos((R-r) / r * theta) def y(theta): return (R-r) * math.sin(theta) - r_*math.sin((R-r) / r * theta) thet...
[ "def", "give_dots_yield", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ")", ":", "def", "x", "(", "theta", ")", ":", "return", "(", "R", "-", "r", ")", "*", "math", ".", "cos", ...
Generate Spirograph dots without numpy using yield.
[ "Generate", "Spirograph", "dots", "without", "numpy", "using", "yield", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L14-L26
train
assamite/creamas
creamas/examples/spiro/spiro.py
give_dots
def give_dots(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots with numpy. ''' thetas = np.arange(0, 2*PI*spins, resolution) Rr = R - r x = Rr * np.cos(thetas) + r_*np.cos(Rr / r * thetas) y = Rr * np.sin(thetas) - r_*np.sin(Rr / r * thetas) return x, y
python
def give_dots(R, r, r_, resolution=2*PI/1000, spins=50): '''Generate Spirograph dots with numpy. ''' thetas = np.arange(0, 2*PI*spins, resolution) Rr = R - r x = Rr * np.cos(thetas) + r_*np.cos(Rr / r * thetas) y = Rr * np.sin(thetas) - r_*np.sin(Rr / r * thetas) return x, y
[ "def", "give_dots", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ")", ":", "thetas", "=", "np", ".", "arange", "(", "0", ",", "2", "*", "PI", "*", "spins", ",", "resolution", ")"...
Generate Spirograph dots with numpy.
[ "Generate", "Spirograph", "dots", "with", "numpy", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L29-L36
train
assamite/creamas
creamas/examples/spiro/spiro.py
spiro_image
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
python
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
[ "def", "spiro_image", "(", "R", ",", "r", ",", "r_", ",", "resolution", "=", "2", "*", "PI", "/", "1000", ",", "spins", "=", "50", ",", "size", "=", "[", "32", ",", "32", "]", ")", ":", "x", ",", "y", "=", "give_dots", "(", "200", ",", "r",...
Create image with given Spirograph parameters using numpy and scipy.
[ "Create", "image", "with", "given", "Spirograph", "parameters", "using", "numpy", "and", "scipy", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro.py#L39-L53
train
mardix/Mocha
mocha/extras/md.py
html
def html(text, lazy_images=False): """ To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the ...
python
def html(text, lazy_images=False): """ To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the ...
[ "def", "html", "(", "text", ",", "lazy_images", "=", "False", ")", ":", "extensions", "=", "[", "'markdown.extensions.nl2br'", ",", "'markdown.extensions.sane_lists'", ",", "'markdown.extensions.toc'", ",", "'markdown.extensions.tables'", ",", "OEmbedExtension", "(", ")...
To render a markdown format text into HTML. - If you want to also build a Table of Content inside of the markdow, add the tags: [TOC] It will include a <ul><li>...</ul> of all <h*> :param text: :param lazy_images: bool - If true, it will activate the LazyImageExtension :return:
[ "To", "render", "a", "markdown", "format", "text", "into", "HTML", "." ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L66-L88
train
mardix/Mocha
mocha/extras/md.py
ExtractImagesTreeprocessor.run
def run(self, root): "Find all images and append to markdown.images. " self.markdown.images = [] for image in root.getiterator("img"): self.markdown.images.append(image.attrib["src"])
python
def run(self, root): "Find all images and append to markdown.images. " self.markdown.images = [] for image in root.getiterator("img"): self.markdown.images.append(image.attrib["src"])
[ "def", "run", "(", "self", ",", "root", ")", ":", "\"Find all images and append to markdown.images. \"", "self", ".", "markdown", ".", "images", "=", "[", "]", "for", "image", "in", "root", ".", "getiterator", "(", "\"img\"", ")", ":", "self", ".", "markdown...
Find all images and append to markdown.images.
[ "Find", "all", "images", "and", "append", "to", "markdown", ".", "images", "." ]
bce481cb31a0972061dd99bc548701411dcb9de3
https://github.com/mardix/Mocha/blob/bce481cb31a0972061dd99bc548701411dcb9de3/mocha/extras/md.py#L25-L29
train
jaraco/jaraco.collections
jaraco/collections.py
dict_map
def dict_map(function, dictionary): """ dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) Tr...
python
def dict_map(function, dictionary): """ dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) Tr...
[ "def", "dict_map", "(", "function", ",", "dictionary", ")", ":", "return", "dict", "(", "(", "key", ",", "function", "(", "value", ")", ")", "for", "key", ",", "value", "in", "dictionary", ".", "items", "(", ")", ")" ]
dict_map is much like the built-in function map. It takes a dictionary and applys a function to the values of that dictionary, returning a new dictionary with the mapped values in the original keys. >>> d = dict_map(lambda x:x+1, dict(a=1, b=2)) >>> d == dict(a=2,b=3) True
[ "dict_map", "is", "much", "like", "the", "built", "-", "in", "function", "map", ".", "It", "takes", "a", "dictionary", "and", "applys", "a", "function", "to", "the", "values", "of", "that", "dictionary", "returning", "a", "new", "dictionary", "with", "the"...
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L139-L149
train
jaraco/jaraco.collections
jaraco/collections.py
sorted_items
def sorted_items(d, key=__identity, reverse=False): """ Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=...
python
def sorted_items(d, key=__identity, reverse=False): """ Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=...
[ "def", "sorted_items", "(", "d", ",", "key", "=", "__identity", ",", "reverse", "=", "False", ")", ":", "def", "pairkey_key", "(", "item", ")", ":", "return", "key", "(", "item", "[", "0", "]", ")", "return", "sorted", "(", "d", ".", "items", "(", ...
Return the items of the dictionary sorted by the keys >>> sample = dict(foo=20, bar=42, baz=10) >>> tuple(sorted_items(sample)) (('bar', 42), ('baz', 10), ('foo', 20)) >>> reverse_string = lambda s: ''.join(reversed(s)) >>> tuple(sorted_items(sample, key=reverse_string)) (('foo', 20), ('bar', 42), ('baz', 10)) ...
[ "Return", "the", "items", "of", "the", "dictionary", "sorted", "by", "the", "keys" ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L269-L287
train
jaraco/jaraco.collections
jaraco/collections.py
invert_map
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceba...
python
def invert_map(map): """ Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceba...
[ "def", "invert_map", "(", "map", ")", ":", "res", "=", "dict", "(", "(", "v", ",", "k", ")", "for", "k", ",", "v", "in", "map", ".", "items", "(", ")", ")", "if", "not", "len", "(", "res", ")", "==", "len", "(", "map", ")", ":", "raise", ...
Given a dictionary, return another dictionary with keys and values switched. If any of the values resolve to the same key, raises a ValueError. >>> numbers = dict(a=1, b=2, c=3) >>> letters = invert_map(numbers) >>> letters[1] 'a' >>> numbers['d'] = 3 >>> invert_map(numbers) Traceback (most recent call last):...
[ "Given", "a", "dictionary", "return", "another", "dictionary", "with", "keys", "and", "values", "switched", ".", "If", "any", "of", "the", "values", "resolve", "to", "the", "same", "key", "raises", "a", "ValueError", "." ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L506-L525
train
jaraco/jaraco.collections
jaraco/collections.py
KeyTransformingDict.matching_key_for
def matching_key_for(self, key): """ Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found. """ try: return next(e_key for e_key in self.keys() if e_key == key) except StopIteration: raise KeyError(key)
python
def matching_key_for(self, key): """ Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found. """ try: return next(e_key for e_key in self.keys() if e_key == key) except StopIteration: raise KeyError(key)
[ "def", "matching_key_for", "(", "self", ",", "key", ")", ":", "try", ":", "return", "next", "(", "e_key", "for", "e_key", "in", "self", ".", "keys", "(", ")", "if", "e_key", "==", "key", ")", "except", "StopIteration", ":", "raise", "KeyError", "(", ...
Given a key, return the actual key stored in self that matches. Raise KeyError if the key isn't found.
[ "Given", "a", "key", "return", "the", "actual", "key", "stored", "in", "self", "that", "matches", ".", "Raise", "KeyError", "if", "the", "key", "isn", "t", "found", "." ]
25db1dab06d7108dc0c2b7e83dc7530fb10718d2
https://github.com/jaraco/jaraco.collections/blob/25db1dab06d7108dc0c2b7e83dc7530fb10718d2/jaraco/collections.py#L335-L343
train
cozy/python_cozy_management
cozy_management/backup.py
backup
def backup(backup_filename=None): ''' Backup a Cozy ''' timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) if not backup_filename: if not os.path.isdir(BACKUPS_PATH): print 'Need to create {}'.format(BACKUPS_PATH) os.makedirs(BACKUPS_PATH, 0700) ...
python
def backup(backup_filename=None): ''' Backup a Cozy ''' timestamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime()) if not backup_filename: if not os.path.isdir(BACKUPS_PATH): print 'Need to create {}'.format(BACKUPS_PATH) os.makedirs(BACKUPS_PATH, 0700) ...
[ "def", "backup", "(", "backup_filename", "=", "None", ")", ":", "timestamp", "=", "time", ".", "strftime", "(", "\"%Y-%m-%d-%H-%M-%S\"", ",", "time", ".", "gmtime", "(", ")", ")", "if", "not", "backup_filename", ":", "if", "not", "os", ".", "path", ".", ...
Backup a Cozy
[ "Backup", "a", "Cozy" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/backup.py#L24-L52
train
projectshift/shift-boiler
boiler/cli/db.py
get_config
def get_config(): """ Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it """ from boiler.migra...
python
def get_config(): """ Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it """ from boiler.migra...
[ "def", "get_config", "(", ")", ":", "from", "boiler", ".", "migrations", ".", "config", "import", "MigrationsConfig", "map", "=", "dict", "(", "path", "=", "'MIGRATIONS_PATH'", ",", "db_url", "=", "'SQLALCHEMY_DATABASE_URI'", ",", "metadata", "=", "'SQLAlchemy m...
Prepare and return alembic config These configurations used to live in alembic config initialiser, but that just tight coupling. Ideally we should move that to userspace and find a way to pass these into alembic commands. @todo: think about it
[ "Prepare", "and", "return", "alembic", "config", "These", "configurations", "used", "to", "live", "in", "alembic", "config", "initialiser", "but", "that", "just", "tight", "coupling", ".", "Ideally", "we", "should", "move", "that", "to", "userspace", "and", "f...
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L10-L40
train
projectshift/shift-boiler
boiler/cli/db.py
init
def init(): """ Initialize new migrations directory """ try: config = get_config() print(config.dir) alembic_command.init(config, config.dir, 'project') except CommandError as e: click.echo(red(str(e)))
python
def init(): """ Initialize new migrations directory """ try: config = get_config() print(config.dir) alembic_command.init(config, config.dir, 'project') except CommandError as e: click.echo(red(str(e)))
[ "def", "init", "(", ")", ":", "try", ":", "config", "=", "get_config", "(", ")", "print", "(", "config", ".", "dir", ")", "alembic_command", ".", "init", "(", "config", ",", "config", ".", "dir", ",", "'project'", ")", "except", "CommandError", "as", ...
Initialize new migrations directory
[ "Initialize", "new", "migrations", "directory" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L59-L66
train
projectshift/shift-boiler
boiler/cli/db.py
revision
def revision(revision, path, branch_label, splice, head, sql, autogenerate, message): """ Create new revision file """ alembic_command.revision( config=get_config(), rev_id=revision, version_path=path, branch_label=branch_label, splice=splice, head=head, s...
python
def revision(revision, path, branch_label, splice, head, sql, autogenerate, message): """ Create new revision file """ alembic_command.revision( config=get_config(), rev_id=revision, version_path=path, branch_label=branch_label, splice=splice, head=head, s...
[ "def", "revision", "(", "revision", ",", "path", ",", "branch_label", ",", "splice", ",", "head", ",", "sql", ",", "autogenerate", ",", "message", ")", ":", "alembic_command", ".", "revision", "(", "config", "=", "get_config", "(", ")", ",", "rev_id", "=...
Create new revision file
[ "Create", "new", "revision", "file" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L78-L90
train
projectshift/shift-boiler
boiler/cli/db.py
merge
def merge(revision, branch_label, message, list_revisions=''): """ Merge two revision together, create new revision file """ alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
python
def merge(revision, branch_label, message, list_revisions=''): """ Merge two revision together, create new revision file """ alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
[ "def", "merge", "(", "revision", ",", "branch_label", ",", "message", ",", "list_revisions", "=", "''", ")", ":", "alembic_command", ".", "merge", "(", "config", "=", "get_config", "(", ")", ",", "revisions", "=", "list_revisions", ",", "message", "=", "me...
Merge two revision together, create new revision file
[ "Merge", "two", "revision", "together", "create", "new", "revision", "file" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L121-L129
train
projectshift/shift-boiler
boiler/cli/db.py
up
def up(tag, sql, revision): """ Upgrade to revision """ alembic_command.upgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def up(tag, sql, revision): """ Upgrade to revision """ alembic_command.upgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "up", "(", "tag", ",", "sql", ",", "revision", ")", ":", "alembic_command", ".", "upgrade", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Upgrade to revision
[ "Upgrade", "to", "revision" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L136-L143
train
projectshift/shift-boiler
boiler/cli/db.py
down
def down(tag, sql, revision): """ Downgrade to revision """ alembic_command.downgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def down(tag, sql, revision): """ Downgrade to revision """ alembic_command.downgrade( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "down", "(", "tag", ",", "sql", ",", "revision", ")", ":", "alembic_command", ".", "downgrade", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Downgrade to revision
[ "Downgrade", "to", "revision" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L150-L157
train
projectshift/shift-boiler
boiler/cli/db.py
history
def history(verbose, range): """ List revision changesets chronologically """ alembic_command.history( config=get_config(), rev_range=range, verbose=verbose )
python
def history(verbose, range): """ List revision changesets chronologically """ alembic_command.history( config=get_config(), rev_range=range, verbose=verbose )
[ "def", "history", "(", "verbose", ",", "range", ")", ":", "alembic_command", ".", "history", "(", "config", "=", "get_config", "(", ")", ",", "rev_range", "=", "range", ",", "verbose", "=", "verbose", ")" ]
List revision changesets chronologically
[ "List", "revision", "changesets", "chronologically" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L173-L179
train
projectshift/shift-boiler
boiler/cli/db.py
heads
def heads(resolve, verbose): """ Show available heads """ alembic_command.heads( config=get_config(), verbose=verbose, resolve_dependencies=resolve )
python
def heads(resolve, verbose): """ Show available heads """ alembic_command.heads( config=get_config(), verbose=verbose, resolve_dependencies=resolve )
[ "def", "heads", "(", "resolve", ",", "verbose", ")", ":", "alembic_command", ".", "heads", "(", "config", "=", "get_config", "(", ")", ",", "verbose", "=", "verbose", ",", "resolve_dependencies", "=", "resolve", ")" ]
Show available heads
[ "Show", "available", "heads" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L185-L191
train
projectshift/shift-boiler
boiler/cli/db.py
stamp
def stamp(revision, sql, tag): """ Stamp db to given revision without migrating """ alembic_command.stamp( config=get_config(), revision=revision, sql=sql, tag=tag )
python
def stamp(revision, sql, tag): """ Stamp db to given revision without migrating """ alembic_command.stamp( config=get_config(), revision=revision, sql=sql, tag=tag )
[ "def", "stamp", "(", "revision", ",", "sql", ",", "tag", ")", ":", "alembic_command", ".", "stamp", "(", "config", "=", "get_config", "(", ")", ",", "revision", "=", "revision", ",", "sql", "=", "sql", ",", "tag", "=", "tag", ")" ]
Stamp db to given revision without migrating
[ "Stamp", "db", "to", "given", "revision", "without", "migrating" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/cli/db.py#L218-L225
train
Kortemme-Lab/klab
klab/db/sqlalchemy_interface.py
get_or_create_in_transaction
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): ''' Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing re...
python
def get_or_create_in_transaction(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): ''' Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing re...
[ "def", "get_or_create_in_transaction", "(", "tsession", ",", "model", ",", "values", ",", "missing_columns", "=", "[", "]", ",", "variable_columns", "=", "[", "]", ",", "updatable_columns", "=", "[", "]", ",", "only_use_supplied_columns", "=", "False", ",", "r...
Uses the SQLAlchemy model to retrieve an existing record based on the supplied field values or, if there is no existing record, to create a new database record. :param tsession: An SQLAlchemy transactioned session :param model: The name of the SQLAlchemy class representing the table :param values: A di...
[ "Uses", "the", "SQLAlchemy", "model", "to", "retrieve", "an", "existing", "record", "based", "on", "the", "supplied", "field", "values", "or", "if", "there", "is", "no", "existing", "record", "to", "create", "a", "new", "database", "record", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L74-L137
train
Kortemme-Lab/klab
klab/db/sqlalchemy_interface.py
get_or_create_in_transaction_wrapper
def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): '''This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling...
python
def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False): '''This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling...
[ "def", "get_or_create_in_transaction_wrapper", "(", "tsession", ",", "model", ",", "values", ",", "missing_columns", "=", "[", "]", ",", "variable_columns", "=", "[", "]", ",", "updatable_columns", "=", "[", "]", ",", "only_use_supplied_columns", "=", "False", "...
This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling the database API. Switch out calls to get_or_create_in_transaction to get_or_create_in_transaction_wrapper in the suspected functions to determine where the pain lies.
[ "This", "function", "can", "be", "used", "to", "determine", "which", "calling", "method", "is", "spending", "time", "in", "get_or_create_in_transaction", "when", "profiling", "the", "database", "API", ".", "Switch", "out", "calls", "to", "get_or_create_in_transactio...
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/db/sqlalchemy_interface.py#L140-L143
train
assamite/creamas
creamas/rules/agent.py
RuleAgent.get_weight
def get_weight(self, rule): """Get weight for rule. If rule is not in :attr:`R`, returns ``None``. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to get weight ({}) is not subclass " "of {} or {}.".format(rule, Rule...
python
def get_weight(self, rule): """Get weight for rule. If rule is not in :attr:`R`, returns ``None``. """ if not issubclass(rule.__class__, (Rule, RuleLeaf)): raise TypeError("Rule to get weight ({}) is not subclass " "of {} or {}.".format(rule, Rule...
[ "def", "get_weight", "(", "self", ",", "rule", ")", ":", "if", "not", "issubclass", "(", "rule", ".", "__class__", ",", "(", "Rule", ",", "RuleLeaf", ")", ")", ":", "raise", "TypeError", "(", "\"Rule to get weight ({}) is not subclass \"", "\"of {} or {}.\"", ...
Get weight for rule. If rule is not in :attr:`R`, returns ``None``.
[ "Get", "weight", "for", "rule", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L68-L80
train
assamite/creamas
creamas/rules/agent.py
RuleAgent.evaluate
def evaluate(self, artifact): r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evalu...
python
def evaluate(self, artifact): r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evalu...
[ "def", "evaluate", "(", "self", ",", "artifact", ")", ":", "r", "s", "=", "0", "w", "=", "0.0", "if", "len", "(", "self", ".", "R", ")", "==", "0", ":", "return", "0.0", ",", "None", "for", "i", "in", "range", "(", "len", "(", "self", ".", ...
r"""Evaluate artifact with agent's current rules and weights. :param artifact: :class:`~creamas.core.artifact.Artifact` to be evaluated :type artifact: :py:class:`~creamas.core.artifact.Artifact` :returns: Agent's evaluation of the artifact, in [-1,1], and ...
[ "r", "Evaluate", "artifact", "with", "agent", "s", "current", "rules", "and", "weights", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/rules/agent.py#L129-L167
train
TheGhouls/oct
oct/results/report.py
ReportResults._init_dates
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
python
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
[ "def", "_init_dates", "(", "self", ")", ":", "if", "self", ".", "total_transactions", "==", "0", ":", "return", "None", "self", ".", "epoch_start", "=", "Result", ".", "select", "(", "Result", ".", "epoch", ")", ".", "order_by", "(", "Result", ".", "ep...
Initialize all dates properties
[ "Initialize", "all", "dates", "properties" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L29-L37
train
TheGhouls/oct
oct/results/report.py
ReportResults._init_dataframes
def _init_dataframes(self): """Initialise the main dataframe for the results and the custom timers dataframes """ df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC", db.get_conn()) self._get_all_tim...
python
def _init_dataframes(self): """Initialise the main dataframe for the results and the custom timers dataframes """ df = pd.read_sql_query("SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC", db.get_conn()) self._get_all_tim...
[ "def", "_init_dataframes", "(", "self", ")", ":", "df", "=", "pd", ".", "read_sql_query", "(", "\"SELECT elapsed, epoch, scriptrun_time, custom_timers FROM result ORDER BY epoch ASC\"", ",", "db", ".", "get_conn", "(", ")", ")", "self", ".", "_get_all_timers", "(", "d...
Initialise the main dataframe for the results and the custom timers dataframes
[ "Initialise", "the", "main", "dataframe", "for", "the", "results", "and", "the", "custom", "timers", "dataframes" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L39-L56
train
TheGhouls/oct
oct/results/report.py
ReportResults._get_all_timers
def _get_all_timers(self, dataframe): """Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results """ s = dataframe['custom_timers'].apply(json.loads) s.index = dataframe['epoch'] for index, value i...
python
def _get_all_timers(self, dataframe): """Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results """ s = dataframe['custom_timers'].apply(json.loads) s.index = dataframe['epoch'] for index, value i...
[ "def", "_get_all_timers", "(", "self", ",", "dataframe", ")", ":", "s", "=", "dataframe", "[", "'custom_timers'", "]", ".", "apply", "(", "json", ".", "loads", ")", "s", ".", "index", "=", "dataframe", "[", "'epoch'", "]", "for", "index", ",", "value",...
Get all timers and set them in the _timers_values property :param pandas.DataFrame dataframe: the main dataframe with row results
[ "Get", "all", "timers", "and", "set", "them", "in", "the", "_timers_values", "property" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L58-L72
train
TheGhouls/oct
oct/results/report.py
ReportResults._get_processed_dataframe
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dat...
python
def _get_processed_dataframe(self, dataframe): """Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict """ dat...
[ "def", "_get_processed_dataframe", "(", "self", ",", "dataframe", ")", ":", "dataframe", ".", "index", "=", "pd", ".", "to_datetime", "(", "dataframe", "[", "'epoch'", "]", ",", "unit", "=", "'s'", ",", "utc", "=", "True", ")", "del", "dataframe", "[", ...
Generate required dataframe for results from raw dataframe :param pandas.DataFrame dataframe: the raw dataframe :return: a dict containing raw, compiled, and summary dataframes from original dataframe :rtype: dict
[ "Generate", "required", "dataframe", "for", "results", "from", "raw", "dataframe" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L74-L91
train
TheGhouls/oct
oct/results/report.py
ReportResults._init_turrets
def _init_turrets(self): """Setup data from database """ for turret in Turret.select(): self.turrets.append(turret.to_dict())
python
def _init_turrets(self): """Setup data from database """ for turret in Turret.select(): self.turrets.append(turret.to_dict())
[ "def", "_init_turrets", "(", "self", ")", ":", "for", "turret", "in", "Turret", ".", "select", "(", ")", ":", "self", ".", "turrets", ".", "append", "(", "turret", ".", "to_dict", "(", ")", ")" ]
Setup data from database
[ "Setup", "data", "from", "database" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L93-L97
train
TheGhouls/oct
oct/results/report.py
ReportResults.compile_results
def compile_results(self): """Compile all results for the current test """ self._init_dataframes() self.total_transactions = len(self.main_results['raw']) self._init_dates()
python
def compile_results(self): """Compile all results for the current test """ self._init_dataframes() self.total_transactions = len(self.main_results['raw']) self._init_dates()
[ "def", "compile_results", "(", "self", ")", ":", "self", ".", "_init_dataframes", "(", ")", "self", ".", "total_transactions", "=", "len", "(", "self", ".", "main_results", "[", "'raw'", "]", ")", "self", ".", "_init_dates", "(", ")" ]
Compile all results for the current test
[ "Compile", "all", "results", "for", "the", "current", "test" ]
7e9bddeb3b8495a26442b1c86744e9fb187fe88f
https://github.com/TheGhouls/oct/blob/7e9bddeb3b8495a26442b1c86744e9fb187fe88f/oct/results/report.py#L99-L105
train
Kortemme-Lab/klab
klab/bio/kabsch.py
centroid
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
python
def centroid(X): """ Calculate the centroid from a matrix X """ C = np.sum(X, axis=0) / len(X) return C
[ "def", "centroid", "(", "X", ")", ":", "C", "=", "np", ".", "sum", "(", "X", ",", "axis", "=", "0", ")", "/", "len", "(", "X", ")", "return", "C" ]
Calculate the centroid from a matrix X
[ "Calculate", "the", "centroid", "from", "a", "matrix", "X" ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/kabsch.py#L30-L35
train
eventbrite/rebar
src/rebar/validators.py
StateValidator.is_valid
def is_valid(self, instance): """Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called. """ errors = self.errors(instance) if...
python
def is_valid(self, instance): """Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called. """ errors = self.errors(instance) if...
[ "def", "is_valid", "(", "self", ",", "instance", ")", ":", "errors", "=", "self", ".", "errors", "(", "instance", ")", "if", "isinstance", "(", "errors", ",", "list", ")", ":", "return", "not", "any", "(", "errors", ")", "return", "not", "bool", "(",...
Return True if no errors are raised when validating instance. instance can be a dict (ie, form.cleaned_data), a form, or a model instance. If instance is a form, full_clean() will be called.
[ "Return", "True", "if", "no", "errors", "are", "raised", "when", "validating", "instance", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L80-L93
train
eventbrite/rebar
src/rebar/validators.py
StateValidator._validate
def _validate(self, data): """Helper to run validators on the field data.""" errors = {} # if the validator is not enabled, return the empty error dict if not self._enabled: return errors for field in self.validators: field_errors = [] for...
python
def _validate(self, data): """Helper to run validators on the field data.""" errors = {} # if the validator is not enabled, return the empty error dict if not self._enabled: return errors for field in self.validators: field_errors = [] for...
[ "def", "_validate", "(", "self", ",", "data", ")", ":", "errors", "=", "{", "}", "if", "not", "self", ".", "_enabled", ":", "return", "errors", "for", "field", "in", "self", ".", "validators", ":", "field_errors", "=", "[", "]", "for", "validator", "...
Helper to run validators on the field data.
[ "Helper", "to", "run", "validators", "on", "the", "field", "data", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L95-L118
train
eventbrite/rebar
src/rebar/validators.py
StateValidator.errors
def errors(self, instance): """Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be cal...
python
def errors(self, instance): """Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be cal...
[ "def", "errors", "(", "self", ",", "instance", ")", ":", "if", "isinstance", "(", "instance", ",", "dict", ")", ":", "return", "self", ".", "_validate", "(", "instance", ")", "elif", "isinstance", "(", "instance", ",", "forms", ".", "BaseForm", ")", ":...
Run all field validators and return a dict of errors. The keys of the resulting dict coorespond to field names. instance can be a dict (ie, form.cleaned_data), a form, a formset, or a model instance. If instance is a form, full_clean() will be called if the form is bound. ...
[ "Run", "all", "field", "validators", "and", "return", "a", "dict", "of", "errors", "." ]
32f8914a2c5529519009d21c85f0d47cc6601901
https://github.com/eventbrite/rebar/blob/32f8914a2c5529519009d21c85f0d47cc6601901/src/rebar/validators.py#L120-L173
train
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/relational.py
queryset_formatter
def queryset_formatter(queryset): """ This is used for custom detail fields returning a QuerySet of admin objects. """ return Markup( base_list_formatter( None, [ '<a href="{}">{}</a>'.format(u.get_admin_url(_external=True), u) for u in...
python
def queryset_formatter(queryset): """ This is used for custom detail fields returning a QuerySet of admin objects. """ return Markup( base_list_formatter( None, [ '<a href="{}">{}</a>'.format(u.get_admin_url(_external=True), u) for u in...
[ "def", "queryset_formatter", "(", "queryset", ")", ":", "return", "Markup", "(", "base_list_formatter", "(", "None", ",", "[", "'<a href=\"{}\">{}</a>'", ".", "format", "(", "u", ".", "get_admin_url", "(", "_external", "=", "True", ")", ",", "u", ")", "for",...
This is used for custom detail fields returning a QuerySet of admin objects.
[ "This", "is", "used", "for", "custom", "detail", "fields", "returning", "a", "QuerySet", "of", "admin", "objects", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/relational.py#L8-L21
train
peergradeio/flask-mongo-profiler
flask_mongo_profiler/contrib/flask_admin/formatters/relational.py
qs_field
def qs_field( model_class, field, filters=None, formatter=queryset_formatter, manager_name='objects', ): """ Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ...
python
def qs_field( model_class, field, filters=None, formatter=queryset_formatter, manager_name='objects', ): """ Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ...
[ "def", "qs_field", "(", "model_class", ",", "field", ",", "filters", "=", "None", ",", "formatter", "=", "queryset_formatter", ",", "manager_name", "=", "'objects'", ",", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "{", "}", "def", "_",...
Show computed fields based on QuerySet's. This is a workaround since sometimes some filtering is involved to see if a user owns and object, is a student, etc. Example ------- class MyModel(ModelView): details_extra_columns = [ ('courses_owned', 'Courses (Owner of)'), ] ...
[ "Show", "computed", "fields", "based", "on", "QuerySet", "s", "." ]
a267eeb49fea07c9a24fb370bd9d7a90ed313ccf
https://github.com/peergradeio/flask-mongo-profiler/blob/a267eeb49fea07c9a24fb370bd9d7a90ed313ccf/flask_mongo_profiler/contrib/flask_admin/formatters/relational.py#L24-L57
train
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM._get_pdb_id
def _get_pdb_id(self, elem, **kwargs): '''If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.''' id = elem.attrib['ID'] if self.restrict_to_transmembrane_proteins: tmp = elem.attrib['TMP'] ...
python
def _get_pdb_id(self, elem, **kwargs): '''If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.''' id = elem.attrib['ID'] if self.restrict_to_transmembrane_proteins: tmp = elem.attrib['TMP'] ...
[ "def", "_get_pdb_id", "(", "self", ",", "elem", ",", "**", "kwargs", ")", ":", "id", "=", "elem", ".", "attrib", "[", "'ID'", "]", "if", "self", ".", "restrict_to_transmembrane_proteins", ":", "tmp", "=", "elem", ".", "attrib", "[", "'TMP'", "]", "asse...
If self.restrict_to_transmembrane_proteins is False then this adds all ids to self.ids. Otherwise, only transmembrane protein ids are added.
[ "If", "self", ".", "restrict_to_transmembrane_proteins", "is", "False", "then", "this", "adds", "all", "ids", "to", "self", ".", "ids", ".", "Otherwise", "only", "transmembrane", "protein", "ids", "are", "added", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L61-L70
train
Kortemme-Lab/klab
klab/bio/pdbtm.py
PDBTM.get_xml
def get_xml(self, pdb_id): ''' Returns the XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_xml, pdb_id = pdb_id.upper()) ...
python
def get_xml(self, pdb_id): ''' Returns the XML for pdb_id if the tag exists.''' self.tmp_string = None context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type) try: fast_iter(context, self._get_xml, pdb_id = pdb_id.upper()) ...
[ "def", "get_xml", "(", "self", ",", "pdb_id", ")", ":", "self", ".", "tmp_string", "=", "None", "context", "=", "etree", ".", "iterparse", "(", "io", ".", "BytesIO", "(", "self", ".", "xml_contents", ")", ",", "events", "=", "(", "'end'", ",", ")", ...
Returns the XML for pdb_id if the tag exists.
[ "Returns", "the", "XML", "for", "pdb_id", "if", "the", "tag", "exists", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/bio/pdbtm.py#L117-L124
train
uogbuji/versa
tools/py/driver/mongo.py
connection.multimatch
def multimatch(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of...
python
def multimatch(self, origin=None, rel=None, target=None, attrs=None, include_ids=False): ''' Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of...
[ "def", "multimatch", "(", "self", ",", "origin", "=", "None", ",", "rel", "=", "None", ",", "target", "=", "None", ",", "attrs", "=", "None", ",", "include_ids", "=", "False", ")", ":", "raise", "NotImplementedError", "origin", "=", "origin", "if", "or...
Iterator over relationship IDs that match a pattern of components, with multiple options provided for each component origin - (optional) origin of the relationship (similar to an RDF subject), or set of values. If omitted any origin will be matched. rel - (optional) type IRI of the relationship (simila...
[ "Iterator", "over", "relationship", "IDs", "that", "match", "a", "pattern", "of", "components", "with", "multiple", "options", "provided", "for", "each", "component" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L167-L198
train
uogbuji/versa
tools/py/driver/mongo.py
connection.add
def add(self, origin, rel, target, attrs=None): ''' Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), ...
python
def add(self, origin, rel, target, attrs=None): ''' Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), ...
[ "def", "add", "(", "self", ",", "origin", ",", "rel", ",", "target", ",", "attrs", "=", "None", ")", ":", "if", "not", "origin", ":", "raise", "ValueError", "(", "'Relationship origin cannot be null'", ")", "if", "not", "rel", ":", "raise", "ValueError", ...
Add one relationship to the model origin - origin of the relationship (similar to an RDF subject) rel - type IRI of the relationship (similar to an RDF predicate) target - target of the relationship (similar to an RDF object), a boolean, floating point or unicode object attrs - optional...
[ "Add", "one", "relationship", "to", "the", "model" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L200-L232
train
uogbuji/versa
tools/py/driver/mongo.py
connection.remove
def remove(self, index): ''' Delete one or more relationship, by index, from the extent index - either a single index or a list of indices ''' raise NotImplementedError if hasattr(index, '__iter__'): ind = set(index) else: ind = [index] ...
python
def remove(self, index): ''' Delete one or more relationship, by index, from the extent index - either a single index or a list of indices ''' raise NotImplementedError if hasattr(index, '__iter__'): ind = set(index) else: ind = [index] ...
[ "def", "remove", "(", "self", ",", "index", ")", ":", "raise", "NotImplementedError", "if", "hasattr", "(", "index", ",", "'__iter__'", ")", ":", "ind", "=", "set", "(", "index", ")", "else", ":", "ind", "=", "[", "index", "]", "self", ".", "_relatio...
Delete one or more relationship, by index, from the extent index - either a single index or a list of indices
[ "Delete", "one", "or", "more", "relationship", "by", "index", "from", "the", "extent" ]
f092ffc7ed363a5b170890955168500f32de0dd5
https://github.com/uogbuji/versa/blob/f092ffc7ed363a5b170890955168500f32de0dd5/tools/py/driver/mongo.py#L260-L273
train
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.act
async def act(self): '''Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details. ''' # Learn from domain artifacts. self.age += 1 self.added_last = False self.learn_from_domain(method=self.env_learning_method, ...
python
async def act(self): '''Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details. ''' # Learn from domain artifacts. self.age += 1 self.added_last = False self.learn_from_domain(method=self.env_learning_method, ...
[ "async", "def", "act", "(", "self", ")", ":", "self", ".", "age", "+=", "1", "self", ".", "added_last", "=", "False", "self", ".", "learn_from_domain", "(", "method", "=", "self", ".", "env_learning_method", ",", "amount", "=", "self", ".", "env_learning...
Agent's main method to create new spirographs. See Simulation and CreativeAgent documentation for details.
[ "Agent", "s", "main", "method", "to", "create", "new", "spirographs", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L213-L246
train
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.learn_from_domain
def learn_from_domain(self, method='random', amount=10): '''Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples c...
python
def learn_from_domain(self, method='random', amount=10): '''Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples c...
[ "def", "learn_from_domain", "(", "self", ",", "method", "=", "'random'", ",", "amount", "=", "10", ")", ":", "if", "method", "==", "'none'", ":", "return", "arts", "=", "self", ".", "env", ".", "artifacts", "if", "len", "(", "arts", ")", "==", "0", ...
Learn SOM from artifacts introduced to the environment. :param str method: learning method, should be either 'random' or 'closest', where 'random' chooses **amount** random artifacts, and 'closest' samples closest artifacts based on spirograph generation artifacts. :...
[ "Learn", "SOM", "from", "artifacts", "introduced", "to", "the", "environment", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L248-L279
train
assamite/creamas
creamas/examples/spiro/spiro_agent.py
SpiroAgent.plot_distances
def plot_distances(self, mean_dist, distances, indeces): '''Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs. ''' from matplotlib import pyplot as plt x = np.arange(len(distances)) y = [mean_dist for i in x] fig, ax = plt.subp...
python
def plot_distances(self, mean_dist, distances, indeces): '''Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs. ''' from matplotlib import pyplot as plt x = np.arange(len(distances)) y = [mean_dist for i in x] fig, ax = plt.subp...
[ "def", "plot_distances", "(", "self", ",", "mean_dist", ",", "distances", ",", "indeces", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "x", "=", "np", ".", "arange", "(", "len", "(", "distances", ")", ")", "y", "=", "[", "mean_dist"...
Plot distances of the generated spirographs w.r.t. the previously generated spirogaphs.
[ "Plot", "distances", "of", "the", "generated", "spirographs", "w", ".", "r", ".", "t", ".", "the", "previously", "generated", "spirogaphs", "." ]
54dc3e31c97a3f938e58272f8ab80b6bcafeff58
https://github.com/assamite/creamas/blob/54dc3e31c97a3f938e58272f8ab80b6bcafeff58/creamas/examples/spiro/spiro_agent.py#L353-L383
train
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
get_qtls_from_mapqtl_data
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
python
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile): """Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective...
[ "def", "get_qtls_from_mapqtl_data", "(", "matrix", ",", "threshold", ",", "inputfile", ")", ":", "trait_name", "=", "inputfile", ".", "split", "(", "')_'", ",", "1", ")", "[", "1", "]", ".", "split", "(", "'.mqo'", ")", "[", "0", "]", "qtls", "=", "[...
Extract the QTLs found by MapQTL reading its file. This assume that there is only one QTL per linkage group. :arg matrix, the MapQTL file read in memory :arg threshold, threshold used to determine if a given LOD value is reflective the presence of a QTL. :arg inputfile, name of the inputfile in...
[ "Extract", "the", "QTLs", "found", "by", "MapQTL", "reading", "its", "file", ".", "This", "assume", "that", "there", "is", "only", "one", "QTL", "per", "linkage", "group", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L89-L123
train
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.get_files
def get_files(cls, folder, session_id=''): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to t...
python
def get_files(cls, folder, session_id=''): """ Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to t...
[ "def", "get_files", "(", "cls", ",", "folder", ",", "session_id", "=", "''", ")", ":", "filelist", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return", "filelist", "if", "sess...
Retrieve the list of files the plugin can work on. Find this list based on the files name, files extension or even actually by reading in the file. If a session identifier is specified it will restrict the list of files returned to those with this session identifier in their name...
[ "Retrieve", "the", "list", "of", "files", "the", "plugin", "can", "work", "on", ".", "Find", "this", "list", "based", "on", "the", "files", "name", "files", "extension", "or", "even", "actually", "by", "reading", "in", "the", "file", ".", "If", "a", "s...
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L155-L180
train
PBR/MQ2
MQ2/plugins/mapqtl_plugin.py
MapQTLPlugin.get_session_identifiers
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the pa...
python
def get_session_identifiers(cls, folder=None, inputfile=None): """ Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the pa...
[ "def", "get_session_identifiers", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ")", ":", "sessions", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return...
Retrieve the list of session identifiers contained in the data on the folder. :kwarg folder: the path to the folder containing the files to check. This folder may contain sub-folders. :kwarg inputfile: the path to the input file to use
[ "Retrieve", "the", "list", "of", "session", "identifiers", "contained", "in", "the", "data", "on", "the", "folder", "." ]
6d84dea47e6751333004743f588f03158e35c28d
https://github.com/PBR/MQ2/blob/6d84dea47e6751333004743f588f03158e35c28d/MQ2/plugins/mapqtl_plugin.py#L183-L202
train
Kortemme-Lab/klab
klab/general/strutil.py
parse_range
def parse_range(s, range_separator = '-'): ''' Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014. ''' return reduce(lambda x,y: x+y, (map(lambda r: (range(int(r.split(range_separator)[0]), int(r.split(range_sep...
python
def parse_range(s, range_separator = '-'): ''' Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014. ''' return reduce(lambda x,y: x+y, (map(lambda r: (range(int(r.split(range_separator)[0]), int(r.split(range_sep...
[ "def", "parse_range", "(", "s", ",", "range_separator", "=", "'-'", ")", ":", "return", "reduce", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ",", "(", "map", "(", "lambda", "r", ":", "(", "range", "(", "int", "(", "r", ".", "split", "(",...
Parses the string s which contains indices and ranges and returns the explicit list of integers defined by s. Written by Laurens Kraal 2014.
[ "Parses", "the", "string", "s", "which", "contains", "indices", "and", "ranges", "and", "returns", "the", "explicit", "list", "of", "integers", "defined", "by", "s", ".", "Written", "by", "Laurens", "Kraal", "2014", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L15-L19
train
Kortemme-Lab/klab
klab/general/strutil.py
merge_range_pairs
def merge_range_pairs(prs): '''Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.''' new_prs = [] sprs = [sorted(p) for p in prs] sprs = sorted(sprs) merged = False x = 0 while x < len(sprs): newx = x + 1 new_pair = list(sprs[x]) ...
python
def merge_range_pairs(prs): '''Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.''' new_prs = [] sprs = [sorted(p) for p in prs] sprs = sorted(sprs) merged = False x = 0 while x < len(sprs): newx = x + 1 new_pair = list(sprs[x]) ...
[ "def", "merge_range_pairs", "(", "prs", ")", ":", "new_prs", "=", "[", "]", "sprs", "=", "[", "sorted", "(", "p", ")", "for", "p", "in", "prs", "]", "sprs", "=", "sorted", "(", "sprs", ")", "merged", "=", "False", "x", "=", "0", "while", "x", "...
Takes in a list of pairs specifying ranges and returns a sorted list of merged, sorted ranges.
[ "Takes", "in", "a", "list", "of", "pairs", "specifying", "ranges", "and", "returns", "a", "sorted", "list", "of", "merged", "sorted", "ranges", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L36-L54
train
Kortemme-Lab/klab
klab/general/strutil.py
split_pdb_residue
def split_pdb_residue(s): '''Splits a PDB residue into the numeric and insertion code components.''' if s.isdigit(): return (int(s), ' ') else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
python
def split_pdb_residue(s): '''Splits a PDB residue into the numeric and insertion code components.''' if s.isdigit(): return (int(s), ' ') else: assert(s[:-1].isdigit()) return ((s[:-1], s[-1]))
[ "def", "split_pdb_residue", "(", "s", ")", ":", "if", "s", ".", "isdigit", "(", ")", ":", "return", "(", "int", "(", "s", ")", ",", "' '", ")", "else", ":", "assert", "(", "s", "[", ":", "-", "1", "]", ".", "isdigit", "(", ")", ")", "return",...
Splits a PDB residue into the numeric and insertion code components.
[ "Splits", "a", "PDB", "residue", "into", "the", "numeric", "and", "insertion", "code", "components", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/general/strutil.py#L57-L63
train
brunato/lograptor
lograptor/utils.py
do_chunked_gzip
def do_chunked_gzip(infh, outfh, filename): """ A memory-friendly way of compressing the data. """ import gzip gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh) if infh.closed: infh = open(infh.name, 'r') else: infh.seek(0) readsize = 0 sys.stdout.w...
python
def do_chunked_gzip(infh, outfh, filename): """ A memory-friendly way of compressing the data. """ import gzip gzfh = gzip.GzipFile('rawlogs', mode='wb', fileobj=outfh) if infh.closed: infh = open(infh.name, 'r') else: infh.seek(0) readsize = 0 sys.stdout.w...
[ "def", "do_chunked_gzip", "(", "infh", ",", "outfh", ",", "filename", ")", ":", "import", "gzip", "gzfh", "=", "gzip", ".", "GzipFile", "(", "'rawlogs'", ",", "mode", "=", "'wb'", ",", "fileobj", "=", "outfh", ")", "if", "infh", ".", "closed", ":", "...
A memory-friendly way of compressing the data.
[ "A", "memory", "-", "friendly", "way", "of", "compressing", "the", "data", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L42-L75
train
brunato/lograptor
lograptor/utils.py
mail_message
def mail_message(smtp_server, message, from_address, rcpt_addresses): """ Send mail using smtp. """ if smtp_server[0] == '/': # Sending the message with local sendmail p = os.popen(smtp_server, 'w') p.write(message) p.close() else: # Sending the message using ...
python
def mail_message(smtp_server, message, from_address, rcpt_addresses): """ Send mail using smtp. """ if smtp_server[0] == '/': # Sending the message with local sendmail p = os.popen(smtp_server, 'w') p.write(message) p.close() else: # Sending the message using ...
[ "def", "mail_message", "(", "smtp_server", ",", "message", ",", "from_address", ",", "rcpt_addresses", ")", ":", "if", "smtp_server", "[", "0", "]", "==", "'/'", ":", "p", "=", "os", ".", "popen", "(", "smtp_server", ",", "'w'", ")", "p", ".", "write",...
Send mail using smtp.
[ "Send", "mail", "using", "smtp", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L78-L93
train
brunato/lograptor
lograptor/utils.py
get_value_unit
def get_value_unit(value, unit, prefix): """ Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round. """ prefixes = ('', 'K', 'M', 'G', 'T') if len(unit): if...
python
def get_value_unit(value, unit, prefix): """ Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round. """ prefixes = ('', 'K', 'M', 'G', 'T') if len(unit): if...
[ "def", "get_value_unit", "(", "value", ",", "unit", ",", "prefix", ")", ":", "prefixes", "=", "(", "''", ",", "'K'", ",", "'M'", ",", "'G'", ",", "'T'", ")", "if", "len", "(", "unit", ")", ":", "if", "unit", "[", ":", "1", "]", "in", "prefixes"...
Return a human-readable value with unit specification. Try to transform the unit prefix to the one passed as parameter. When transform to higher prefix apply nearest integer round.
[ "Return", "a", "human", "-", "readable", "value", "with", "unit", "specification", ".", "Try", "to", "transform", "the", "unit", "prefix", "to", "the", "one", "passed", "as", "parameter", ".", "When", "transform", "to", "higher", "prefix", "apply", "nearest"...
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L96-L124
train
brunato/lograptor
lograptor/utils.py
get_fmt_results
def get_fmt_results(results, limit=5, sep='::', fmt=None): """ Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements ...
python
def get_fmt_results(results, limit=5, sep='::', fmt=None): """ Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements ...
[ "def", "get_fmt_results", "(", "results", ",", "limit", "=", "5", ",", "sep", "=", "'::'", ",", "fmt", "=", "None", ")", ":", "result_list", "=", "[", "]", "for", "key", "in", "sorted", "(", "results", ",", "key", "=", "lambda", "x", ":", "results"...
Return a list of formatted strings representation on a result dictionary. The elements of the key are divided by a separator string. The result is appended after the key between parentheses. Apply a format transformation to odd elements of the key if a fmt parameter is passed.
[ "Return", "a", "list", "of", "formatted", "strings", "representation", "on", "a", "result", "dictionary", ".", "The", "elements", "of", "the", "key", "are", "divided", "by", "a", "separator", "string", ".", "The", "result", "is", "appended", "after", "the", ...
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L137-L164
train
brunato/lograptor
lograptor/utils.py
safe_expand
def safe_expand(template, mapping): """ Safe string template expansion. Raises an error if the provided substitution mapping has circularities. """ for _ in range(len(mapping) + 1): _template = template template = string.Template(template).safe_substitute(mapping) if template == ...
python
def safe_expand(template, mapping): """ Safe string template expansion. Raises an error if the provided substitution mapping has circularities. """ for _ in range(len(mapping) + 1): _template = template template = string.Template(template).safe_substitute(mapping) if template == ...
[ "def", "safe_expand", "(", "template", ",", "mapping", ")", ":", "for", "_", "in", "range", "(", "len", "(", "mapping", ")", "+", "1", ")", ":", "_template", "=", "template", "template", "=", "string", ".", "Template", "(", "template", ")", ".", "saf...
Safe string template expansion. Raises an error if the provided substitution mapping has circularities.
[ "Safe", "string", "template", "expansion", ".", "Raises", "an", "error", "if", "the", "provided", "substitution", "mapping", "has", "circularities", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L186-L196
train
brunato/lograptor
lograptor/utils.py
protected_property
def protected_property(func): """ Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined. """ if func.__name__.startswith('_'): raise ValueError("%r: Cannot decorate a protecte...
python
def protected_property(func): """ Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined. """ if func.__name__.startswith('_'): raise ValueError("%r: Cannot decorate a protecte...
[ "def", "protected_property", "(", "func", ")", ":", "if", "func", ".", "__name__", ".", "startswith", "(", "'_'", ")", ":", "raise", "ValueError", "(", "\"%r: Cannot decorate a protected method!\"", "%", "func", ")", "@", "property", "@", "wraps", "(", "func",...
Class method decorator that creates a property that returns the protected attribute or the value returned by the wrapped method, if the protected attribute is not defined.
[ "Class", "method", "decorator", "that", "creates", "a", "property", "that", "returns", "the", "protected", "attribute", "or", "the", "value", "returned", "by", "the", "wrapped", "method", "if", "the", "protected", "attribute", "is", "not", "defined", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L214-L231
train
brunato/lograptor
lograptor/utils.py
open_resource
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
python
def open_resource(source): """ Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL. """ try: return open(source, mode='rb') except (IOError, OSError) as err: try: resourc...
[ "def", "open_resource", "(", "source", ")", ":", "try", ":", "return", "open", "(", "source", ",", "mode", "=", "'rb'", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "err", ":", "try", ":", "resource", "=", "urlopen", "(", "source", ")", ...
Opens a resource in binary reading mode. Wraps the resource with a context manager when it doesn't have one. :param source: a filepath or an URL.
[ "Opens", "a", "resource", "in", "binary", "reading", "mode", ".", "Wraps", "the", "resource", "with", "a", "context", "manager", "when", "it", "doesn", "t", "have", "one", "." ]
b1f09fe1b429ed15110610092704ef12d253f3c9
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/utils.py#L255-L279
train
DsixTools/python-smeftrunner
smeftrunner/io.py
load
def load(stream, fmt='lha'): """Load a parameter file in DSixTools SLHA-like format or its JSON or YAML representation.""" if fmt == 'lha': return pylha.load(stream) elif fmt == 'json': if isinstance(stream, str): return json.loads(stream) else: return jso...
python
def load(stream, fmt='lha'): """Load a parameter file in DSixTools SLHA-like format or its JSON or YAML representation.""" if fmt == 'lha': return pylha.load(stream) elif fmt == 'json': if isinstance(stream, str): return json.loads(stream) else: return jso...
[ "def", "load", "(", "stream", ",", "fmt", "=", "'lha'", ")", ":", "if", "fmt", "==", "'lha'", ":", "return", "pylha", ".", "load", "(", "stream", ")", "elif", "fmt", "==", "'json'", ":", "if", "isinstance", "(", "stream", ",", "str", ")", ":", "r...
Load a parameter file in DSixTools SLHA-like format or its JSON or YAML representation.
[ "Load", "a", "parameter", "file", "in", "DSixTools", "SLHA", "-", "like", "format", "or", "its", "JSON", "or", "YAML", "representation", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L8-L19
train
DsixTools/python-smeftrunner
smeftrunner/io.py
sm_lha2dict
def sm_lha2dict(lha): """Convert a dictionary returned by pylha from a DSixTools SM input file into a dictionary of SM values.""" d = OrderedDict() v = dict(lha['BLOCK']['GAUGE']['values']) d['g'] = v[1] d['gp'] = v[2] d['gs'] = v[3] v = dict(lha['BLOCK']['SCALAR']['values']) d['Lamb...
python
def sm_lha2dict(lha): """Convert a dictionary returned by pylha from a DSixTools SM input file into a dictionary of SM values.""" d = OrderedDict() v = dict(lha['BLOCK']['GAUGE']['values']) d['g'] = v[1] d['gp'] = v[2] d['gs'] = v[3] v = dict(lha['BLOCK']['SCALAR']['values']) d['Lamb...
[ "def", "sm_lha2dict", "(", "lha", ")", ":", "d", "=", "OrderedDict", "(", ")", "v", "=", "dict", "(", "lha", "[", "'BLOCK'", "]", "[", "'GAUGE'", "]", "[", "'values'", "]", ")", "d", "[", "'g'", "]", "=", "v", "[", "1", "]", "d", "[", "'gp'",...
Convert a dictionary returned by pylha from a DSixTools SM input file into a dictionary of SM values.
[ "Convert", "a", "dictionary", "returned", "by", "pylha", "from", "a", "DSixTools", "SM", "input", "file", "into", "a", "dictionary", "of", "SM", "values", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L40-L70
train
DsixTools/python-smeftrunner
smeftrunner/io.py
sm_dict2lha
def sm_dict2lha(d): """Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.""" blocks = OrderedDict([ ('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}), ('SCALAR', {'values': [[1, d['Lambda'].real], [2...
python
def sm_dict2lha(d): """Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.""" blocks = OrderedDict([ ('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}), ('SCALAR', {'values': [[1, d['Lambda'].real], [2...
[ "def", "sm_dict2lha", "(", "d", ")", ":", "blocks", "=", "OrderedDict", "(", "[", "(", "'GAUGE'", ",", "{", "'values'", ":", "[", "[", "1", ",", "d", "[", "'g'", "]", ".", "real", "]", ",", "[", "2", ",", "d", "[", "'gp'", "]", ".", "real", ...
Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.
[ "Convert", "a", "a", "dictionary", "of", "SM", "parameters", "into", "a", "dictionary", "that", "pylha", "can", "convert", "into", "a", "DSixTools", "SM", "output", "file", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L72-L86
train
DsixTools/python-smeftrunner
smeftrunner/io.py
wc_lha2dict
def wc_lha2dict(lha): """Convert a dictionary returned by pylha from a DSixTools WC input file into a dictionary of Wilson coefficients.""" C = OrderedDict() # try to read all WCs with 0, 2, or 4 fermions; if not found, set to zero for k, (block, i) in WC_dict_0f.items(): try: C[...
python
def wc_lha2dict(lha): """Convert a dictionary returned by pylha from a DSixTools WC input file into a dictionary of Wilson coefficients.""" C = OrderedDict() # try to read all WCs with 0, 2, or 4 fermions; if not found, set to zero for k, (block, i) in WC_dict_0f.items(): try: C[...
[ "def", "wc_lha2dict", "(", "lha", ")", ":", "C", "=", "OrderedDict", "(", ")", "for", "k", ",", "(", "block", ",", "i", ")", "in", "WC_dict_0f", ".", "items", "(", ")", ":", "try", ":", "C", "[", "k", "]", "=", "dict", "(", "lha", "[", "'BLOC...
Convert a dictionary returned by pylha from a DSixTools WC input file into a dictionary of Wilson coefficients.
[ "Convert", "a", "dictionary", "returned", "by", "pylha", "from", "a", "DSixTools", "WC", "input", "file", "into", "a", "dictionary", "of", "Wilson", "coefficients", "." ]
4c9130e53ad4f7bbb526657a82150ca9d57c4b37
https://github.com/DsixTools/python-smeftrunner/blob/4c9130e53ad4f7bbb526657a82150ca9d57c4b37/smeftrunner/io.py#L107-L135
train
Kortemme-Lab/klab
klab/pymath/cartesian/rmsd.py
compute_rmsd_by_matrix
def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False): '''Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion can be set to assert that the row indices match. ''' if use_assertion: assert([i for i in dataframe_1.index] ...
python
def compute_rmsd_by_matrix(dataframe_1, dataframe_2, use_assertion = False): '''Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion can be set to assert that the row indices match. ''' if use_assertion: assert([i for i in dataframe_1.index] ...
[ "def", "compute_rmsd_by_matrix", "(", "dataframe_1", ",", "dataframe_2", ",", "use_assertion", "=", "False", ")", ":", "if", "use_assertion", ":", "assert", "(", "[", "i", "for", "i", "in", "dataframe_1", ".", "index", "]", "==", "[", "i", "for", "i", "i...
Computes the RMSD of two pandas dataframes. The dataframes are expected to be of equal dimensions and use_assertion can be set to assert that the row indices match.
[ "Computes", "the", "RMSD", "of", "two", "pandas", "dataframes", ".", "The", "dataframes", "are", "expected", "to", "be", "of", "equal", "dimensions", "and", "use_assertion", "can", "be", "set", "to", "assert", "that", "the", "row", "indices", "match", "." ]
6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b
https://github.com/Kortemme-Lab/klab/blob/6d410ad08f1bd9f7cbbb28d7d946e94fbaaa2b6b/klab/pymath/cartesian/rmsd.py#L3-L8
train
projectshift/shift-boiler
boiler/feature/jinja_extensions.py
jinja_extensions_feature
def jinja_extensions_feature(app): """ Enables custom templating extensions """ # register jinja filters app.jinja_env.globals['momentjs'] = MomentJsFilters app.jinja_env.filters.update(MomentJsFilters().get_filters()) app.jinja_env.filters.update(DateFilters().get_filters()) app.jinja_env.filt...
python
def jinja_extensions_feature(app): """ Enables custom templating extensions """ # register jinja filters app.jinja_env.globals['momentjs'] = MomentJsFilters app.jinja_env.filters.update(MomentJsFilters().get_filters()) app.jinja_env.filters.update(DateFilters().get_filters()) app.jinja_env.filt...
[ "def", "jinja_extensions_feature", "(", "app", ")", ":", "app", ".", "jinja_env", ".", "globals", "[", "'momentjs'", "]", "=", "MomentJsFilters", "app", ".", "jinja_env", ".", "filters", ".", "update", "(", "MomentJsFilters", "(", ")", ".", "get_filters", "(...
Enables custom templating extensions
[ "Enables", "custom", "templating", "extensions" ]
8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b
https://github.com/projectshift/shift-boiler/blob/8e6f3a3e4b9493fb6c8bd16bed160ede153bfb0b/boiler/feature/jinja_extensions.py#L7-L20
train
ethan92429/onshapepy
onshapepy/core/utils.py
log
def log(msg, level=0): ''' Logs a message to the console, with optional level paramater Args: - msg (str): message to send to console - level (int): log level; 0 for info, 1 for error (default = 0) ''' red = '\033[91m' endc = '\033[0m' # configure the logging module cf...
python
def log(msg, level=0): ''' Logs a message to the console, with optional level paramater Args: - msg (str): message to send to console - level (int): log level; 0 for info, 1 for error (default = 0) ''' red = '\033[91m' endc = '\033[0m' # configure the logging module cf...
[ "def", "log", "(", "msg", ",", "level", "=", "0", ")", ":", "red", "=", "'\\033[91m'", "endc", "=", "'\\033[0m'", "cfg", "=", "{", "'version'", ":", "1", ",", "'disable_existing_loggers'", ":", "False", ",", "'formatters'", ":", "{", "'stdout'", ":", "...
Logs a message to the console, with optional level paramater Args: - msg (str): message to send to console - level (int): log level; 0 for info, 1 for error (default = 0)
[ "Logs", "a", "message", "to", "the", "console", "with", "optional", "level", "paramater" ]
61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df
https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/core/utils.py#L17-L75
train
ethan92429/onshapepy
onshapepy/assembly.py
Assembly.insert
def insert(self, part): """ Insert a part into this assembly. Args: - part (onshapepy.part.Part) A Part instance that will be inserted. Returns: - requests.Response: Onshape response data """ params = {k: str(v) for k,v in part.params.items()} r...
python
def insert(self, part): """ Insert a part into this assembly. Args: - part (onshapepy.part.Part) A Part instance that will be inserted. Returns: - requests.Response: Onshape response data """ params = {k: str(v) for k,v in part.params.items()} r...
[ "def", "insert", "(", "self", ",", "part", ")", ":", "params", "=", "{", "k", ":", "str", "(", "v", ")", "for", "k", ",", "v", "in", "part", ".", "params", ".", "items", "(", ")", "}", "res", "=", "c", ".", "create_assembly_instance", "(", "sel...
Insert a part into this assembly. Args: - part (onshapepy.part.Part) A Part instance that will be inserted. Returns: - requests.Response: Onshape response data
[ "Insert", "a", "part", "into", "this", "assembly", "." ]
61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df
https://github.com/ethan92429/onshapepy/blob/61dc7ccbdc6095fa6cc3b4a414e2f72d03d1c9df/onshapepy/assembly.py#L26-L38
train
TUNE-Archive/freight_forwarder
freight_forwarder/utils/utils.py
parse_http_scheme
def parse_http_scheme(uri): """ match on http scheme if no match is found will assume http """ regex = re.compile( r'^(?:http)s?://', flags=re.IGNORECASE ) match = regex.match(uri) return match.group(0) if match else 'http://'
python
def parse_http_scheme(uri): """ match on http scheme if no match is found will assume http """ regex = re.compile( r'^(?:http)s?://', flags=re.IGNORECASE ) match = regex.match(uri) return match.group(0) if match else 'http://'
[ "def", "parse_http_scheme", "(", "uri", ")", ":", "regex", "=", "re", ".", "compile", "(", "r'^(?:http)s?://'", ",", "flags", "=", "re", ".", "IGNORECASE", ")", "match", "=", "regex", ".", "match", "(", "uri", ")", "return", "match", ".", "group", "(",...
match on http scheme if no match is found will assume http
[ "match", "on", "http", "scheme", "if", "no", "match", "is", "found", "will", "assume", "http" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L110-L120
train
TUNE-Archive/freight_forwarder
freight_forwarder/utils/utils.py
parse_stream
def parse_stream(response): """ take stream from docker-py lib and display it to the user. this also builds a stream list and returns it. """ stream_data = [] stream = stdout for data in response: if data: try: data = data.decode('utf-8') exc...
python
def parse_stream(response): """ take stream from docker-py lib and display it to the user. this also builds a stream list and returns it. """ stream_data = [] stream = stdout for data in response: if data: try: data = data.decode('utf-8') exc...
[ "def", "parse_stream", "(", "response", ")", ":", "stream_data", "=", "[", "]", "stream", "=", "stdout", "for", "data", "in", "response", ":", "if", "data", ":", "try", ":", "data", "=", "data", ".", "decode", "(", "'utf-8'", ")", "except", "AttributeE...
take stream from docker-py lib and display it to the user. this also builds a stream list and returns it.
[ "take", "stream", "from", "docker", "-", "py", "lib", "and", "display", "it", "to", "the", "user", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L159-L204
train
TUNE-Archive/freight_forwarder
freight_forwarder/utils/utils.py
normalize_keys
def normalize_keys(suspect, snake_case=True): """ take a dict and turn all of its type string keys into snake_case """ if not isinstance(suspect, dict): raise TypeError('you must pass a dict.') for key in list(suspect): if not isinstance(key, six.string_types): continue ...
python
def normalize_keys(suspect, snake_case=True): """ take a dict and turn all of its type string keys into snake_case """ if not isinstance(suspect, dict): raise TypeError('you must pass a dict.') for key in list(suspect): if not isinstance(key, six.string_types): continue ...
[ "def", "normalize_keys", "(", "suspect", ",", "snake_case", "=", "True", ")", ":", "if", "not", "isinstance", "(", "suspect", ",", "dict", ")", ":", "raise", "TypeError", "(", "'you must pass a dict.'", ")", "for", "key", "in", "list", "(", "suspect", ")",...
take a dict and turn all of its type string keys into snake_case
[ "take", "a", "dict", "and", "turn", "all", "of", "its", "type", "string", "keys", "into", "snake_case" ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L227-L256
train
TUNE-Archive/freight_forwarder
freight_forwarder/utils/utils.py
_display_status
def _display_status(normalized_data, stream): """ print status message from docker-py stream. """ if 'Pull complete' in normalized_data['status'] or 'Download complete' in normalized_data['status']: stream.write("\n") if 'id' in normalized_data: stream.write("%s - " % normalized_dat...
python
def _display_status(normalized_data, stream): """ print status message from docker-py stream. """ if 'Pull complete' in normalized_data['status'] or 'Download complete' in normalized_data['status']: stream.write("\n") if 'id' in normalized_data: stream.write("%s - " % normalized_dat...
[ "def", "_display_status", "(", "normalized_data", ",", "stream", ")", ":", "if", "'Pull complete'", "in", "normalized_data", "[", "'status'", "]", "or", "'Download complete'", "in", "normalized_data", "[", "'status'", "]", ":", "stream", ".", "write", "(", "\"\\...
print status message from docker-py stream.
[ "print", "status", "message", "from", "docker", "-", "py", "stream", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L367-L377
train
TUNE-Archive/freight_forwarder
freight_forwarder/utils/utils.py
_display_stream
def _display_stream(normalized_data, stream): """ print stream message from docker-py stream. """ try: stream.write(normalized_data['stream']) except UnicodeEncodeError: stream.write(normalized_data['stream'].encode("utf-8"))
python
def _display_stream(normalized_data, stream): """ print stream message from docker-py stream. """ try: stream.write(normalized_data['stream']) except UnicodeEncodeError: stream.write(normalized_data['stream'].encode("utf-8"))
[ "def", "_display_stream", "(", "normalized_data", ",", "stream", ")", ":", "try", ":", "stream", ".", "write", "(", "normalized_data", "[", "'stream'", "]", ")", "except", "UnicodeEncodeError", ":", "stream", ".", "write", "(", "normalized_data", "[", "'stream...
print stream message from docker-py stream.
[ "print", "stream", "message", "from", "docker", "-", "py", "stream", "." ]
6ea4a49f474ec04abb8bb81b175c774a16b5312f
https://github.com/TUNE-Archive/freight_forwarder/blob/6ea4a49f474ec04abb8bb81b175c774a16b5312f/freight_forwarder/utils/utils.py#L380-L387
train
fjwCode/cerium
cerium/service.py
BaseService.version
def version(self) -> str: '''Show the version number of Android Debug Bridge.''' output, _ = self._execute('version') return output.splitlines()[0].split()[-1]
python
def version(self) -> str: '''Show the version number of Android Debug Bridge.''' output, _ = self._execute('version') return output.splitlines()[0].split()[-1]
[ "def", "version", "(", "self", ")", "->", "str", ":", "output", ",", "_", "=", "self", ".", "_execute", "(", "'version'", ")", "return", "output", ".", "splitlines", "(", ")", "[", "0", "]", ".", "split", "(", ")", "[", "-", "1", "]" ]
Show the version number of Android Debug Bridge.
[ "Show", "the", "version", "number", "of", "Android", "Debug", "Bridge", "." ]
f6e06e0dcf83a0bc924828e9d6cb81383ed2364f
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L68-L71
train
fjwCode/cerium
cerium/service.py
BaseService.get_state
def get_state(self) -> str: '''offline | bootloader | device''' output, error = self._execute('get-state') if error: raise DeviceConnectionException(error.split(':', 1)[-1].strip()) return output.strip()
python
def get_state(self) -> str: '''offline | bootloader | device''' output, error = self._execute('get-state') if error: raise DeviceConnectionException(error.split(':', 1)[-1].strip()) return output.strip()
[ "def", "get_state", "(", "self", ")", "->", "str", ":", "output", ",", "error", "=", "self", ".", "_execute", "(", "'get-state'", ")", "if", "error", ":", "raise", "DeviceConnectionException", "(", "error", ".", "split", "(", "':'", ",", "1", ")", "[",...
offline | bootloader | device
[ "offline", "|", "bootloader", "|", "device" ]
f6e06e0dcf83a0bc924828e9d6cb81383ed2364f
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/service.py#L102-L107
train
cozy/python_cozy_management
cozy_management/ssl.py
acme_init
def acme_init(): ''' Init acme key ''' acme_private_key = ACME_PRIVATE_KEY acme_intermediate_cert = ACME_INTERMEDIATE_CERT acme_intermediate_cert_url = ACME_INTERMEDIATE_CERT_URL if not os.path.isfile(acme_private_key): print 'Create {}'.format(acme_private_key) cmd = 'o...
python
def acme_init(): ''' Init acme key ''' acme_private_key = ACME_PRIVATE_KEY acme_intermediate_cert = ACME_INTERMEDIATE_CERT acme_intermediate_cert_url = ACME_INTERMEDIATE_CERT_URL if not os.path.isfile(acme_private_key): print 'Create {}'.format(acme_private_key) cmd = 'o...
[ "def", "acme_init", "(", ")", ":", "acme_private_key", "=", "ACME_PRIVATE_KEY", "acme_intermediate_cert", "=", "ACME_INTERMEDIATE_CERT", "acme_intermediate_cert_url", "=", "ACME_INTERMEDIATE_CERT_URL", "if", "not", "os", ".", "path", ".", "isfile", "(", "acme_private_key"...
Init acme key
[ "Init", "acme", "key" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L57-L90
train
cozy/python_cozy_management
cozy_management/ssl.py
acme_sign_certificate
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name) certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name) certificate_request_path = '{}/...
python
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name) certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name) certificate_request_path = '{}/...
[ "def", "acme_sign_certificate", "(", "common_name", ",", "size", "=", "DEFAULT_KEY_SIZE", ")", ":", "private_key_path", "=", "'{}/{}.key'", ".", "format", "(", "CERTIFICATES_PATH", ",", "common_name", ")", "certificate_path", "=", "'{}/{}.crt'", ".", "format", "(", ...
Sign certificate with acme_tiny for let's encrypt
[ "Sign", "certificate", "with", "acme_tiny", "for", "let", "s", "encrypt" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L120-L155
train
cozy/python_cozy_management
cozy_management/ssl.py
acme_renew_certificates
def acme_renew_certificates(): ''' Renew certificates with acme_tiny for let's encrypt ''' for csr in glob(os.path.join(CERTIFICATES_PATH, '*.csr')): common_name = os.path.basename(csr) common_name = os.path.splitext(common_name)[0] certificate_path = "{}.crt".format(common...
python
def acme_renew_certificates(): ''' Renew certificates with acme_tiny for let's encrypt ''' for csr in glob(os.path.join(CERTIFICATES_PATH, '*.csr')): common_name = os.path.basename(csr) common_name = os.path.splitext(common_name)[0] certificate_path = "{}.crt".format(common...
[ "def", "acme_renew_certificates", "(", ")", ":", "for", "csr", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "CERTIFICATES_PATH", ",", "'*.csr'", ")", ")", ":", "common_name", "=", "os", ".", "path", ".", "basename", "(", "csr", ")", "common_...
Renew certificates with acme_tiny for let's encrypt
[ "Renew", "certificates", "with", "acme_tiny", "for", "let", "s", "encrypt" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L160-L192
train
cozy/python_cozy_management
cozy_management/ssl.py
get_crt_common_name
def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH): ''' Get CN from certificate ''' try: certificate_file = open(certificate_path) crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate_file.read()) ...
python
def get_crt_common_name(certificate_path=OLD_CERTIFICATE_PATH): ''' Get CN from certificate ''' try: certificate_file = open(certificate_path) crt = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, certificate_file.read()) ...
[ "def", "get_crt_common_name", "(", "certificate_path", "=", "OLD_CERTIFICATE_PATH", ")", ":", "try", ":", "certificate_file", "=", "open", "(", "certificate_path", ")", "crt", "=", "OpenSSL", ".", "crypto", ".", "load_certificate", "(", "OpenSSL", ".", "crypto", ...
Get CN from certificate
[ "Get", "CN", "from", "certificate" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L246-L256
train
cozy/python_cozy_management
cozy_management/ssl.py
normalize_cert_dir
def normalize_cert_dir(): ''' Put old cerfificate form to new one ''' current_cn = get_crt_common_name() if not os.path.isdir(COZY_CONFIG_PATH): print 'Need to create {}'.format(COZY_CONFIG_PATH) os.mkdir(COZY_CONFIG_PATH, 0755) if not os.path.isdir(CERTIFICATES_PATH): ...
python
def normalize_cert_dir(): ''' Put old cerfificate form to new one ''' current_cn = get_crt_common_name() if not os.path.isdir(COZY_CONFIG_PATH): print 'Need to create {}'.format(COZY_CONFIG_PATH) os.mkdir(COZY_CONFIG_PATH, 0755) if not os.path.isdir(CERTIFICATES_PATH): ...
[ "def", "normalize_cert_dir", "(", ")", ":", "current_cn", "=", "get_crt_common_name", "(", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "COZY_CONFIG_PATH", ")", ":", "print", "'Need to create {}'", ".", "format", "(", "COZY_CONFIG_PATH", ")", "os", ...
Put old cerfificate form to new one
[ "Put", "old", "cerfificate", "form", "to", "new", "one" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L259-L294
train
cozy/python_cozy_management
cozy_management/ssl.py
clean_links
def clean_links(): ''' Clean symlink for nginx ''' if os.path.isfile(CURRENT_CERTIFICATE_PATH): print 'Delete symlink {}'.format(CURRENT_CERTIFICATE_PATH) os.remove(CURRENT_CERTIFICATE_PATH) if os.path.isfile(CURRENT_PRIVATE_KEY_PATH): print 'Delete symlink {}'.format(CU...
python
def clean_links(): ''' Clean symlink for nginx ''' if os.path.isfile(CURRENT_CERTIFICATE_PATH): print 'Delete symlink {}'.format(CURRENT_CERTIFICATE_PATH) os.remove(CURRENT_CERTIFICATE_PATH) if os.path.isfile(CURRENT_PRIVATE_KEY_PATH): print 'Delete symlink {}'.format(CU...
[ "def", "clean_links", "(", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "CURRENT_CERTIFICATE_PATH", ")", ":", "print", "'Delete symlink {}'", ".", "format", "(", "CURRENT_CERTIFICATE_PATH", ")", "os", ".", "remove", "(", "CURRENT_CERTIFICATE_PATH", ")"...
Clean symlink for nginx
[ "Clean", "symlink", "for", "nginx" ]
820cea58458ae3e067fa8cc2da38edbda4681dac
https://github.com/cozy/python_cozy_management/blob/820cea58458ae3e067fa8cc2da38edbda4681dac/cozy_management/ssl.py#L297-L307
train