repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
letuananh/chirptext | chirptext/texttaglib.py | read | def read(path, mode='tsv'):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
if mode == 'tsv':
return TxtReader.from_path(path).read()
elif mode == 'json':
return read_jso... | python | def read(path, mode='tsv'):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
if mode == 'tsv':
return TxtReader.from_path(path).read()
elif mode == 'json':
return read_jso... | [
"def",
"read",
"(",
"path",
",",
"mode",
"=",
"'tsv'",
")",
":",
"if",
"mode",
"==",
"'tsv'",
":",
"return",
"TxtReader",
".",
"from_path",
"(",
"path",
")",
".",
"read",
"(",
")",
"elif",
"mode",
"==",
"'json'",
":",
"return",
"read_json",
"(",
"p... | Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. read('~/data/myfile') is the same as Document('myfile', '~/data/').read() | [
"Helper",
"function",
"to",
"read",
"Document",
"in",
"TTL",
"-",
"TXT",
"format",
"(",
"i",
".",
"e",
".",
"$",
"{",
"docname",
"}",
"_",
"*",
".",
"txt",
")",
"E",
".",
"g",
".",
"read",
"(",
"~",
"/",
"data",
"/",
"myfile",
")",
"is",
"the... | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L936-L945 |
letuananh/chirptext | chirptext/texttaglib.py | write | def write(path, doc, mode=MODE_TSV, **kwargs):
''' Helper function to write doc to TTL-TXT format '''
if mode == MODE_TSV:
with TxtWriter.from_path(path) as writer:
writer.write_doc(doc)
elif mode == MODE_JSON:
write_json(path, doc, **kwargs) | python | def write(path, doc, mode=MODE_TSV, **kwargs):
''' Helper function to write doc to TTL-TXT format '''
if mode == MODE_TSV:
with TxtWriter.from_path(path) as writer:
writer.write_doc(doc)
elif mode == MODE_JSON:
write_json(path, doc, **kwargs) | [
"def",
"write",
"(",
"path",
",",
"doc",
",",
"mode",
"=",
"MODE_TSV",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mode",
"==",
"MODE_TSV",
":",
"with",
"TxtWriter",
".",
"from_path",
"(",
"path",
")",
"as",
"writer",
":",
"writer",
".",
"write_doc",
... | Helper function to write doc to TTL-TXT format | [
"Helper",
"function",
"to",
"write",
"doc",
"to",
"TTL",
"-",
"TXT",
"format"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L948-L954 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.tcmap | def tcmap(self):
''' Create a tokens-concepts map '''
tcmap = dd(list)
for concept in self.__concept_map.values():
for w in concept.tokens:
tcmap[w].append(concept)
return tcmap | python | def tcmap(self):
''' Create a tokens-concepts map '''
tcmap = dd(list)
for concept in self.__concept_map.values():
for w in concept.tokens:
tcmap[w].append(concept)
return tcmap | [
"def",
"tcmap",
"(",
"self",
")",
":",
"tcmap",
"=",
"dd",
"(",
"list",
")",
"for",
"concept",
"in",
"self",
".",
"__concept_map",
".",
"values",
"(",
")",
":",
"for",
"w",
"in",
"concept",
".",
"tokens",
":",
"tcmap",
"[",
"w",
"]",
".",
"append... | Create a tokens-concepts map | [
"Create",
"a",
"tokens",
"-",
"concepts",
"map"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L195-L201 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.msw | def msw(self):
''' Return a generator of tokens with more than one sense. '''
return (t for t, c in self.tcmap().items() if len(c) > 1) | python | def msw(self):
''' Return a generator of tokens with more than one sense. '''
return (t for t, c in self.tcmap().items() if len(c) > 1) | [
"def",
"msw",
"(",
"self",
")",
":",
"return",
"(",
"t",
"for",
"t",
",",
"c",
"in",
"self",
".",
"tcmap",
"(",
")",
".",
"items",
"(",
")",
"if",
"len",
"(",
"c",
")",
">",
"1",
")"
] | Return a generator of tokens with more than one sense. | [
"Return",
"a",
"generator",
"of",
"tokens",
"with",
"more",
"than",
"one",
"sense",
"."
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L207-L209 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.surface | def surface(self, tag):
''' Get surface string that is associated with a tag object '''
if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0:
return self.text[tag.cfrom:tag.cto]
else:
return '' | python | def surface(self, tag):
''' Get surface string that is associated with a tag object '''
if tag.cfrom is not None and tag.cto is not None and tag.cfrom >= 0 and tag.cto >= 0:
return self.text[tag.cfrom:tag.cto]
else:
return '' | [
"def",
"surface",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
".",
"cfrom",
"is",
"not",
"None",
"and",
"tag",
".",
"cto",
"is",
"not",
"None",
"and",
"tag",
".",
"cfrom",
">=",
"0",
"and",
"tag",
".",
"cto",
">=",
"0",
":",
"return",
"self... | Get surface string that is associated with a tag object | [
"Get",
"surface",
"string",
"that",
"is",
"associated",
"with",
"a",
"tag",
"object"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L211-L216 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.new_tag | def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs):
''' Create a sentence-level tag '''
tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs)
return self.add_tag(tag_obj) | python | def new_tag(self, label, cfrom=-1, cto=-1, tagtype='', **kwargs):
''' Create a sentence-level tag '''
tag_obj = Tag(label, cfrom, cto, tagtype=tagtype, **kwargs)
return self.add_tag(tag_obj) | [
"def",
"new_tag",
"(",
"self",
",",
"label",
",",
"cfrom",
"=",
"-",
"1",
",",
"cto",
"=",
"-",
"1",
",",
"tagtype",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"tag_obj",
"=",
"Tag",
"(",
"label",
",",
"cfrom",
",",
"cto",
",",
"tagtype",
... | Create a sentence-level tag | [
"Create",
"a",
"sentence",
"-",
"level",
"tag"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L222-L225 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.get_tag | def get_tag(self, tagtype):
''' Get the first tag of a particular type'''
for tag in self.__tags:
if tag.tagtype == tagtype:
return tag
return None | python | def get_tag(self, tagtype):
''' Get the first tag of a particular type'''
for tag in self.__tags:
if tag.tagtype == tagtype:
return tag
return None | [
"def",
"get_tag",
"(",
"self",
",",
"tagtype",
")",
":",
"for",
"tag",
"in",
"self",
".",
"__tags",
":",
"if",
"tag",
".",
"tagtype",
"==",
"tagtype",
":",
"return",
"tag",
"return",
"None"
] | Get the first tag of a particular type | [
"Get",
"the",
"first",
"tag",
"of",
"a",
"particular",
"type"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L227-L232 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.get_tags | def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] | python | def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] | [
"def",
"get_tags",
"(",
"self",
",",
"tagtype",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"__tags",
"if",
"t",
".",
"tagtype",
"==",
"tagtype",
"]"
] | Get all tags of a type | [
"Get",
"all",
"tags",
"of",
"a",
"type"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L234-L236 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.add_token_object | def add_token_object(self, token):
''' Add a token object into this sentence '''
token.sent = self # take ownership of given token
self.__tokens.append(token)
return token | python | def add_token_object(self, token):
''' Add a token object into this sentence '''
token.sent = self # take ownership of given token
self.__tokens.append(token)
return token | [
"def",
"add_token_object",
"(",
"self",
",",
"token",
")",
":",
"token",
".",
"sent",
"=",
"self",
"# take ownership of given token",
"self",
".",
"__tokens",
".",
"append",
"(",
"token",
")",
"return",
"token"
] | Add a token object into this sentence | [
"Add",
"a",
"token",
"object",
"into",
"this",
"sentence"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L242-L246 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.new_concept | def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs):
''' Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices
'''
if cidx is None:
cidx = self.new_concept_id()
if tokens:
tokens =... | python | def new_concept(self, tag, clemma="", tokens=None, cidx=None, **kwargs):
''' Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices
'''
if cidx is None:
cidx = self.new_concept_id()
if tokens:
tokens =... | [
"def",
"new_concept",
"(",
"self",
",",
"tag",
",",
"clemma",
"=",
"\"\"",
",",
"tokens",
"=",
"None",
",",
"cidx",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cidx",
"is",
"None",
":",
"cidx",
"=",
"self",
".",
"new_concept_id",
"(",
... | Create a new concept object and add it to concept list
tokens can be a list of Token objects or token indices | [
"Create",
"a",
"new",
"concept",
"object",
"and",
"add",
"it",
"to",
"concept",
"list",
"tokens",
"can",
"be",
"a",
"list",
"of",
"Token",
"objects",
"or",
"token",
"indices"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L254-L263 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.add_concept | def add_concept(self, concept_obj):
''' Add a concept to current concept list '''
if concept_obj is None:
raise Exception("Concept object cannot be None")
elif concept_obj in self.__concepts:
raise Exception("Concept object is already inside")
elif concept_obj.cid... | python | def add_concept(self, concept_obj):
''' Add a concept to current concept list '''
if concept_obj is None:
raise Exception("Concept object cannot be None")
elif concept_obj in self.__concepts:
raise Exception("Concept object is already inside")
elif concept_obj.cid... | [
"def",
"add_concept",
"(",
"self",
",",
"concept_obj",
")",
":",
"if",
"concept_obj",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Concept object cannot be None\"",
")",
"elif",
"concept_obj",
"in",
"self",
".",
"__concepts",
":",
"raise",
"Exception",
"(",
... | Add a concept to current concept list | [
"Add",
"a",
"concept",
"to",
"current",
"concept",
"list"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L265-L276 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.concept | def concept(self, cid, **kwargs):
''' Get concept by concept ID '''
if cid not in self.__concept_map:
if 'default' in kwargs:
return kwargs['default']
else:
raise KeyError("Invalid cid")
else:
return self.__concept_map[cid] | python | def concept(self, cid, **kwargs):
''' Get concept by concept ID '''
if cid not in self.__concept_map:
if 'default' in kwargs:
return kwargs['default']
else:
raise KeyError("Invalid cid")
else:
return self.__concept_map[cid] | [
"def",
"concept",
"(",
"self",
",",
"cid",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cid",
"not",
"in",
"self",
".",
"__concept_map",
":",
"if",
"'default'",
"in",
"kwargs",
":",
"return",
"kwargs",
"[",
"'default'",
"]",
"else",
":",
"raise",
"KeyEr... | Get concept by concept ID | [
"Get",
"concept",
"by",
"concept",
"ID"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L289-L297 |
letuananh/chirptext | chirptext/texttaglib.py | Sentence.import_tokens | def import_tokens(self, tokens, import_hook=None, ignorecase=True):
''' Import a list of string as tokens '''
text = self.text.lower() if ignorecase else self.text
has_hooker = import_hook and callable(import_hook)
cfrom = 0
if self.__tokens:
for tk in self.__tokens:
... | python | def import_tokens(self, tokens, import_hook=None, ignorecase=True):
''' Import a list of string as tokens '''
text = self.text.lower() if ignorecase else self.text
has_hooker = import_hook and callable(import_hook)
cfrom = 0
if self.__tokens:
for tk in self.__tokens:
... | [
"def",
"import_tokens",
"(",
"self",
",",
"tokens",
",",
"import_hook",
"=",
"None",
",",
"ignorecase",
"=",
"True",
")",
":",
"text",
"=",
"self",
".",
"text",
".",
"lower",
"(",
")",
"if",
"ignorecase",
"else",
"self",
".",
"text",
"has_hooker",
"=",... | Import a list of string as tokens | [
"Import",
"a",
"list",
"of",
"string",
"as",
"tokens"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L315-L345 |
letuananh/chirptext | chirptext/texttaglib.py | Token.tag_map | def tag_map(self):
''' Build a map from tagtype to list of tags '''
tm = dd(list)
for tag in self.__tags:
tm[tag.tagtype].append(tag)
return tm | python | def tag_map(self):
''' Build a map from tagtype to list of tags '''
tm = dd(list)
for tag in self.__tags:
tm[tag.tagtype].append(tag)
return tm | [
"def",
"tag_map",
"(",
"self",
")",
":",
"tm",
"=",
"dd",
"(",
"list",
")",
"for",
"tag",
"in",
"self",
".",
"__tags",
":",
"tm",
"[",
"tag",
".",
"tagtype",
"]",
".",
"append",
"(",
"tag",
")",
"return",
"tm"
] | Build a map from tagtype to list of tags | [
"Build",
"a",
"map",
"from",
"tagtype",
"to",
"list",
"of",
"tags"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L420-L425 |
letuananh/chirptext | chirptext/texttaglib.py | Token.find | def find(self, tagtype, **kwargs):
'''Get the first tag with a type in this token '''
for t in self.__tags:
if t.tagtype == tagtype:
return t
if 'default' in kwargs:
return kwargs['default']
else:
raise LookupError("Token {} is not tagg... | python | def find(self, tagtype, **kwargs):
'''Get the first tag with a type in this token '''
for t in self.__tags:
if t.tagtype == tagtype:
return t
if 'default' in kwargs:
return kwargs['default']
else:
raise LookupError("Token {} is not tagg... | [
"def",
"find",
"(",
"self",
",",
"tagtype",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"t",
"in",
"self",
".",
"__tags",
":",
"if",
"t",
".",
"tagtype",
"==",
"tagtype",
":",
"return",
"t",
"if",
"'default'",
"in",
"kwargs",
":",
"return",
"kwargs",... | Get the first tag with a type in this token | [
"Get",
"the",
"first",
"tag",
"with",
"a",
"type",
"in",
"this",
"token"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L430-L438 |
letuananh/chirptext | chirptext/texttaglib.py | Token.find_all | def find_all(self, tagtype):
''' Find all token-level tags with the specified tagtype '''
return [t for t in self.__tags if t.tagtype == tagtype] | python | def find_all(self, tagtype):
''' Find all token-level tags with the specified tagtype '''
return [t for t in self.__tags if t.tagtype == tagtype] | [
"def",
"find_all",
"(",
"self",
",",
"tagtype",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"__tags",
"if",
"t",
".",
"tagtype",
"==",
"tagtype",
"]"
] | Find all token-level tags with the specified tagtype | [
"Find",
"all",
"token",
"-",
"level",
"tags",
"with",
"the",
"specified",
"tagtype"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L440-L442 |
letuananh/chirptext | chirptext/texttaglib.py | Token.new_tag | def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs):
''' Create a new tag on this token '''
if cfrom is None:
cfrom = self.cfrom
if cto is None:
cto = self.cto
tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs)
retur... | python | def new_tag(self, label, cfrom=None, cto=None, tagtype=None, **kwargs):
''' Create a new tag on this token '''
if cfrom is None:
cfrom = self.cfrom
if cto is None:
cto = self.cto
tag = Tag(label=label, cfrom=cfrom, cto=cto, tagtype=tagtype, **kwargs)
retur... | [
"def",
"new_tag",
"(",
"self",
",",
"label",
",",
"cfrom",
"=",
"None",
",",
"cto",
"=",
"None",
",",
"tagtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cfrom",
"is",
"None",
":",
"cfrom",
"=",
"self",
".",
"cfrom",
"if",
"cto",
... | Create a new tag on this token | [
"Create",
"a",
"new",
"tag",
"on",
"this",
"token"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L448-L455 |
letuananh/chirptext | chirptext/texttaglib.py | Document.get | def get(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int):
sent_id = int(sent_id)
if sent_id is ... | python | def get(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int):
sent_id = int(sent_id)
if sent_id is ... | [
"def",
"get",
"(",
"self",
",",
"sent_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sent_id",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"sent_id",
",",
"int",
")",
":",
"sent_id",
"=",
"int",
"(",
"sent_id",
")",
"if",
"sent_id",
"is",... | If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised. | [
"If",
"sent_id",
"exists",
"remove",
"and",
"return",
"the",
"associated",
"sentence",
"object",
"else",
"return",
"default",
".",
"If",
"no",
"default",
"is",
"provided",
"KeyError",
"will",
"be",
"raised",
"."
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L588-L598 |
letuananh/chirptext | chirptext/texttaglib.py | Document.add_sent | def add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif sent_obj.ID is None:
# if sentID is None, create a new ID
sent_obj.ID = next(self.__idgen)
elif... | python | def add_sent(self, sent_obj):
''' Add a ttl.Sentence object to this document '''
if sent_obj is None:
raise Exception("Sentence object cannot be None")
elif sent_obj.ID is None:
# if sentID is None, create a new ID
sent_obj.ID = next(self.__idgen)
elif... | [
"def",
"add_sent",
"(",
"self",
",",
"sent_obj",
")",
":",
"if",
"sent_obj",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Sentence object cannot be None\"",
")",
"elif",
"sent_obj",
".",
"ID",
"is",
"None",
":",
"# if sentID is None, create a new ID",
"sent_ob... | Add a ttl.Sentence object to this document | [
"Add",
"a",
"ttl",
".",
"Sentence",
"object",
"to",
"this",
"document"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L603-L614 |
letuananh/chirptext | chirptext/texttaglib.py | Document.new_sent | def new_sent(self, text, ID=None, **kwargs):
''' Create a new sentence and add it to this Document '''
if ID is None:
ID = next(self.__idgen)
return self.add_sent(Sentence(text, ID=ID, **kwargs)) | python | def new_sent(self, text, ID=None, **kwargs):
''' Create a new sentence and add it to this Document '''
if ID is None:
ID = next(self.__idgen)
return self.add_sent(Sentence(text, ID=ID, **kwargs)) | [
"def",
"new_sent",
"(",
"self",
",",
"text",
",",
"ID",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ID",
"is",
"None",
":",
"ID",
"=",
"next",
"(",
"self",
".",
"__idgen",
")",
"return",
"self",
".",
"add_sent",
"(",
"Sentence",
"(",
... | Create a new sentence and add it to this Document | [
"Create",
"a",
"new",
"sentence",
"and",
"add",
"it",
"to",
"this",
"Document"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L616-L620 |
letuananh/chirptext | chirptext/texttaglib.py | Document.pop | def pop(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int):
sent_id = int(sent_id)
if not self.ha... | python | def pop(self, sent_id, **kwargs):
''' If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised.'''
if sent_id is not None and not isinstance(sent_id, int):
sent_id = int(sent_id)
if not self.ha... | [
"def",
"pop",
"(",
"self",
",",
"sent_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"sent_id",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"sent_id",
",",
"int",
")",
":",
"sent_id",
"=",
"int",
"(",
"sent_id",
")",
"if",
"not",
"self",
... | If sent_id exists, remove and return the associated sentence object else return default.
If no default is provided, KeyError will be raised. | [
"If",
"sent_id",
"exists",
"remove",
"and",
"return",
"the",
"associated",
"sentence",
"object",
"else",
"return",
"default",
".",
"If",
"no",
"default",
"is",
"provided",
"KeyError",
"will",
"be",
"raised",
"."
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L622-L637 |
letuananh/chirptext | chirptext/texttaglib.py | Document.read | def read(self):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning)
with TxtReader.from_doc(self) as reader:
reader.read(self)
return self | python | def read(self):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning)
with TxtReader.from_doc(self) as reader:
reader.read(self)
return self | [
"def",
"read",
"(",
"self",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Document.read() is deprecated and will be removed in near future.\"",
",",
"DeprecationWarning",
")",
"with",
"TxtReader",
".",
"from_doc",
"(",
"self",
")",
"as",
"reader",
":",
"reader",
".",
... | Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) | [
"Read",
"tagged",
"doc",
"from",
"mutliple",
"files",
"(",
"sents",
"tokens",
"concepts",
"links",
"tags",
")"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L639-L644 |
letuananh/chirptext | chirptext/texttaglib.py | Document.read_ttl | def read_ttl(path):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read... | python | def read_ttl(path):
''' Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read()
'''
warnings.warn("Document.read_ttl() is deprecated and will be removed in near future. Use read... | [
"def",
"read_ttl",
"(",
"path",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Document.read_ttl() is deprecated and will be removed in near future. Use read() instead\"",
",",
"DeprecationWarning",
")",
"doc_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
... | Helper function to read Document in TTL-TXT format (i.e. ${docname}_*.txt)
E.g. Document.read_ttl('~/data/myfile') is the same as Document('myfile', '~/data/').read() | [
"Helper",
"function",
"to",
"read",
"Document",
"in",
"TTL",
"-",
"TXT",
"format",
"(",
"i",
".",
"e",
".",
"$",
"{",
"docname",
"}",
"_",
"*",
".",
"txt",
")",
"E",
".",
"g",
".",
"Document",
".",
"read_ttl",
"(",
"~",
"/",
"data",
"/",
"myfil... | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L647-L654 |
letuananh/chirptext | chirptext/texttaglib.py | TxtReader.read | def read(self, doc=None):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
if not self.sent_stream:
raise Exception("There is no sentence data stream available")
if doc is None:
doc = Document(name=self.doc_name, path=self.doc_path)
... | python | def read(self, doc=None):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
if not self.sent_stream:
raise Exception("There is no sentence data stream available")
if doc is None:
doc = Document(name=self.doc_name, path=self.doc_path)
... | [
"def",
"read",
"(",
"self",
",",
"doc",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"sent_stream",
":",
"raise",
"Exception",
"(",
"\"There is no sentence data stream available\"",
")",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"Document",
"(",
"nam... | Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) | [
"Read",
"tagged",
"doc",
"from",
"mutliple",
"files",
"(",
"sents",
"tokens",
"concepts",
"links",
"tags",
")"
] | train | https://github.com/letuananh/chirptext/blob/ce60b47257b272a587c8703ea1f86cd1a45553a7/chirptext/texttaglib.py#L723-L792 |
alefnula/tea | tea/console/format.py | format_page | def format_page(text):
"""Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string.
"""
width = max(map(len, text.splitlines()))
page = "+-" + "-" * width + "-+\n"
for line in... | python | def format_page(text):
"""Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string.
"""
width = max(map(len, text.splitlines()))
page = "+-" + "-" * width + "-+\n"
for line in... | [
"def",
"format_page",
"(",
"text",
")",
":",
"width",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"text",
".",
"splitlines",
"(",
")",
")",
")",
"page",
"=",
"\"+-\"",
"+",
"\"-\"",
"*",
"width",
"+",
"\"-+\\n\"",
"for",
"line",
"in",
"text",
".",
"... | Format the text for output adding ASCII frame around the text.
Args:
text (str): Text that needs to be formatted.
Returns:
str: Formatted string. | [
"Format",
"the",
"text",
"for",
"output",
"adding",
"ASCII",
"frame",
"around",
"the",
"text",
".",
"Args",
":",
"text",
"(",
"str",
")",
":",
"Text",
"that",
"needs",
"to",
"be",
"formatted",
".",
"Returns",
":",
"str",
":",
"Formatted",
"string",
"."... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L16-L30 |
alefnula/tea | tea/console/format.py | table | def table(text):
"""Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+... | python | def table(text):
"""Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+... | [
"def",
"table",
"(",
"text",
")",
":",
"def",
"table_bar",
"(",
"col_lengths",
")",
":",
"return",
"\"+-%s-+%s\"",
"%",
"(",
"\"-+-\"",
".",
"join",
"(",
"[",
"\"-\"",
"*",
"length",
"for",
"length",
"in",
"col_lengths",
"]",
")",
",",
"os",
".",
"li... | Format the text as a table.
Text in format:
first | second
row 2 col 1 | 4
Will be formatted as::
+-------------+--------+
| first | second |
+-------------+--------+
| row 2 col 1 | 4 |
+-------------+--------+
Args:
te... | [
"Format",
"the",
"text",
"as",
"a",
"table",
".",
"Text",
"in",
"format",
":",
"first",
"|",
"second",
"row",
"2",
"col",
"1",
"|",
"4",
"Will",
"be",
"formatted",
"as",
"::",
"+",
"-------------",
"+",
"--------",
"+",
"|",
"first",
"|",
"second",
... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L33-L82 |
alefnula/tea | tea/console/format.py | print_page | def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | python | def print_page(text):
"""Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text.
"""
... | [
"def",
"print_page",
"(",
"text",
")",
":",
"color_re",
"=",
"re",
".",
"compile",
"(",
"r\"\\[(?P<color>[FB]G_[A-Z_]+|NORMAL)\\]\"",
")",
"width",
"=",
"max",
"(",
"[",
"len",
"(",
"strip_colors",
"(",
"x",
")",
")",
"for",
"x",
"in",
"text",
".",
"spli... | Format the text and prints it on stdout.
Text is formatted by adding a ASCII frame around it and coloring the text.
Colors can be added to text using color tags, for example:
My [FG_BLUE]blue[NORMAL] text.
My [BG_BLUE]blue background[NORMAL] text. | [
"Format",
"the",
"text",
"and",
"prints",
"it",
"on",
"stdout",
".",
"Text",
"is",
"formatted",
"by",
"adding",
"a",
"ASCII",
"frame",
"around",
"it",
"and",
"coloring",
"the",
"text",
".",
"Colors",
"can",
"be",
"added",
"to",
"text",
"using",
"color",
... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L97-L123 |
alefnula/tea | tea/console/format.py | wrap_text | def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | python | def wrap_text(text, width=80):
"""Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text.
"""
text =... | [
"def",
"wrap_text",
"(",
"text",
",",
"width",
"=",
"80",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
")",
".",
"strip",
"(",
")",
"wrapper",
"=",
"TextWrapper",
"(",
"width",
"=",
"width",
",",
"break_long... | Wrap text lines to maximum *width* characters.
Wrapped text is aligned against the left text border.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Wrapped text. | [
"Wrap",
"text",
"lines",
"to",
"maximum",
"*",
"width",
"*",
"characters",
".",
"Wrapped",
"text",
"is",
"aligned",
"against",
"the",
"left",
"text",
"border",
".",
"Args",
":",
"text",
"(",
"str",
")",
":",
"Text",
"to",
"wrap",
".",
"width",
"(",
"... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L126-L142 |
alefnula/tea | tea/console/format.py | rjust_text | def rjust_text(text, width=80, indent=0, subsequent=None):
"""Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of chara... | python | def rjust_text(text, width=80, indent=0, subsequent=None):
"""Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of chara... | [
"def",
"rjust_text",
"(",
"text",
",",
"width",
"=",
"80",
",",
"indent",
"=",
"0",
",",
"subsequent",
"=",
"None",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"text",
")",
".",
"strip",
"(",
")",
"if",
"subseque... | Wrap text and adjust it to right border.
Same as L{wrap_text} with the difference that the text is aligned against
the right text border.
Args:
text (str): Text to wrap and align.
width (int): Maximum number of characters per line.
indent (int): Indentation of the first lin... | [
"Wrap",
"text",
"and",
"adjust",
"it",
"to",
"right",
"border",
".",
"Same",
"as",
"L",
"{",
"wrap_text",
"}",
"with",
"the",
"difference",
"that",
"the",
"text",
"is",
"aligned",
"against",
"the",
"right",
"text",
"border",
".",
"Args",
":",
"text",
"... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L145-L168 |
alefnula/tea | tea/console/format.py | center_text | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
... | python | def center_text(text, width=80):
"""Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
... | [
"def",
"center_text",
"(",
"text",
",",
"width",
"=",
"80",
")",
":",
"centered",
"=",
"[",
"]",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
":",
"centered",
".",
"append",
"(",
"line",
".",
"center",
"(",
"width",
")",
")",
"return",... | Center all lines of the text.
It is assumed that all lines width is smaller then B{width}, because the
line width will not be checked.
Args:
text (str): Text to wrap.
width (int): Maximum number of characters per line.
Returns:
str: Centered text. | [
"Center",
"all",
"lines",
"of",
"the",
"text",
".",
"It",
"is",
"assumed",
"that",
"all",
"lines",
"width",
"is",
"smaller",
"then",
"B",
"{",
"width",
"}",
"because",
"the",
"line",
"width",
"will",
"not",
"be",
"checked",
".",
"Args",
":",
"text",
... | train | https://github.com/alefnula/tea/blob/f5a0a724a425ec4f9dd2c7fe966ef06faf3a15a3/tea/console/format.py#L171-L187 |
RI-imaging/qpimage | qpimage/integrity_check.py | check | def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | python | def check(qpi_or_h5file, checks=["attributes", "background"]):
"""Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to per... | [
"def",
"check",
"(",
"qpi_or_h5file",
",",
"checks",
"=",
"[",
"\"attributes\"",
",",
"\"background\"",
"]",
")",
":",
"if",
"isinstance",
"(",
"checks",
",",
"str",
")",
":",
"checks",
"=",
"[",
"checks",
"]",
"for",
"ch",
"in",
"checks",
":",
"if",
... | Checks various properties of a :class:`qpimage.core.QPImage` instance
Parameters
----------
qpi_or_h5file: qpimage.core.QPImage or str
A QPImage object or a path to an hdf5 file
checks: list of str
Which checks to perform ("attributes" and/or "background")
Raises
------
Int... | [
"Checks",
"various",
"properties",
"of",
"a",
":",
"class",
":",
"qpimage",
".",
"core",
".",
"QPImage",
"instance"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L13-L45 |
RI-imaging/qpimage | qpimage/integrity_check.py | check_attributes | def check_attributes(qpi):
"""Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)... | python | def check_attributes(qpi):
"""Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
missing_attrs = []
for key in DATA_KEYS:
if key not in qpi.meta:
missing_attrs.append(key)... | [
"def",
"check_attributes",
"(",
"qpi",
")",
":",
"missing_attrs",
"=",
"[",
"]",
"for",
"key",
"in",
"DATA_KEYS",
":",
"if",
"key",
"not",
"in",
"qpi",
".",
"meta",
":",
"missing_attrs",
".",
"append",
"(",
"key",
")",
"if",
"missing_attrs",
":",
"msg"... | Check QPimage attributes
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails | [
"Check",
"QPimage",
"attributes"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L48-L67 |
RI-imaging/qpimage | qpimage/integrity_check.py | check_background | def check_background(qpi):
"""Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr... | python | def check_background(qpi):
"""Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails
"""
for imdat in [qpi._amp, qpi._pha]:
try:
fit, attrs = imdat.get_bg(key="fit", ret_attrs=Tr... | [
"def",
"check_background",
"(",
"qpi",
")",
":",
"for",
"imdat",
"in",
"[",
"qpi",
".",
"_amp",
",",
"qpi",
".",
"_pha",
"]",
":",
"try",
":",
"fit",
",",
"attrs",
"=",
"imdat",
".",
"get_bg",
"(",
"key",
"=",
"\"fit\"",
",",
"ret_attrs",
"=",
"T... | Check QPimage background data
Parameters
----------
qpi: qpimage.core.QPImage
Raises
------
IntegrityCheckError
if the check fails | [
"Check",
"QPimage",
"background",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/integrity_check.py#L70-L115 |
RI-imaging/qpimage | qpimage/image_data.py | write_image_dataset | def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parame... | python | def write_image_dataset(group, key, data, h5dtype=None):
"""Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parame... | [
"def",
"write_image_dataset",
"(",
"group",
",",
"key",
",",
"data",
",",
"h5dtype",
"=",
"None",
")",
":",
"if",
"h5dtype",
"is",
"None",
":",
"h5dtype",
"=",
"data",
".",
"dtype",
"if",
"key",
"in",
"group",
":",
"del",
"group",
"[",
"key",
"]",
... | Write an image to an hdf5 group as a dataset
This convenience function sets all attributes such that the image
can be visualized with HDFView, sets the compression and fletcher32
filters, and sets the chunk size to the image shape.
Parameters
----------
group: h5py.Group
HDF5 group to ... | [
"Write",
"an",
"image",
"to",
"an",
"hdf5",
"group",
"as",
"a",
"dataset"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L326-L369 |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.info | def info(self):
"""list of background correction parameters"""
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey ... | python | def info(self):
"""list of background correction parameters"""
info = []
name = self.__class__.__name__.lower()
# get bg information
for key in VALID_BG_KEYS:
if key in self.h5["bg_data"]:
attrs = self.h5["bg_data"][key].attrs
for akey ... | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"[",
"]",
"name",
"=",
"self",
".",
"__class__",
".",
"__name__",
".",
"lower",
"(",
")",
"# get bg information",
"for",
"key",
"in",
"VALID_BG_KEYS",
":",
"if",
"key",
"in",
"self",
".",
"h5",
"[",
... | list of background correction parameters | [
"list",
"of",
"background",
"correction",
"parameters"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L96-L122 |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.del_bg | def del_bg(self, key):
"""Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS`
"""
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
... | python | def del_bg(self, key):
"""Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS`
"""
if key not in VALID_BG_KEYS:
raise ValueError("Invalid bg key: {}".format(key))
if key in self.h5["bg_data"]:
... | [
"def",
"del_bg",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"not",
"in",
"VALID_BG_KEYS",
":",
"raise",
"ValueError",
"(",
"\"Invalid bg key: {}\"",
".",
"format",
"(",
"key",
")",
")",
"if",
"key",
"in",
"self",
".",
"h5",
"[",
"\"bg_data\"",
"]"... | Remove the background image data
Parameters
----------
key: str
One of :const:`VALID_BG_KEYS` | [
"Remove",
"the",
"background",
"image",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L129-L143 |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.estimate_bg | def estimate_bg(self, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
... | python | def estimate_bg(self, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
... | [
"def",
"estimate_bg",
"(",
"self",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"None",
",",
"ret_mask",
"=",
"False",
")",
":",
"# remove existing bg before accessing imdat.image",
"... | Estimate image background
Parameters
----------
fit_profile: str
The type of background profile to fit:
- "offset": offset only
- "poly2o": 2D 2nd order polynomial with mixed terms
- "tilt": 2D linear tilt with offset (default)
fit_offset... | [
"Estimate",
"image",
"background"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L145-L206 |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.get_bg | def get_bg(self, key=None, ret_attrs=False):
"""Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background corr... | python | def get_bg(self, key=None, ret_attrs=False):
"""Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background corr... | [
"def",
"get_bg",
"(",
"self",
",",
"key",
"=",
"None",
",",
"ret_attrs",
"=",
"False",
")",
":",
"if",
"key",
"is",
"None",
":",
"if",
"ret_attrs",
":",
"raise",
"ValueError",
"(",
"\"No attributes for combined background!\"",
")",
"return",
"self",
".",
"... | Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background correction
(see :const:`VALID_BG_KEYS`). If set ... | [
"Get",
"the",
"background",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L208-L242 |
RI-imaging/qpimage | qpimage/image_data.py | ImageData.set_bg | def set_bg(self, bg, key="data", attrs={}):
"""Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is cre... | python | def set_bg(self, bg, key="data", attrs={}):
"""Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is cre... | [
"def",
"set_bg",
"(",
"self",
",",
"bg",
",",
"key",
"=",
"\"data\"",
",",
"attrs",
"=",
"{",
"}",
")",
":",
"if",
"key",
"not",
"in",
"VALID_BG_KEYS",
":",
"raise",
"ValueError",
"(",
"\"Invalid bg key: {}\"",
".",
"format",
"(",
"key",
")",
")",
"#... | Set the background data
Parameters
----------
bg: numbers.Real, 2d ndarray, ImageData, or h5py.Dataset
The background data. If `bg` is an `h5py.Dataset` object,
it must exist in the same hdf5 file (a hard link is created).
If set to `None`, the data will be r... | [
"Set",
"the",
"background",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L244-L283 |
RI-imaging/qpimage | qpimage/image_data.py | Amplitude._bg_combine | def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | python | def _bg_combine(self, bgs):
"""Combine several background amplitude images"""
out = np.ones(self.h5["raw"].shape, dtype=float)
# bg is an h5py.DataSet
for bg in bgs:
out *= bg[:]
return out | [
"def",
"_bg_combine",
"(",
"self",
",",
"bgs",
")",
":",
"out",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"h5",
"[",
"\"raw\"",
"]",
".",
"shape",
",",
"dtype",
"=",
"float",
")",
"# bg is an h5py.DataSet",
"for",
"bg",
"in",
"bgs",
":",
"out",
"*=... | Combine several background amplitude images | [
"Combine",
"several",
"background",
"amplitude",
"images"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/image_data.py#L293-L299 |
devoperate/chronos | chronos/helpers.py | git_tags | def git_tags() -> str:
"""
Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags.
"""
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProce... | python | def git_tags() -> str:
"""
Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags.
"""
try:
subprocess.check_call(['git', 'fetch', '--tags'])
except CalledProce... | [
"def",
"git_tags",
"(",
")",
"->",
"str",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"'git'",
",",
"'fetch'",
",",
"'--tags'",
"]",
")",
"except",
"CalledProcessError",
":",
"pass",
"cmd",
"=",
"[",
"'git'",
",",
"'tag'",
",",
"'--list... | Calls ``git tag -l --sort=-v:refname`` (sorts output) and returns the
output as a UTF-8 encoded string. Raises a NoGitTagsException if the
repository doesn't contain any Git tags. | [
"Calls",
"git",
"tag",
"-",
"l",
"--",
"sort",
"=",
"-",
"v",
":",
"refname",
"(",
"sorts",
"output",
")",
"and",
"returns",
"the",
"output",
"as",
"a",
"UTF",
"-",
"8",
"encoded",
"string",
".",
"Raises",
"a",
"NoGitTagsException",
"if",
"the",
"rep... | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L45-L62 |
devoperate/chronos | chronos/helpers.py | git_tag_to_semver | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | python | def git_tag_to_semver(git_tag: str) -> SemVer:
"""
:git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object.
"""
pattern = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
match = pattern.search(git_tag)
if match:... | [
"def",
"git_tag_to_semver",
"(",
"git_tag",
":",
"str",
")",
"->",
"SemVer",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]+\\.[0-9]+\\.[0-9]+$'",
")",
"match",
"=",
"pattern",
".",
"search",
"(",
"git_tag",
")",
"if",
"match",
":",
"version",
"=... | :git_tag: A string representation of a Git tag.
Searches a Git tag's string representation for a SemVer, and returns that
as a SemVer object. | [
":",
"git_tag",
":",
"A",
"string",
"representation",
"of",
"a",
"Git",
"tag",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L65-L79 |
devoperate/chronos | chronos/helpers.py | last_git_release_tag | def last_git_release_tag(git_tags: str) -> str:
"""
:git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string.
"""
semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
str_ver = []
for i in git_tags.split():
if semver_re.search(... | python | def last_git_release_tag(git_tags: str) -> str:
"""
:git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string.
"""
semver_re = re.compile(r'[0-9]+\.[0-9]+\.[0-9]+$')
str_ver = []
for i in git_tags.split():
if semver_re.search(... | [
"def",
"last_git_release_tag",
"(",
"git_tags",
":",
"str",
")",
"->",
"str",
":",
"semver_re",
"=",
"re",
".",
"compile",
"(",
"r'[0-9]+\\.[0-9]+\\.[0-9]+$'",
")",
"str_ver",
"=",
"[",
"]",
"for",
"i",
"in",
"git_tags",
".",
"split",
"(",
")",
":",
"if"... | :git_tags: chronos.helpers.git_tags() function output.
Returns the latest Git tag ending with a SemVer as a string. | [
":",
"git_tags",
":",
"chronos",
".",
"helpers",
".",
"git_tags",
"()",
"function",
"output",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L82-L97 |
devoperate/chronos | chronos/helpers.py | git_commits_since_last_tag | def git_commits_since_last_tag(last_tag: str) -> dict:
"""
:last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs.
"""
try:
cmd = ['git', 'log', ... | python | def git_commits_since_last_tag(last_tag: str) -> dict:
"""
:last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs.
"""
try:
cmd = ['git', 'log', ... | [
"def",
"git_commits_since_last_tag",
"(",
"last_tag",
":",
"str",
")",
"->",
"dict",
":",
"try",
":",
"cmd",
"=",
"[",
"'git'",
",",
"'log'",
",",
"last_tag",
"+",
"'..'",
",",
"\"--format='%H %s'\"",
"]",
"commit_log",
"=",
"subprocess",
".",
"check_output"... | :last_tag: The Git tag that should serve as the starting point for the
commit log lookup.
Calls ``git log <last_tag>.. --format='%H %s'`` and returns the output as a
dict of hash-message pairs. | [
":",
"last_tag",
":",
"The",
"Git",
"tag",
"that",
"should",
"serve",
"as",
"the",
"starting",
"point",
"for",
"the",
"commit",
"log",
"lookup",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L100-L127 |
devoperate/chronos | chronos/helpers.py | parse_commit_log | def parse_commit_log(commit_log: dict) -> str:
"""
:commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'.
"""
rv = 'pat'
cc_patterns = patterns()
for value in commit_log.values():
if re.search(cc_patterns['feat'], ... | python | def parse_commit_log(commit_log: dict) -> str:
"""
:commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'.
"""
rv = 'pat'
cc_patterns = patterns()
for value in commit_log.values():
if re.search(cc_patterns['feat'], ... | [
"def",
"parse_commit_log",
"(",
"commit_log",
":",
"dict",
")",
"->",
"str",
":",
"rv",
"=",
"'pat'",
"cc_patterns",
"=",
"patterns",
"(",
")",
"for",
"value",
"in",
"commit_log",
".",
"values",
"(",
")",
":",
"if",
"re",
".",
"search",
"(",
"cc_patter... | :commit_log: chronos.helpers.git_commits_since_last_tag() output.
Parse Git log and return either 'maj', 'min', or 'pat'. | [
":",
"commit_log",
":",
"chronos",
".",
"helpers",
".",
"git_commits_since_last_tag",
"()",
"output",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/helpers.py#L130-L146 |
devoperate/chronos | chronos/semver.py | SemVer.from_str | def from_str(cls, version_str: str):
"""
Alternate constructor that accepts a string SemVer.
"""
o = cls()
o.version = version_str
return o | python | def from_str(cls, version_str: str):
"""
Alternate constructor that accepts a string SemVer.
"""
o = cls()
o.version = version_str
return o | [
"def",
"from_str",
"(",
"cls",
",",
"version_str",
":",
"str",
")",
":",
"o",
"=",
"cls",
"(",
")",
"o",
".",
"version",
"=",
"version_str",
"return",
"o"
] | Alternate constructor that accepts a string SemVer. | [
"Alternate",
"constructor",
"that",
"accepts",
"a",
"string",
"SemVer",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L87-L93 |
devoperate/chronos | chronos/semver.py | SemVer.major | def major(self, major: int) -> None:
"""
param major
Major version number property. Must be a non-negative integer.
"""
self.filter_negatives(major)
self._major = major | python | def major(self, major: int) -> None:
"""
param major
Major version number property. Must be a non-negative integer.
"""
self.filter_negatives(major)
self._major = major | [
"def",
"major",
"(",
"self",
",",
"major",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"major",
")",
"self",
".",
"_major",
"=",
"major"
] | param major
Major version number property. Must be a non-negative integer. | [
"param",
"major"
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L103-L110 |
devoperate/chronos | chronos/semver.py | SemVer.minor | def minor(self, minor: int) -> None:
"""
param minor
Minor version number property. Must be a non-negative integer.
"""
self.filter_negatives(minor)
self._minor = minor | python | def minor(self, minor: int) -> None:
"""
param minor
Minor version number property. Must be a non-negative integer.
"""
self.filter_negatives(minor)
self._minor = minor | [
"def",
"minor",
"(",
"self",
",",
"minor",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"minor",
")",
"self",
".",
"_minor",
"=",
"minor"
] | param minor
Minor version number property. Must be a non-negative integer. | [
"param",
"minor"
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L120-L127 |
devoperate/chronos | chronos/semver.py | SemVer.patch | def patch(self, patch: int) -> None:
"""
param patch
Patch version number property. Must be a non-negative integer.
"""
self.filter_negatives(patch)
self._patch = patch | python | def patch(self, patch: int) -> None:
"""
param patch
Patch version number property. Must be a non-negative integer.
"""
self.filter_negatives(patch)
self._patch = patch | [
"def",
"patch",
"(",
"self",
",",
"patch",
":",
"int",
")",
"->",
"None",
":",
"self",
".",
"filter_negatives",
"(",
"patch",
")",
"self",
".",
"_patch",
"=",
"patch"
] | param patch
Patch version number property. Must be a non-negative integer. | [
"param",
"patch"
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L137-L144 |
devoperate/chronos | chronos/semver.py | SemVer.version | def version(self) -> str:
"""
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
version: str = (
str(self._major) + '.' +
str(self._minor) + '.' +
str(self._patch... | python | def version(self) -> str:
"""
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
version: str = (
str(self._major) + '.' +
str(self._minor) + '.' +
str(self._patch... | [
"def",
"version",
"(",
"self",
")",
"->",
"str",
":",
"version",
":",
"str",
"=",
"(",
"str",
"(",
"self",
".",
"_major",
")",
"+",
"'.'",
"+",
"str",
"(",
"self",
".",
"_minor",
")",
"+",
"'.'",
"+",
"str",
"(",
"self",
".",
"_patch",
")",
"... | Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1'). | [
"Version",
"version",
"number",
"property",
".",
"Must",
"be",
"a",
"string",
"consisting",
"of",
"three",
"non",
"-",
"negative",
"integers",
"delimited",
"by",
"periods",
"(",
"eg",
".",
"1",
".",
"0",
".",
"1",
")",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L147-L157 |
devoperate/chronos | chronos/semver.py | SemVer.version | def version(self, version_str: str) -> None:
"""
param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
ver = []
for i in version_str.split('.'):
ver.append(int... | python | def version(self, version_str: str) -> None:
"""
param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1').
"""
ver = []
for i in version_str.split('.'):
ver.append(int... | [
"def",
"version",
"(",
"self",
",",
"version_str",
":",
"str",
")",
"->",
"None",
":",
"ver",
"=",
"[",
"]",
"for",
"i",
"in",
"version_str",
".",
"split",
"(",
"'.'",
")",
":",
"ver",
".",
"append",
"(",
"int",
"(",
"i",
")",
")",
"self",
".",... | param version
Version version number property. Must be a string consisting of three
non-negative integers delimited by periods (eg. '1.0.1'). | [
"param",
"version"
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/semver.py#L160-L171 |
RI-imaging/qpimage | qpimage/bg_estimate.py | estimate | def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of backg... | python | def estimate(data, fit_offset="mean", fit_profile="tilt",
border_px=0, from_mask=None, ret_mask=False):
"""Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of backg... | [
"def",
"estimate",
"(",
"data",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"None",
",",
"ret_mask",
"=",
"False",
")",
":",
"if",
"fit_profile",
"not",
"in",
"VALID_FIT_PROFIL... | Estimate the background value of an image
Parameters
----------
data: np.ndarray
Data from which to compute the background value
fit_profile: str
The type of background profile to fit:
- "offset": offset only
- "poly2o": 2D 2nd order polynomial with mixed terms
... | [
"Estimate",
"the",
"background",
"value",
"of",
"an",
"image"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L11-L100 |
RI-imaging/qpimage | qpimage/bg_estimate.py | offset_gaussian | def offset_gaussian(data):
"""Fit a gaussian model to `data` and return its center"""
nbins = 2 * int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2)
histo = np.histogram(data, nbins, density=True, range=drange)
dx = ... | python | def offset_gaussian(data):
"""Fit a gaussian model to `data` and return its center"""
nbins = 2 * int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
drange = (mind - (maxd - mind) / 2, maxd + (maxd - mind) / 2)
histo = np.histogram(data, nbins, density=True, range=drange)
dx = ... | [
"def",
"offset_gaussian",
"(",
"data",
")",
":",
"nbins",
"=",
"2",
"*",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"data",
".",
"size",
")",
")",
")",
"mind",
",",
"maxd",
"=",
"data",
".",
"min",
"(",
")",
",",
"data",
".",... | Fit a gaussian model to `data` and return its center | [
"Fit",
"a",
"gaussian",
"model",
"to",
"data",
"and",
"return",
"its",
"center"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L103-L116 |
RI-imaging/qpimage | qpimage/bg_estimate.py | offset_mode | def offset_mode(data):
"""Compute Mode using a histogram with `sqrt(data.size)` bins"""
nbins = int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
histo = np.histogram(data, nbins, density=True, range=(mind, maxd))
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
... | python | def offset_mode(data):
"""Compute Mode using a histogram with `sqrt(data.size)` bins"""
nbins = int(np.ceil(np.sqrt(data.size)))
mind, maxd = data.min(), data.max()
histo = np.histogram(data, nbins, density=True, range=(mind, maxd))
dx = abs(histo[1][1] - histo[1][2]) / 2
hx = histo[1][1:] - dx
... | [
"def",
"offset_mode",
"(",
"data",
")",
":",
"nbins",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"data",
".",
"size",
")",
")",
")",
"mind",
",",
"maxd",
"=",
"data",
".",
"min",
"(",
")",
",",
"data",
".",
"max",
"(",
... | Compute Mode using a histogram with `sqrt(data.size)` bins | [
"Compute",
"Mode",
"using",
"a",
"histogram",
"with",
"sqrt",
"(",
"data",
".",
"size",
")",
"bins"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L119-L128 |
RI-imaging/qpimage | qpimage/bg_estimate.py | profile_tilt | def profile_tilt(data, mask):
"""Fit a 2D tilt to `data[mask]`"""
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="off", value=np.average(data[mask]))
fr = lmfit.minimize(tilt_residual, params, args=(data, mask))
bg = tilt_model(fr.pa... | python | def profile_tilt(data, mask):
"""Fit a 2D tilt to `data[mask]`"""
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="off", value=np.average(data[mask]))
fr = lmfit.minimize(tilt_residual, params, args=(data, mask))
bg = tilt_model(fr.pa... | [
"def",
"profile_tilt",
"(",
"data",
",",
"mask",
")",
":",
"params",
"=",
"lmfit",
".",
"Parameters",
"(",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"mx\"",
",",
"value",
"=",
"0",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"my\"",
",",
... | Fit a 2D tilt to `data[mask]` | [
"Fit",
"a",
"2D",
"tilt",
"to",
"data",
"[",
"mask",
"]"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L131-L139 |
RI-imaging/qpimage | qpimage/bg_estimate.py | profile_poly2o | def profile_poly2o(data, mask):
"""Fit a 2D 2nd order polynomial to `data[mask]`"""
# lmfit
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="mxy", value=0)
params.add(name="ax", value=0)
params.add(name="ay", value=0)
params.a... | python | def profile_poly2o(data, mask):
"""Fit a 2D 2nd order polynomial to `data[mask]`"""
# lmfit
params = lmfit.Parameters()
params.add(name="mx", value=0)
params.add(name="my", value=0)
params.add(name="mxy", value=0)
params.add(name="ax", value=0)
params.add(name="ay", value=0)
params.a... | [
"def",
"profile_poly2o",
"(",
"data",
",",
"mask",
")",
":",
"# lmfit",
"params",
"=",
"lmfit",
".",
"Parameters",
"(",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"mx\"",
",",
"value",
"=",
"0",
")",
"params",
".",
"add",
"(",
"name",
"=",
"\"m... | Fit a 2D 2nd order polynomial to `data[mask]` | [
"Fit",
"a",
"2D",
"2nd",
"order",
"polynomial",
"to",
"data",
"[",
"mask",
"]"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L142-L154 |
RI-imaging/qpimage | qpimage/bg_estimate.py | poly2o_model | def poly2o_model(params, shape):
"""lmfit 2nd order polynomial model"""
mx = params["mx"].value
my = params["my"].value
mxy = params["mxy"].value
ax = params["ax"].value
ay = params["ay"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0... | python | def poly2o_model(params, shape):
"""lmfit 2nd order polynomial model"""
mx = params["mx"].value
my = params["my"].value
mxy = params["mxy"].value
ax = params["ax"].value
ay = params["ay"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0... | [
"def",
"poly2o_model",
"(",
"params",
",",
"shape",
")",
":",
"mx",
"=",
"params",
"[",
"\"mx\"",
"]",
".",
"value",
"my",
"=",
"params",
"[",
"\"my\"",
"]",
".",
"value",
"mxy",
"=",
"params",
"[",
"\"mxy\"",
"]",
".",
"value",
"ax",
"=",
"params"... | lmfit 2nd order polynomial model | [
"lmfit",
"2nd",
"order",
"polynomial",
"model"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L157-L171 |
RI-imaging/qpimage | qpimage/bg_estimate.py | poly2o_residual | def poly2o_residual(params, data, mask):
"""lmfit 2nd order polynomial residuals"""
bg = poly2o_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | python | def poly2o_residual(params, data, mask):
"""lmfit 2nd order polynomial residuals"""
bg = poly2o_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | [
"def",
"poly2o_residual",
"(",
"params",
",",
"data",
",",
"mask",
")",
":",
"bg",
"=",
"poly2o_model",
"(",
"params",
",",
"shape",
"=",
"data",
".",
"shape",
")",
"res",
"=",
"(",
"data",
"-",
"bg",
")",
"[",
"mask",
"]",
"return",
"res",
".",
... | lmfit 2nd order polynomial residuals | [
"lmfit",
"2nd",
"order",
"polynomial",
"residuals"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L174-L178 |
RI-imaging/qpimage | qpimage/bg_estimate.py | tilt_model | def tilt_model(params, shape):
"""lmfit tilt model"""
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y =... | python | def tilt_model(params, shape):
"""lmfit tilt model"""
mx = params["mx"].value
my = params["my"].value
off = params["off"].value
bg = np.zeros(shape, dtype=float) + off
x = np.arange(bg.shape[0]) - bg.shape[0] // 2
y = np.arange(bg.shape[1]) - bg.shape[1] // 2
x = x.reshape(-1, 1)
y =... | [
"def",
"tilt_model",
"(",
"params",
",",
"shape",
")",
":",
"mx",
"=",
"params",
"[",
"\"mx\"",
"]",
".",
"value",
"my",
"=",
"params",
"[",
"\"my\"",
"]",
".",
"value",
"off",
"=",
"params",
"[",
"\"off\"",
"]",
".",
"value",
"bg",
"=",
"np",
".... | lmfit tilt model | [
"lmfit",
"tilt",
"model"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L181-L192 |
RI-imaging/qpimage | qpimage/bg_estimate.py | tilt_residual | def tilt_residual(params, data, mask):
"""lmfit tilt residuals"""
bg = tilt_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | python | def tilt_residual(params, data, mask):
"""lmfit tilt residuals"""
bg = tilt_model(params, shape=data.shape)
res = (data - bg)[mask]
return res.flatten() | [
"def",
"tilt_residual",
"(",
"params",
",",
"data",
",",
"mask",
")",
":",
"bg",
"=",
"tilt_model",
"(",
"params",
",",
"shape",
"=",
"data",
".",
"shape",
")",
"res",
"=",
"(",
"data",
"-",
"bg",
")",
"[",
"mask",
"]",
"return",
"res",
".",
"fla... | lmfit tilt residuals | [
"lmfit",
"tilt",
"residuals"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/bg_estimate.py#L195-L199 |
devoperate/chronos | chronos/cli.py | main | def main(cmd_args: list = None) -> None:
"""
:cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool.
"""
parser = argparse.ArgumentParser(description='Auto-versioning utility.')
subparsers = parser.add_subparsers()
infer_parser = subparsers.add_parser('inf... | python | def main(cmd_args: list = None) -> None:
"""
:cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool.
"""
parser = argparse.ArgumentParser(description='Auto-versioning utility.')
subparsers = parser.add_subparsers()
infer_parser = subparsers.add_parser('inf... | [
"def",
"main",
"(",
"cmd_args",
":",
"list",
"=",
"None",
")",
"->",
"None",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Auto-versioning utility.'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
")",
"inf... | :cmd_args: An optional list of command line arguments.
Main function of chronos CLI tool. | [
":",
"cmd_args",
":",
"An",
"optional",
"list",
"of",
"command",
"line",
"arguments",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L18-L48 |
devoperate/chronos | chronos/cli.py | infer | def infer(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI.
"""
try:
last_tag = last_git_release_tag(git_tags())
except NoGitTagsException:
print(SemVer(0,... | python | def infer(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI.
"""
try:
last_tag = last_git_release_tag(git_tags())
except NoGitTagsException:
print(SemVer(0,... | [
"def",
"infer",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | :args: An argparse.Namespace object.
This is the function called when the 'infer' sub-command is passed as an
argument to the CLI. | [
":",
"args",
":",
"An",
"argparse",
".",
"Namespace",
"object",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L51-L76 |
devoperate/chronos | chronos/cli.py | bump | def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | python | def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | [
"def",
"bump",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | :args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch'). | [
":",
"args",
":",
"An",
"argparse",
".",
"Namespace",
"object",
"."
] | train | https://github.com/devoperate/chronos/blob/5ae6047c4f13db9f5e85a0c72a3dc47f05a8d7bd/chronos/cli.py#L91-L111 |
RI-imaging/qpimage | qpimage/holo.py | find_sideband | def find_sideband(ft_data, which=+1, copy=True):
"""Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the ho... | python | def find_sideband(ft_data, which=+1, copy=True):
"""Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the ho... | [
"def",
"find_sideband",
"(",
"ft_data",
",",
"which",
"=",
"+",
"1",
",",
"copy",
"=",
"True",
")",
":",
"if",
"copy",
":",
"ft_data",
"=",
"ft_data",
".",
"copy",
"(",
")",
"if",
"which",
"not",
"in",
"[",
"+",
"1",
",",
"-",
"1",
"]",
":",
... | Find the side band position of a hologram
The hologram is Fourier-transformed and the side band
is determined by finding the maximum amplitude in
Fourier space.
Parameters
----------
ft_data: 2d ndarray
Fourier transform of the hologram image
which: +1 or -1
which sideband ... | [
"Find",
"the",
"side",
"band",
"position",
"of",
"a",
"hologram"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L5-L58 |
RI-imaging/qpimage | qpimage/holo.py | fourier2dpad | def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2
"""
if zero_pad:
# zero padding size is next order ... | python | def fourier2dpad(data, zero_pad=True):
"""Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2
"""
if zero_pad:
# zero padding size is next order ... | [
"def",
"fourier2dpad",
"(",
"data",
",",
"zero_pad",
"=",
"True",
")",
":",
"if",
"zero_pad",
":",
"# zero padding size is next order of 2",
"(",
"N",
",",
"M",
")",
"=",
"data",
".",
"shape",
"order",
"=",
"np",
".",
"int",
"(",
"max",
"(",
"64.",
","... | Compute the 2D Fourier transform with zero padding
Parameters
----------
data: 2d fload ndarray
real-valued image data
zero_pad: bool
perform zero-padding to next order of 2 | [
"Compute",
"the",
"2D",
"Fourier",
"transform",
"with",
"zero",
"padding"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L61-L84 |
RI-imaging/qpimage | qpimage/holo.py | get_field | def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3,
subtract_mean=True, zero_pad=True, copy=True):
"""Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1,... | python | def get_field(hologram, sideband=+1, filter_name="disk", filter_size=1 / 3,
subtract_mean=True, zero_pad=True, copy=True):
"""Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1,... | [
"def",
"get_field",
"(",
"hologram",
",",
"sideband",
"=",
"+",
"1",
",",
"filter_name",
"=",
"\"disk\"",
",",
"filter_size",
"=",
"1",
"/",
"3",
",",
"subtract_mean",
"=",
"True",
",",
"zero_pad",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"if... | Compute the complex field from a hologram using Fourier analysis
Parameters
----------
hologram: real-valued 2d ndarray
hologram data
sideband: +1, -1, or tuple of (float, float)
specifies the location of the sideband:
- +1: sideband in the upper half in Fourier space,
... | [
"Compute",
"the",
"complex",
"field",
"from",
"a",
"hologram",
"using",
"Fourier",
"analysis"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/holo.py#L87-L219 |
RI-imaging/qpimage | qpimage/core.py | copyh5 | def copyh5(inh5, outh5):
"""Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or... | python | def copyh5(inh5, outh5):
"""Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or... | [
"def",
"copyh5",
"(",
"inh5",
",",
"outh5",
")",
":",
"if",
"not",
"isinstance",
"(",
"inh5",
",",
"h5py",
".",
"Group",
")",
":",
"inh5",
"=",
"h5py",
".",
"File",
"(",
"inh5",
",",
"mode",
"=",
"\"r\"",
")",
"if",
"outh5",
"is",
"None",
":",
... | Recursively copy all hdf5 data from one group to another
Data from links is copied.
Parameters
----------
inh5: str, h5py.File, or h5py.Group
The input hdf5 data. This can be either a file name or
an hdf5 object.
outh5: str, h5py.File, h5py.Group, or None
The output hdf5 da... | [
"Recursively",
"copy",
"all",
"hdf5",
"data",
"from",
"one",
"group",
"to",
"another"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L597-L655 |
RI-imaging/qpimage | qpimage/core.py | QPImage._conv_which_data | def _conv_which_data(which_data):
"""Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method.
"""
if isinstan... | python | def _conv_which_data(which_data):
"""Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method.
"""
if isinstan... | [
"def",
"_conv_which_data",
"(",
"which_data",
")",
":",
"if",
"isinstance",
"(",
"which_data",
",",
"str",
")",
":",
"which_data",
"=",
"which_data",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"which_data",
".",
"count",
"(",
"\",\"",
")",
"... | Convert which data to string or tuple
This function improves user convenience,
as `which_data` may be of several types
(str, ,str with spaces and commas, list, tuple) which
is internally handled by this method. | [
"Convert",
"which",
"data",
"to",
"string",
"or",
"tuple"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L208-L237 |
RI-imaging/qpimage | qpimage/core.py | QPImage._get_amp_pha | def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings ind... | python | def _get_amp_pha(self, data, which_data):
"""Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings ind... | [
"def",
"_get_amp_pha",
"(",
"self",
",",
"data",
",",
"which_data",
")",
":",
"which_data",
"=",
"QPImage",
".",
"_conv_which_data",
"(",
"which_data",
")",
"if",
"which_data",
"not",
"in",
"VALID_INPUT_DATA",
":",
"msg",
"=",
"\"`which_data` must be one of {}!\""... | Convert input data to phase and amplitude
Parameters
----------
data: 2d ndarray (float or complex) or list
The experimental data (see `which_data`)
which_data: str
String or comma-separated list of strings indicating
the order and type of input data.... | [
"Convert",
"input",
"data",
"to",
"phase",
"and",
"amplitude"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L239-L294 |
RI-imaging/qpimage | qpimage/core.py | QPImage.info | def info(self):
"""list of tuples with QPImage meta data"""
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
r... | python | def info(self):
"""list of tuples with QPImage meta data"""
info = []
# meta data
meta = self.meta
for key in meta:
info.append((key, self.meta[key]))
# background correction
for imdat in [self._amp, self._pha]:
info += imdat.info
r... | [
"def",
"info",
"(",
"self",
")",
":",
"info",
"=",
"[",
"]",
"# meta data",
"meta",
"=",
"self",
".",
"meta",
"for",
"key",
"in",
"meta",
":",
"info",
".",
"append",
"(",
"(",
"key",
",",
"self",
".",
"meta",
"[",
"key",
"]",
")",
")",
"# backg... | list of tuples with QPImage meta data | [
"list",
"of",
"tuples",
"with",
"QPImage",
"meta",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L322-L332 |
RI-imaging/qpimage | qpimage/core.py | QPImage.clear_bg | def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"):
"""Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
... | python | def clear_bg(self, which_data=("amplitude", "phase"), keys="fit"):
"""Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
... | [
"def",
"clear_bg",
"(",
"self",
",",
"which_data",
"=",
"(",
"\"amplitude\"",
",",
"\"phase\"",
")",
",",
"keys",
"=",
"\"fit\"",
")",
":",
"which_data",
"=",
"QPImage",
".",
"_conv_which_data",
"(",
"which_data",
")",
"if",
"isinstance",
"(",
"keys",
",",... | Clear background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
"phase", or both.
keys: str or list of str
Which type of b... | [
"Clear",
"background",
"correction"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L359-L392 |
RI-imaging/qpimage | qpimage/core.py | QPImage.compute_bg | def compute_bg(self, which_data="phase",
fit_offset="mean", fit_profile="tilt",
border_m=0, border_perc=0, border_px=0,
from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or lis... | python | def compute_bg(self, which_data="phase",
fit_offset="mean", fit_profile="tilt",
border_m=0, border_perc=0, border_px=0,
from_mask=None, ret_mask=False):
"""Compute background correction
Parameters
----------
which_data: str or lis... | [
"def",
"compute_bg",
"(",
"self",
",",
"which_data",
"=",
"\"phase\"",
",",
"fit_offset",
"=",
"\"mean\"",
",",
"fit_profile",
"=",
"\"tilt\"",
",",
"border_m",
"=",
"0",
",",
"border_perc",
"=",
"0",
",",
"border_px",
"=",
"0",
",",
"from_mask",
"=",
"N... | Compute background correction
Parameters
----------
which_data: str or list of str
From which type of data to remove the background
information. The list contains either "amplitude",
"phase", or both.
fit_profile: str
The type of backgroun... | [
"Compute",
"background",
"correction"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L394-L494 |
RI-imaging/qpimage | qpimage/core.py | QPImage.copy | def copy(self, h5file=None):
"""Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__`
"""
h5 = copyh5(self.h5, h5fi... | python | def copy(self, h5file=None):
"""Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__`
"""
h5 = copyh5(self.h5, h5fi... | [
"def",
"copy",
"(",
"self",
",",
"h5file",
"=",
"None",
")",
":",
"h5",
"=",
"copyh5",
"(",
"self",
".",
"h5",
",",
"h5file",
")",
"return",
"QPImage",
"(",
"h5file",
"=",
"h5",
",",
"h5dtype",
"=",
"self",
".",
"h5dtype",
")"
] | Create a copy of the current instance
This is done by recursively copying the underlying hdf5 data.
Parameters
----------
h5file: str, h5py.File, h5py.Group, or None
see `QPImage.__init__` | [
"Create",
"a",
"copy",
"of",
"the",
"current",
"instance"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L496-L507 |
RI-imaging/qpimage | qpimage/core.py | QPImage.refocus | def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: ... | python | def refocus(self, distance, method="helmholtz", h5file=None, h5mode="a"):
"""Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: ... | [
"def",
"refocus",
"(",
"self",
",",
"distance",
",",
"method",
"=",
"\"helmholtz\"",
",",
"h5file",
"=",
"None",
",",
"h5mode",
"=",
"\"a\"",
")",
":",
"field2",
"=",
"nrefocus",
".",
"refocus",
"(",
"field",
"=",
"self",
".",
"field",
",",
"d",
"=",... | Compute a numerically refocused QPImage
Parameters
----------
distance: float
Focusing distance [m]
method: str
Refocusing method, one of ["helmholtz","fresnel"]
h5file: str, h5py.Group, h5py.File, or None
A path to an hdf5 data file where the... | [
"Compute",
"a",
"numerically",
"refocused",
"QPImage"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L509-L564 |
RI-imaging/qpimage | qpimage/core.py | QPImage.set_bg_data | def set_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background ... | python | def set_bg_data(self, bg_data, which_data=None):
"""Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background ... | [
"def",
"set_bg_data",
"(",
"self",
",",
"bg_data",
",",
"which_data",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"bg_data",
",",
"QPImage",
")",
":",
"if",
"which_data",
"is",
"not",
"None",
":",
"msg",
"=",
"\"`which_data` must not be set if `bg_data` is... | Set background amplitude and phase data
Parameters
----------
bg_data: 2d ndarray (float or complex), list, QPImage, or `None`
The background data (must be same type as `data`).
If set to `None`, the background data is reset.
which_data: str
String or... | [
"Set",
"background",
"amplitude",
"and",
"phase",
"data"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/core.py#L566-L594 |
RI-imaging/qpimage | qpimage/series.py | QPSeries.add_qpimage | def add_qpimage(self, qpi, identifier=None, bg_from_idx=None):
"""Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int o... | python | def add_qpimage(self, qpi, identifier=None, bg_from_idx=None):
"""Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int o... | [
"def",
"add_qpimage",
"(",
"self",
",",
"qpi",
",",
"identifier",
"=",
"None",
",",
"bg_from_idx",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"qpi",
",",
"QPImage",
")",
":",
"raise",
"ValueError",
"(",
"\"`fli` must be instance of QPImage!\"",
"... | Add a QPImage instance to the QPSeries
Parameters
----------
qpi: qpimage.QPImage
The QPImage that is added to the series
identifier: str
Identifier key for `qpi`
bg_from_idx: int or None
Use the background data from the data stored in this in... | [
"Add",
"a",
"QPImage",
"instance",
"to",
"the",
"QPSeries"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/series.py#L130-L168 |
RI-imaging/qpimage | qpimage/series.py | QPSeries.get_qpimage | def get_qpimage(self, index):
"""Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[in... | python | def get_qpimage(self, index):
"""Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[in... | [
"def",
"get_qpimage",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"str",
")",
":",
"# search for the identifier",
"for",
"ii",
"in",
"range",
"(",
"len",
"(",
"self",
")",
")",
":",
"qpi",
"=",
"self",
"[",
"ii",
"]",
... | Return a single QPImage of the series
Parameters
----------
index: int or str
Index or identifier of the QPImage
Notes
-----
Instead of ``qps.get_qpimage(index)``, it is possible
to use the short-hand ``qps[index]``. | [
"Return",
"a",
"single",
"QPImage",
"of",
"the",
"series"
] | train | https://github.com/RI-imaging/qpimage/blob/863c0fce5735b4c0ae369f75c0df9a33411b2bb2/qpimage/series.py#L170-L208 |
Parquery/icontract | precommit.py | main | def main() -> int:
""""
Main routine
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--overwrite",
help="Overwrites the unformatted source files with the well-formatted code in place. "
"If not set, an exception is raised if any of the files do not conform to the... | python | def main() -> int:
""""
Main routine
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--overwrite",
help="Overwrites the unformatted source files with the well-formatted code in place. "
"If not set, an exception is raised if any of the files do not conform to the... | [
"def",
"main",
"(",
")",
"->",
"int",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--overwrite\"",
",",
"help",
"=",
"\"Overwrites the unformatted source files with the well-formatted code in place. \"",
"\"If n... | Main routine | [
"Main",
"routine"
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/precommit.py#L10-L72 |
Parquery/icontract | icontract/_metaclass.py | _collapse_invariants | def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__inv... | python | def _collapse_invariants(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""Collect invariants from the bases and merge them with the invariants in the namespace."""
invariants = [] # type: List[Contract]
# Add invariants of the bases
for base in bases:
if hasattr(base, "__inv... | [
"def",
"_collapse_invariants",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"invariants",
"=",
"[",
"]",
"# type: List[Contract]",
"# Add invariants of the bases",
"f... | Collect invariants from the bases and merge them with the invariants in the namespace. | [
"Collect",
"invariants",
"from",
"the",
"bases",
"and",
"merge",
"them",
"with",
"the",
"invariants",
"in",
"the",
"namespace",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L16-L31 |
Parquery/icontract | icontract/_metaclass.py | _collapse_preconditions | def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool,
preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]:
"""
Collapse function preconditions with the preconditions collected from the base classes.
:param... | python | def _collapse_preconditions(base_preconditions: List[List[Contract]], bases_have_func: bool,
preconditions: List[List[Contract]], func: Callable[..., Any]) -> List[List[Contract]]:
"""
Collapse function preconditions with the preconditions collected from the base classes.
:param... | [
"def",
"_collapse_preconditions",
"(",
"base_preconditions",
":",
"List",
"[",
"List",
"[",
"Contract",
"]",
"]",
",",
"bases_have_func",
":",
"bool",
",",
"preconditions",
":",
"List",
"[",
"List",
"[",
"Contract",
"]",
"]",
",",
"func",
":",
"Callable",
... | Collapse function preconditions with the preconditions collected from the base classes.
:param base_preconditions: preconditions collected from the base classes (grouped by base class)
:param bases_have_func: True if one of the base classes has the function
:param preconditions: preconditions of the functi... | [
"Collapse",
"function",
"preconditions",
"with",
"the",
"preconditions",
"collected",
"from",
"the",
"base",
"classes",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L34-L51 |
Parquery/icontract | icontract/_metaclass.py | _collapse_snapshots | def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]:
"""
Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the f... | python | def _collapse_snapshots(base_snapshots: List[Snapshot], snapshots: List[Snapshot]) -> List[Snapshot]:
"""
Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the f... | [
"def",
"_collapse_snapshots",
"(",
"base_snapshots",
":",
"List",
"[",
"Snapshot",
"]",
",",
"snapshots",
":",
"List",
"[",
"Snapshot",
"]",
")",
"->",
"List",
"[",
"Snapshot",
"]",
":",
"seen_names",
"=",
"set",
"(",
")",
"# type: Set[str]",
"collapsed",
... | Collapse snapshots of pre-invocation values with the snapshots collected from the base classes.
:param base_snapshots: snapshots collected from the base classes
:param snapshots: snapshots of the function (before the collapse)
:return: collapsed sequence of snapshots | [
"Collapse",
"snapshots",
"of",
"pre",
"-",
"invocation",
"values",
"with",
"the",
"snapshots",
"collected",
"from",
"the",
"base",
"classes",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L54-L73 |
Parquery/icontract | icontract/_metaclass.py | _collapse_postconditions | def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]:
"""
Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postcondit... | python | def _collapse_postconditions(base_postconditions: List[Contract], postconditions: List[Contract]) -> List[Contract]:
"""
Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postcondit... | [
"def",
"_collapse_postconditions",
"(",
"base_postconditions",
":",
"List",
"[",
"Contract",
"]",
",",
"postconditions",
":",
"List",
"[",
"Contract",
"]",
")",
"->",
"List",
"[",
"Contract",
"]",
":",
"return",
"base_postconditions",
"+",
"postconditions"
] | Collapse function postconditions with the postconditions collected from the base classes.
:param base_postconditions: postconditions collected from the base classes
:param postconditions: postconditions of the function (before the collapse)
:return: collapsed sequence of postconditions | [
"Collapse",
"function",
"postconditions",
"with",
"the",
"postconditions",
"collected",
"from",
"the",
"base",
"classes",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L76-L84 |
Parquery/icontract | icontract/_metaclass.py | _decorate_namespace_function | def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect preconditions and postconditions from the bases and decorate the function at the ``key``."""
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
value = namespace[key... | python | def _decorate_namespace_function(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect preconditions and postconditions from the bases and decorate the function at the ``key``."""
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
value = namespace[key... | [
"def",
"_decorate_namespace_function",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"# pylint: disable=too-many-branches",
"# pylint: disable=to... | Collect preconditions and postconditions from the bases and decorate the function at the ``key``. | [
"Collect",
"preconditions",
"and",
"postconditions",
"from",
"the",
"bases",
"and",
"decorate",
"the",
"function",
"at",
"the",
"key",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L87-L169 |
Parquery/icontract | icontract/_metaclass.py | _decorate_namespace_property | def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them."""
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-man... | python | def _decorate_namespace_property(bases: List[type], namespace: MutableMapping[str, Any], key: str) -> None:
"""Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them."""
# pylint: disable=too-many-locals
# pylint: disable=too-many-branches
# pylint: disable=too-man... | [
"def",
"_decorate_namespace_property",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"# pylint: disable=too-many-locals",
"# pylint: disable=too-... | Collect contracts for all getters/setters/deleters corresponding to ``key`` and decorate them. | [
"Collect",
"contracts",
"for",
"all",
"getters",
"/",
"setters",
"/",
"deleters",
"corresponding",
"to",
"key",
"and",
"decorate",
"them",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L172-L268 |
Parquery/icontract | icontract/_metaclass.py | _dbc_decorate_namespace | def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""
Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a... | python | def _dbc_decorate_namespace(bases: List[type], namespace: MutableMapping[str, Any]) -> None:
"""
Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods a... | [
"def",
"_dbc_decorate_namespace",
"(",
"bases",
":",
"List",
"[",
"type",
"]",
",",
"namespace",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"_collapse_invariants",
"(",
"bases",
"=",
"bases",
",",
"namespace",
"=",
"namespa... | Collect invariants, preconditions and postconditions from the bases and decorate all the methods.
Instance methods are simply replaced with the decorated function/ Properties, class methods and static methods are
overridden with new instances of ``property``, ``classmethod`` and ``staticmethod``, respectively. | [
"Collect",
"invariants",
"preconditions",
"and",
"postconditions",
"from",
"the",
"bases",
"and",
"decorate",
"all",
"the",
"methods",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_metaclass.py#L271-L289 |
Parquery/icontract | icontract/_represent.py | _representable | def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... | python | def _representable(value: Any) -> bool:
"""
Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violatio... | [
"def",
"_representable",
"(",
"value",
":",
"Any",
")",
"->",
"bool",
":",
"return",
"not",
"inspect",
".",
"isclass",
"(",
"value",
")",
"and",
"not",
"inspect",
".",
"isfunction",
"(",
"value",
")",
"and",
"not",
"inspect",
".",
"ismethod",
"(",
"val... | Check whether we want to represent the value in the error message on contract breach.
We do not want to represent classes, methods, modules and functions.
:param value: value related to an AST node
:return: True if we want to represent it in the violation error | [
"Check",
"whether",
"we",
"want",
"to",
"represent",
"the",
"value",
"in",
"the",
"error",
"message",
"on",
"contract",
"breach",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L21-L31 |
Parquery/icontract | icontract/_represent.py | inspect_decorator | def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection:
"""
Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting ... | python | def inspect_decorator(lines: List[str], lineno: int, filename: str) -> DecoratorInspection:
"""
Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting ... | [
"def",
"inspect_decorator",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"lineno",
":",
"int",
",",
"filename",
":",
"str",
")",
"->",
"DecoratorInspection",
":",
"if",
"lineno",
"<",
"0",
"or",
"lineno",
">=",
"len",
"(",
"lines",
")",
":",
"rai... | Parse the file in which the decorator is called and figure out the corresponding call AST node.
:param lines: lines of the source file corresponding to the decorator call
:param lineno: line index (starting with 0) of one of the lines in the decorator call
:param filename: name of the file where decorator ... | [
"Parse",
"the",
"file",
"in",
"which",
"the",
"decorator",
"is",
"called",
"and",
"figure",
"out",
"the",
"corresponding",
"call",
"AST",
"node",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L183-L245 |
Parquery/icontract | icontract/_represent.py | find_lambda_condition | def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]:
"""
Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None.
"""
call_node = decorator_inspection.node
lambda_node = N... | python | def find_lambda_condition(decorator_inspection: DecoratorInspection) -> Optional[ConditionLambdaInspection]:
"""
Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None.
"""
call_node = decorator_inspection.node
lambda_node = N... | [
"def",
"find_lambda_condition",
"(",
"decorator_inspection",
":",
"DecoratorInspection",
")",
"->",
"Optional",
"[",
"ConditionLambdaInspection",
"]",
":",
"call_node",
"=",
"decorator_inspection",
".",
"node",
"lambda_node",
"=",
"None",
"# type: Optional[ast.Lambda]",
"... | Inspect the decorator and extract the condition as lambda.
If the condition is not given as a lambda function, return None. | [
"Inspect",
"the",
"decorator",
"and",
"extract",
"the",
"condition",
"as",
"lambda",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L248-L280 |
Parquery/icontract | icontract/_represent.py | repr_values | def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
# pylint: disable=too-many-locals
"""
Represent function arguments and frame values in the error message on contrac... | python | def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspection],
condition_kwargs: Mapping[str, Any], a_repr: reprlib.Repr) -> List[str]:
# pylint: disable=too-many-locals
"""
Represent function arguments and frame values in the error message on contrac... | [
"def",
"repr_values",
"(",
"condition",
":",
"Callable",
"[",
"...",
",",
"bool",
"]",
",",
"lambda_inspection",
":",
"Optional",
"[",
"ConditionLambdaInspection",
"]",
",",
"condition_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"a_repr",
":",... | Represent function arguments and frame values in the error message on contract breach.
:param condition: condition function of the contract
:param lambda_inspection:
inspected lambda AST node corresponding to the condition function (None if the condition was not given as a
lambda function)
... | [
"Represent",
"function",
"arguments",
"and",
"frame",
"values",
"in",
"the",
"error",
"message",
"on",
"contract",
"breach",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L283-L351 |
Parquery/icontract | icontract/_represent.py | generate_message | def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if co... | python | def generate_message(contract: Contract, condition_kwargs: Mapping[str, Any]) -> str:
"""Generate the message upon contract violation."""
# pylint: disable=protected-access
parts = [] # type: List[str]
if contract.location is not None:
parts.append("{}:\n".format(contract.location))
if co... | [
"def",
"generate_message",
"(",
"contract",
":",
"Contract",
",",
"condition_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"# pylint: disable=protected-access",
"parts",
"=",
"[",
"]",
"# type: List[str]",
"if",
"contract",
".",
... | Generate the message upon contract violation. | [
"Generate",
"the",
"message",
"upon",
"contract",
"violation",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L354-L405 |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Name | def visit_Name(self, node: ast.Name) -> None:
"""
Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored.
"""
if node in self._recomputed_values:... | python | def visit_Name(self, node: ast.Name) -> None:
"""
Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored.
"""
if node in self._recomputed_values:... | [
"def",
"visit_Name",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Name",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"# Check if it is a non-built-in",
... | Resolve the name from the variable look-up and the built-ins.
Due to possible branching (e.g., If-expressions), some nodes might lack the recomputed values. These nodes
are ignored. | [
"Resolve",
"the",
"name",
"from",
"the",
"variable",
"look",
"-",
"up",
"and",
"the",
"built",
"-",
"ins",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L57-L78 |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Attribute | def visit_Attribute(self, node: ast.Attribute) -> None:
"""Represent the attribute by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
if _representable(value=value):
text = self._atok.get_text(node)
... | python | def visit_Attribute(self, node: ast.Attribute) -> None:
"""Represent the attribute by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
if _representable(value=value):
text = self._atok.get_text(node)
... | [
"def",
"visit_Attribute",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Attribute",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"if",
"_representable",... | Represent the attribute by dumping its source code. | [
"Represent",
"the",
"attribute",
"by",
"dumping",
"its",
"source",
"code",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L80-L89 |
Parquery/icontract | icontract/_represent.py | Visitor.visit_Call | def visit_Call(self, node: ast.Call) -> None:
"""Represent the call by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=nod... | python | def visit_Call(self, node: ast.Call) -> None:
"""Represent the call by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.generic_visit(node=nod... | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
":",
"ast",
".",
"Call",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
".",
"... | Represent the call by dumping its source code. | [
"Represent",
"the",
"call",
"by",
"dumping",
"its",
"source",
"code",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L91-L99 |
Parquery/icontract | icontract/_represent.py | Visitor.visit_ListComp | def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.... | python | def visit_ListComp(self, node: ast.ListComp) -> None:
"""Represent the list comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
self.... | [
"def",
"visit_ListComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"ListComp",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
... | Represent the list comprehension by dumping its source code. | [
"Represent",
"the",
"list",
"comprehension",
"by",
"dumping",
"its",
"source",
"code",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L101-L109 |
Parquery/icontract | icontract/_represent.py | Visitor.visit_DictComp | def visit_DictComp(self, node: ast.DictComp) -> None:
"""Represent the dictionary comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
... | python | def visit_DictComp(self, node: ast.DictComp) -> None:
"""Represent the dictionary comprehension by dumping its source code."""
if node in self._recomputed_values:
value = self._recomputed_values[node]
text = self._atok.get_text(node)
self.reprs[text] = value
... | [
"def",
"visit_DictComp",
"(",
"self",
",",
"node",
":",
"ast",
".",
"DictComp",
")",
"->",
"None",
":",
"if",
"node",
"in",
"self",
".",
"_recomputed_values",
":",
"value",
"=",
"self",
".",
"_recomputed_values",
"[",
"node",
"]",
"text",
"=",
"self",
... | Represent the dictionary comprehension by dumping its source code. | [
"Represent",
"the",
"dictionary",
"comprehension",
"by",
"dumping",
"its",
"source",
"code",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_represent.py#L121-L129 |
Parquery/icontract | icontract/_checkers.py | _walk_decorator_stack | def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']:
"""
Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper.
"""
while hasattr(func, "__wrapped__"):
yield func
func = getattr(func, "... | python | def _walk_decorator_stack(func: CallableT) -> Iterable['CallableT']:
"""
Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper.
"""
while hasattr(func, "__wrapped__"):
yield func
func = getattr(func, "... | [
"def",
"_walk_decorator_stack",
"(",
"func",
":",
"CallableT",
")",
"->",
"Iterable",
"[",
"'CallableT'",
"]",
":",
"while",
"hasattr",
"(",
"func",
",",
"\"__wrapped__\"",
")",
":",
"yield",
"func",
"func",
"=",
"getattr",
"(",
"func",
",",
"\"__wrapped__\"... | Iterate through the stack of decorated functions until the original function.
Assume that all decorators used functools.update_wrapper. | [
"Iterate",
"through",
"the",
"stack",
"of",
"decorated",
"functions",
"until",
"the",
"original",
"function",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L17-L28 |
Parquery/icontract | icontract/_checkers.py | find_checker | def find_checker(func: CallableT) -> Optional[CallableT]:
"""Iterate through the decorator stack till we find the contract checker."""
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "... | python | def find_checker(func: CallableT) -> Optional[CallableT]:
"""Iterate through the decorator stack till we find the contract checker."""
contract_checker = None # type: Optional[CallableT]
for a_wrapper in _walk_decorator_stack(func):
if hasattr(a_wrapper, "__preconditions__") or hasattr(a_wrapper, "... | [
"def",
"find_checker",
"(",
"func",
":",
"CallableT",
")",
"->",
"Optional",
"[",
"CallableT",
"]",
":",
"contract_checker",
"=",
"None",
"# type: Optional[CallableT]",
"for",
"a_wrapper",
"in",
"_walk_decorator_stack",
"(",
"func",
")",
":",
"if",
"hasattr",
"(... | Iterate through the decorator stack till we find the contract checker. | [
"Iterate",
"through",
"the",
"decorator",
"stack",
"till",
"we",
"find",
"the",
"contract",
"checker",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L31-L38 |
Parquery/icontract | icontract/_checkers.py | _kwargs_from_call | def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...],
kwargs: Dict[str, Any]) -> MutableMapping[str, Any]:
"""
Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) name... | python | def _kwargs_from_call(param_names: List[str], kwdefaults: Dict[str, Any], args: Tuple[Any, ...],
kwargs: Dict[str, Any]) -> MutableMapping[str, Any]:
"""
Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) name... | [
"def",
"_kwargs_from_call",
"(",
"param_names",
":",
"List",
"[",
"str",
"]",
",",
"kwdefaults",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"args",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
... | Inspect the input values received at the wrapper for the actual function call.
:param param_names: parameter (*i.e.* argument) names of the original (decorated) function
:param kwdefaults: default argument values of the original function
:param args: arguments supplied to the call
:param kwargs: keywor... | [
"Inspect",
"the",
"input",
"values",
"received",
"at",
"the",
"wrapper",
"for",
"the",
"actual",
"function",
"call",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L41-L66 |
Parquery/icontract | icontract/_checkers.py | _assert_precondition | def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:
"""
Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return:
"""
# Check tha... | python | def _assert_precondition(contract: Contract, resolved_kwargs: Mapping[str, Any]) -> None:
"""
Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return:
"""
# Check tha... | [
"def",
"_assert_precondition",
"(",
"contract",
":",
"Contract",
",",
"resolved_kwargs",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"# Check that all arguments to the condition function have been set.",
"missing_args",
"=",
"[",
"arg_name",
"... | Assert that the contract holds as a precondition.
:param contract: contract to be verified
:param resolved_kwargs: resolved keyword arguments (including the default values)
:return: | [
"Assert",
"that",
"the",
"contract",
"holds",
"as",
"a",
"precondition",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L69-L120 |
Parquery/icontract | icontract/_checkers.py | _assert_invariant | def _assert_invariant(contract: Contract, instance: Any) -> None:
"""Assert that the contract holds as a class invariant given the instance of the class."""
if 'self' in contract.condition_arg_set:
check = contract.condition(self=instance)
else:
check = contract.condition()
if not check... | python | def _assert_invariant(contract: Contract, instance: Any) -> None:
"""Assert that the contract holds as a class invariant given the instance of the class."""
if 'self' in contract.condition_arg_set:
check = contract.condition(self=instance)
else:
check = contract.condition()
if not check... | [
"def",
"_assert_invariant",
"(",
"contract",
":",
"Contract",
",",
"instance",
":",
"Any",
")",
"->",
"None",
":",
"if",
"'self'",
"in",
"contract",
".",
"condition_arg_set",
":",
"check",
"=",
"contract",
".",
"condition",
"(",
"self",
"=",
"instance",
")... | Assert that the contract holds as a class invariant given the instance of the class. | [
"Assert",
"that",
"the",
"contract",
"holds",
"as",
"a",
"class",
"invariant",
"given",
"the",
"instance",
"of",
"the",
"class",
"."
] | train | https://github.com/Parquery/icontract/blob/846e3187869a9ba790e9b893c98e5055e1cce274/icontract/_checkers.py#L123-L150 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.