repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
gtsystem/parallelpipe
parallelpipe.py
Task.run
def run(self): """Execute the task on all the input and send the needed number of EXIT at the end""" input = self._consume() put_item = self._que_out.put try: if input is None: # producer res = self._callable(*self._args, **self._kwargs) else: res = self._callable(input, *self._args, **self._kwargs) if res != None: for item in res: put_item(item) except Exception as e: # we catch an error, we send on the error que, we consume the input and we exit # consuming the input queue avoid to keep running processes before exiting with # errors self._que_err.put((self.name, e)) if input is not None: for i in input: pass raise finally: for i in range(self._num_followers): put_item(EXIT) self._que_err.put(EXIT)
python
def run(self): """Execute the task on all the input and send the needed number of EXIT at the end""" input = self._consume() put_item = self._que_out.put try: if input is None: # producer res = self._callable(*self._args, **self._kwargs) else: res = self._callable(input, *self._args, **self._kwargs) if res != None: for item in res: put_item(item) except Exception as e: # we catch an error, we send on the error que, we consume the input and we exit # consuming the input queue avoid to keep running processes before exiting with # errors self._que_err.put((self.name, e)) if input is not None: for i in input: pass raise finally: for i in range(self._num_followers): put_item(EXIT) self._que_err.put(EXIT)
[ "def", "run", "(", "self", ")", ":", "input", "=", "self", ".", "_consume", "(", ")", "put_item", "=", "self", ".", "_que_out", ".", "put", "try", ":", "if", "input", "is", "None", ":", "# producer", "res", "=", "self", ".", "_callable", "(", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")", "else", ":", "res", "=", "self", ".", "_callable", "(", "input", ",", "*", "self", ".", "_args", ",", "*", "*", "self", ".", "_kwargs", ")", "if", "res", "!=", "None", ":", "for", "item", "in", "res", ":", "put_item", "(", "item", ")", "except", "Exception", "as", "e", ":", "# we catch an error, we send on the error que, we consume the input and we exit", "# consuming the input queue avoid to keep running processes before exiting with", "# errors", "self", ".", "_que_err", ".", "put", "(", "(", "self", ".", "name", ",", "e", ")", ")", "if", "input", "is", "not", "None", ":", "for", "i", "in", "input", ":", "pass", "raise", "finally", ":", "for", "i", "in", "range", "(", "self", ".", "_num_followers", ")", ":", "put_item", "(", "EXIT", ")", "self", ".", "_que_err", ".", "put", "(", "EXIT", ")" ]
Execute the task on all the input and send the needed number of EXIT at the end
[ "Execute", "the", "task", "on", "all", "the", "input", "and", "send", "the", "needed", "number", "of", "EXIT", "at", "the", "end" ]
b10eba28de6019cbf34e08ac575d31a4c493b39c
https://github.com/gtsystem/parallelpipe/blob/b10eba28de6019cbf34e08ac575d31a4c493b39c/parallelpipe.py#L56-L83
train
gtsystem/parallelpipe
parallelpipe.py
Stage.setup
def setup(self, workers=1, qsize=0): """Setup the pool parameters like number of workers and output queue size""" if workers <= 0: raise ValueError("workers have to be greater then zero") if qsize < 0: raise ValueError("qsize have to be greater or equal zero") self.qsize = qsize # output que size self.workers = workers return self
python
def setup(self, workers=1, qsize=0): """Setup the pool parameters like number of workers and output queue size""" if workers <= 0: raise ValueError("workers have to be greater then zero") if qsize < 0: raise ValueError("qsize have to be greater or equal zero") self.qsize = qsize # output que size self.workers = workers return self
[ "def", "setup", "(", "self", ",", "workers", "=", "1", ",", "qsize", "=", "0", ")", ":", "if", "workers", "<=", "0", ":", "raise", "ValueError", "(", "\"workers have to be greater then zero\"", ")", "if", "qsize", "<", "0", ":", "raise", "ValueError", "(", "\"qsize have to be greater or equal zero\"", ")", "self", ".", "qsize", "=", "qsize", "# output que size", "self", ".", "workers", "=", "workers", "return", "self" ]
Setup the pool parameters like number of workers and output queue size
[ "Setup", "the", "pool", "parameters", "like", "number", "of", "workers", "and", "output", "queue", "size" ]
b10eba28de6019cbf34e08ac575d31a4c493b39c
https://github.com/gtsystem/parallelpipe/blob/b10eba28de6019cbf34e08ac575d31a4c493b39c/parallelpipe.py#L104-L112
train
gtsystem/parallelpipe
parallelpipe.py
Stage.processes
def processes(self): """Initialise and return the list of processes associated with this pool""" if self._processes is None: self._processes = [] for p in range(self.workers): t = Task(self._target, self._args, self._kwargs) t.name = "%s-%d" % (self.target_name, p) self._processes.append(t) return self._processes
python
def processes(self): """Initialise and return the list of processes associated with this pool""" if self._processes is None: self._processes = [] for p in range(self.workers): t = Task(self._target, self._args, self._kwargs) t.name = "%s-%d" % (self.target_name, p) self._processes.append(t) return self._processes
[ "def", "processes", "(", "self", ")", ":", "if", "self", ".", "_processes", "is", "None", ":", "self", ".", "_processes", "=", "[", "]", "for", "p", "in", "range", "(", "self", ".", "workers", ")", ":", "t", "=", "Task", "(", "self", ".", "_target", ",", "self", ".", "_args", ",", "self", ".", "_kwargs", ")", "t", ".", "name", "=", "\"%s-%d\"", "%", "(", "self", ".", "target_name", ",", "p", ")", "self", ".", "_processes", ".", "append", "(", "t", ")", "return", "self", ".", "_processes" ]
Initialise and return the list of processes associated with this pool
[ "Initialise", "and", "return", "the", "list", "of", "processes", "associated", "with", "this", "pool" ]
b10eba28de6019cbf34e08ac575d31a4c493b39c
https://github.com/gtsystem/parallelpipe/blob/b10eba28de6019cbf34e08ac575d31a4c493b39c/parallelpipe.py#L115-L124
train
gtsystem/parallelpipe
parallelpipe.py
Pipeline.results
def results(self): """Start all the tasks and return data on an iterator""" tt = None for i, tf in enumerate(self[:-1]): tt = self[i+1] q = Queue(tf.qsize) tf.set_out(q, tt.workers) tt.set_in(q, tf.workers) if tt is None: # we have only one pool tt = self[0] q = Queue(tt.qsize) err_q = Queue() tt.set_out(q, 1) for t in self: t.set_err(err_q) t._start() for item in iterqueue(q, tt.workers): yield item errors = list(iterqueue(err_q, sum(t.workers for t in self))) for t in self: t._join() if len(errors) > 0: task_name, ex = errors[0] if len(errors) == 1: msg = 'The task "%s" raised %s' % (task_name, repr(ex),) else: msg = '%d tasks raised an exeption. First error reported on task "%s": %s' % (len(errors), task_name, repr(ex)) raise TaskException(msg)
python
def results(self): """Start all the tasks and return data on an iterator""" tt = None for i, tf in enumerate(self[:-1]): tt = self[i+1] q = Queue(tf.qsize) tf.set_out(q, tt.workers) tt.set_in(q, tf.workers) if tt is None: # we have only one pool tt = self[0] q = Queue(tt.qsize) err_q = Queue() tt.set_out(q, 1) for t in self: t.set_err(err_q) t._start() for item in iterqueue(q, tt.workers): yield item errors = list(iterqueue(err_q, sum(t.workers for t in self))) for t in self: t._join() if len(errors) > 0: task_name, ex = errors[0] if len(errors) == 1: msg = 'The task "%s" raised %s' % (task_name, repr(ex),) else: msg = '%d tasks raised an exeption. First error reported on task "%s": %s' % (len(errors), task_name, repr(ex)) raise TaskException(msg)
[ "def", "results", "(", "self", ")", ":", "tt", "=", "None", "for", "i", ",", "tf", "in", "enumerate", "(", "self", "[", ":", "-", "1", "]", ")", ":", "tt", "=", "self", "[", "i", "+", "1", "]", "q", "=", "Queue", "(", "tf", ".", "qsize", ")", "tf", ".", "set_out", "(", "q", ",", "tt", ".", "workers", ")", "tt", ".", "set_in", "(", "q", ",", "tf", ".", "workers", ")", "if", "tt", "is", "None", ":", "# we have only one pool", "tt", "=", "self", "[", "0", "]", "q", "=", "Queue", "(", "tt", ".", "qsize", ")", "err_q", "=", "Queue", "(", ")", "tt", ".", "set_out", "(", "q", ",", "1", ")", "for", "t", "in", "self", ":", "t", ".", "set_err", "(", "err_q", ")", "t", ".", "_start", "(", ")", "for", "item", "in", "iterqueue", "(", "q", ",", "tt", ".", "workers", ")", ":", "yield", "item", "errors", "=", "list", "(", "iterqueue", "(", "err_q", ",", "sum", "(", "t", ".", "workers", "for", "t", "in", "self", ")", ")", ")", "for", "t", "in", "self", ":", "t", ".", "_join", "(", ")", "if", "len", "(", "errors", ")", ">", "0", ":", "task_name", ",", "ex", "=", "errors", "[", "0", "]", "if", "len", "(", "errors", ")", "==", "1", ":", "msg", "=", "'The task \"%s\" raised %s'", "%", "(", "task_name", ",", "repr", "(", "ex", ")", ",", ")", "else", ":", "msg", "=", "'%d tasks raised an exeption. First error reported on task \"%s\": %s'", "%", "(", "len", "(", "errors", ")", ",", "task_name", ",", "repr", "(", "ex", ")", ")", "raise", "TaskException", "(", "msg", ")" ]
Start all the tasks and return data on an iterator
[ "Start", "all", "the", "tasks", "and", "return", "data", "on", "an", "iterator" ]
b10eba28de6019cbf34e08ac575d31a4c493b39c
https://github.com/gtsystem/parallelpipe/blob/b10eba28de6019cbf34e08ac575d31a4c493b39c/parallelpipe.py#L215-L249
train
The-Politico/politico-civic-election-night
electionnight/managers/page_content.py
PageContentManager.office_content
def office_content(self, election_day, office): """ Return serialized content for an office page. """ from electionnight.models import PageType office_type = ContentType.objects.get_for_model(office) page_type = PageType.objects.get( model_type=office_type, election_day=election_day, division_level=office.division.level, ) page_content = self.get( content_type__pk=office_type.pk, object_id=office.pk, election_day=election_day, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(page_content), }
python
def office_content(self, election_day, office): """ Return serialized content for an office page. """ from electionnight.models import PageType office_type = ContentType.objects.get_for_model(office) page_type = PageType.objects.get( model_type=office_type, election_day=election_day, division_level=office.division.level, ) page_content = self.get( content_type__pk=office_type.pk, object_id=office.pk, election_day=election_day, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(page_content), }
[ "def", "office_content", "(", "self", ",", "election_day", ",", "office", ")", ":", "from", "electionnight", ".", "models", "import", "PageType", "office_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "office", ")", "page_type", "=", "PageType", ".", "objects", ".", "get", "(", "model_type", "=", "office_type", ",", "election_day", "=", "election_day", ",", "division_level", "=", "office", ".", "division", ".", "level", ",", ")", "page_content", "=", "self", ".", "get", "(", "content_type__pk", "=", "office_type", ".", "pk", ",", "object_id", "=", "office", ".", "pk", ",", "election_day", "=", "election_day", ",", ")", "page_type_content", "=", "self", ".", "get", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "page_type", ")", ",", "object_id", "=", "page_type", ".", "pk", ",", "election_day", "=", "election_day", ",", ")", "return", "{", "\"site\"", ":", "self", ".", "site_content", "(", "election_day", ")", "[", "\"site\"", "]", ",", "\"page_type\"", ":", "self", ".", "serialize_content_blocks", "(", "page_type_content", ")", ",", "\"page\"", ":", "self", ".", "serialize_content_blocks", "(", "page_content", ")", ",", "}" ]
Return serialized content for an office page.
[ "Return", "serialized", "content", "for", "an", "office", "page", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/managers/page_content.py#L17-L44
train
The-Politico/politico-civic-election-night
electionnight/managers/page_content.py
PageContentManager.body_content
def body_content(self, election_day, body, division=None): """ Return serialized content for a body page. """ from electionnight.models import PageType body_type = ContentType.objects.get_for_model(body) page_type = PageType.objects.get( model_type=body_type, election_day=election_day, body=body, jurisdiction=body.jurisdiction, division_level=body.jurisdiction.division.level, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) kwargs = { "content_type__pk": body_type.pk, "object_id": body.pk, "election_day": election_day, } if division: kwargs["division"] = division content = self.get(**kwargs) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(content), "featured": [ e.meta.ap_election_id for e in content.featured.all() ], }
python
def body_content(self, election_day, body, division=None): """ Return serialized content for a body page. """ from electionnight.models import PageType body_type = ContentType.objects.get_for_model(body) page_type = PageType.objects.get( model_type=body_type, election_day=election_day, body=body, jurisdiction=body.jurisdiction, division_level=body.jurisdiction.division.level, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) kwargs = { "content_type__pk": body_type.pk, "object_id": body.pk, "election_day": election_day, } if division: kwargs["division"] = division content = self.get(**kwargs) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(content), "featured": [ e.meta.ap_election_id for e in content.featured.all() ], }
[ "def", "body_content", "(", "self", ",", "election_day", ",", "body", ",", "division", "=", "None", ")", ":", "from", "electionnight", ".", "models", "import", "PageType", "body_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "body", ")", "page_type", "=", "PageType", ".", "objects", ".", "get", "(", "model_type", "=", "body_type", ",", "election_day", "=", "election_day", ",", "body", "=", "body", ",", "jurisdiction", "=", "body", ".", "jurisdiction", ",", "division_level", "=", "body", ".", "jurisdiction", ".", "division", ".", "level", ",", ")", "page_type_content", "=", "self", ".", "get", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "page_type", ")", ",", "object_id", "=", "page_type", ".", "pk", ",", "election_day", "=", "election_day", ",", ")", "kwargs", "=", "{", "\"content_type__pk\"", ":", "body_type", ".", "pk", ",", "\"object_id\"", ":", "body", ".", "pk", ",", "\"election_day\"", ":", "election_day", ",", "}", "if", "division", ":", "kwargs", "[", "\"division\"", "]", "=", "division", "content", "=", "self", ".", "get", "(", "*", "*", "kwargs", ")", "return", "{", "\"site\"", ":", "self", ".", "site_content", "(", "election_day", ")", "[", "\"site\"", "]", ",", "\"page_type\"", ":", "self", ".", "serialize_content_blocks", "(", "page_type_content", ")", ",", "\"page\"", ":", "self", ".", "serialize_content_blocks", "(", "content", ")", ",", "\"featured\"", ":", "[", "e", ".", "meta", ".", "ap_election_id", "for", "e", "in", "content", ".", "featured", ".", "all", "(", ")", "]", ",", "}" ]
Return serialized content for a body page.
[ "Return", "serialized", "content", "for", "a", "body", "page", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/managers/page_content.py#L46-L83
train
The-Politico/politico-civic-election-night
electionnight/managers/page_content.py
PageContentManager.division_content
def division_content(self, election_day, division, special=False): """ Return serialized content for a division page. """ from electionnight.models import PageType division_type = ContentType.objects.get_for_model(division) page_type = PageType.objects.get( model_type=division_type, election_day=election_day, division_level=division.level, ) page_content = self.get( content_type__pk=division_type.pk, object_id=division.pk, election_day=election_day, special_election=special, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(page_content), }
python
def division_content(self, election_day, division, special=False): """ Return serialized content for a division page. """ from electionnight.models import PageType division_type = ContentType.objects.get_for_model(division) page_type = PageType.objects.get( model_type=division_type, election_day=election_day, division_level=division.level, ) page_content = self.get( content_type__pk=division_type.pk, object_id=division.pk, election_day=election_day, special_election=special, ) page_type_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return { "site": self.site_content(election_day)["site"], "page_type": self.serialize_content_blocks(page_type_content), "page": self.serialize_content_blocks(page_content), }
[ "def", "division_content", "(", "self", ",", "election_day", ",", "division", ",", "special", "=", "False", ")", ":", "from", "electionnight", ".", "models", "import", "PageType", "division_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "division", ")", "page_type", "=", "PageType", ".", "objects", ".", "get", "(", "model_type", "=", "division_type", ",", "election_day", "=", "election_day", ",", "division_level", "=", "division", ".", "level", ",", ")", "page_content", "=", "self", ".", "get", "(", "content_type__pk", "=", "division_type", ".", "pk", ",", "object_id", "=", "division", ".", "pk", ",", "election_day", "=", "election_day", ",", "special_election", "=", "special", ",", ")", "page_type_content", "=", "self", ".", "get", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "page_type", ")", ",", "object_id", "=", "page_type", ".", "pk", ",", "election_day", "=", "election_day", ",", ")", "return", "{", "\"site\"", ":", "self", ".", "site_content", "(", "election_day", ")", "[", "\"site\"", "]", ",", "\"page_type\"", ":", "self", ".", "serialize_content_blocks", "(", "page_type_content", ")", ",", "\"page\"", ":", "self", ".", "serialize_content_blocks", "(", "page_content", ")", ",", "}" ]
Return serialized content for a division page.
[ "Return", "serialized", "content", "for", "a", "division", "page", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/managers/page_content.py#L85-L112
train
The-Politico/politico-civic-election-night
electionnight/managers/page_content.py
PageContentManager.site_content
def site_content(self, election_day): """ Site content represents content for the entire site on a given election day. """ from electionnight.models import PageType page_type = PageType.objects.get( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ) site_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return {"site": self.serialize_content_blocks(site_content)}
python
def site_content(self, election_day): """ Site content represents content for the entire site on a given election day. """ from electionnight.models import PageType page_type = PageType.objects.get( model_type=ContentType.objects.get( app_label="election", model="electionday" ), election_day=election_day, ) site_content = self.get( content_type=ContentType.objects.get_for_model(page_type), object_id=page_type.pk, election_day=election_day, ) return {"site": self.serialize_content_blocks(site_content)}
[ "def", "site_content", "(", "self", ",", "election_day", ")", ":", "from", "electionnight", ".", "models", "import", "PageType", "page_type", "=", "PageType", ".", "objects", ".", "get", "(", "model_type", "=", "ContentType", ".", "objects", ".", "get", "(", "app_label", "=", "\"election\"", ",", "model", "=", "\"electionday\"", ")", ",", "election_day", "=", "election_day", ",", ")", "site_content", "=", "self", ".", "get", "(", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "page_type", ")", ",", "object_id", "=", "page_type", ".", "pk", ",", "election_day", "=", "election_day", ",", ")", "return", "{", "\"site\"", ":", "self", ".", "serialize_content_blocks", "(", "site_content", ")", "}" ]
Site content represents content for the entire site on a given election day.
[ "Site", "content", "represents", "content", "for", "the", "entire", "site", "on", "a", "given", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/managers/page_content.py#L114-L132
train
mardix/Juice
juice/core.py
get_interesting_members
def get_interesting_members(base_class, cls): """Returns a list of methods that can be routed to""" base_members = dir(base_class) predicate = inspect.ismethod if _py2 else inspect.isfunction all_members = inspect.getmembers(cls, predicate=predicate) return [member for member in all_members if not member[0] in base_members and ((hasattr(member[1], "__self__") and not member[1].__self__ in inspect.getmro(cls)) if _py2 else True) and not member[0].startswith("_") and not member[0].startswith("before_") and not member[0].startswith("after_")]
python
def get_interesting_members(base_class, cls): """Returns a list of methods that can be routed to""" base_members = dir(base_class) predicate = inspect.ismethod if _py2 else inspect.isfunction all_members = inspect.getmembers(cls, predicate=predicate) return [member for member in all_members if not member[0] in base_members and ((hasattr(member[1], "__self__") and not member[1].__self__ in inspect.getmro(cls)) if _py2 else True) and not member[0].startswith("_") and not member[0].startswith("before_") and not member[0].startswith("after_")]
[ "def", "get_interesting_members", "(", "base_class", ",", "cls", ")", ":", "base_members", "=", "dir", "(", "base_class", ")", "predicate", "=", "inspect", ".", "ismethod", "if", "_py2", "else", "inspect", ".", "isfunction", "all_members", "=", "inspect", ".", "getmembers", "(", "cls", ",", "predicate", "=", "predicate", ")", "return", "[", "member", "for", "member", "in", "all_members", "if", "not", "member", "[", "0", "]", "in", "base_members", "and", "(", "(", "hasattr", "(", "member", "[", "1", "]", ",", "\"__self__\"", ")", "and", "not", "member", "[", "1", "]", ".", "__self__", "in", "inspect", ".", "getmro", "(", "cls", ")", ")", "if", "_py2", "else", "True", ")", "and", "not", "member", "[", "0", "]", ".", "startswith", "(", "\"_\"", ")", "and", "not", "member", "[", "0", "]", ".", "startswith", "(", "\"before_\"", ")", "and", "not", "member", "[", "0", "]", ".", "startswith", "(", "\"after_\"", ")", "]" ]
Returns a list of methods that can be routed to
[ "Returns", "a", "list", "of", "methods", "that", "can", "be", "routed", "to" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/core.py#L688-L699
train
BrianHicks/tinyobj
tinyobj/fields.py
Field.initialize
def initialize(self, value=()): """\ initialize returns a cleaned value or the default, raising ValueErrors as necessary. """ if value == (): try: return self.default() except TypeError: return self.default else: return self.clean(value)
python
def initialize(self, value=()): """\ initialize returns a cleaned value or the default, raising ValueErrors as necessary. """ if value == (): try: return self.default() except TypeError: return self.default else: return self.clean(value)
[ "def", "initialize", "(", "self", ",", "value", "=", "(", ")", ")", ":", "if", "value", "==", "(", ")", ":", "try", ":", "return", "self", ".", "default", "(", ")", "except", "TypeError", ":", "return", "self", ".", "default", "else", ":", "return", "self", ".", "clean", "(", "value", ")" ]
\ initialize returns a cleaned value or the default, raising ValueErrors as necessary.
[ "\\", "initialize", "returns", "a", "cleaned", "value", "or", "the", "default", "raising", "ValueErrors", "as", "necessary", "." ]
c1ea7a007d70c2b815b4879d383af3825c74e7e8
https://github.com/BrianHicks/tinyobj/blob/c1ea7a007d70c2b815b4879d383af3825c74e7e8/tinyobj/fields.py#L10-L21
train
BrianHicks/tinyobj
tinyobj/fields.py
NumberField.clean
def clean(self, value): """clean a value, converting and performing bounds checking""" if not isinstance(value, self.t): value = self.t(value) if not self.allow_negative and value < 0: raise ValueError('value was negative') if not self.allow_positive and value > 0: raise ValueError('values was positive') return value
python
def clean(self, value): """clean a value, converting and performing bounds checking""" if not isinstance(value, self.t): value = self.t(value) if not self.allow_negative and value < 0: raise ValueError('value was negative') if not self.allow_positive and value > 0: raise ValueError('values was positive') return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "self", ".", "t", ")", ":", "value", "=", "self", ".", "t", "(", "value", ")", "if", "not", "self", ".", "allow_negative", "and", "value", "<", "0", ":", "raise", "ValueError", "(", "'value was negative'", ")", "if", "not", "self", ".", "allow_positive", "and", "value", ">", "0", ":", "raise", "ValueError", "(", "'values was positive'", ")", "return", "value" ]
clean a value, converting and performing bounds checking
[ "clean", "a", "value", "converting", "and", "performing", "bounds", "checking" ]
c1ea7a007d70c2b815b4879d383af3825c74e7e8
https://github.com/BrianHicks/tinyobj/blob/c1ea7a007d70c2b815b4879d383af3825c74e7e8/tinyobj/fields.py#L40-L51
train
adamheins/r12
r12/arm.py
r12_serial_port
def r12_serial_port(port): ''' Create a serial connect to the arm. ''' return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY, stopbits=STOP_BITS, bytesize=BYTE_SIZE)
python
def r12_serial_port(port): ''' Create a serial connect to the arm. ''' return serial.Serial(port, baudrate=BAUD_RATE, parity=PARITY, stopbits=STOP_BITS, bytesize=BYTE_SIZE)
[ "def", "r12_serial_port", "(", "port", ")", ":", "return", "serial", ".", "Serial", "(", "port", ",", "baudrate", "=", "BAUD_RATE", ",", "parity", "=", "PARITY", ",", "stopbits", "=", "STOP_BITS", ",", "bytesize", "=", "BYTE_SIZE", ")" ]
Create a serial connect to the arm.
[ "Create", "a", "serial", "connect", "to", "the", "arm", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L36-L39
train
adamheins/r12
r12/arm.py
search_for_port
def search_for_port(port_glob, req, expected_res): ''' Find the serial port the arm is connected to. ''' # Check that the USB port actually exists, based on the known vendor and # product ID. if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None: return None # Find ports matching the supplied glob. ports = glob.glob(port_glob) if len(ports) == 0: return None for port in ports: with r12_serial_port(port) as ser: if not ser.isOpen(): ser.open() # Write a request out. if sys.version_info[0] == 2: ser.write(str(req).encode('utf-8')) else: ser.write(bytes(req, 'utf-8')) # Wait a short period to allow the connection to generate output. time.sleep(0.1) # Read output from the serial connection check if it's what we want. res = ser.read(ser.in_waiting).decode(OUTPUT_ENCODING) if expected_res in res: return port raise ArmException('ST Robotics connection found, but is not responsive.' + ' Is the arm powered on?') return None
python
def search_for_port(port_glob, req, expected_res): ''' Find the serial port the arm is connected to. ''' # Check that the USB port actually exists, based on the known vendor and # product ID. if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None: return None # Find ports matching the supplied glob. ports = glob.glob(port_glob) if len(ports) == 0: return None for port in ports: with r12_serial_port(port) as ser: if not ser.isOpen(): ser.open() # Write a request out. if sys.version_info[0] == 2: ser.write(str(req).encode('utf-8')) else: ser.write(bytes(req, 'utf-8')) # Wait a short period to allow the connection to generate output. time.sleep(0.1) # Read output from the serial connection check if it's what we want. res = ser.read(ser.in_waiting).decode(OUTPUT_ENCODING) if expected_res in res: return port raise ArmException('ST Robotics connection found, but is not responsive.' + ' Is the arm powered on?') return None
[ "def", "search_for_port", "(", "port_glob", ",", "req", ",", "expected_res", ")", ":", "# Check that the USB port actually exists, based on the known vendor and", "# product ID.", "if", "usb", ".", "core", ".", "find", "(", "idVendor", "=", "0x0403", ",", "idProduct", "=", "0x6001", ")", "is", "None", ":", "return", "None", "# Find ports matching the supplied glob.", "ports", "=", "glob", ".", "glob", "(", "port_glob", ")", "if", "len", "(", "ports", ")", "==", "0", ":", "return", "None", "for", "port", "in", "ports", ":", "with", "r12_serial_port", "(", "port", ")", "as", "ser", ":", "if", "not", "ser", ".", "isOpen", "(", ")", ":", "ser", ".", "open", "(", ")", "# Write a request out.", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "ser", ".", "write", "(", "str", "(", "req", ")", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "ser", ".", "write", "(", "bytes", "(", "req", ",", "'utf-8'", ")", ")", "# Wait a short period to allow the connection to generate output.", "time", ".", "sleep", "(", "0.1", ")", "# Read output from the serial connection check if it's what we want.", "res", "=", "ser", ".", "read", "(", "ser", ".", "in_waiting", ")", ".", "decode", "(", "OUTPUT_ENCODING", ")", "if", "expected_res", "in", "res", ":", "return", "port", "raise", "ArmException", "(", "'ST Robotics connection found, but is not responsive.'", "+", "' Is the arm powered on?'", ")", "return", "None" ]
Find the serial port the arm is connected to.
[ "Find", "the", "serial", "port", "the", "arm", "is", "connected", "to", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L42-L76
train
adamheins/r12
r12/arm.py
Arm.connect
def connect(self, port=None): ''' Open a serial connection to the arm. ''' if port is None: self.port = search_for_port('/dev/ttyUSB*', 'ROBOFORTH\r\n', 'ROBOFORTH') else: self.port = port if self.port is None: raise ArmException('ST Robotics connection not found.') self.ser = r12_serial_port(port) if not self.ser.isOpen(): self.ser.open() if not self.ser.isOpen(): raise ArmException('Failed to open serial port. Exiting.') return self.port
python
def connect(self, port=None): ''' Open a serial connection to the arm. ''' if port is None: self.port = search_for_port('/dev/ttyUSB*', 'ROBOFORTH\r\n', 'ROBOFORTH') else: self.port = port if self.port is None: raise ArmException('ST Robotics connection not found.') self.ser = r12_serial_port(port) if not self.ser.isOpen(): self.ser.open() if not self.ser.isOpen(): raise ArmException('Failed to open serial port. Exiting.') return self.port
[ "def", "connect", "(", "self", ",", "port", "=", "None", ")", ":", "if", "port", "is", "None", ":", "self", ".", "port", "=", "search_for_port", "(", "'/dev/ttyUSB*'", ",", "'ROBOFORTH\\r\\n'", ",", "'ROBOFORTH'", ")", "else", ":", "self", ".", "port", "=", "port", "if", "self", ".", "port", "is", "None", ":", "raise", "ArmException", "(", "'ST Robotics connection not found.'", ")", "self", ".", "ser", "=", "r12_serial_port", "(", "port", ")", "if", "not", "self", ".", "ser", ".", "isOpen", "(", ")", ":", "self", ".", "ser", ".", "open", "(", ")", "if", "not", "self", ".", "ser", ".", "isOpen", "(", ")", ":", "raise", "ArmException", "(", "'Failed to open serial port. Exiting.'", ")", "return", "self", ".", "port" ]
Open a serial connection to the arm.
[ "Open", "a", "serial", "connection", "to", "the", "arm", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L97-L116
train
adamheins/r12
r12/arm.py
Arm.write
def write(self, text): ''' Write text out to the arm. ''' # Output is converted to bytes with Windows-style line endings. if sys.version_info[0] == 2: text_bytes = str(text.upper() + '\r\n').encode('utf-8') else: text_bytes = bytes(text.upper() + '\r\n', 'utf-8') self.ser.write(text_bytes)
python
def write(self, text): ''' Write text out to the arm. ''' # Output is converted to bytes with Windows-style line endings. if sys.version_info[0] == 2: text_bytes = str(text.upper() + '\r\n').encode('utf-8') else: text_bytes = bytes(text.upper() + '\r\n', 'utf-8') self.ser.write(text_bytes)
[ "def", "write", "(", "self", ",", "text", ")", ":", "# Output is converted to bytes with Windows-style line endings.", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "text_bytes", "=", "str", "(", "text", ".", "upper", "(", ")", "+", "'\\r\\n'", ")", ".", "encode", "(", "'utf-8'", ")", "else", ":", "text_bytes", "=", "bytes", "(", "text", ".", "upper", "(", ")", "+", "'\\r\\n'", ",", "'utf-8'", ")", "self", ".", "ser", ".", "write", "(", "text_bytes", ")" ]
Write text out to the arm.
[ "Write", "text", "out", "to", "the", "arm", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L126-L133
train
adamheins/r12
r12/arm.py
Arm.read
def read(self, timeout=READ_TIMEOUT, raw=False): ''' Read data from the arm. Data is returned as a latin_1 encoded string, or raw bytes if 'raw' is True. ''' time.sleep(READ_SLEEP_TIME) raw_out = self.ser.read(self.ser.in_waiting) out = raw_out.decode(OUTPUT_ENCODING) time_waiting = 0 while len(out) == 0 or ending_in(out.strip(OUTPUT_STRIP_CHARS), RESPONSE_END_WORDS) is None: time.sleep(READ_SLEEP_TIME) time_waiting += READ_SLEEP_TIME raw_out += self.ser.read(self.ser.in_waiting) out = raw_out.decode(OUTPUT_ENCODING) # TODO how to handle timeouts, if they're now unexpected? if time_waiting >= timeout: break if raw: return raw_out return out
python
def read(self, timeout=READ_TIMEOUT, raw=False): ''' Read data from the arm. Data is returned as a latin_1 encoded string, or raw bytes if 'raw' is True. ''' time.sleep(READ_SLEEP_TIME) raw_out = self.ser.read(self.ser.in_waiting) out = raw_out.decode(OUTPUT_ENCODING) time_waiting = 0 while len(out) == 0 or ending_in(out.strip(OUTPUT_STRIP_CHARS), RESPONSE_END_WORDS) is None: time.sleep(READ_SLEEP_TIME) time_waiting += READ_SLEEP_TIME raw_out += self.ser.read(self.ser.in_waiting) out = raw_out.decode(OUTPUT_ENCODING) # TODO how to handle timeouts, if they're now unexpected? if time_waiting >= timeout: break if raw: return raw_out return out
[ "def", "read", "(", "self", ",", "timeout", "=", "READ_TIMEOUT", ",", "raw", "=", "False", ")", ":", "time", ".", "sleep", "(", "READ_SLEEP_TIME", ")", "raw_out", "=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "out", "=", "raw_out", ".", "decode", "(", "OUTPUT_ENCODING", ")", "time_waiting", "=", "0", "while", "len", "(", "out", ")", "==", "0", "or", "ending_in", "(", "out", ".", "strip", "(", "OUTPUT_STRIP_CHARS", ")", ",", "RESPONSE_END_WORDS", ")", "is", "None", ":", "time", ".", "sleep", "(", "READ_SLEEP_TIME", ")", "time_waiting", "+=", "READ_SLEEP_TIME", "raw_out", "+=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "out", "=", "raw_out", ".", "decode", "(", "OUTPUT_ENCODING", ")", "# TODO how to handle timeouts, if they're now unexpected?", "if", "time_waiting", ">=", "timeout", ":", "break", "if", "raw", ":", "return", "raw_out", "return", "out" ]
Read data from the arm. Data is returned as a latin_1 encoded string, or raw bytes if 'raw' is True.
[ "Read", "data", "from", "the", "arm", ".", "Data", "is", "returned", "as", "a", "latin_1", "encoded", "string", "or", "raw", "bytes", "if", "raw", "is", "True", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L136-L157
train
adamheins/r12
r12/arm.py
Arm.dump
def dump(self, raw=False): ''' Dump all output currently in the arm's output queue. ''' raw_out = self.ser.read(self.ser.in_waiting) if raw: return raw_out return raw_out.decode(OUTPUT_ENCODING)
python
def dump(self, raw=False): ''' Dump all output currently in the arm's output queue. ''' raw_out = self.ser.read(self.ser.in_waiting) if raw: return raw_out return raw_out.decode(OUTPUT_ENCODING)
[ "def", "dump", "(", "self", ",", "raw", "=", "False", ")", ":", "raw_out", "=", "self", ".", "ser", ".", "read", "(", "self", ".", "ser", ".", "in_waiting", ")", "if", "raw", ":", "return", "raw_out", "return", "raw_out", ".", "decode", "(", "OUTPUT_ENCODING", ")" ]
Dump all output currently in the arm's output queue.
[ "Dump", "all", "output", "currently", "in", "the", "arm", "s", "output", "queue", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L160-L165
train
adamheins/r12
r12/arm.py
Arm.get_info
def get_info(self): ''' Returns status of the robot arm. ''' return { 'Connected': self.is_connected(), 'Port': self.port, 'Bytes Waiting': self.ser.in_waiting if self.ser else 0 }
python
def get_info(self): ''' Returns status of the robot arm. ''' return { 'Connected': self.is_connected(), 'Port': self.port, 'Bytes Waiting': self.ser.in_waiting if self.ser else 0 }
[ "def", "get_info", "(", "self", ")", ":", "return", "{", "'Connected'", ":", "self", ".", "is_connected", "(", ")", ",", "'Port'", ":", "self", ".", "port", ",", "'Bytes Waiting'", ":", "self", ".", "ser", ".", "in_waiting", "if", "self", ".", "ser", "else", "0", "}" ]
Returns status of the robot arm.
[ "Returns", "status", "of", "the", "robot", "arm", "." ]
ff78178332140930bf46a94a0b15ee082bb92491
https://github.com/adamheins/r12/blob/ff78178332140930bf46a94a0b15ee082bb92491/r12/arm.py#L173-L179
train
fabaff/python-opensensemap-api
opensensemap_api/__init__.py
OpenSenseMap.get_data
async def get_data(self): """Get details of OpenSenseMap station.""" try: async with async_timeout.timeout(5, loop=self._loop): response = await self._session.get(self.base_url) _LOGGER.info( "Response from OpenSenseMap API: %s", response.status) self.data = await response.json() _LOGGER.debug(self.data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): _LOGGER.error("Can not load data from openSenseMap API") raise exceptions.OpenSenseMapConnectionError
python
async def get_data(self): """Get details of OpenSenseMap station.""" try: async with async_timeout.timeout(5, loop=self._loop): response = await self._session.get(self.base_url) _LOGGER.info( "Response from OpenSenseMap API: %s", response.status) self.data = await response.json() _LOGGER.debug(self.data) except (asyncio.TimeoutError, aiohttp.ClientError, socket.gaierror): _LOGGER.error("Can not load data from openSenseMap API") raise exceptions.OpenSenseMapConnectionError
[ "async", "def", "get_data", "(", "self", ")", ":", "try", ":", "async", "with", "async_timeout", ".", "timeout", "(", "5", ",", "loop", "=", "self", ".", "_loop", ")", ":", "response", "=", "await", "self", ".", "_session", ".", "get", "(", "self", ".", "base_url", ")", "_LOGGER", ".", "info", "(", "\"Response from OpenSenseMap API: %s\"", ",", "response", ".", "status", ")", "self", ".", "data", "=", "await", "response", ".", "json", "(", ")", "_LOGGER", ".", "debug", "(", "self", ".", "data", ")", "except", "(", "asyncio", ".", "TimeoutError", ",", "aiohttp", ".", "ClientError", ",", "socket", ".", "gaierror", ")", ":", "_LOGGER", ".", "error", "(", "\"Can not load data from openSenseMap API\"", ")", "raise", "exceptions", ".", "OpenSenseMapConnectionError" ]
Get details of OpenSenseMap station.
[ "Get", "details", "of", "OpenSenseMap", "station", "." ]
3c4f5473c514185087aae5d766ab4d5736ec1f30
https://github.com/fabaff/python-opensensemap-api/blob/3c4f5473c514185087aae5d766ab4d5736ec1f30/opensensemap_api/__init__.py#L48-L61
train
fabaff/python-opensensemap-api
opensensemap_api/__init__.py
OpenSenseMap.get_value
def get_value(self, key): """Extract a value for a given key.""" for title in _TITLES.get(key, ()) + (key,): try: value = [entry['lastMeasurement']['value'] for entry in self.data['sensors'] if entry['title'] == title][0] return value except IndexError: pass return None
python
def get_value(self, key): """Extract a value for a given key.""" for title in _TITLES.get(key, ()) + (key,): try: value = [entry['lastMeasurement']['value'] for entry in self.data['sensors'] if entry['title'] == title][0] return value except IndexError: pass return None
[ "def", "get_value", "(", "self", ",", "key", ")", ":", "for", "title", "in", "_TITLES", ".", "get", "(", "key", ",", "(", ")", ")", "+", "(", "key", ",", ")", ":", "try", ":", "value", "=", "[", "entry", "[", "'lastMeasurement'", "]", "[", "'value'", "]", "for", "entry", "in", "self", ".", "data", "[", "'sensors'", "]", "if", "entry", "[", "'title'", "]", "==", "title", "]", "[", "0", "]", "return", "value", "except", "IndexError", ":", "pass", "return", "None" ]
Extract a value for a given key.
[ "Extract", "a", "value", "for", "a", "given", "key", "." ]
3c4f5473c514185087aae5d766ab4d5736ec1f30
https://github.com/fabaff/python-opensensemap-api/blob/3c4f5473c514185087aae5d766ab4d5736ec1f30/opensensemap_api/__init__.py#L123-L132
train
tjcsl/cslbot
cslbot/commands/note.py
cmd
def cmd(send, msg, args): """Leaves a note for a user or users. Syntax: {command} <nick>[,nick2,...] <note> """ if not args['config']['feature'].getboolean('hooks'): send("Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).") return if args['type'] == 'privmsg': send("Note-passing should be done in public.") return try: nick, note = msg.split(maxsplit=1) nicks = set(x for x in nick.split(',') if x) except ValueError: send("Not enough arguments.") return nickregex = args['config']['core']['nickregex'] + '+$' successful_nicks = [] failed_nicks = [] for nick in nicks: if re.match(nickregex, nick): row = Notes(note=note, submitter=args['nick'], nick=nick, time=datetime.now()) args['db'].add(row) successful_nicks.append(nick) else: failed_nicks.append(nick) if successful_nicks: send("Note left for %s." % ", ".join(successful_nicks)) if failed_nicks: send("Invalid nick(s): %s." % ", ".join(failed_nicks))
python
def cmd(send, msg, args): """Leaves a note for a user or users. Syntax: {command} <nick>[,nick2,...] <note> """ if not args['config']['feature'].getboolean('hooks'): send("Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).") return if args['type'] == 'privmsg': send("Note-passing should be done in public.") return try: nick, note = msg.split(maxsplit=1) nicks = set(x for x in nick.split(',') if x) except ValueError: send("Not enough arguments.") return nickregex = args['config']['core']['nickregex'] + '+$' successful_nicks = [] failed_nicks = [] for nick in nicks: if re.match(nickregex, nick): row = Notes(note=note, submitter=args['nick'], nick=nick, time=datetime.now()) args['db'].add(row) successful_nicks.append(nick) else: failed_nicks.append(nick) if successful_nicks: send("Note left for %s." % ", ".join(successful_nicks)) if failed_nicks: send("Invalid nick(s): %s." % ", ".join(failed_nicks))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "args", "[", "'config'", "]", "[", "'feature'", "]", ".", "getboolean", "(", "'hooks'", ")", ":", "send", "(", "\"Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s).\"", ")", "return", "if", "args", "[", "'type'", "]", "==", "'privmsg'", ":", "send", "(", "\"Note-passing should be done in public.\"", ")", "return", "try", ":", "nick", ",", "note", "=", "msg", ".", "split", "(", "maxsplit", "=", "1", ")", "nicks", "=", "set", "(", "x", "for", "x", "in", "nick", ".", "split", "(", "','", ")", "if", "x", ")", "except", "ValueError", ":", "send", "(", "\"Not enough arguments.\"", ")", "return", "nickregex", "=", "args", "[", "'config'", "]", "[", "'core'", "]", "[", "'nickregex'", "]", "+", "'+$'", "successful_nicks", "=", "[", "]", "failed_nicks", "=", "[", "]", "for", "nick", "in", "nicks", ":", "if", "re", ".", "match", "(", "nickregex", ",", "nick", ")", ":", "row", "=", "Notes", "(", "note", "=", "note", ",", "submitter", "=", "args", "[", "'nick'", "]", ",", "nick", "=", "nick", ",", "time", "=", "datetime", ".", "now", "(", ")", ")", "args", "[", "'db'", "]", ".", "add", "(", "row", ")", "successful_nicks", ".", "append", "(", "nick", ")", "else", ":", "failed_nicks", ".", "append", "(", "nick", ")", "if", "successful_nicks", ":", "send", "(", "\"Note left for %s.\"", "%", "\", \"", ".", "join", "(", "successful_nicks", ")", ")", "if", "failed_nicks", ":", "send", "(", "\"Invalid nick(s): %s.\"", "%", "\", \"", ".", "join", "(", "failed_nicks", ")", ")" ]
Leaves a note for a user or users. Syntax: {command} <nick>[,nick2,...] <note>
[ "Leaves", "a", "note", "for", "a", "user", "or", "users", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/note.py#L26-L57
train
ktdreyer/txkoji
txkoji/messages.py
BuildStateChange.from_frame
def from_frame(klass, frame, connection): """ Create a new BuildStateChange event from a Stompest Frame. """ event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] build = Build.fromDict(info) build.connection = connection return klass(build, event)
python
def from_frame(klass, frame, connection): """ Create a new BuildStateChange event from a Stompest Frame. """ event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] build = Build.fromDict(info) build.connection = connection return klass(build, event)
[ "def", "from_frame", "(", "klass", ",", "frame", ",", "connection", ")", ":", "event", "=", "frame", ".", "headers", "[", "'new'", "]", "data", "=", "json", ".", "loads", "(", "frame", ".", "body", ")", "info", "=", "data", "[", "'info'", "]", "build", "=", "Build", ".", "fromDict", "(", "info", ")", "build", ".", "connection", "=", "connection", "return", "klass", "(", "build", ",", "event", ")" ]
Create a new BuildStateChange event from a Stompest Frame.
[ "Create", "a", "new", "BuildStateChange", "event", "from", "a", "Stompest", "Frame", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/messages.py#L31-L40
train
ktdreyer/txkoji
txkoji/messages.py
TaskStateChange.from_frame
def from_frame(klass, frame, connection): """ Create a new TaskStateChange event from a Stompest Frame. """ event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] task = Task.fromDict(info) task.connection = connection return klass(task, event)
python
def from_frame(klass, frame, connection): """ Create a new TaskStateChange event from a Stompest Frame. """ event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] task = Task.fromDict(info) task.connection = connection return klass(task, event)
[ "def", "from_frame", "(", "klass", ",", "frame", ",", "connection", ")", ":", "event", "=", "frame", ".", "headers", "[", "'new'", "]", "data", "=", "json", ".", "loads", "(", "frame", ".", "body", ")", "info", "=", "data", "[", "'info'", "]", "task", "=", "Task", ".", "fromDict", "(", "info", ")", "task", ".", "connection", "=", "connection", "return", "klass", "(", "task", ",", "event", ")" ]
Create a new TaskStateChange event from a Stompest Frame.
[ "Create", "a", "new", "TaskStateChange", "event", "from", "a", "Stompest", "Frame", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/messages.py#L60-L69
train
tjcsl/cslbot
cslbot/commands/ping.py
cmd
def cmd(send, msg, args): """Ping something. Syntax: {command} <target> """ if not msg: send("Ping what?") return channel = args['target'] if args['target'] != 'private' else args['nick'] # CTCP PING if "." not in msg and ":" not in msg: targets = set(msg.split()) if len(targets) > 3: send("Please specify three or fewer people to ping.") return for target in targets: if not re.match(args['config']['core']['nickregex'], target): send("Invalid nick %s" % target) else: args['handler'].ping_map[target] = channel args['handler'].connection.ctcp("PING", target, " ".join(str(time()).split('.'))) return try: answer = subprocess.check_output([args['name'], '-W', '1', '-c', '1', msg], stderr=subprocess.STDOUT) answer = answer.decode().splitlines() send(answer[0]) send(answer[1]) except subprocess.CalledProcessError as e: if e.returncode == 2: send("ping: unknown host " + msg) elif e.returncode == 1: send(e.output.decode().splitlines()[-2])
python
def cmd(send, msg, args): """Ping something. Syntax: {command} <target> """ if not msg: send("Ping what?") return channel = args['target'] if args['target'] != 'private' else args['nick'] # CTCP PING if "." not in msg and ":" not in msg: targets = set(msg.split()) if len(targets) > 3: send("Please specify three or fewer people to ping.") return for target in targets: if not re.match(args['config']['core']['nickregex'], target): send("Invalid nick %s" % target) else: args['handler'].ping_map[target] = channel args['handler'].connection.ctcp("PING", target, " ".join(str(time()).split('.'))) return try: answer = subprocess.check_output([args['name'], '-W', '1', '-c', '1', msg], stderr=subprocess.STDOUT) answer = answer.decode().splitlines() send(answer[0]) send(answer[1]) except subprocess.CalledProcessError as e: if e.returncode == 2: send("ping: unknown host " + msg) elif e.returncode == 1: send(e.output.decode().splitlines()[-2])
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"Ping what?\"", ")", "return", "channel", "=", "args", "[", "'target'", "]", "if", "args", "[", "'target'", "]", "!=", "'private'", "else", "args", "[", "'nick'", "]", "# CTCP PING", "if", "\".\"", "not", "in", "msg", "and", "\":\"", "not", "in", "msg", ":", "targets", "=", "set", "(", "msg", ".", "split", "(", ")", ")", "if", "len", "(", "targets", ")", ">", "3", ":", "send", "(", "\"Please specify three or fewer people to ping.\"", ")", "return", "for", "target", "in", "targets", ":", "if", "not", "re", ".", "match", "(", "args", "[", "'config'", "]", "[", "'core'", "]", "[", "'nickregex'", "]", ",", "target", ")", ":", "send", "(", "\"Invalid nick %s\"", "%", "target", ")", "else", ":", "args", "[", "'handler'", "]", ".", "ping_map", "[", "target", "]", "=", "channel", "args", "[", "'handler'", "]", ".", "connection", ".", "ctcp", "(", "\"PING\"", ",", "target", ",", "\" \"", ".", "join", "(", "str", "(", "time", "(", ")", ")", ".", "split", "(", "'.'", ")", ")", ")", "return", "try", ":", "answer", "=", "subprocess", ".", "check_output", "(", "[", "args", "[", "'name'", "]", ",", "'-W'", ",", "'1'", ",", "'-c'", ",", "'1'", ",", "msg", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "answer", "=", "answer", ".", "decode", "(", ")", ".", "splitlines", "(", ")", "send", "(", "answer", "[", "0", "]", ")", "send", "(", "answer", "[", "1", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "if", "e", ".", "returncode", "==", "2", ":", "send", "(", "\"ping: unknown host \"", "+", "msg", ")", "elif", "e", ".", "returncode", "==", "1", ":", "send", "(", "e", ".", "output", ".", "decode", "(", ")", ".", "splitlines", "(", ")", "[", "-", "2", "]", ")" ]
Ping something. Syntax: {command} <target>
[ "Ping", "something", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/ping.py#L26-L58
train
shapiromatron/bmds
bmds/models/base.py
BMDModel.execution_duration
def execution_duration(self): """ Returns total BMDS execution time, in seconds. """ duration = None if self.execution_start and self.execution_end: delta = self.execution_end - self.execution_start duration = delta.total_seconds() return duration
python
def execution_duration(self): """ Returns total BMDS execution time, in seconds. """ duration = None if self.execution_start and self.execution_end: delta = self.execution_end - self.execution_start duration = delta.total_seconds() return duration
[ "def", "execution_duration", "(", "self", ")", ":", "duration", "=", "None", "if", "self", ".", "execution_start", "and", "self", ".", "execution_end", ":", "delta", "=", "self", ".", "execution_end", "-", "self", ".", "execution_start", "duration", "=", "delta", ".", "total_seconds", "(", ")", "return", "duration" ]
Returns total BMDS execution time, in seconds.
[ "Returns", "total", "BMDS", "execution", "time", "in", "seconds", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L155-L163
train
shapiromatron/bmds
bmds/models/base.py
BMDModel.get_exe_path
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
python
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
[ "def", "get_exe_path", "(", "cls", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "cls", ".", "bmds_version_dir", ",", "cls", ".", "exe", "+", "\".exe\"", ")", ")" ]
Return the full path to the executable.
[ "Return", "the", "full", "path", "to", "the", "executable", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L173-L177
train
shapiromatron/bmds
bmds/models/base.py
BMDModel.plot
def plot(self): """ After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure:: ../tests/resources/test_exponential_m4_plot.png :scale: 80% :align: center :alt: Example generated BMD plot BMD models can generate plots using the ``plot()`` method; an example is shown here. """ fig = self.dataset.plot() ax = fig.gca() ax.set_title( "{}\n{}, {}".format(self.dataset._get_dataset_name(), self.name, self.get_bmr_text()) ) if self.has_successfully_executed: self._set_x_range(ax) ax.plot(self._xs, self.get_ys(self._xs), label=self.name, **plotting.LINE_FORMAT) self._add_bmr_lines(ax) else: self._add_plot_failure(ax) ax.legend(**settings.LEGEND_OPTS) return fig
python
def plot(self): """ After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure:: ../tests/resources/test_exponential_m4_plot.png :scale: 80% :align: center :alt: Example generated BMD plot BMD models can generate plots using the ``plot()`` method; an example is shown here. """ fig = self.dataset.plot() ax = fig.gca() ax.set_title( "{}\n{}, {}".format(self.dataset._get_dataset_name(), self.name, self.get_bmr_text()) ) if self.has_successfully_executed: self._set_x_range(ax) ax.plot(self._xs, self.get_ys(self._xs), label=self.name, **plotting.LINE_FORMAT) self._add_bmr_lines(ax) else: self._add_plot_failure(ax) ax.legend(**settings.LEGEND_OPTS) return fig
[ "def", "plot", "(", "self", ")", ":", "fig", "=", "self", ".", "dataset", ".", "plot", "(", ")", "ax", "=", "fig", ".", "gca", "(", ")", "ax", ".", "set_title", "(", "\"{}\\n{}, {}\"", ".", "format", "(", "self", ".", "dataset", ".", "_get_dataset_name", "(", ")", ",", "self", ".", "name", ",", "self", ".", "get_bmr_text", "(", ")", ")", ")", "if", "self", ".", "has_successfully_executed", ":", "self", ".", "_set_x_range", "(", "ax", ")", "ax", ".", "plot", "(", "self", ".", "_xs", ",", "self", ".", "get_ys", "(", "self", ".", "_xs", ")", ",", "label", "=", "self", ".", "name", ",", "*", "*", "plotting", ".", "LINE_FORMAT", ")", "self", ".", "_add_bmr_lines", "(", "ax", ")", "else", ":", "self", ".", "_add_plot_failure", "(", "ax", ")", "ax", ".", "legend", "(", "*", "*", "settings", ".", "LEGEND_OPTS", ")", "return", "fig" ]
After model execution, print the dataset, curve-fit, BMD, and BMDL. Example ------- >>> import os >>> fn = os.path.expanduser('~/Desktop/image.png') >>> fig = model.plot() >>> fig.savefig(fn) >>> fig.clear() .. figure:: ../tests/resources/test_exponential_m4_plot.png :scale: 80% :align: center :alt: Example generated BMD plot BMD models can generate plots using the ``plot()`` method; an example is shown here.
[ "After", "model", "execution", "print", "the", "dataset", "curve", "-", "fit", "BMD", "and", "BMDL", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L215-L251
train
shapiromatron/bmds
bmds/models/base.py
BMDModel.write_dfile
def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
python
def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
[ "def", "write_dfile", "(", "self", ")", ":", "f_in", "=", "self", ".", "tempfiles", ".", "get_tempfile", "(", "prefix", "=", "\"bmds-\"", ",", "suffix", "=", "\".(d)\"", ")", "with", "open", "(", "f_in", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "self", ".", "as_dfile", "(", ")", ")", "return", "f_in" ]
Write the generated d_file to a temporary file.
[ "Write", "the", "generated", "d_file", "to", "a", "temporary", "file", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L316-L323
train
shapiromatron/bmds
bmds/models/base.py
BMDModel.to_dict
def to_dict(self, model_index): """ Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary A dictionary of model inputs, and raw and parsed outputs """ return dict( name=self.name, model_index=model_index, model_name=self.model_name, model_version=self.version, has_output=self.output_created, dfile=self.as_dfile(), execution_halted=self.execution_halted, stdout=self.stdout, stderr=self.stderr, outfile=getattr(self, "outfile", None), output=getattr(self, "output", None), logic_bin=getattr(self, "logic_bin", None), logic_notes=getattr(self, "logic_notes", None), recommended=getattr(self, "recommended", None), recommended_variable=getattr(self, "recommended_variable", None), )
python
def to_dict(self, model_index): """ Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary A dictionary of model inputs, and raw and parsed outputs """ return dict( name=self.name, model_index=model_index, model_name=self.model_name, model_version=self.version, has_output=self.output_created, dfile=self.as_dfile(), execution_halted=self.execution_halted, stdout=self.stdout, stderr=self.stderr, outfile=getattr(self, "outfile", None), output=getattr(self, "output", None), logic_bin=getattr(self, "logic_bin", None), logic_notes=getattr(self, "logic_notes", None), recommended=getattr(self, "recommended", None), recommended_variable=getattr(self, "recommended_variable", None), )
[ "def", "to_dict", "(", "self", ",", "model_index", ")", ":", "return", "dict", "(", "name", "=", "self", ".", "name", ",", "model_index", "=", "model_index", ",", "model_name", "=", "self", ".", "model_name", ",", "model_version", "=", "self", ".", "version", ",", "has_output", "=", "self", ".", "output_created", ",", "dfile", "=", "self", ".", "as_dfile", "(", ")", ",", "execution_halted", "=", "self", ".", "execution_halted", ",", "stdout", "=", "self", ".", "stdout", ",", "stderr", "=", "self", ".", "stderr", ",", "outfile", "=", "getattr", "(", "self", ",", "\"outfile\"", ",", "None", ")", ",", "output", "=", "getattr", "(", "self", ",", "\"output\"", ",", "None", ")", ",", "logic_bin", "=", "getattr", "(", "self", ",", "\"logic_bin\"", ",", "None", ")", ",", "logic_notes", "=", "getattr", "(", "self", ",", "\"logic_notes\"", ",", "None", ")", ",", "recommended", "=", "getattr", "(", "self", ",", "\"recommended\"", ",", "None", ")", ",", "recommended_variable", "=", "getattr", "(", "self", ",", "\"recommended_variable\"", ",", "None", ")", ",", ")" ]
Return a summary of the model in a dictionary format for serialization. Parameters ---------- model_index : int The index of the model in a list of models, should be unique Returns ------- out : dictionary A dictionary of model inputs, and raw and parsed outputs
[ "Return", "a", "summary", "of", "the", "model", "in", "a", "dictionary", "format", "for", "serialization", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/models/base.py#L395-L425
train
jlesquembre/autopilot
src/autopilot/utils.py
merge_config
def merge_config(d1, d2): '''Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered. ''' result = deepcopy(d1) elements = deque() elements.append((result, d2)) while elements: old, new = elements.popleft() new = OrderedDict([(k.lower(), (k, v)) for k, v in new.items()]) visited_keys = [] for k, old_value in old.items(): klow = k.lower() if klow in new: new_key, new_value = new[klow] visited_keys.append(new_key) if all(isinstance(e, MutableMapping) for e in (old_value, new_value)): elements.append((old_value, new_value)) else: old[k] = deepcopy(new_value) for k, v in new.values(): if k not in visited_keys: old[k] = deepcopy(v) return result
python
def merge_config(d1, d2): '''Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered. ''' result = deepcopy(d1) elements = deque() elements.append((result, d2)) while elements: old, new = elements.popleft() new = OrderedDict([(k.lower(), (k, v)) for k, v in new.items()]) visited_keys = [] for k, old_value in old.items(): klow = k.lower() if klow in new: new_key, new_value = new[klow] visited_keys.append(new_key) if all(isinstance(e, MutableMapping) for e in (old_value, new_value)): elements.append((old_value, new_value)) else: old[k] = deepcopy(new_value) for k, v in new.values(): if k not in visited_keys: old[k] = deepcopy(v) return result
[ "def", "merge_config", "(", "d1", ",", "d2", ")", ":", "result", "=", "deepcopy", "(", "d1", ")", "elements", "=", "deque", "(", ")", "elements", ".", "append", "(", "(", "result", ",", "d2", ")", ")", "while", "elements", ":", "old", ",", "new", "=", "elements", ".", "popleft", "(", ")", "new", "=", "OrderedDict", "(", "[", "(", "k", ".", "lower", "(", ")", ",", "(", "k", ",", "v", ")", ")", "for", "k", ",", "v", "in", "new", ".", "items", "(", ")", "]", ")", "visited_keys", "=", "[", "]", "for", "k", ",", "old_value", "in", "old", ".", "items", "(", ")", ":", "klow", "=", "k", ".", "lower", "(", ")", "if", "klow", "in", "new", ":", "new_key", ",", "new_value", "=", "new", "[", "klow", "]", "visited_keys", ".", "append", "(", "new_key", ")", "if", "all", "(", "isinstance", "(", "e", ",", "MutableMapping", ")", "for", "e", "in", "(", "old_value", ",", "new_value", ")", ")", ":", "elements", ".", "append", "(", "(", "old_value", ",", "new_value", ")", ")", "else", ":", "old", "[", "k", "]", "=", "deepcopy", "(", "new_value", ")", "for", "k", ",", "v", "in", "new", ".", "values", "(", ")", ":", "if", "k", "not", "in", "visited_keys", ":", "old", "[", "k", "]", "=", "deepcopy", "(", "v", ")", "return", "result" ]
Merges to config dicts. Key values are case insensitive for merging, but the value of d1 is remembered.
[ "Merges", "to", "config", "dicts", ".", "Key", "values", "are", "case", "insensitive", "for", "merging", "but", "the", "value", "of", "d1", "is", "remembered", "." ]
ca5f36269ba0173bd29c39db6971dac57a58513d
https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/utils.py#L74-L102
train
jlesquembre/autopilot
src/autopilot/utils.py
set_if_none
def set_if_none(user_config, config, key, value): ''' If the value of the key in is None, and doesn't exist on the user config, set it to a different value ''' keys = key.split('.') for k in keys[:-1]: try: user_config = user_config[k] except KeyError: user_config = {} config = config[k] key = keys[-1] if key not in user_config and not config[key]: config[key] = value
python
def set_if_none(user_config, config, key, value): ''' If the value of the key in is None, and doesn't exist on the user config, set it to a different value ''' keys = key.split('.') for k in keys[:-1]: try: user_config = user_config[k] except KeyError: user_config = {} config = config[k] key = keys[-1] if key not in user_config and not config[key]: config[key] = value
[ "def", "set_if_none", "(", "user_config", ",", "config", ",", "key", ",", "value", ")", ":", "keys", "=", "key", ".", "split", "(", "'.'", ")", "for", "k", "in", "keys", "[", ":", "-", "1", "]", ":", "try", ":", "user_config", "=", "user_config", "[", "k", "]", "except", "KeyError", ":", "user_config", "=", "{", "}", "config", "=", "config", "[", "k", "]", "key", "=", "keys", "[", "-", "1", "]", "if", "key", "not", "in", "user_config", "and", "not", "config", "[", "key", "]", ":", "config", "[", "key", "]", "=", "value" ]
If the value of the key in is None, and doesn't exist on the user config, set it to a different value
[ "If", "the", "value", "of", "the", "key", "in", "is", "None", "and", "doesn", "t", "exist", "on", "the", "user", "config", "set", "it", "to", "a", "different", "value" ]
ca5f36269ba0173bd29c39db6971dac57a58513d
https://github.com/jlesquembre/autopilot/blob/ca5f36269ba0173bd29c39db6971dac57a58513d/src/autopilot/utils.py#L116-L134
train
tjcsl/cslbot
cslbot/helpers/acl.py
set_admin
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['feature']['servicestype'] == "atheme": match = re.match("(.*) ACC ([0-3])", msg) if match: status = int(match.group(2)) nick = match.group(1) if status != 3: return with handler.db.session_scope() as session: admin = session.query(Permissions).filter(Permissions.nick == nick).first() if admin is None: session.add(Permissions(nick=nick, role='admin', registered=True, time=datetime.now())) else: admin.registered = True admin.time = datetime.now()
python
def set_admin(msg, handler): """Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified. """ if handler.config['feature']['servicestype'] == "ircservices": match = re.match("STATUS (.*) ([0-3])", msg) elif handler.config['feature']['servicestype'] == "atheme": match = re.match("(.*) ACC ([0-3])", msg) if match: status = int(match.group(2)) nick = match.group(1) if status != 3: return with handler.db.session_scope() as session: admin = session.query(Permissions).filter(Permissions.nick == nick).first() if admin is None: session.add(Permissions(nick=nick, role='admin', registered=True, time=datetime.now())) else: admin.registered = True admin.time = datetime.now()
[ "def", "set_admin", "(", "msg", ",", "handler", ")", ":", "if", "handler", ".", "config", "[", "'feature'", "]", "[", "'servicestype'", "]", "==", "\"ircservices\"", ":", "match", "=", "re", ".", "match", "(", "\"STATUS (.*) ([0-3])\"", ",", "msg", ")", "elif", "handler", ".", "config", "[", "'feature'", "]", "[", "'servicestype'", "]", "==", "\"atheme\"", ":", "match", "=", "re", ".", "match", "(", "\"(.*) ACC ([0-3])\"", ",", "msg", ")", "if", "match", ":", "status", "=", "int", "(", "match", ".", "group", "(", "2", ")", ")", "nick", "=", "match", ".", "group", "(", "1", ")", "if", "status", "!=", "3", ":", "return", "with", "handler", ".", "db", ".", "session_scope", "(", ")", "as", "session", ":", "admin", "=", "session", ".", "query", "(", "Permissions", ")", ".", "filter", "(", "Permissions", ".", "nick", "==", "nick", ")", ".", "first", "(", ")", "if", "admin", "is", "None", ":", "session", ".", "add", "(", "Permissions", "(", "nick", "=", "nick", ",", "role", "=", "'admin'", ",", "registered", "=", "True", ",", "time", "=", "datetime", ".", "now", "(", ")", ")", ")", "else", ":", "admin", ".", "registered", "=", "True", "admin", ".", "time", "=", "datetime", ".", "now", "(", ")" ]
Handle admin verification responses from NickServ. | If NickServ tells us that the nick is authed, mark it as verified.
[ "Handle", "admin", "verification", "responses", "from", "NickServ", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/acl.py#L24-L45
train
Xion/taipan
taipan/collections/tuples.py
is_tuple
def is_tuple(obj, len_=None): """Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise """ if not isinstance(obj, tuple): return False if len_ is None: return True if not isinstance(len_, Integral): raise TypeError( "length must be a number (got %s instead)" % type(len_).__name__) if len_ < 0: raise ValueError("length must be positive (got %s instead)" % len_) return len(obj) == len_
python
def is_tuple(obj, len_=None): """Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise """ if not isinstance(obj, tuple): return False if len_ is None: return True if not isinstance(len_, Integral): raise TypeError( "length must be a number (got %s instead)" % type(len_).__name__) if len_ < 0: raise ValueError("length must be positive (got %s instead)" % len_) return len(obj) == len_
[ "def", "is_tuple", "(", "obj", ",", "len_", "=", "None", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "tuple", ")", ":", "return", "False", "if", "len_", "is", "None", ":", "return", "True", "if", "not", "isinstance", "(", "len_", ",", "Integral", ")", ":", "raise", "TypeError", "(", "\"length must be a number (got %s instead)\"", "%", "type", "(", "len_", ")", ".", "__name__", ")", "if", "len_", "<", "0", ":", "raise", "ValueError", "(", "\"length must be positive (got %s instead)\"", "%", "len_", ")", "return", "len", "(", "obj", ")", "==", "len_" ]
Checks whether given object is a tuple. :param len_: Optional expected length of the tuple :return: ``True`` if argument is a tuple (of given length, if any), ``False`` otherwise
[ "Checks", "whether", "given", "object", "is", "a", "tuple", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L30-L49
train
Xion/taipan
taipan/collections/tuples.py
select
def select(indices, from_, strict=False): """Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding to the order of ``indices``. :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. """ ensure_iterable(indices) ensure_sequence(from_) if strict: return from_.__class__(from_[index] for index in indices) else: len_ = len(from_) return from_.__class__(from_[index] for index in indices if 0 <= index < len_)
python
def select(indices, from_, strict=False): """Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding to the order of ``indices``. :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. """ ensure_iterable(indices) ensure_sequence(from_) if strict: return from_.__class__(from_[index] for index in indices) else: len_ = len(from_) return from_.__class__(from_[index] for index in indices if 0 <= index < len_)
[ "def", "select", "(", "indices", ",", "from_", ",", "strict", "=", "False", ")", ":", "ensure_iterable", "(", "indices", ")", "ensure_sequence", "(", "from_", ")", "if", "strict", ":", "return", "from_", ".", "__class__", "(", "from_", "[", "index", "]", "for", "index", "in", "indices", ")", "else", ":", "len_", "=", "len", "(", "from_", ")", "return", "from_", ".", "__class__", "(", "from_", "[", "index", "]", "for", "index", "in", "indices", "if", "0", "<=", "index", "<", "len_", ")" ]
Selects a subsequence of given tuple, including only specified indices. :param indices: Iterable of indices to include :param strict: Whether ``indices`` are required to exist in the tuple. :return: Tuple with selected elements, in the order corresponding to the order of ``indices``. :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range.
[ "Selects", "a", "subsequence", "of", "given", "tuple", "including", "only", "specified", "indices", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L189-L209
train
Xion/taipan
taipan/collections/tuples.py
omit
def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. .. versionadded:: 0.0.3 """ from taipan.collections.sets import remove_subset ensure_iterable(indices) ensure_sequence(from_) if strict: remaining_indices = set(xrange(len(from_))) try: remove_subset(remaining_indices, indices) except KeyError as e: raise IndexError(int(str(e))) else: remaining_indices = set(xrange(len(from_))) - set(indices) return from_.__class__(from_[index] for index in remaining_indices)
python
def omit(indices, from_, strict=False): """Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. .. versionadded:: 0.0.3 """ from taipan.collections.sets import remove_subset ensure_iterable(indices) ensure_sequence(from_) if strict: remaining_indices = set(xrange(len(from_))) try: remove_subset(remaining_indices, indices) except KeyError as e: raise IndexError(int(str(e))) else: remaining_indices = set(xrange(len(from_))) - set(indices) return from_.__class__(from_[index] for index in remaining_indices)
[ "def", "omit", "(", "indices", ",", "from_", ",", "strict", "=", "False", ")", ":", "from", "taipan", ".", "collections", ".", "sets", "import", "remove_subset", "ensure_iterable", "(", "indices", ")", "ensure_sequence", "(", "from_", ")", "if", "strict", ":", "remaining_indices", "=", "set", "(", "xrange", "(", "len", "(", "from_", ")", ")", ")", "try", ":", "remove_subset", "(", "remaining_indices", ",", "indices", ")", "except", "KeyError", "as", "e", ":", "raise", "IndexError", "(", "int", "(", "str", "(", "e", ")", ")", ")", "else", ":", "remaining_indices", "=", "set", "(", "xrange", "(", "len", "(", "from_", ")", ")", ")", "-", "set", "(", "indices", ")", "return", "from_", ".", "__class__", "(", "from_", "[", "index", "]", "for", "index", "in", "remaining_indices", ")" ]
Returns a subsequence from given tuple, omitting specified indices. :param indices: Iterable of indices to exclude :param strict: Whether ``indices`` are required to exist in the tuple :return: Tuple without elements of specified indices :raise IndexError: If ``strict`` is True and one of ``indices`` is out of range. .. versionadded:: 0.0.3
[ "Returns", "a", "subsequence", "from", "given", "tuple", "omitting", "specified", "indices", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L217-L244
train
Xion/taipan
taipan/collections/tuples.py
_describe_type
def _describe_type(arg): """Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got tuple of length 2 """ if isinstance(arg, tuple): return "tuple of length %s" % len(arg) else: return type(arg).__name__
python
def _describe_type(arg): """Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got tuple of length 2 """ if isinstance(arg, tuple): return "tuple of length %s" % len(arg) else: return type(arg).__name__
[ "def", "_describe_type", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "tuple", ")", ":", "return", "\"tuple of length %s\"", "%", "len", "(", "arg", ")", "else", ":", "return", "type", "(", "arg", ")", ".", "__name__" ]
Describe given argument, including length if it's a tuple. The purpose is to prevent nonsensical exception messages such as:: expected a tuple of length 2, got tuple expected a tuple, got tuple by turning them into:: expected a tuple of length 3, got tuple of length 2
[ "Describe", "given", "argument", "including", "length", "if", "it", "s", "a", "tuple", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/collections/tuples.py#L249-L264
train
textbook/atmdb
atmdb/models.py
BaseModel._create_image_url
def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ if self.image_config is None: logger.warning('no image configuration available') return return ''.join([ self.image_config['secure_base_url'], self._image_size(self.image_config, type_, target_size), file_path, ])
python
def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ if self.image_config is None: logger.warning('no image configuration available') return return ''.join([ self.image_config['secure_base_url'], self._image_size(self.image_config, type_, target_size), file_path, ])
[ "def", "_create_image_url", "(", "self", ",", "file_path", ",", "type_", ",", "target_size", ")", ":", "if", "self", ".", "image_config", "is", "None", ":", "logger", ".", "warning", "(", "'no image configuration available'", ")", "return", "return", "''", ".", "join", "(", "[", "self", ".", "image_config", "[", "'secure_base_url'", "]", ",", "self", ".", "_image_size", "(", "self", ".", "image_config", ",", "type_", ",", "target_size", ")", ",", "file_path", ",", "]", ")" ]
The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height).
[ "The", "the", "closest", "available", "size", "for", "specified", "image", "type", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L65-L83
train
textbook/atmdb
atmdb/models.py
BaseModel.from_json
def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. """ cls.image_config = image_config return cls(**{ attr: json.get(attr if key is None else key) for attr, key in cls.JSON_MAPPING.items() })
python
def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. """ cls.image_config = image_config return cls(**{ attr: json.get(attr if key is None else key) for attr, key in cls.JSON_MAPPING.items() })
[ "def", "from_json", "(", "cls", ",", "json", ",", "image_config", "=", "None", ")", ":", "cls", ".", "image_config", "=", "image_config", "return", "cls", "(", "*", "*", "{", "attr", ":", "json", ".", "get", "(", "attr", "if", "key", "is", "None", "else", "key", ")", "for", "attr", ",", "key", "in", "cls", ".", "JSON_MAPPING", ".", "items", "(", ")", "}", ")" ]
Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance.
[ "Create", "a", "model", "instance" ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L86-L102
train
textbook/atmdb
atmdb/models.py
BaseModel._image_size
def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ return min( image_config['{}_sizes'.format(type_)], key=lambda size: (abs(target_size - int(size[1:])) if size.startswith('w') or size.startswith('h') else 999), )
python
def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ return min( image_config['{}_sizes'.format(type_)], key=lambda size: (abs(target_size - int(size[1:])) if size.startswith('w') or size.startswith('h') else 999), )
[ "def", "_image_size", "(", "image_config", ",", "type_", ",", "target_size", ")", ":", "return", "min", "(", "image_config", "[", "'{}_sizes'", ".", "format", "(", "type_", ")", "]", ",", "key", "=", "lambda", "size", ":", "(", "abs", "(", "target_size", "-", "int", "(", "size", "[", "1", ":", "]", ")", ")", "if", "size", ".", "startswith", "(", "'w'", ")", "or", "size", ".", "startswith", "(", "'h'", ")", "else", "999", ")", ",", ")" ]
Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height).
[ "Find", "the", "closest", "available", "size", "for", "specified", "image", "type", "." ]
cab14547d2e777a1e26c2560266365c484855789
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L105-L121
train
rchatterjee/pwmodels
src/pwmodel/helper.py
getallgroups
def getallgroups(arr, k=-1): """ returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr) """ if k < 0: k = len(arr) return itertools.chain.from_iterable(itertools.combinations(set(arr), j) for j in range(1, k + 1))
python
def getallgroups(arr, k=-1): """ returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr) """ if k < 0: k = len(arr) return itertools.chain.from_iterable(itertools.combinations(set(arr), j) for j in range(1, k + 1))
[ "def", "getallgroups", "(", "arr", ",", "k", "=", "-", "1", ")", ":", "if", "k", "<", "0", ":", "k", "=", "len", "(", "arr", ")", "return", "itertools", ".", "chain", ".", "from_iterable", "(", "itertools", ".", "combinations", "(", "set", "(", "arr", ")", ",", "j", ")", "for", "j", "in", "range", "(", "1", ",", "k", "+", "1", ")", ")" ]
returns all the subset of @arr of size less than equalto @k the return array will be of size \sum_{i=1}^k nCi, n = len(arr)
[ "returns", "all", "the", "subset", "of" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L273-L281
train
rchatterjee/pwmodels
src/pwmodel/helper.py
open_get_line
def open_get_line(filename, limit=-1, **kwargs): """Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer """ allowed_keys_for_get_line = {'sep', 'pw_filter', 'errors'} for k in list(kwargs.keys()): if k not in allowed_keys_for_get_line: del kwargs[k] print("After filtering: {}".format(kwargs)) with open_(filename, 'rt') as f: for w, c in get_line(f, limit, **kwargs): yield w, c
python
def open_get_line(filename, limit=-1, **kwargs): """Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer """ allowed_keys_for_get_line = {'sep', 'pw_filter', 'errors'} for k in list(kwargs.keys()): if k not in allowed_keys_for_get_line: del kwargs[k] print("After filtering: {}".format(kwargs)) with open_(filename, 'rt') as f: for w, c in get_line(f, limit, **kwargs): yield w, c
[ "def", "open_get_line", "(", "filename", ",", "limit", "=", "-", "1", ",", "*", "*", "kwargs", ")", ":", "allowed_keys_for_get_line", "=", "{", "'sep'", ",", "'pw_filter'", ",", "'errors'", "}", "for", "k", "in", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "if", "k", "not", "in", "allowed_keys_for_get_line", ":", "del", "kwargs", "[", "k", "]", "print", "(", "\"After filtering: {}\"", ".", "format", "(", "kwargs", ")", ")", "with", "open_", "(", "filename", ",", "'rt'", ")", "as", "f", ":", "for", "w", ",", "c", "in", "get_line", "(", "f", ",", "limit", ",", "*", "*", "kwargs", ")", ":", "yield", "w", ",", "c" ]
Opens the password file named @filename and reads first @limit passwords. @kwargs are passed to get_line for further processing. For example, pw_filter etc. @fielname: string @limit: integer
[ "Opens", "the", "password", "file", "named" ]
e277411f8ebaf4ad1c208d2b035b4b68f7471517
https://github.com/rchatterjee/pwmodels/blob/e277411f8ebaf4ad1c208d2b035b4b68f7471517/src/pwmodel/helper.py#L317-L331
train
tjcsl/cslbot
cslbot/helpers/workers.py
Workers.stop_workers
def stop_workers(self, clean): """Stop workers and deferred events.""" with executor_lock: self.executor.shutdown(clean) del self.executor with self.worker_lock: if clean: self.pool.close() else: self.pool.terminate() self.pool.join() del self.pool for x in self.events.values(): x.event.cancel() self.events.clear()
python
def stop_workers(self, clean): """Stop workers and deferred events.""" with executor_lock: self.executor.shutdown(clean) del self.executor with self.worker_lock: if clean: self.pool.close() else: self.pool.terminate() self.pool.join() del self.pool for x in self.events.values(): x.event.cancel() self.events.clear()
[ "def", "stop_workers", "(", "self", ",", "clean", ")", ":", "with", "executor_lock", ":", "self", ".", "executor", ".", "shutdown", "(", "clean", ")", "del", "self", ".", "executor", "with", "self", ".", "worker_lock", ":", "if", "clean", ":", "self", ".", "pool", ".", "close", "(", ")", "else", ":", "self", ".", "pool", ".", "terminate", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "del", "self", ".", "pool", "for", "x", "in", "self", ".", "events", ".", "values", "(", ")", ":", "x", ".", "event", ".", "cancel", "(", ")", "self", ".", "events", ".", "clear", "(", ")" ]
Stop workers and deferred events.
[ "Stop", "workers", "and", "deferred", "events", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/workers.py#L108-L122
train
adamziel/python_translate
python_translate/extractors/python.py
PythonExtractor.extract_translations
def extract_translations(self, string): """Extract messages from Python string.""" tree = ast.parse(string) # ast_visit(tree) visitor = TransVisitor( self.tranz_functions, self.tranzchoice_functions) visitor.visit(tree) return visitor.translations
python
def extract_translations(self, string): """Extract messages from Python string.""" tree = ast.parse(string) # ast_visit(tree) visitor = TransVisitor( self.tranz_functions, self.tranzchoice_functions) visitor.visit(tree) return visitor.translations
[ "def", "extract_translations", "(", "self", ",", "string", ")", ":", "tree", "=", "ast", ".", "parse", "(", "string", ")", "# ast_visit(tree)", "visitor", "=", "TransVisitor", "(", "self", ".", "tranz_functions", ",", "self", ".", "tranzchoice_functions", ")", "visitor", ".", "visit", "(", "tree", ")", "return", "visitor", ".", "translations" ]
Extract messages from Python string.
[ "Extract", "messages", "from", "Python", "string", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/extractors/python.py#L34-L44
train
tjcsl/cslbot
cslbot/commands/isup.py
cmd
def cmd(send, msg, args): """Checks if a website is up. Syntax: {command} <website> """ if not msg: send("What are you trying to get to?") return nick = args['nick'] isup = get("http://isup.me/%s" % msg).text if "looks down from here" in isup: send("%s: %s is down" % (nick, msg)) elif "like a site on the interwho" in isup: send("%s: %s is not a valid url" % (nick, msg)) else: send("%s: %s is up" % (nick, msg))
python
def cmd(send, msg, args): """Checks if a website is up. Syntax: {command} <website> """ if not msg: send("What are you trying to get to?") return nick = args['nick'] isup = get("http://isup.me/%s" % msg).text if "looks down from here" in isup: send("%s: %s is down" % (nick, msg)) elif "like a site on the interwho" in isup: send("%s: %s is not a valid url" % (nick, msg)) else: send("%s: %s is up" % (nick, msg))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "send", "(", "\"What are you trying to get to?\"", ")", "return", "nick", "=", "args", "[", "'nick'", "]", "isup", "=", "get", "(", "\"http://isup.me/%s\"", "%", "msg", ")", ".", "text", "if", "\"looks down from here\"", "in", "isup", ":", "send", "(", "\"%s: %s is down\"", "%", "(", "nick", ",", "msg", ")", ")", "elif", "\"like a site on the interwho\"", "in", "isup", ":", "send", "(", "\"%s: %s is not a valid url\"", "%", "(", "nick", ",", "msg", ")", ")", "else", ":", "send", "(", "\"%s: %s is up\"", "%", "(", "nick", ",", "msg", ")", ")" ]
Checks if a website is up. Syntax: {command} <website>
[ "Checks", "if", "a", "website", "is", "up", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/isup.py#L24-L40
train
tylerbutler/engineer
engineer/conf.py
EngineerConfiguration.create_required_directories
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder in required: ensure_exists(folder, assume_dirs=True)
python
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder in required: ensure_exists(folder, assume_dirs=True)
[ "def", "create_required_directories", "(", "self", ")", ":", "required", "=", "(", "self", ".", "CACHE_DIR", ",", "self", ".", "LOG_DIR", ",", "self", ".", "OUTPUT_DIR", ",", "self", ".", "ENGINEER", ".", "JINJA_CACHE_DIR", ",", ")", "for", "folder", "in", "required", ":", "ensure_exists", "(", "folder", ",", "assume_dirs", "=", "True", ")" ]
Creates any directories required for Engineer to function if they don't already exist.
[ "Creates", "any", "directories", "required", "for", "Engineer", "to", "function", "if", "they", "don", "t", "already", "exist", "." ]
8884f587297f37646c40e5553174852b444a4024
https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/conf.py#L432-L440
train
tjcsl/cslbot
cslbot/commands/wiki.py
cmd
def cmd(send, msg, args): """Returns the first wikipedia result for the argument. Syntax: {command} [term] """ if 'livedoc' in args['name']: url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else: url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not msg: msg = get_rand(url) params = {'format': 'json', 'action': 'query', 'list': 'search', 'srlimit': '1', 'srsearch': msg} data = get('%s/api.php' % url, params=params).json() try: article = data['query']['search'][0]['title'] except IndexError: send("%s isn't important enough to have a %s article." % (msg, name)) return article = article.replace(' ', '_') # wikipedia uses /w for api and /wiki for articles url += 'iki' send('%s/%s' % (url, article))
python
def cmd(send, msg, args): """Returns the first wikipedia result for the argument. Syntax: {command} [term] """ if 'livedoc' in args['name']: url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else: url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not msg: msg = get_rand(url) params = {'format': 'json', 'action': 'query', 'list': 'search', 'srlimit': '1', 'srsearch': msg} data = get('%s/api.php' % url, params=params).json() try: article = data['query']['search'][0]['title'] except IndexError: send("%s isn't important enough to have a %s article." % (msg, name)) return article = article.replace(' ', '_') # wikipedia uses /w for api and /wiki for articles url += 'iki' send('%s/%s' % (url, article))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "'livedoc'", "in", "args", "[", "'name'", "]", ":", "url", "=", "'http://livedoc.tjhsst.edu/w'", "name", "=", "'livedoc'", "else", ":", "url", "=", "'http://en.wikipedia.org/w'", "name", "=", "'wikipedia'", "if", "not", "msg", ":", "msg", "=", "get_rand", "(", "url", ")", "params", "=", "{", "'format'", ":", "'json'", ",", "'action'", ":", "'query'", ",", "'list'", ":", "'search'", ",", "'srlimit'", ":", "'1'", ",", "'srsearch'", ":", "msg", "}", "data", "=", "get", "(", "'%s/api.php'", "%", "url", ",", "params", "=", "params", ")", ".", "json", "(", ")", "try", ":", "article", "=", "data", "[", "'query'", "]", "[", "'search'", "]", "[", "0", "]", "[", "'title'", "]", "except", "IndexError", ":", "send", "(", "\"%s isn't important enough to have a %s article.\"", "%", "(", "msg", ",", "name", ")", ")", "return", "article", "=", "article", ".", "replace", "(", "' '", ",", "'_'", ")", "# wikipedia uses /w for api and /wiki for articles", "url", "+=", "'iki'", "send", "(", "'%s/%s'", "%", "(", "url", ",", "article", ")", ")" ]
Returns the first wikipedia result for the argument. Syntax: {command} [term]
[ "Returns", "the", "first", "wikipedia", "result", "for", "the", "argument", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wiki.py#L30-L54
train
jmbeach/KEP.py
src/keppy/channel.py
Channel.parse_devices
def parse_devices(self): """Creates an array of Device objects from the channel""" devices = [] for device in self._channel_dict["devices"]: devices.append(Device(device, self._is_sixteen_bit, self._ignore_list)) return devices
python
def parse_devices(self): """Creates an array of Device objects from the channel""" devices = [] for device in self._channel_dict["devices"]: devices.append(Device(device, self._is_sixteen_bit, self._ignore_list)) return devices
[ "def", "parse_devices", "(", "self", ")", ":", "devices", "=", "[", "]", "for", "device", "in", "self", ".", "_channel_dict", "[", "\"devices\"", "]", ":", "devices", ".", "append", "(", "Device", "(", "device", ",", "self", ".", "_is_sixteen_bit", ",", "self", ".", "_ignore_list", ")", ")", "return", "devices" ]
Creates an array of Device objects from the channel
[ "Creates", "an", "array", "of", "Device", "objects", "from", "the", "channel" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/channel.py#L19-L24
train
jmbeach/KEP.py
src/keppy/channel.py
Channel.update
def update(self): """Updates the dictionary of the channel""" for device in self.devices: device.update() for i in range(len(self._channel_dict["devices"])): device_dict = self._channel_dict["devices"][i] for device in self._devices: if device.name == device_dict["common.ALLTYPES_NAME"]: self._channel_dict["devices"][i] = device.as_dict()
python
def update(self): """Updates the dictionary of the channel""" for device in self.devices: device.update() for i in range(len(self._channel_dict["devices"])): device_dict = self._channel_dict["devices"][i] for device in self._devices: if device.name == device_dict["common.ALLTYPES_NAME"]: self._channel_dict["devices"][i] = device.as_dict()
[ "def", "update", "(", "self", ")", ":", "for", "device", "in", "self", ".", "devices", ":", "device", ".", "update", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_channel_dict", "[", "\"devices\"", "]", ")", ")", ":", "device_dict", "=", "self", ".", "_channel_dict", "[", "\"devices\"", "]", "[", "i", "]", "for", "device", "in", "self", ".", "_devices", ":", "if", "device", ".", "name", "==", "device_dict", "[", "\"common.ALLTYPES_NAME\"", "]", ":", "self", ".", "_channel_dict", "[", "\"devices\"", "]", "[", "i", "]", "=", "device", ".", "as_dict", "(", ")" ]
Updates the dictionary of the channel
[ "Updates", "the", "dictionary", "of", "the", "channel" ]
68cda64ab649640a486534867c81274c41e39446
https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/channel.py#L44-L52
train
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.open_config
def open_config(self,type="shared"): """ Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**. Examples: .. code-block:: python #Open shared config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close() #Open private config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config("private") dev.close_config() dev.close() """ try: #attempt to open a configuration output = self.dev.rpc("<open-configuration><{0}/></open-configuration>".format(type)) except Exception as err: #output an error if the configuration is not availble print err
python
def open_config(self,type="shared"): """ Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**. Examples: .. code-block:: python #Open shared config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close() #Open private config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config("private") dev.close_config() dev.close() """ try: #attempt to open a configuration output = self.dev.rpc("<open-configuration><{0}/></open-configuration>".format(type)) except Exception as err: #output an error if the configuration is not availble print err
[ "def", "open_config", "(", "self", ",", "type", "=", "\"shared\"", ")", ":", "try", ":", "#attempt to open a configuration", "output", "=", "self", ".", "dev", ".", "rpc", "(", "\"<open-configuration><{0}/></open-configuration>\"", ".", "format", "(", "type", ")", ")", "except", "Exception", "as", "err", ":", "#output an error if the configuration is not availble", "print", "err" ]
Opens the configuration of the currently connected device Args: :type: The type of configuration you want to open. Any string can be provided, however the standard supported options are: **exclusive**, **private**, and **shared**. The default mode is **shared**. Examples: .. code-block:: python #Open shared config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close() #Open private config from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config("private") dev.close_config() dev.close()
[ "Opens", "the", "configuration", "of", "the", "currently", "connected", "device" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L95-L131
train
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.close_config
def close_config(self): """ Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close() """ try: self.dev.rpc.close_configuration() except Exception as err: print err
python
def close_config(self): """ Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close() """ try: self.dev.rpc.close_configuration() except Exception as err: print err
[ "def", "close_config", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "close_configuration", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Closes the exiting opened configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.close_config() dev.close()
[ "Closes", "the", "exiting", "opened", "configuration" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L133-L153
train
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.commit_config
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close_config() dev.close() """ try: self.dev.rpc.commit_configuration() except Exception as err: print err
python
def commit_config(self): """ Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close_config() dev.close() """ try: self.dev.rpc.commit_configuration() except Exception as err: print err
[ "def", "commit_config", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "commit_configuration", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Commits exiting configuration Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.open_config() dev.commit_config() dev.close_config() dev.close()
[ "Commits", "exiting", "configuration" ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L189-L209
train
JNPRAutomate/pyJunosManager
pyJunosManager/pyJunosManager.py
JunosDevice.commit_and_quit
def commit_and_quit(self): """ Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.load_config_template("system{ host-name {{ hostname }};}",hostname="foo") dev commit_and_quit() dev.close() """ try: self.dev.rpc.commit_configuration() self.close_config() except Exception as err: print err
python
def commit_and_quit(self): """ Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.load_config_template("system{ host-name {{ hostname }};}",hostname="foo") dev commit_and_quit() dev.close() """ try: self.dev.rpc.commit_configuration() self.close_config() except Exception as err: print err
[ "def", "commit_and_quit", "(", "self", ")", ":", "try", ":", "self", ".", "dev", ".", "rpc", ".", "commit_configuration", "(", ")", "self", ".", "close_config", "(", ")", "except", "Exception", "as", "err", ":", "print", "err" ]
Commits and closes the currently open configration. Saves a step by not needing to manually close the config. Example: .. code-block:: python from pyJunosManager import JunosDevice dev = JunosDevice(host="1.2.3.4",username="root",password="Juniper") dev.open() dev.load_config_template("system{ host-name {{ hostname }};}",hostname="foo") dev commit_and_quit() dev.close()
[ "Commits", "and", "closes", "the", "currently", "open", "configration", ".", "Saves", "a", "step", "by", "not", "needing", "to", "manually", "close", "the", "config", "." ]
cfbe87bb55488f44bad0b383771a88be7b2ccf2a
https://github.com/JNPRAutomate/pyJunosManager/blob/cfbe87bb55488f44bad0b383771a88be7b2ccf2a/pyJunosManager/pyJunosManager.py#L211-L232
train
Genida/archan
src/archan/config.py
Config.load_local_plugin
def load_local_plugin(name): """Import a local plugin accessible through Python path.""" try: module_name = '.'.join(name.split('.')[:-1]) module_obj = importlib.import_module(name=module_name) obj = getattr(module_obj, name.split('.')[-1]) return obj except (ImportError, AttributeError, ValueError) as e: raise PluginNotFoundError(e)
python
def load_local_plugin(name): """Import a local plugin accessible through Python path.""" try: module_name = '.'.join(name.split('.')[:-1]) module_obj = importlib.import_module(name=module_name) obj = getattr(module_obj, name.split('.')[-1]) return obj except (ImportError, AttributeError, ValueError) as e: raise PluginNotFoundError(e)
[ "def", "load_local_plugin", "(", "name", ")", ":", "try", ":", "module_name", "=", "'.'", ".", "join", "(", "name", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "module_obj", "=", "importlib", ".", "import_module", "(", "name", "=", "module_name", ")", "obj", "=", "getattr", "(", "module_obj", ",", "name", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "return", "obj", "except", "(", "ImportError", ",", "AttributeError", ",", "ValueError", ")", "as", "e", ":", "raise", "PluginNotFoundError", "(", "e", ")" ]
Import a local plugin accessible through Python path.
[ "Import", "a", "local", "plugin", "accessible", "through", "Python", "path", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L68-L76
train
Genida/archan
src/archan/config.py
Config.load_installed_plugins
def load_installed_plugins(): """Search and load every installed plugin through entry points.""" providers = {} checkers = {} for entry_point in pkg_resources.iter_entry_points(group='archan'): obj = entry_point.load() if issubclass(obj, Provider): providers[entry_point.name] = obj elif issubclass(obj, Checker): checkers[entry_point.name] = obj return collections.namedtuple( 'Plugins', 'providers checkers')( providers=providers, checkers=checkers)
python
def load_installed_plugins(): """Search and load every installed plugin through entry points.""" providers = {} checkers = {} for entry_point in pkg_resources.iter_entry_points(group='archan'): obj = entry_point.load() if issubclass(obj, Provider): providers[entry_point.name] = obj elif issubclass(obj, Checker): checkers[entry_point.name] = obj return collections.namedtuple( 'Plugins', 'providers checkers')( providers=providers, checkers=checkers)
[ "def", "load_installed_plugins", "(", ")", ":", "providers", "=", "{", "}", "checkers", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'archan'", ")", ":", "obj", "=", "entry_point", ".", "load", "(", ")", "if", "issubclass", "(", "obj", ",", "Provider", ")", ":", "providers", "[", "entry_point", ".", "name", "]", "=", "obj", "elif", "issubclass", "(", "obj", ",", "Checker", ")", ":", "checkers", "[", "entry_point", ".", "name", "]", "=", "obj", "return", "collections", ".", "namedtuple", "(", "'Plugins'", ",", "'providers checkers'", ")", "(", "providers", "=", "providers", ",", "checkers", "=", "checkers", ")" ]
Search and load every installed plugin through entry points.
[ "Search", "and", "load", "every", "installed", "plugin", "through", "entry", "points", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L79-L92
train
Genida/archan
src/archan/config.py
Config.from_file
def from_file(path): """Return a ``Config`` instance by reading a configuration file.""" with open(path) as stream: obj = yaml.safe_load(stream) Config.lint(obj) return Config(config_dict=obj)
python
def from_file(path): """Return a ``Config`` instance by reading a configuration file.""" with open(path) as stream: obj = yaml.safe_load(stream) Config.lint(obj) return Config(config_dict=obj)
[ "def", "from_file", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "stream", ":", "obj", "=", "yaml", ".", "safe_load", "(", "stream", ")", "Config", ".", "lint", "(", "obj", ")", "return", "Config", "(", "config_dict", "=", "obj", ")" ]
Return a ``Config`` instance by reading a configuration file.
[ "Return", "a", "Config", "instance", "by", "reading", "a", "configuration", "file", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L103-L108
train
Genida/archan
src/archan/config.py
Config.find
def find(): """Find the configuration file if any.""" names = ('archan.yml', 'archan.yaml', '.archan.yml', '.archan.yaml') current_dir = os.getcwd() configconfig_file = os.path.join(current_dir, '.configconfig') default_config_dir = os.path.join(current_dir, 'config') if os.path.isfile(configconfig_file): logger.debug('Reading %s to get config folder path', configconfig_file) with open(configconfig_file) as stream: config_dir = os.path.join(current_dir, stream.read()).strip() elif os.path.isdir(default_config_dir): config_dir = default_config_dir else: config_dir = current_dir logger.debug('Config folder = %s', config_dir) for name in names: config_file = os.path.join(config_dir, name) logger.debug('Searching for config file at %s', config_file) if os.path.isfile(config_file): logger.debug('Found %s', config_file) return config_file logger.debug('No config file found') return None
python
def find(): """Find the configuration file if any.""" names = ('archan.yml', 'archan.yaml', '.archan.yml', '.archan.yaml') current_dir = os.getcwd() configconfig_file = os.path.join(current_dir, '.configconfig') default_config_dir = os.path.join(current_dir, 'config') if os.path.isfile(configconfig_file): logger.debug('Reading %s to get config folder path', configconfig_file) with open(configconfig_file) as stream: config_dir = os.path.join(current_dir, stream.read()).strip() elif os.path.isdir(default_config_dir): config_dir = default_config_dir else: config_dir = current_dir logger.debug('Config folder = %s', config_dir) for name in names: config_file = os.path.join(config_dir, name) logger.debug('Searching for config file at %s', config_file) if os.path.isfile(config_file): logger.debug('Found %s', config_file) return config_file logger.debug('No config file found') return None
[ "def", "find", "(", ")", ":", "names", "=", "(", "'archan.yml'", ",", "'archan.yaml'", ",", "'.archan.yml'", ",", "'.archan.yaml'", ")", "current_dir", "=", "os", ".", "getcwd", "(", ")", "configconfig_file", "=", "os", ".", "path", ".", "join", "(", "current_dir", ",", "'.configconfig'", ")", "default_config_dir", "=", "os", ".", "path", ".", "join", "(", "current_dir", ",", "'config'", ")", "if", "os", ".", "path", ".", "isfile", "(", "configconfig_file", ")", ":", "logger", ".", "debug", "(", "'Reading %s to get config folder path'", ",", "configconfig_file", ")", "with", "open", "(", "configconfig_file", ")", "as", "stream", ":", "config_dir", "=", "os", ".", "path", ".", "join", "(", "current_dir", ",", "stream", ".", "read", "(", ")", ")", ".", "strip", "(", ")", "elif", "os", ".", "path", ".", "isdir", "(", "default_config_dir", ")", ":", "config_dir", "=", "default_config_dir", "else", ":", "config_dir", "=", "current_dir", "logger", ".", "debug", "(", "'Config folder = %s'", ",", "config_dir", ")", "for", "name", "in", "names", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "config_dir", ",", "name", ")", "logger", ".", "debug", "(", "'Searching for config file at %s'", ",", "config_file", ")", "if", "os", ".", "path", ".", "isfile", "(", "config_file", ")", ":", "logger", ".", "debug", "(", "'Found %s'", ",", "config_file", ")", "return", "config_file", "logger", ".", "debug", "(", "'No config file found'", ")", "return", "None" ]
Find the configuration file if any.
[ "Find", "the", "configuration", "file", "if", "any", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L111-L134
train
Genida/archan
src/archan/config.py
Config.inflate_nd_checker
def inflate_nd_checker(identifier, definition): """ Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "passes" and "allow_failure". Returns: Checker: a checker instance. Raises: ValueError: when the definition type is not bool or dict. """ if isinstance(definition, bool): return Checker(name=identifier, passes=definition) elif isinstance(definition, dict): return Checker(definition.pop('name', identifier), **definition) else: raise ValueError('%s type is not supported for no-data checkers, ' 'use bool or dict' % type(definition))
python
def inflate_nd_checker(identifier, definition): """ Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "passes" and "allow_failure". Returns: Checker: a checker instance. Raises: ValueError: when the definition type is not bool or dict. """ if isinstance(definition, bool): return Checker(name=identifier, passes=definition) elif isinstance(definition, dict): return Checker(definition.pop('name', identifier), **definition) else: raise ValueError('%s type is not supported for no-data checkers, ' 'use bool or dict' % type(definition))
[ "def", "inflate_nd_checker", "(", "identifier", ",", "definition", ")", ":", "if", "isinstance", "(", "definition", ",", "bool", ")", ":", "return", "Checker", "(", "name", "=", "identifier", ",", "passes", "=", "definition", ")", "elif", "isinstance", "(", "definition", ",", "dict", ")", ":", "return", "Checker", "(", "definition", ".", "pop", "(", "'name'", ",", "identifier", ")", ",", "*", "*", "definition", ")", "else", ":", "raise", "ValueError", "(", "'%s type is not supported for no-data checkers, '", "'use bool or dict'", "%", "type", "(", "definition", ")", ")" ]
Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "passes" and "allow_failure". Returns: Checker: a checker instance. Raises: ValueError: when the definition type is not bool or dict.
[ "Inflate", "a", "no", "-", "data", "checker", "from", "a", "basic", "definition", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L215-L236
train
Genida/archan
src/archan/config.py
Config.get_plugin
def get_plugin(self, identifier, cls=None): """ Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class. """ if ((cls is None or cls == 'provider') and identifier in self.available_providers): return self.available_providers[identifier] elif ((cls is None or cls == 'checker') and identifier in self.available_checkers): return self.available_checkers[identifier] return Config.load_local_plugin(identifier)
python
def get_plugin(self, identifier, cls=None): """ Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class. """ if ((cls is None or cls == 'provider') and identifier in self.available_providers): return self.available_providers[identifier] elif ((cls is None or cls == 'checker') and identifier in self.available_checkers): return self.available_checkers[identifier] return Config.load_local_plugin(identifier)
[ "def", "get_plugin", "(", "self", ",", "identifier", ",", "cls", "=", "None", ")", ":", "if", "(", "(", "cls", "is", "None", "or", "cls", "==", "'provider'", ")", "and", "identifier", "in", "self", ".", "available_providers", ")", ":", "return", "self", ".", "available_providers", "[", "identifier", "]", "elif", "(", "(", "cls", "is", "None", "or", "cls", "==", "'checker'", ")", "and", "identifier", "in", "self", ".", "available_checkers", ")", ":", "return", "self", ".", "available_checkers", "[", "identifier", "]", "return", "Config", ".", "load_local_plugin", "(", "identifier", ")" ]
Return the plugin corresponding to the given identifier and type. Args: identifier (str): identifier of the plugin. cls (str): one of checker / provider. Returns: Checker/Provider: plugin class.
[ "Return", "the", "plugin", "corresponding", "to", "the", "given", "identifier", "and", "type", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L255-L272
train
Genida/archan
src/archan/config.py
Config.provider_from_dict
def provider_from_dict(self, dct): """Return a provider instance from a dict object.""" provider_identifier = list(dct.keys())[0] provider_class = self.get_provider(provider_identifier) if provider_class: return provider_class(**dct[provider_identifier]) return None
python
def provider_from_dict(self, dct): """Return a provider instance from a dict object.""" provider_identifier = list(dct.keys())[0] provider_class = self.get_provider(provider_identifier) if provider_class: return provider_class(**dct[provider_identifier]) return None
[ "def", "provider_from_dict", "(", "self", ",", "dct", ")", ":", "provider_identifier", "=", "list", "(", "dct", ".", "keys", "(", ")", ")", "[", "0", "]", "provider_class", "=", "self", ".", "get_provider", "(", "provider_identifier", ")", "if", "provider_class", ":", "return", "provider_class", "(", "*", "*", "dct", "[", "provider_identifier", "]", ")", "return", "None" ]
Return a provider instance from a dict object.
[ "Return", "a", "provider", "instance", "from", "a", "dict", "object", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L282-L288
train
Genida/archan
src/archan/config.py
Config.checker_from_dict
def checker_from_dict(self, dct): """Return a checker instance from a dict object.""" checker_identifier = list(dct.keys())[0] checker_class = self.get_checker(checker_identifier) if checker_class: return checker_class(**dct[checker_identifier]) return None
python
def checker_from_dict(self, dct): """Return a checker instance from a dict object.""" checker_identifier = list(dct.keys())[0] checker_class = self.get_checker(checker_identifier) if checker_class: return checker_class(**dct[checker_identifier]) return None
[ "def", "checker_from_dict", "(", "self", ",", "dct", ")", ":", "checker_identifier", "=", "list", "(", "dct", ".", "keys", "(", ")", ")", "[", "0", "]", "checker_class", "=", "self", ".", "get_checker", "(", "checker_identifier", ")", "if", "checker_class", ":", "return", "checker_class", "(", "*", "*", "dct", "[", "checker_identifier", "]", ")", "return", "None" ]
Return a checker instance from a dict object.
[ "Return", "a", "checker", "instance", "from", "a", "dict", "object", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L290-L296
train
Genida/archan
src/archan/config.py
Config.inflate_plugin
def inflate_plugin(self, identifier, definition=None, cls=None): """ Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "provider", "checker", or None. Returns: Provider/Checker: instance of plugin. """ cls = self.get_plugin(identifier, cls) # TODO: implement re-usability of plugins? # same instances shared across analyses (to avoid re-computing stuff) return cls(**definition or {})
python
def inflate_plugin(self, identifier, definition=None, cls=None): """ Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "provider", "checker", or None. Returns: Provider/Checker: instance of plugin. """ cls = self.get_plugin(identifier, cls) # TODO: implement re-usability of plugins? # same instances shared across analyses (to avoid re-computing stuff) return cls(**definition or {})
[ "def", "inflate_plugin", "(", "self", ",", "identifier", ",", "definition", "=", "None", ",", "cls", "=", "None", ")", ":", "cls", "=", "self", ".", "get_plugin", "(", "identifier", ",", "cls", ")", "# TODO: implement re-usability of plugins?", "# same instances shared across analyses (to avoid re-computing stuff)", "return", "cls", "(", "*", "*", "definition", "or", "{", "}", ")" ]
Inflate a plugin thanks to it's identifier, definition and class. Args: identifier (str): the plugin identifier. definition (dict): the kwargs to instantiate the plugin with. cls (str): "provider", "checker", or None. Returns: Provider/Checker: instance of plugin.
[ "Inflate", "a", "plugin", "thanks", "to", "it", "s", "identifier", "definition", "and", "class", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L298-L313
train
Genida/archan
src/archan/config.py
Config.inflate_analysis_group
def inflate_analysis_group(self, identifier, definition): """ Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: AnalysisGroup: an instance of AnalysisGroup. Raises: ValueError: when identifier targets a plugin of a certain type, and the definition does not contain the entry for the other-type plugins (providers <-> checkers). """ providers_definition = definition.pop('providers', None) checkers_definition = definition.pop('checkers', None) analysis_group = AnalysisGroup() try: first_plugin = self.inflate_plugin(identifier, definition) if isinstance(first_plugin, Checker): analysis_group.checkers.append(first_plugin) if providers_definition is None: raise ValueError( 'when declaring an analysis group with a checker ' 'identifier, you must also declare providers with ' 'the "providers" key.') analysis_group.providers.extend( self.inflate_providers(providers_definition)) elif isinstance(first_plugin, Provider): analysis_group.providers.append(first_plugin) if checkers_definition is None: raise ValueError( 'when declaring an analysis group with a provider ' 'identifier, you must also declare checkers with ' 'the "checkers" key.') analysis_group.checkers.extend( self.inflate_checkers(checkers_definition)) except PluginNotFoundError as e: logger.warning( 'Could not find any plugin identified by %s, ' 'considering entry as group name. Exception: %s.', identifier, e) analysis_group.name = definition.pop('name', identifier) analysis_group.description = definition.pop('description', None) if bool(providers_definition) != bool(checkers_definition): raise ValueError( 'when declaring an analysis group with a name, you must ' 'either declare both "providers" and "checkers" or none.') if providers_definition and checkers_definition: analysis_group.providers.extend( self.inflate_providers(providers_definition)) analysis_group.checkers.extend( self.inflate_checkers(checkers_definition)) self.cleanup_definition(definition) for nd_identifier, nd_definition in definition.items(): analysis_group.checkers.append( self.inflate_nd_checker(nd_identifier, nd_definition)) return analysis_group
python
def inflate_analysis_group(self, identifier, definition): """ Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: AnalysisGroup: an instance of AnalysisGroup. Raises: ValueError: when identifier targets a plugin of a certain type, and the definition does not contain the entry for the other-type plugins (providers <-> checkers). """ providers_definition = definition.pop('providers', None) checkers_definition = definition.pop('checkers', None) analysis_group = AnalysisGroup() try: first_plugin = self.inflate_plugin(identifier, definition) if isinstance(first_plugin, Checker): analysis_group.checkers.append(first_plugin) if providers_definition is None: raise ValueError( 'when declaring an analysis group with a checker ' 'identifier, you must also declare providers with ' 'the "providers" key.') analysis_group.providers.extend( self.inflate_providers(providers_definition)) elif isinstance(first_plugin, Provider): analysis_group.providers.append(first_plugin) if checkers_definition is None: raise ValueError( 'when declaring an analysis group with a provider ' 'identifier, you must also declare checkers with ' 'the "checkers" key.') analysis_group.checkers.extend( self.inflate_checkers(checkers_definition)) except PluginNotFoundError as e: logger.warning( 'Could not find any plugin identified by %s, ' 'considering entry as group name. Exception: %s.', identifier, e) analysis_group.name = definition.pop('name', identifier) analysis_group.description = definition.pop('description', None) if bool(providers_definition) != bool(checkers_definition): raise ValueError( 'when declaring an analysis group with a name, you must ' 'either declare both "providers" and "checkers" or none.') if providers_definition and checkers_definition: analysis_group.providers.extend( self.inflate_providers(providers_definition)) analysis_group.checkers.extend( self.inflate_checkers(checkers_definition)) self.cleanup_definition(definition) for nd_identifier, nd_definition in definition.items(): analysis_group.checkers.append( self.inflate_nd_checker(nd_identifier, nd_definition)) return analysis_group
[ "def", "inflate_analysis_group", "(", "self", ",", "identifier", ",", "definition", ")", ":", "providers_definition", "=", "definition", ".", "pop", "(", "'providers'", ",", "None", ")", "checkers_definition", "=", "definition", ".", "pop", "(", "'checkers'", ",", "None", ")", "analysis_group", "=", "AnalysisGroup", "(", ")", "try", ":", "first_plugin", "=", "self", ".", "inflate_plugin", "(", "identifier", ",", "definition", ")", "if", "isinstance", "(", "first_plugin", ",", "Checker", ")", ":", "analysis_group", ".", "checkers", ".", "append", "(", "first_plugin", ")", "if", "providers_definition", "is", "None", ":", "raise", "ValueError", "(", "'when declaring an analysis group with a checker '", "'identifier, you must also declare providers with '", "'the \"providers\" key.'", ")", "analysis_group", ".", "providers", ".", "extend", "(", "self", ".", "inflate_providers", "(", "providers_definition", ")", ")", "elif", "isinstance", "(", "first_plugin", ",", "Provider", ")", ":", "analysis_group", ".", "providers", ".", "append", "(", "first_plugin", ")", "if", "checkers_definition", "is", "None", ":", "raise", "ValueError", "(", "'when declaring an analysis group with a provider '", "'identifier, you must also declare checkers with '", "'the \"checkers\" key.'", ")", "analysis_group", ".", "checkers", ".", "extend", "(", "self", ".", "inflate_checkers", "(", "checkers_definition", ")", ")", "except", "PluginNotFoundError", "as", "e", ":", "logger", ".", "warning", "(", "'Could not find any plugin identified by %s, '", "'considering entry as group name. Exception: %s.'", ",", "identifier", ",", "e", ")", "analysis_group", ".", "name", "=", "definition", ".", "pop", "(", "'name'", ",", "identifier", ")", "analysis_group", ".", "description", "=", "definition", ".", "pop", "(", "'description'", ",", "None", ")", "if", "bool", "(", "providers_definition", ")", "!=", "bool", "(", "checkers_definition", ")", ":", "raise", "ValueError", "(", "'when declaring an analysis group with a name, you must '", "'either declare both \"providers\" and \"checkers\" or none.'", ")", "if", "providers_definition", "and", "checkers_definition", ":", "analysis_group", ".", "providers", ".", "extend", "(", "self", ".", "inflate_providers", "(", "providers_definition", ")", ")", "analysis_group", ".", "checkers", ".", "extend", "(", "self", ".", "inflate_checkers", "(", "checkers_definition", ")", ")", "self", ".", "cleanup_definition", "(", "definition", ")", "for", "nd_identifier", ",", "nd_definition", "in", "definition", ".", "items", "(", ")", ":", "analysis_group", ".", "checkers", ".", "append", "(", "self", ".", "inflate_nd_checker", "(", "nd_identifier", ",", "nd_definition", ")", ")", "return", "analysis_group" ]
Inflate a whole analysis group. An analysis group is a section defined in the YAML file. Args: identifier (str): the group identifier. definition (list/dict): the group definition. Returns: AnalysisGroup: an instance of AnalysisGroup. Raises: ValueError: when identifier targets a plugin of a certain type, and the definition does not contain the entry for the other-type plugins (providers <-> checkers).
[ "Inflate", "a", "whole", "analysis", "group", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L353-L431
train
Genida/archan
src/archan/config.py
Config.print_plugins
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available_providers.values(), key=lambda x: x.identifier): provider().print() print() if self.available_checkers: print(line + ' ' * middle + 'CHECKERS') for checker in sorted(self.available_checkers.values(), key=lambda x: x.identifier): checker().print() print()
python
def print_plugins(self): """Print the available plugins.""" width = console_width() line = Style.BRIGHT + '=' * width + '\n' middle = int(width / 2) if self.available_providers: print(line + ' ' * middle + 'PROVIDERS') for provider in sorted(self.available_providers.values(), key=lambda x: x.identifier): provider().print() print() if self.available_checkers: print(line + ' ' * middle + 'CHECKERS') for checker in sorted(self.available_checkers.values(), key=lambda x: x.identifier): checker().print() print()
[ "def", "print_plugins", "(", "self", ")", ":", "width", "=", "console_width", "(", ")", "line", "=", "Style", ".", "BRIGHT", "+", "'='", "*", "width", "+", "'\\n'", "middle", "=", "int", "(", "width", "/", "2", ")", "if", "self", ".", "available_providers", ":", "print", "(", "line", "+", "' '", "*", "middle", "+", "'PROVIDERS'", ")", "for", "provider", "in", "sorted", "(", "self", ".", "available_providers", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identifier", ")", ":", "provider", "(", ")", ".", "print", "(", ")", "print", "(", ")", "if", "self", ".", "available_checkers", ":", "print", "(", "line", "+", "' '", "*", "middle", "+", "'CHECKERS'", ")", "for", "checker", "in", "sorted", "(", "self", ".", "available_checkers", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "identifier", ")", ":", "checker", "(", ")", ".", "print", "(", ")", "print", "(", ")" ]
Print the available plugins.
[ "Print", "the", "available", "plugins", "." ]
a026d3105c7e86f30e6c9507b93ceb736684bfdc
https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/config.py#L433-L449
train
tjcsl/cslbot
cslbot/commands/random.py
cmd
def cmd(send, msg, args): """For when you don't have enough randomness in your life. Syntax: {command} [--int] [len] """ match = re.match(r'--(.+?)\b', msg) randtype = 'hex' if match: if match.group(1) == 'int': randtype = 'int' else: send("Invalid Flag.") return if randtype == 'hex': send(hex(getrandbits(50))) else: maxlen = 1000000000 msg = msg.split() if len(msg) == 2: if msg[1].isdigit(): maxlen = int(msg[1]) else: send("Invalid Length") return send(str(randrange(maxlen)))
python
def cmd(send, msg, args): """For when you don't have enough randomness in your life. Syntax: {command} [--int] [len] """ match = re.match(r'--(.+?)\b', msg) randtype = 'hex' if match: if match.group(1) == 'int': randtype = 'int' else: send("Invalid Flag.") return if randtype == 'hex': send(hex(getrandbits(50))) else: maxlen = 1000000000 msg = msg.split() if len(msg) == 2: if msg[1].isdigit(): maxlen = int(msg[1]) else: send("Invalid Length") return send(str(randrange(maxlen)))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "match", "=", "re", ".", "match", "(", "r'--(.+?)\\b'", ",", "msg", ")", "randtype", "=", "'hex'", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'int'", ":", "randtype", "=", "'int'", "else", ":", "send", "(", "\"Invalid Flag.\"", ")", "return", "if", "randtype", "==", "'hex'", ":", "send", "(", "hex", "(", "getrandbits", "(", "50", ")", ")", ")", "else", ":", "maxlen", "=", "1000000000", "msg", "=", "msg", ".", "split", "(", ")", "if", "len", "(", "msg", ")", "==", "2", ":", "if", "msg", "[", "1", "]", ".", "isdigit", "(", ")", ":", "maxlen", "=", "int", "(", "msg", "[", "1", "]", ")", "else", ":", "send", "(", "\"Invalid Length\"", ")", "return", "send", "(", "str", "(", "randrange", "(", "maxlen", ")", ")", ")" ]
For when you don't have enough randomness in your life. Syntax: {command} [--int] [len]
[ "For", "when", "you", "don", "t", "have", "enough", "randomness", "in", "your", "life", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/random.py#L25-L50
train
VIVelev/PyDojoML
dojo/tree/utils/functions.py
split
def split(X, Y, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_X, false_X = [], [] true_Y, false_Y = [], [] for x, y in zip(X, Y): if question.match(x): true_X.append(x) true_Y.append(y) else: false_X.append(x) false_Y.append(y) return (np.array(true_X), np.array(false_X), np.array(true_Y), np.array(false_Y))
python
def split(X, Y, question): """Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. """ true_X, false_X = [], [] true_Y, false_Y = [], [] for x, y in zip(X, Y): if question.match(x): true_X.append(x) true_Y.append(y) else: false_X.append(x) false_Y.append(y) return (np.array(true_X), np.array(false_X), np.array(true_Y), np.array(false_Y))
[ "def", "split", "(", "X", ",", "Y", ",", "question", ")", ":", "true_X", ",", "false_X", "=", "[", "]", ",", "[", "]", "true_Y", ",", "false_Y", "=", "[", "]", ",", "[", "]", "for", "x", ",", "y", "in", "zip", "(", "X", ",", "Y", ")", ":", "if", "question", ".", "match", "(", "x", ")", ":", "true_X", ".", "append", "(", "x", ")", "true_Y", ".", "append", "(", "y", ")", "else", ":", "false_X", ".", "append", "(", "x", ")", "false_Y", ".", "append", "(", "y", ")", "return", "(", "np", ".", "array", "(", "true_X", ")", ",", "np", ".", "array", "(", "false_X", ")", ",", "np", ".", "array", "(", "true_Y", ")", ",", "np", ".", "array", "(", "false_Y", ")", ")" ]
Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'.
[ "Partitions", "a", "dataset", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L17-L37
train
VIVelev/PyDojoML
dojo/tree/utils/functions.py
build_tree
def build_tree(X, y, criterion, max_depth, current_depth=1): """Builds the decision tree. """ # check for max_depth accomplished if max_depth >= 0 and current_depth >= max_depth: return Leaf(y) # check for 0 gain gain, question = find_best_question(X, y, criterion) if gain == 0: return Leaf(y) # split true_X, false_X, true_y, false_y = split(X, y, question) # Build the `true` branch of the tree recursively true_branch = build_tree( true_X, true_y, criterion, max_depth, current_depth=current_depth+1 ) # Build the `false` branch of the tree recursively false_branch = build_tree( false_X, false_y, criterion, max_depth, current_depth=current_depth+1 ) # returning the root of the tree/subtree return Node( question=question, true_branch=true_branch, false_branch=false_branch )
python
def build_tree(X, y, criterion, max_depth, current_depth=1): """Builds the decision tree. """ # check for max_depth accomplished if max_depth >= 0 and current_depth >= max_depth: return Leaf(y) # check for 0 gain gain, question = find_best_question(X, y, criterion) if gain == 0: return Leaf(y) # split true_X, false_X, true_y, false_y = split(X, y, question) # Build the `true` branch of the tree recursively true_branch = build_tree( true_X, true_y, criterion, max_depth, current_depth=current_depth+1 ) # Build the `false` branch of the tree recursively false_branch = build_tree( false_X, false_y, criterion, max_depth, current_depth=current_depth+1 ) # returning the root of the tree/subtree return Node( question=question, true_branch=true_branch, false_branch=false_branch )
[ "def", "build_tree", "(", "X", ",", "y", ",", "criterion", ",", "max_depth", ",", "current_depth", "=", "1", ")", ":", "# check for max_depth accomplished", "if", "max_depth", ">=", "0", "and", "current_depth", ">=", "max_depth", ":", "return", "Leaf", "(", "y", ")", "# check for 0 gain", "gain", ",", "question", "=", "find_best_question", "(", "X", ",", "y", ",", "criterion", ")", "if", "gain", "==", "0", ":", "return", "Leaf", "(", "y", ")", "# split", "true_X", ",", "false_X", ",", "true_y", ",", "false_y", "=", "split", "(", "X", ",", "y", ",", "question", ")", "# Build the `true` branch of the tree recursively", "true_branch", "=", "build_tree", "(", "true_X", ",", "true_y", ",", "criterion", ",", "max_depth", ",", "current_depth", "=", "current_depth", "+", "1", ")", "# Build the `false` branch of the tree recursively", "false_branch", "=", "build_tree", "(", "false_X", ",", "false_y", ",", "criterion", ",", "max_depth", ",", "current_depth", "=", "current_depth", "+", "1", ")", "# returning the root of the tree/subtree", "return", "Node", "(", "question", "=", "question", ",", "true_branch", "=", "true_branch", ",", "false_branch", "=", "false_branch", ")" ]
Builds the decision tree.
[ "Builds", "the", "decision", "tree", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L92-L129
train
VIVelev/PyDojoML
dojo/tree/utils/functions.py
print_tree
def print_tree(root, space=' '): """Prints the Decision Tree in a pretty way. """ if isinstance(root, Leaf): print(space + "Prediction: " + str(root.most_frequent)) return print(space + str(root.question)) print(space + "--> True:") print_tree(root.true_branch, space+' ') print(space + "--> False:") print_tree(root.false_branch, space+' ')
python
def print_tree(root, space=' '): """Prints the Decision Tree in a pretty way. """ if isinstance(root, Leaf): print(space + "Prediction: " + str(root.most_frequent)) return print(space + str(root.question)) print(space + "--> True:") print_tree(root.true_branch, space+' ') print(space + "--> False:") print_tree(root.false_branch, space+' ')
[ "def", "print_tree", "(", "root", ",", "space", "=", "' '", ")", ":", "if", "isinstance", "(", "root", ",", "Leaf", ")", ":", "print", "(", "space", "+", "\"Prediction: \"", "+", "str", "(", "root", ".", "most_frequent", ")", ")", "return", "print", "(", "space", "+", "str", "(", "root", ".", "question", ")", ")", "print", "(", "space", "+", "\"--> True:\"", ")", "print_tree", "(", "root", ".", "true_branch", ",", "space", "+", "' '", ")", "print", "(", "space", "+", "\"--> False:\"", ")", "print_tree", "(", "root", ".", "false_branch", ",", "space", "+", "' '", ")" ]
Prints the Decision Tree in a pretty way.
[ "Prints", "the", "Decision", "Tree", "in", "a", "pretty", "way", "." ]
773fdce6866aa6decd306a5a85f94129fed816eb
https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/functions.py#L193-L207
train
levi-rs/explicit
explicit/waiter.py
find_element
def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located """ wait = WebDriverWait(driver, timeout, poll_frequency) return wait.until(EC.presence_of_element_located((by, elem_path)))
python
def find_element(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located """ wait = WebDriverWait(driver, timeout, poll_frequency) return wait.until(EC.presence_of_element_located((by, elem_path)))
[ "def", "find_element", "(", "driver", ",", "elem_path", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "wait", "=", "WebDriverWait", "(", "driver", ",", "timeout", ",", "poll_frequency", ")", "return", "wait", ".", "until", "(", "EC", ".", "presence_of_element_located", "(", "(", "by", ",", "elem_path", ")", ")", ")" ]
Find and return an element once located find_element locates an element on the page, waiting for up to timeout seconds. The element, when located, is returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located
[ "Find", "and", "return", "an", "element", "once", "located" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L20-L41
train
levi-rs/explicit
explicit/waiter.py
find_elements
def find_elements(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: list of elements: Selenium element Raises: TimeoutException: Raised when target element isn't located """ wait = WebDriverWait(driver, timeout, poll_frequency) return wait.until(EC.presence_of_all_elements_located((by, elem_path)))
python
def find_elements(driver, elem_path, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: list of elements: Selenium element Raises: TimeoutException: Raised when target element isn't located """ wait = WebDriverWait(driver, timeout, poll_frequency) return wait.until(EC.presence_of_all_elements_located((by, elem_path)))
[ "def", "find_elements", "(", "driver", ",", "elem_path", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "wait", "=", "WebDriverWait", "(", "driver", ",", "timeout", ",", "poll_frequency", ")", "return", "wait", ".", "until", "(", "EC", ".", "presence_of_all_elements_located", "(", "(", "by", ",", "elem_path", ")", ")", ")" ]
Find and return all elements once located find_elements locates all elements on the page, waiting for up to timeout seconds. The elements, when located, are returned. If not located, a TimeoutException is raised. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: list of elements: Selenium element Raises: TimeoutException: Raised when target element isn't located
[ "Find", "and", "return", "all", "elements", "once", "located" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L44-L65
train
levi-rs/explicit
explicit/waiter.py
find_write
def find_write(driver, elem_path, write_str, clear_first=True, send_enter=False, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string to it. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element write_str (str): String to write clear_first (bool): Clear the contents before writing (default True) send_enter (bool): Send a keyboard ENTER after writing string by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located """ elem = find_element(driver, elem_path=elem_path, by=by, timeout=timeout, poll_frequency=poll_frequency) if clear_first: elem.clear() elem.send_keys(write_str) if send_enter: elem.send_keys(Keys.ENTER) return elem
python
def find_write(driver, elem_path, write_str, clear_first=True, send_enter=False, by=CSS, timeout=TIMEOUT, poll_frequency=0.5): """ Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string to it. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element write_str (str): String to write clear_first (bool): Clear the contents before writing (default True) send_enter (bool): Send a keyboard ENTER after writing string by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located """ elem = find_element(driver, elem_path=elem_path, by=by, timeout=timeout, poll_frequency=poll_frequency) if clear_first: elem.clear() elem.send_keys(write_str) if send_enter: elem.send_keys(Keys.ENTER) return elem
[ "def", "find_write", "(", "driver", ",", "elem_path", ",", "write_str", ",", "clear_first", "=", "True", ",", "send_enter", "=", "False", ",", "by", "=", "CSS", ",", "timeout", "=", "TIMEOUT", ",", "poll_frequency", "=", "0.5", ")", ":", "elem", "=", "find_element", "(", "driver", ",", "elem_path", "=", "elem_path", ",", "by", "=", "by", ",", "timeout", "=", "timeout", ",", "poll_frequency", "=", "poll_frequency", ")", "if", "clear_first", ":", "elem", ".", "clear", "(", ")", "elem", ".", "send_keys", "(", "write_str", ")", "if", "send_enter", ":", "elem", ".", "send_keys", "(", "Keys", ".", "ENTER", ")", "return", "elem" ]
Find a writable element and write to it find_write locates a writable element on the page, waiting for up to timeout seconds. Once found, it writes the string to it. Args: driver (selenium webdriver or element): A driver or element elem_path (str): String used to located the element write_str (str): String to write clear_first (bool): Clear the contents before writing (default True) send_enter (bool): Send a keyboard ENTER after writing string by (selenium By): Selenium By reference timeout (int): Selenium Wait timeout, in seconds poll_frequency (float): Selenium Wait polling frequency, in seconds Returns: element: Selenium element Raises: TimeoutException: Raised when target element isn't located
[ "Find", "a", "writable", "element", "and", "write", "to", "it" ]
0ebdd4c8e74dae02fd92b914325e37e386694e4c
https://github.com/levi-rs/explicit/blob/0ebdd4c8e74dae02fd92b914325e37e386694e4c/explicit/waiter.py#L110-L145
train
tjcsl/cslbot
cslbot/commands/intensify.py
cmd
def cmd(send, msg, args): """Intensifies text. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_intensify(msg))
python
def cmd(send, msg, args): """Intensifies text. Syntax: {command} [text] """ if not msg: msg = gen_word() send(gen_intensify(msg))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "msg", "=", "gen_word", "(", ")", "send", "(", "gen_intensify", "(", "msg", ")", ")" ]
Intensifies text. Syntax: {command} [text]
[ "Intensifies", "text", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/intensify.py#L23-L31
train
The-Politico/politico-civic-election-night
electionnight/management/commands/bake_elections.py
Command.fetch_states
def fetch_states(self, elections): """ Returns the unique divisions for all elections on an election day. """ states = [] for election in elections: if election.division.level.name == DivisionLevel.DISTRICT: division = election.division.parent else: division = election.division states.append(division) return sorted(list(set(states)), key=lambda s: s.label)
python
def fetch_states(self, elections): """ Returns the unique divisions for all elections on an election day. """ states = [] for election in elections: if election.division.level.name == DivisionLevel.DISTRICT: division = election.division.parent else: division = election.division states.append(division) return sorted(list(set(states)), key=lambda s: s.label)
[ "def", "fetch_states", "(", "self", ",", "elections", ")", ":", "states", "=", "[", "]", "for", "election", "in", "elections", ":", "if", "election", ".", "division", ".", "level", ".", "name", "==", "DivisionLevel", ".", "DISTRICT", ":", "division", "=", "election", ".", "division", ".", "parent", "else", ":", "division", "=", "election", ".", "division", "states", ".", "append", "(", "division", ")", "return", "sorted", "(", "list", "(", "set", "(", "states", ")", ")", ",", "key", "=", "lambda", "s", ":", "s", ".", "label", ")" ]
Returns the unique divisions for all elections on an election day.
[ "Returns", "the", "unique", "divisions", "for", "all", "elections", "on", "an", "election", "day", "." ]
a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6
https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/bake_elections.py#L25-L39
train
ktdreyer/txkoji
txkoji/cache.py
Cache.get_name
def get_name(self, type_, id_): """ Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None """ cachefile = self.filename(type_, id_) try: with open(cachefile, 'r') as f: return f.read() except (OSError, IOError) as e: if e.errno != errno.ENOENT: raise
python
def get_name(self, type_, id_): """ Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None """ cachefile = self.filename(type_, id_) try: with open(cachefile, 'r') as f: return f.read() except (OSError, IOError) as e: if e.errno != errno.ENOENT: raise
[ "def", "get_name", "(", "self", ",", "type_", ",", "id_", ")", ":", "cachefile", "=", "self", ".", "filename", "(", "type_", ",", "id_", ")", "try", ":", "with", "open", "(", "cachefile", ",", "'r'", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")", "except", "(", "OSError", ",", "IOError", ")", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOENT", ":", "raise" ]
Read a cached name if available. :param type_: str, "owner" or "tag" :param id_: int, eg. 123456 :returns: str, or None
[ "Read", "a", "cached", "name", "if", "available", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L29-L43
train
ktdreyer/txkoji
txkoji/cache.py
Cache.put_name
def put_name(self, type_, id_, name): """ Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None """ cachefile = self.filename(type_, id_) dirname = os.path.dirname(cachefile) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise with open(cachefile, 'w') as f: f.write(name)
python
def put_name(self, type_, id_, name): """ Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None """ cachefile = self.filename(type_, id_) dirname = os.path.dirname(cachefile) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise with open(cachefile, 'w') as f: f.write(name)
[ "def", "put_name", "(", "self", ",", "type_", ",", "id_", ",", "name", ")", ":", "cachefile", "=", "self", ".", "filename", "(", "type_", ",", "id_", ")", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "cachefile", ")", "try", ":", "os", ".", "makedirs", "(", "dirname", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "with", "open", "(", "cachefile", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "name", ")" ]
Write a cached name to disk. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :returns: None
[ "Write", "a", "cached", "name", "to", "disk", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L45-L61
train
ktdreyer/txkoji
txkoji/cache.py
Cache.get_or_load_name
def get_or_load_name(self, type_, id_, method): """ read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this value is not in the cache. This method must return a deferred that fires with an object with a ".name" attribute. :returns: deferred that when fired returns a str, or None """ name = self.get_name(type_, id_) if name is not None: defer.returnValue(name) instance = yield method(id_) if instance is None: defer.returnValue(None) self.put_name(type_, id_, instance.name) defer.returnValue(instance.name)
python
def get_or_load_name(self, type_, id_, method): """ read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this value is not in the cache. This method must return a deferred that fires with an object with a ".name" attribute. :returns: deferred that when fired returns a str, or None """ name = self.get_name(type_, id_) if name is not None: defer.returnValue(name) instance = yield method(id_) if instance is None: defer.returnValue(None) self.put_name(type_, id_, instance.name) defer.returnValue(instance.name)
[ "def", "get_or_load_name", "(", "self", ",", "type_", ",", "id_", ",", "method", ")", ":", "name", "=", "self", ".", "get_name", "(", "type_", ",", "id_", ")", "if", "name", "is", "not", "None", ":", "defer", ".", "returnValue", "(", "name", ")", "instance", "=", "yield", "method", "(", "id_", ")", "if", "instance", "is", "None", ":", "defer", ".", "returnValue", "(", "None", ")", "self", ".", "put_name", "(", "type_", ",", "id_", ",", "instance", ".", "name", ")", "defer", ".", "returnValue", "(", "instance", ".", "name", ")" ]
read-through cache for a type of object's name. If we don't have a cached name for this type/id, then we will query the live Koji server and store the value before returning. :param type_: str, "user" or "tag" :param id_: int, eg. 123456 :param method: function to call if this value is not in the cache. This method must return a deferred that fires with an object with a ".name" attribute. :returns: deferred that when fired returns a str, or None
[ "read", "-", "through", "cache", "for", "a", "type", "of", "object", "s", "name", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/cache.py#L75-L96
train
ktdreyer/txkoji
txkoji/multicall.py
MultiCall.call
def call(self, name, *args, **kwargs): """ Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. """ # Like txkoji.Connection, we always want the full request for tasks: if name in ('getTaskInfo', 'getTaskDescendants'): kwargs['request'] = True if kwargs: kwargs['__starstar'] = True args = args + (kwargs,) payload = {'methodName': name, 'params': args} self.calls.append(payload)
python
def call(self, name, *args, **kwargs): """ Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now. """ # Like txkoji.Connection, we always want the full request for tasks: if name in ('getTaskInfo', 'getTaskDescendants'): kwargs['request'] = True if kwargs: kwargs['__starstar'] = True args = args + (kwargs,) payload = {'methodName': name, 'params': args} self.calls.append(payload)
[ "def", "call", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Like txkoji.Connection, we always want the full request for tasks:", "if", "name", "in", "(", "'getTaskInfo'", ",", "'getTaskDescendants'", ")", ":", "kwargs", "[", "'request'", "]", "=", "True", "if", "kwargs", ":", "kwargs", "[", "'__starstar'", "]", "=", "True", "args", "=", "args", "+", "(", "kwargs", ",", ")", "payload", "=", "{", "'methodName'", ":", "name", ",", "'params'", ":", "args", "}", "self", ".", "calls", ".", "append", "(", "payload", ")" ]
Add a new call to the list that we will submit to the server. Similar to txkoji.Connection.call(), but this will store the call for later instead of sending it now.
[ "Add", "a", "new", "call", "to", "the", "list", "that", "we", "will", "submit", "to", "the", "server", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/multicall.py#L44-L58
train
ktdreyer/txkoji
txkoji/multicall.py
MultiCall._multicall_callback
def _multicall_callback(self, values, calls): """ Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :param calls: list of calls we sent in this multicall RPC :returns: KojiMultiCallIterator with the resulting values from all our calls. """ result = KojiMultiCallIterator(values) result.connection = self.connection result.calls = calls return result
python
def _multicall_callback(self, values, calls): """ Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :param calls: list of calls we sent in this multicall RPC :returns: KojiMultiCallIterator with the resulting values from all our calls. """ result = KojiMultiCallIterator(values) result.connection = self.connection result.calls = calls return result
[ "def", "_multicall_callback", "(", "self", ",", "values", ",", "calls", ")", ":", "result", "=", "KojiMultiCallIterator", "(", "values", ")", "result", ".", "connection", "=", "self", ".", "connection", "result", ".", "calls", "=", "calls", "return", "result" ]
Fires when we get information back from the XML-RPC server. This is processes the raw results of system.multicall into a usable iterator of values (and/or Faults). :param values: list of data txkoji.Connection.call() :param calls: list of calls we sent in this multicall RPC :returns: KojiMultiCallIterator with the resulting values from all our calls.
[ "Fires", "when", "we", "get", "information", "back", "from", "the", "XML", "-", "RPC", "server", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/multicall.py#L60-L75
train
mardix/Juice
juice/utils.py
time_ago
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
python
def time_ago(dt): """ Return the current time ago """ now = datetime.datetime.now() return humanize.naturaltime(now - dt)
[ "def", "time_ago", "(", "dt", ")", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "return", "humanize", ".", "naturaltime", "(", "now", "-", "dt", ")" ]
Return the current time ago
[ "Return", "the", "current", "time", "ago" ]
7afa8d4238868235dfcdae82272bd77958dd416a
https://github.com/mardix/Juice/blob/7afa8d4238868235dfcdae82272bd77958dd416a/juice/utils.py#L228-L233
train
tjcsl/cslbot
cslbot/commands/insult.py
cmd
def cmd(send, msg, args): """Insults a user. Syntax: {command} [nick] """ if not msg: user = choice(get_users(args)) else: user = msg send(gen_insult(user))
python
def cmd(send, msg, args): """Insults a user. Syntax: {command} [nick] """ if not msg: user = choice(get_users(args)) else: user = msg send(gen_insult(user))
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "user", "=", "choice", "(", "get_users", "(", "args", ")", ")", "else", ":", "user", "=", "msg", "send", "(", "gen_insult", "(", "user", ")", ")" ]
Insults a user. Syntax: {command} [nick]
[ "Insults", "a", "user", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/insult.py#L26-L37
train
klahnakoski/mo-json
mo_json/stream.py
needed
def needed(name, required): """ RETURN SUBSET IF name IN REQUIRED """ return [ relative_field(r, name) if r and startswith_field(r, name) else None for r in required ]
python
def needed(name, required): """ RETURN SUBSET IF name IN REQUIRED """ return [ relative_field(r, name) if r and startswith_field(r, name) else None for r in required ]
[ "def", "needed", "(", "name", ",", "required", ")", ":", "return", "[", "relative_field", "(", "r", ",", "name", ")", "if", "r", "and", "startswith_field", "(", "r", ",", "name", ")", "else", "None", "for", "r", "in", "required", "]" ]
RETURN SUBSET IF name IN REQUIRED
[ "RETURN", "SUBSET", "IF", "name", "IN", "REQUIRED" ]
0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f
https://github.com/klahnakoski/mo-json/blob/0d44d6a7e37f0ea50e583c30c2cbc42488d5de7f/mo_json/stream.py#L326-L333
train
toumorokoshi/swagger-schema
swagger_schema/parameter.py
_match_data_to_parameter
def _match_data_to_parameter(cls, data): """ find the appropriate parameter for a parameter field """ in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
python
def _match_data_to_parameter(cls, data): """ find the appropriate parameter for a parameter field """ in_value = data["in"] for cls in [QueryParameter, HeaderParameter, FormDataParameter, PathParameter, BodyParameter]: if in_value == cls.IN: return cls return None
[ "def", "_match_data_to_parameter", "(", "cls", ",", "data", ")", ":", "in_value", "=", "data", "[", "\"in\"", "]", "for", "cls", "in", "[", "QueryParameter", ",", "HeaderParameter", ",", "FormDataParameter", ",", "PathParameter", ",", "BodyParameter", "]", ":", "if", "in_value", "==", "cls", ".", "IN", ":", "return", "cls", "return", "None" ]
find the appropriate parameter for a parameter field
[ "find", "the", "appropriate", "parameter", "for", "a", "parameter", "field" ]
24aa13d1f4ac59dfd81af2f5d8d4d1e66a139c97
https://github.com/toumorokoshi/swagger-schema/blob/24aa13d1f4ac59dfd81af2f5d8d4d1e66a139c97/swagger_schema/parameter.py#L49-L56
train
tjcsl/cslbot
cslbot/commands/eix.py
cmd
def cmd(send, msg, args): """Runs eix with the given arguments. Syntax: {command} <package> """ if not msg: result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True) if result.returncode: send("eix what?") return send(choice(result.stdout.splitlines())) return args = ['eix', '-c'] + msg.split() result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) if result.returncode: send("%s isn't important enough for Gentoo." % msg) else: send(result.stdout.splitlines()[0].strip())
python
def cmd(send, msg, args): """Runs eix with the given arguments. Syntax: {command} <package> """ if not msg: result = subprocess.run(['eix', '-c'], env={'EIX_LIMIT': '0', 'HOME': os.environ['HOME']}, stdout=subprocess.PIPE, universal_newlines=True) if result.returncode: send("eix what?") return send(choice(result.stdout.splitlines())) return args = ['eix', '-c'] + msg.split() result = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) if result.returncode: send("%s isn't important enough for Gentoo." % msg) else: send(result.stdout.splitlines()[0].strip())
[ "def", "cmd", "(", "send", ",", "msg", ",", "args", ")", ":", "if", "not", "msg", ":", "result", "=", "subprocess", ".", "run", "(", "[", "'eix'", ",", "'-c'", "]", ",", "env", "=", "{", "'EIX_LIMIT'", ":", "'0'", ",", "'HOME'", ":", "os", ".", "environ", "[", "'HOME'", "]", "}", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "universal_newlines", "=", "True", ")", "if", "result", ".", "returncode", ":", "send", "(", "\"eix what?\"", ")", "return", "send", "(", "choice", "(", "result", ".", "stdout", ".", "splitlines", "(", ")", ")", ")", "return", "args", "=", "[", "'eix'", ",", "'-c'", "]", "+", "msg", ".", "split", "(", ")", "result", "=", "subprocess", ".", "run", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", "True", ")", "if", "result", ".", "returncode", ":", "send", "(", "\"%s isn't important enough for Gentoo.\"", "%", "msg", ")", "else", ":", "send", "(", "result", ".", "stdout", ".", "splitlines", "(", ")", "[", "0", "]", ".", "strip", "(", ")", ")" ]
Runs eix with the given arguments. Syntax: {command} <package>
[ "Runs", "eix", "with", "the", "given", "arguments", "." ]
aebe07be47141f61d7c180706bddfb707f19b2b5
https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/eix.py#L26-L44
train
ktdreyer/txkoji
txkoji/task_states.py
to_str
def to_str(number): """ Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number. """ states = globals() for name, value in states.items(): if number == value and name.isalpha() and name.isupper(): return name return '(unknown state %d)' % number
python
def to_str(number): """ Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number. """ states = globals() for name, value in states.items(): if number == value and name.isalpha() and name.isupper(): return name return '(unknown state %d)' % number
[ "def", "to_str", "(", "number", ")", ":", "states", "=", "globals", "(", ")", "for", "name", ",", "value", "in", "states", ".", "items", "(", ")", ":", "if", "number", "==", "value", "and", "name", ".", "isalpha", "(", ")", "and", "name", ".", "isupper", "(", ")", ":", "return", "name", "return", "'(unknown state %d)'", "%", "number" ]
Convert a task state ID number to a string. :param int number: task state ID, eg. 1 :returns: state name like eg. "OPEN", or "(unknown)" if we don't know the name of this task state ID number.
[ "Convert", "a", "task", "state", "ID", "number", "to", "a", "string", "." ]
a7de380f29f745bf11730b27217208f6d4da7733
https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/task_states.py#L14-L26
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_json
def to_json(self, filename, indent=2): """ Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : int, optional Indentation level for JSON output. Returns ------- out : str JSON formatted output string. """ d = self.to_dicts() if hasattr(filename, "write"): json.dump(d, filename, indent=indent) elif isinstance(filename, string_types): with open(os.path.expanduser(filename), "w") as f: json.dump(d, f, indent=indent) else: raise ValueError("Unknown filename or file-object")
python
def to_json(self, filename, indent=2): """ Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : int, optional Indentation level for JSON output. Returns ------- out : str JSON formatted output string. """ d = self.to_dicts() if hasattr(filename, "write"): json.dump(d, filename, indent=indent) elif isinstance(filename, string_types): with open(os.path.expanduser(filename), "w") as f: json.dump(d, f, indent=indent) else: raise ValueError("Unknown filename or file-object")
[ "def", "to_json", "(", "self", ",", "filename", ",", "indent", "=", "2", ")", ":", "d", "=", "self", ".", "to_dicts", "(", ")", "if", "hasattr", "(", "filename", ",", "\"write\"", ")", ":", "json", ".", "dump", "(", "d", ",", "filename", ",", "indent", "=", "indent", ")", "elif", "isinstance", "(", "filename", ",", "string_types", ")", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "filename", ")", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "d", ",", "f", ",", "indent", "=", "indent", ")", "else", ":", "raise", "ValueError", "(", "\"Unknown filename or file-object\"", ")" ]
Return a JSON string of all model inputs and outputs. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. indent : int, optional Indentation level for JSON output. Returns ------- out : str JSON formatted output string.
[ "Return", "a", "JSON", "string", "of", "all", "model", "inputs", "and", "outputs", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L59-L84
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_df
def to_df(self, recommended_only=False, include_io=True): """ Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- out : pandas.DataFrame Data frame containing models and outputs """ od = BMDS._df_ordered_dict(include_io) [ session._add_to_to_ordered_dict(od, i, recommended_only) for i, session in enumerate(self) ] return pd.DataFrame(od)
python
def to_df(self, recommended_only=False, include_io=True): """ Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- out : pandas.DataFrame Data frame containing models and outputs """ od = BMDS._df_ordered_dict(include_io) [ session._add_to_to_ordered_dict(od, i, recommended_only) for i, session in enumerate(self) ] return pd.DataFrame(od)
[ "def", "to_df", "(", "self", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "od", "=", "BMDS", ".", "_df_ordered_dict", "(", "include_io", ")", "[", "session", ".", "_add_to_to_ordered_dict", "(", "od", ",", "i", ",", "recommended_only", ")", "for", "i", ",", "session", "in", "enumerate", "(", "self", ")", "]", "return", "pd", ".", "DataFrame", "(", "od", ")" ]
Return a pandas DataFrame for each model and dataset. Parameters ---------- recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- out : pandas.DataFrame Data frame containing models and outputs
[ "Return", "a", "pandas", "DataFrame", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L86-L111
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_csv
def to_csv(self, filename, delimiter=",", recommended_only=False, include_io=True): """ Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. delimiter : str, optional Delimiter used in CSV file between fields. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None """ df = self.to_df(recommended_only, include_io) df.to_csv(filename, index=False, sep=delimiter)
python
def to_csv(self, filename, delimiter=",", recommended_only=False, include_io=True): """ Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. delimiter : str, optional Delimiter used in CSV file between fields. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None """ df = self.to_df(recommended_only, include_io) df.to_csv(filename, index=False, sep=delimiter)
[ "def", "to_csv", "(", "self", ",", "filename", ",", "delimiter", "=", "\",\"", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "df", "=", "self", ".", "to_df", "(", "recommended_only", ",", "include_io", ")", "df", ".", "to_csv", "(", "filename", ",", "index", "=", "False", ",", "sep", "=", "delimiter", ")" ]
Return a CSV for each model and dataset. Parameters ---------- filename : str or file Either the file name (string) or an open file (file-like object) where the data will be saved. delimiter : str, optional Delimiter used in CSV file between fields. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None
[ "Return", "a", "CSV", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L113-L138
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_excel
def to_excel(self, filename, recommended_only=False, include_io=True): """ Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None """ df = self.to_df(recommended_only, include_io) if isinstance(filename, string_types): filename = os.path.expanduser(filename) df.to_excel(filename, index=False)
python
def to_excel(self, filename, recommended_only=False, include_io=True): """ Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None """ df = self.to_df(recommended_only, include_io) if isinstance(filename, string_types): filename = os.path.expanduser(filename) df.to_excel(filename, index=False)
[ "def", "to_excel", "(", "self", ",", "filename", ",", "recommended_only", "=", "False", ",", "include_io", "=", "True", ")", ":", "df", "=", "self", ".", "to_df", "(", "recommended_only", ",", "include_io", ")", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "df", ".", "to_excel", "(", "filename", ",", "index", "=", "False", ")" ]
Return an Excel file for each model and dataset. Parameters ---------- filename : str or ExcelWriter object Either the file name (string) or an ExcelWriter object. recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. include_io : bool, optional If True, then the input/output files from BMDS will also be included, specifically the (d) input file and the out file. Returns ------- None
[ "Return", "an", "Excel", "file", "for", "each", "model", "and", "dataset", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L140-L164
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.to_docx
def to_docx( self, filename=None, input_dataset=True, summary_table=True, recommendation_details=True, recommended_model=True, all_models=False, ): """ Write batch sessions to a Word file. Parameters ---------- filename : str or None If provided, the file is saved to this location, otherwise this method returns a docx.Document input_dataset : bool Include input dataset data table summary_table : bool Include model summary table recommendation_details : bool Include model recommendation details table recommended_model : bool Include the recommended model output and dose-response plot, if one exists all_models : bool Include all models output and dose-response plots Returns ------- bmds.Reporter The bmds.Reporter object. """ rep = Reporter() for model in self: rep.add_session( model, input_dataset, summary_table, recommendation_details, recommended_model, all_models, ) if filename: rep.save(filename) return rep
python
def to_docx( self, filename=None, input_dataset=True, summary_table=True, recommendation_details=True, recommended_model=True, all_models=False, ): """ Write batch sessions to a Word file. Parameters ---------- filename : str or None If provided, the file is saved to this location, otherwise this method returns a docx.Document input_dataset : bool Include input dataset data table summary_table : bool Include model summary table recommendation_details : bool Include model recommendation details table recommended_model : bool Include the recommended model output and dose-response plot, if one exists all_models : bool Include all models output and dose-response plots Returns ------- bmds.Reporter The bmds.Reporter object. """ rep = Reporter() for model in self: rep.add_session( model, input_dataset, summary_table, recommendation_details, recommended_model, all_models, ) if filename: rep.save(filename) return rep
[ "def", "to_docx", "(", "self", ",", "filename", "=", "None", ",", "input_dataset", "=", "True", ",", "summary_table", "=", "True", ",", "recommendation_details", "=", "True", ",", "recommended_model", "=", "True", ",", "all_models", "=", "False", ",", ")", ":", "rep", "=", "Reporter", "(", ")", "for", "model", "in", "self", ":", "rep", ".", "add_session", "(", "model", ",", "input_dataset", ",", "summary_table", ",", "recommendation_details", ",", "recommended_model", ",", "all_models", ",", ")", "if", "filename", ":", "rep", ".", "save", "(", "filename", ")", "return", "rep" ]
Write batch sessions to a Word file. Parameters ---------- filename : str or None If provided, the file is saved to this location, otherwise this method returns a docx.Document input_dataset : bool Include input dataset data table summary_table : bool Include model summary table recommendation_details : bool Include model recommendation details table recommended_model : bool Include the recommended model output and dose-response plot, if one exists all_models : bool Include all models output and dose-response plots Returns ------- bmds.Reporter The bmds.Reporter object.
[ "Write", "batch", "sessions", "to", "a", "Word", "file", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L166-L215
train
shapiromatron/bmds
bmds/batch.py
SessionBatch.save_plots
def save_plots(self, directory, format="png", recommended_only=False): """ Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image output format. Valid options include: png, pdf, svg, ps, eps recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. Returns ------- None """ for i, session in enumerate(self): session.save_plots( directory, prefix=str(i), format=format, recommended_only=recommended_only )
python
def save_plots(self, directory, format="png", recommended_only=False): """ Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image output format. Valid options include: png, pdf, svg, ps, eps recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. Returns ------- None """ for i, session in enumerate(self): session.save_plots( directory, prefix=str(i), format=format, recommended_only=recommended_only )
[ "def", "save_plots", "(", "self", ",", "directory", ",", "format", "=", "\"png\"", ",", "recommended_only", "=", "False", ")", ":", "for", "i", ",", "session", "in", "enumerate", "(", "self", ")", ":", "session", ".", "save_plots", "(", "directory", ",", "prefix", "=", "str", "(", "i", ")", ",", "format", "=", "format", ",", "recommended_only", "=", "recommended_only", ")" ]
Save images of dose-response curve-fits for each model. Parameters ---------- directory : str Directory where the PNG files will be saved. format : str, optional Image output format. Valid options include: png, pdf, svg, ps, eps recommended_only : bool, optional If True, only recommended models for each session are included. If no model is recommended, then a row with it's ID will be included, but all fields will be null. Returns ------- None
[ "Save", "images", "of", "dose", "-", "response", "curve", "-", "fits", "for", "each", "model", "." ]
395c6ce84ad82876fd9fa4a89a3497fb61616de0
https://github.com/shapiromatron/bmds/blob/395c6ce84ad82876fd9fa4a89a3497fb61616de0/bmds/batch.py#L217-L240
train
adamziel/python_translate
python_translate/glue.py
TransationLoader.load_messages
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError """ if not os.path.isdir(directory): raise ValueError("{0} is not a directory".format(directory)) for format, loader in list(self.loaders.items()): extension = "{0}.{1}".format(catalogue.locale, format) files = find_files(directory, "*.{0}".format(extension)) for file in files: domain = file.split("/")[-1][:-1 * len(extension) - 1] catalogue.add_catalogue( loader.load( file, catalogue.locale, domain))
python
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError """ if not os.path.isdir(directory): raise ValueError("{0} is not a directory".format(directory)) for format, loader in list(self.loaders.items()): extension = "{0}.{1}".format(catalogue.locale, format) files = find_files(directory, "*.{0}".format(extension)) for file in files: domain = file.split("/")[-1][:-1 * len(extension) - 1] catalogue.add_catalogue( loader.load( file, catalogue.locale, domain))
[ "def", "load_messages", "(", "self", ",", "directory", ",", "catalogue", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "raise", "ValueError", "(", "\"{0} is not a directory\"", ".", "format", "(", "directory", ")", ")", "for", "format", ",", "loader", "in", "list", "(", "self", ".", "loaders", ".", "items", "(", ")", ")", ":", "extension", "=", "\"{0}.{1}\"", ".", "format", "(", "catalogue", ".", "locale", ",", "format", ")", "files", "=", "find_files", "(", "directory", ",", "\"*.{0}\"", ".", "format", "(", "extension", ")", ")", "for", "file", "in", "files", ":", "domain", "=", "file", ".", "split", "(", "\"/\"", ")", "[", "-", "1", "]", "[", ":", "-", "1", "*", "len", "(", "extension", ")", "-", "1", "]", "catalogue", ".", "add_catalogue", "(", "loader", ".", "load", "(", "file", ",", "catalogue", ".", "locale", ",", "domain", ")", ")" ]
Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError
[ "Loads", "translation", "found", "in", "a", "directory", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L37-L61
train
adamziel/python_translate
python_translate/glue.py
TranslationWriter.disable_backup
def disable_backup(self): """ Disables dumper backup. """ for dumper in list(self.dumpers.values()): dumper.set_backup(False)
python
def disable_backup(self): """ Disables dumper backup. """ for dumper in list(self.dumpers.values()): dumper.set_backup(False)
[ "def", "disable_backup", "(", "self", ")", ":", "for", "dumper", "in", "list", "(", "self", ".", "dumpers", ".", "values", "(", ")", ")", ":", "dumper", ".", "set_backup", "(", "False", ")" ]
Disables dumper backup.
[ "Disables", "dumper", "backup", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L85-L90
train
adamziel/python_translate
python_translate/glue.py
TranslationWriter.write_translations
def write_translations(self, catalogue, format, options={}): """ Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to use to dump the messages @type options: array @param options: Options that are passed to the dumper @raises: ValueError """ if format not in self.dumpers: raise ValueError( 'There is no dumper associated with format "{0}"'.format(format)) dumper = self.dumpers[format] if "path" in options and not os.path.isdir(options['path']): os.mkdir(options['path']) dumper.dump(catalogue, options)
python
def write_translations(self, catalogue, format, options={}): """ Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to use to dump the messages @type options: array @param options: Options that are passed to the dumper @raises: ValueError """ if format not in self.dumpers: raise ValueError( 'There is no dumper associated with format "{0}"'.format(format)) dumper = self.dumpers[format] if "path" in options and not os.path.isdir(options['path']): os.mkdir(options['path']) dumper.dump(catalogue, options)
[ "def", "write_translations", "(", "self", ",", "catalogue", ",", "format", ",", "options", "=", "{", "}", ")", ":", "if", "format", "not", "in", "self", ".", "dumpers", ":", "raise", "ValueError", "(", "'There is no dumper associated with format \"{0}\"'", ".", "format", "(", "format", ")", ")", "dumper", "=", "self", ".", "dumpers", "[", "format", "]", "if", "\"path\"", "in", "options", "and", "not", "os", ".", "path", ".", "isdir", "(", "options", "[", "'path'", "]", ")", ":", "os", ".", "mkdir", "(", "options", "[", "'path'", "]", ")", "dumper", ".", "dump", "(", "catalogue", ",", "options", ")" ]
Writes translation from the catalogue according to the selected format. @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @type format: string @param format: The format to use to dump the messages @type options: array @param options: Options that are passed to the dumper @raises: ValueError
[ "Writes", "translation", "from", "the", "catalogue", "according", "to", "the", "selected", "format", "." ]
0aee83f434bd2d1b95767bcd63adb7ac7036c7df
https://github.com/adamziel/python_translate/blob/0aee83f434bd2d1b95767bcd63adb7ac7036c7df/python_translate/glue.py#L100-L123
train
acutesoftware/virtual-AI-simulator
scripts/recipe_finder.py
main
def main(): """ script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] Use this = Tofu Use this = Cheese """ s = rawdata.content.DataFiles() all_ingredients = list(s.get_collist_by_name(data_files[1]['file'], data_files[1]['col'])[0]) #find_best_ingredients(ingredients_on_hand, dinner_guests) best_ingred, worst_ingred = find_best_ingredients(all_ingredients, dinner_guests) print('best ingred = ', best_ingred) print('worst ingred = ', worst_ingred) for have in ingredients_on_hand: if have in best_ingred: print('Use this = ', have)
python
def main(): """ script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] Use this = Tofu Use this = Cheese """ s = rawdata.content.DataFiles() all_ingredients = list(s.get_collist_by_name(data_files[1]['file'], data_files[1]['col'])[0]) #find_best_ingredients(ingredients_on_hand, dinner_guests) best_ingred, worst_ingred = find_best_ingredients(all_ingredients, dinner_guests) print('best ingred = ', best_ingred) print('worst ingred = ', worst_ingred) for have in ingredients_on_hand: if have in best_ingred: print('Use this = ', have)
[ "def", "main", "(", ")", ":", "s", "=", "rawdata", ".", "content", ".", "DataFiles", "(", ")", "all_ingredients", "=", "list", "(", "s", ".", "get_collist_by_name", "(", "data_files", "[", "1", "]", "[", "'file'", "]", ",", "data_files", "[", "1", "]", "[", "'col'", "]", ")", "[", "0", "]", ")", "#find_best_ingredients(ingredients_on_hand, dinner_guests)", "best_ingred", ",", "worst_ingred", "=", "find_best_ingredients", "(", "all_ingredients", ",", "dinner_guests", ")", "print", "(", "'best ingred = '", ",", "best_ingred", ")", "print", "(", "'worst ingred = '", ",", "worst_ingred", ")", "for", "have", "in", "ingredients_on_hand", ":", "if", "have", "in", "best_ingred", ":", "print", "(", "'Use this = '", ",", "have", ")" ]
script to find a list of recipes for a group of people with specific likes and dislikes. Output of script best ingred = ['Tea', 'Tofu', 'Cheese', 'Cucumber', 'Salad', 'Chocolate'] worst ingred = ['Fish', 'Lamb', 'Pie', 'Asparagus', 'Chicken', 'Turnips'] Use this = Tofu Use this = Cheese
[ "script", "to", "find", "a", "list", "of", "recipes", "for", "a", "group", "of", "people", "with", "specific", "likes", "and", "dislikes", ".", "Output", "of", "script" ]
57de679a5b1a58c38fefe6aea58af1f3a7e79c58
https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/scripts/recipe_finder.py#L32-L55
train
Xion/taipan
taipan/algorithms.py
batch
def batch(iterable, n, fillvalue=None): """Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. If None, last batch might be shorter than ``n`` elements :return: Iterable of batches .. note:: This is an extended version of grouper() recipe from the :module:`itertools` module documentation. """ ensure_iterable(iterable) if not isinstance(n, Integral): raise TypeError("invalid number of elements in a batch") if not (n > 0): raise ValueError("number of elements in a batch must be positive") # since we must use ``izip_longest`` # (``izip`` fails if ``n`` is greater than length of ``iterable``), # we will apply some 'trimming' to resulting tuples if necessary if fillvalue is None: fillvalue = object() trimmer = lambda item: tuple(x for x in item if x is not fillvalue) else: trimmer = identity() args = [iter(iterable)] * n zipped = izip_longest(*args, fillvalue=fillvalue) return imap(trimmer, zipped)
python
def batch(iterable, n, fillvalue=None): """Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. If None, last batch might be shorter than ``n`` elements :return: Iterable of batches .. note:: This is an extended version of grouper() recipe from the :module:`itertools` module documentation. """ ensure_iterable(iterable) if not isinstance(n, Integral): raise TypeError("invalid number of elements in a batch") if not (n > 0): raise ValueError("number of elements in a batch must be positive") # since we must use ``izip_longest`` # (``izip`` fails if ``n`` is greater than length of ``iterable``), # we will apply some 'trimming' to resulting tuples if necessary if fillvalue is None: fillvalue = object() trimmer = lambda item: tuple(x for x in item if x is not fillvalue) else: trimmer = identity() args = [iter(iterable)] * n zipped = izip_longest(*args, fillvalue=fillvalue) return imap(trimmer, zipped)
[ "def", "batch", "(", "iterable", ",", "n", ",", "fillvalue", "=", "None", ")", ":", "ensure_iterable", "(", "iterable", ")", "if", "not", "isinstance", "(", "n", ",", "Integral", ")", ":", "raise", "TypeError", "(", "\"invalid number of elements in a batch\"", ")", "if", "not", "(", "n", ">", "0", ")", ":", "raise", "ValueError", "(", "\"number of elements in a batch must be positive\"", ")", "# since we must use ``izip_longest``", "# (``izip`` fails if ``n`` is greater than length of ``iterable``),", "# we will apply some 'trimming' to resulting tuples if necessary", "if", "fillvalue", "is", "None", ":", "fillvalue", "=", "object", "(", ")", "trimmer", "=", "lambda", "item", ":", "tuple", "(", "x", "for", "x", "in", "item", "if", "x", "is", "not", "fillvalue", ")", "else", ":", "trimmer", "=", "identity", "(", ")", "args", "=", "[", "iter", "(", "iterable", ")", "]", "*", "n", "zipped", "=", "izip_longest", "(", "*", "args", ",", "fillvalue", "=", "fillvalue", ")", "return", "imap", "(", "trimmer", ",", "zipped", ")" ]
Batches the elements of given iterable. Resulting iterable will yield tuples containing at most ``n`` elements (might be less if ``fillvalue`` isn't specified). :param n: Number of items in every batch :param fillvalue: Value to fill the last batch with. If None, last batch might be shorter than ``n`` elements :return: Iterable of batches .. note:: This is an extended version of grouper() recipe from the :module:`itertools` module documentation.
[ "Batches", "the", "elements", "of", "given", "iterable", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L24-L58
train
Xion/taipan
taipan/algorithms.py
intertwine
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ iterables = tuple(imap(ensure_iterable, iterables)) empty = object() return (item for iterable in izip_longest(*iterables, fillvalue=empty) for item in iterable if item is not empty)
python
def intertwine(*iterables): """Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted. """ iterables = tuple(imap(ensure_iterable, iterables)) empty = object() return (item for iterable in izip_longest(*iterables, fillvalue=empty) for item in iterable if item is not empty)
[ "def", "intertwine", "(", "*", "iterables", ")", ":", "iterables", "=", "tuple", "(", "imap", "(", "ensure_iterable", ",", "iterables", ")", ")", "empty", "=", "object", "(", ")", "return", "(", "item", "for", "iterable", "in", "izip_longest", "(", "*", "iterables", ",", "fillvalue", "=", "empty", ")", "for", "item", "in", "iterable", "if", "item", "is", "not", "empty", ")" ]
Constructs an iterable which intertwines given iterables. The resulting iterable will return an item from first sequence, then from second, etc. until the last one - and then another item from first, then from second, etc. - up until all iterables are exhausted.
[ "Constructs", "an", "iterable", "which", "intertwines", "given", "iterables", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L88-L100
train
Xion/taipan
taipan/algorithms.py
iterate
def iterate(iterator, n=None): """Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end. """ ensure_iterable(iterator) if n is None: deque(iterator, maxlen=0) else: next(islice(iterator, n, n), None)
python
def iterate(iterator, n=None): """Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end. """ ensure_iterable(iterator) if n is None: deque(iterator, maxlen=0) else: next(islice(iterator, n, n), None)
[ "def", "iterate", "(", "iterator", ",", "n", "=", "None", ")", ":", "ensure_iterable", "(", "iterator", ")", "if", "n", "is", "None", ":", "deque", "(", "iterator", ",", "maxlen", "=", "0", ")", "else", ":", "next", "(", "islice", "(", "iterator", ",", "n", ",", "n", ")", ",", "None", ")" ]
Efficiently advances the iterator N times; by default goes to its end. The actual loop is done "in C" and hence it is faster than equivalent 'for'. :param n: How much the iterator should be advanced. If None, it will be advanced until the end.
[ "Efficiently", "advances", "the", "iterator", "N", "times", ";", "by", "default", "goes", "to", "its", "end", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L103-L115
train
Xion/taipan
taipan/algorithms.py
unique
def unique(iterable, key=None): """Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed """ ensure_iterable(iterable) key = hash if key is None else ensure_callable(key) def generator(): seen = set() for elem in iterable: k = key(elem) if k not in seen: seen.add(k) yield elem return generator()
python
def unique(iterable, key=None): """Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed """ ensure_iterable(iterable) key = hash if key is None else ensure_callable(key) def generator(): seen = set() for elem in iterable: k = key(elem) if k not in seen: seen.add(k) yield elem return generator()
[ "def", "unique", "(", "iterable", ",", "key", "=", "None", ")", ":", "ensure_iterable", "(", "iterable", ")", "key", "=", "hash", "if", "key", "is", "None", "else", "ensure_callable", "(", "key", ")", "def", "generator", "(", ")", ":", "seen", "=", "set", "(", ")", "for", "elem", "in", "iterable", ":", "k", "=", "key", "(", "elem", ")", "if", "k", "not", "in", "seen", ":", "seen", ".", "add", "(", "k", ")", "yield", "elem", "return", "generator", "(", ")" ]
Removes duplicates from given iterable, using given key as criterion. :param key: Key function which returns a hashable, uniquely identifying an object. :return: Iterable with duplicates removed
[ "Removes", "duplicates", "from", "given", "iterable", "using", "given", "key", "as", "criterion", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L130-L149
train
Xion/taipan
taipan/algorithms.py
breadth_first
def breadth_first(start, expand): """Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order Example:: tree = json.loads(some_data) for item in breadth_first(tree, key_func('children', default=())): do_something_with(item) """ ensure_callable(expand) def generator(): queue = deque([start]) while queue: node = queue.popleft() yield node queue.extend(expand(node)) return generator()
python
def breadth_first(start, expand): """Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order Example:: tree = json.loads(some_data) for item in breadth_first(tree, key_func('children', default=())): do_something_with(item) """ ensure_callable(expand) def generator(): queue = deque([start]) while queue: node = queue.popleft() yield node queue.extend(expand(node)) return generator()
[ "def", "breadth_first", "(", "start", ",", "expand", ")", ":", "ensure_callable", "(", "expand", ")", "def", "generator", "(", ")", ":", "queue", "=", "deque", "(", "[", "start", "]", ")", "while", "queue", ":", "node", "=", "queue", ".", "popleft", "(", ")", "yield", "node", "queue", ".", "extend", "(", "expand", "(", "node", ")", ")", "return", "generator", "(", ")" ]
Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order Example:: tree = json.loads(some_data) for item in breadth_first(tree, key_func('children', default=())): do_something_with(item)
[ "Performs", "a", "breadth", "-", "first", "search", "of", "a", "graph", "-", "like", "structure", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L154-L178
train
Xion/taipan
taipan/algorithms.py
depth_first
def depth_first(start, descend): """Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Example:: for node in depth_first(graph, attr_func('adjacent')): visit(node) """ ensure_callable(descend) def generator(): stack = [start] while stack: node = stack.pop() yield node stack.extend(descend(node)) return generator()
python
def depth_first(start, descend): """Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Example:: for node in depth_first(graph, attr_func('adjacent')): visit(node) """ ensure_callable(descend) def generator(): stack = [start] while stack: node = stack.pop() yield node stack.extend(descend(node)) return generator()
[ "def", "depth_first", "(", "start", ",", "descend", ")", ":", "ensure_callable", "(", "descend", ")", "def", "generator", "(", ")", ":", "stack", "=", "[", "start", "]", "while", "stack", ":", "node", "=", "stack", ".", "pop", "(", ")", "yield", "node", "stack", ".", "extend", "(", "descend", "(", "node", ")", ")", "return", "generator", "(", ")" ]
Performs a depth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the DFS order Example:: for node in depth_first(graph, attr_func('adjacent')): visit(node)
[ "Performs", "a", "depth", "-", "first", "search", "of", "a", "graph", "-", "like", "structure", "." ]
f333f0287c8bd0915182c7d5308e5f05ef0cca78
https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/algorithms.py#L181-L204
train
maximkulkin/hypothesis-regex
hypothesis_regex.py
regex
def regex(regex): """Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled regex (specify flags in call to `re.compile()`) or inside pattern with (?iLmsux) group. Some tricky regular expressions are partly supported or not supported at all. "^" and "$" do not affect generation. Positive lookahead/lookbehind groups are considered normal groups. Negative lookahead/lookbehind groups do not do anything. Ternary regex groups ('(?(name)yes-pattern|no-pattern)') are not supported at all. """ if not hasattr(regex, 'pattern'): regex = re.compile(regex) pattern = regex.pattern flags = regex.flags codes = sre.parse(pattern) return _strategy(codes, Context(flags=flags)).filter(regex.match)
python
def regex(regex): """Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled regex (specify flags in call to `re.compile()`) or inside pattern with (?iLmsux) group. Some tricky regular expressions are partly supported or not supported at all. "^" and "$" do not affect generation. Positive lookahead/lookbehind groups are considered normal groups. Negative lookahead/lookbehind groups do not do anything. Ternary regex groups ('(?(name)yes-pattern|no-pattern)') are not supported at all. """ if not hasattr(regex, 'pattern'): regex = re.compile(regex) pattern = regex.pattern flags = regex.flags codes = sre.parse(pattern) return _strategy(codes, Context(flags=flags)).filter(regex.match)
[ "def", "regex", "(", "regex", ")", ":", "if", "not", "hasattr", "(", "regex", ",", "'pattern'", ")", ":", "regex", "=", "re", ".", "compile", "(", "regex", ")", "pattern", "=", "regex", ".", "pattern", "flags", "=", "regex", ".", "flags", "codes", "=", "sre", ".", "parse", "(", "pattern", ")", "return", "_strategy", "(", "codes", ",", "Context", "(", "flags", "=", "flags", ")", ")", ".", "filter", "(", "regex", ".", "match", ")" ]
Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled regex (specify flags in call to `re.compile()`) or inside pattern with (?iLmsux) group. Some tricky regular expressions are partly supported or not supported at all. "^" and "$" do not affect generation. Positive lookahead/lookbehind groups are considered normal groups. Negative lookahead/lookbehind groups do not do anything. Ternary regex groups ('(?(name)yes-pattern|no-pattern)') are not supported at all.
[ "Return", "strategy", "that", "generates", "strings", "that", "match", "given", "regex", "." ]
dd139e97f5ef555dc61e9636bbe96558a5c7801f
https://github.com/maximkulkin/hypothesis-regex/blob/dd139e97f5ef555dc61e9636bbe96558a5c7801f/hypothesis_regex.py#L144-L167
train