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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
teepark/greenhouse | greenhouse/util.py | Event.set | def set(self):
"""set the event to triggered
after calling this method, all greenlets waiting on the event will be
rescheduled, and calling :meth:`wait` will not block until
:meth:`clear` has been called
"""
self._is_set = True
scheduler.state.awoken_from_events.update(self._waiters)
del self._waiters[:] | python | def set(self):
"""set the event to triggered
after calling this method, all greenlets waiting on the event will be
rescheduled, and calling :meth:`wait` will not block until
:meth:`clear` has been called
"""
self._is_set = True
scheduler.state.awoken_from_events.update(self._waiters)
del self._waiters[:] | [
"def",
"set",
"(",
"self",
")",
":",
"self",
".",
"_is_set",
"=",
"True",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"update",
"(",
"self",
".",
"_waiters",
")",
"del",
"self",
".",
"_waiters",
"[",
":",
"]"
] | set the event to triggered
after calling this method, all greenlets waiting on the event will be
rescheduled, and calling :meth:`wait` will not block until
:meth:`clear` has been called | [
"set",
"the",
"event",
"to",
"triggered"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L35-L44 | train |
teepark/greenhouse | greenhouse/util.py | Event.wait | def wait(self, timeout=None):
"""pause the current coroutine until this event is set
.. note::
this method will block the current coroutine if :meth:`set` has not
been called.
:param timeout:
the maximum amount of time to block in seconds. the default of
``None`` allows indefinite blocking.
:type timeout: number or None
:returns:
``True`` if a timeout was provided and was hit, otherwise ``False``
"""
if self._is_set:
return False
current = compat.getcurrent() # the waiting greenlet
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append(current)
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
scheduler.state.awoken_from_events.discard(current)
if current in self._waiters:
self._waiters.remove(current)
return True
return False | python | def wait(self, timeout=None):
"""pause the current coroutine until this event is set
.. note::
this method will block the current coroutine if :meth:`set` has not
been called.
:param timeout:
the maximum amount of time to block in seconds. the default of
``None`` allows indefinite blocking.
:type timeout: number or None
:returns:
``True`` if a timeout was provided and was hit, otherwise ``False``
"""
if self._is_set:
return False
current = compat.getcurrent() # the waiting greenlet
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append(current)
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
scheduler.state.awoken_from_events.discard(current)
if current in self._waiters:
self._waiters.remove(current)
return True
return False | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_is_set",
":",
"return",
"False",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"# the waiting greenlet",
"waketime",
"=",
"None",
"if",
"timeout",
"is",
"None",
"else",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"scheduler",
".",
"schedule_at",
"(",
"waketime",
",",
"current",
")",
"self",
".",
"_waiters",
".",
"append",
"(",
"current",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"if",
"not",
"scheduler",
".",
"_remove_timer",
"(",
"waketime",
",",
"current",
")",
":",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"discard",
"(",
"current",
")",
"if",
"current",
"in",
"self",
".",
"_waiters",
":",
"self",
".",
"_waiters",
".",
"remove",
"(",
"current",
")",
"return",
"True",
"return",
"False"
] | pause the current coroutine until this event is set
.. note::
this method will block the current coroutine if :meth:`set` has not
been called.
:param timeout:
the maximum amount of time to block in seconds. the default of
``None`` allows indefinite blocking.
:type timeout: number or None
:returns:
``True`` if a timeout was provided and was hit, otherwise ``False`` | [
"pause",
"the",
"current",
"coroutine",
"until",
"this",
"event",
"is",
"set"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L54-L89 | train |
teepark/greenhouse | greenhouse/util.py | RLock.acquire | def acquire(self, blocking=True):
"""acquire ownership of the lock
if the lock is already owned by the calling greenlet, a counter simply
gets incremented. if it is owned by a different greenlet then it will
block until the lock becomes available.
.. note::
this method will block the current coroutine if the lock is not
already owned by another coroutine.
:param blocking:
whether to block if the lock is owned by a different greenlet
(default ``True``)
:type blocking: bool
:returns:
a `bool` indicating whether the lock was acquired. In the default
case of ``blocking = True`` this will always be the case, but may
not be otherwise.
"""
current = compat.getcurrent()
if self._owner is current:
self._count += 1
return True
if self._locked and not blocking:
return False
if self._locked:
self._waiters.append(compat.getcurrent())
scheduler.state.mainloop.switch()
else:
self._locked = True
self._owner = current
self._count = 1
return True | python | def acquire(self, blocking=True):
"""acquire ownership of the lock
if the lock is already owned by the calling greenlet, a counter simply
gets incremented. if it is owned by a different greenlet then it will
block until the lock becomes available.
.. note::
this method will block the current coroutine if the lock is not
already owned by another coroutine.
:param blocking:
whether to block if the lock is owned by a different greenlet
(default ``True``)
:type blocking: bool
:returns:
a `bool` indicating whether the lock was acquired. In the default
case of ``blocking = True`` this will always be the case, but may
not be otherwise.
"""
current = compat.getcurrent()
if self._owner is current:
self._count += 1
return True
if self._locked and not blocking:
return False
if self._locked:
self._waiters.append(compat.getcurrent())
scheduler.state.mainloop.switch()
else:
self._locked = True
self._owner = current
self._count = 1
return True | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"if",
"self",
".",
"_owner",
"is",
"current",
":",
"self",
".",
"_count",
"+=",
"1",
"return",
"True",
"if",
"self",
".",
"_locked",
"and",
"not",
"blocking",
":",
"return",
"False",
"if",
"self",
".",
"_locked",
":",
"self",
".",
"_waiters",
".",
"append",
"(",
"compat",
".",
"getcurrent",
"(",
")",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"else",
":",
"self",
".",
"_locked",
"=",
"True",
"self",
".",
"_owner",
"=",
"current",
"self",
".",
"_count",
"=",
"1",
"return",
"True"
] | acquire ownership of the lock
if the lock is already owned by the calling greenlet, a counter simply
gets incremented. if it is owned by a different greenlet then it will
block until the lock becomes available.
.. note::
this method will block the current coroutine if the lock is not
already owned by another coroutine.
:param blocking:
whether to block if the lock is owned by a different greenlet
(default ``True``)
:type blocking: bool
:returns:
a `bool` indicating whether the lock was acquired. In the default
case of ``blocking = True`` this will always be the case, but may
not be otherwise. | [
"acquire",
"ownership",
"of",
"the",
"lock"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L186-L221 | train |
teepark/greenhouse | greenhouse/util.py | RLock.release | def release(self):
"""release one ownership of the lock
if the calling greenlet has :meth:`acquired <acquire>` the lock more
than once this will simply decrement the counter. if this is a final
release then a waiting greenlet is awoken
:raises:
`RuntimeError` if the calling greenlet is not the lock's owner
"""
if not self._locked or self._owner is not compat.getcurrent():
raise RuntimeError("cannot release un-acquired lock")
self._count -= 1
if self._count == 0:
self._owner = None
if self._waiters:
waiter = self._waiters.popleft()
self._locked = True
self._owner = waiter
scheduler.state.awoken_from_events.add(waiter)
else:
self._locked = False
self._owner = None | python | def release(self):
"""release one ownership of the lock
if the calling greenlet has :meth:`acquired <acquire>` the lock more
than once this will simply decrement the counter. if this is a final
release then a waiting greenlet is awoken
:raises:
`RuntimeError` if the calling greenlet is not the lock's owner
"""
if not self._locked or self._owner is not compat.getcurrent():
raise RuntimeError("cannot release un-acquired lock")
self._count -= 1
if self._count == 0:
self._owner = None
if self._waiters:
waiter = self._waiters.popleft()
self._locked = True
self._owner = waiter
scheduler.state.awoken_from_events.add(waiter)
else:
self._locked = False
self._owner = None | [
"def",
"release",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_locked",
"or",
"self",
".",
"_owner",
"is",
"not",
"compat",
".",
"getcurrent",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"cannot release un-acquired lock\"",
")",
"self",
".",
"_count",
"-=",
"1",
"if",
"self",
".",
"_count",
"==",
"0",
":",
"self",
".",
"_owner",
"=",
"None",
"if",
"self",
".",
"_waiters",
":",
"waiter",
"=",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
"self",
".",
"_locked",
"=",
"True",
"self",
".",
"_owner",
"=",
"waiter",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"add",
"(",
"waiter",
")",
"else",
":",
"self",
".",
"_locked",
"=",
"False",
"self",
".",
"_owner",
"=",
"None"
] | release one ownership of the lock
if the calling greenlet has :meth:`acquired <acquire>` the lock more
than once this will simply decrement the counter. if this is a final
release then a waiting greenlet is awoken
:raises:
`RuntimeError` if the calling greenlet is not the lock's owner | [
"release",
"one",
"ownership",
"of",
"the",
"lock"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L223-L245 | train |
teepark/greenhouse | greenhouse/util.py | Condition.wait | def wait(self, timeout=None):
"""wait to be woken up by the condition
.. note::
this method will block the current coroutine until a :meth:`notify`
wakes it back up.
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
self._lock.release()
scheduler.state.mainloop.switch()
self._lock.acquire()
if timeout is not None:
timedout = not scheduler._remove_timer(waketime, current)
if timedout:
self._waiters.remove((current, waketime))
return timedout
return False | python | def wait(self, timeout=None):
"""wait to be woken up by the condition
.. note::
this method will block the current coroutine until a :meth:`notify`
wakes it back up.
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
self._lock.release()
scheduler.state.mainloop.switch()
self._lock.acquire()
if timeout is not None:
timedout = not scheduler._remove_timer(waketime, current)
if timedout:
self._waiters.remove((current, waketime))
return timedout
return False | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_is_owned",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"cannot wait on un-acquired lock\"",
")",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"waketime",
"=",
"None",
"if",
"timeout",
"is",
"None",
"else",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"scheduler",
".",
"schedule_at",
"(",
"waketime",
",",
"current",
")",
"self",
".",
"_waiters",
".",
"append",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timedout",
"=",
"not",
"scheduler",
".",
"_remove_timer",
"(",
"waketime",
",",
"current",
")",
"if",
"timedout",
":",
"self",
".",
"_waiters",
".",
"remove",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"return",
"timedout",
"return",
"False"
] | wait to be woken up by the condition
.. note::
this method will block the current coroutine until a :meth:`notify`
wakes it back up.
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>` | [
"wait",
"to",
"be",
"woken",
"up",
"by",
"the",
"condition"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L274-L306 | train |
teepark/greenhouse | greenhouse/util.py | Condition.notify | def notify(self, num=1):
"""wake one or more waiting greenlets
:param num: the number of waiters to wake (default 1)
:type num: int
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
for i in xrange(min(num, len(self._waiters))):
scheduler.state.awoken_from_events.add(self._waiters.popleft()[0]) | python | def notify(self, num=1):
"""wake one or more waiting greenlets
:param num: the number of waiters to wake (default 1)
:type num: int
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
for i in xrange(min(num, len(self._waiters))):
scheduler.state.awoken_from_events.add(self._waiters.popleft()[0]) | [
"def",
"notify",
"(",
"self",
",",
"num",
"=",
"1",
")",
":",
"if",
"not",
"self",
".",
"_is_owned",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"cannot wait on un-acquired lock\"",
")",
"for",
"i",
"in",
"xrange",
"(",
"min",
"(",
"num",
",",
"len",
"(",
"self",
".",
"_waiters",
")",
")",
")",
":",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"add",
"(",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
"[",
"0",
"]",
")"
] | wake one or more waiting greenlets
:param num: the number of waiters to wake (default 1)
:type num: int
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>` | [
"wake",
"one",
"or",
"more",
"waiting",
"greenlets"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L308-L321 | train |
teepark/greenhouse | greenhouse/util.py | Condition.notify_all | def notify_all(self):
"""wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
scheduler.state.awoken_from_events.update(x[0] for x in self._waiters)
self._waiters.clear() | python | def notify_all(self):
"""wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>`
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
scheduler.state.awoken_from_events.update(x[0] for x in self._waiters)
self._waiters.clear() | [
"def",
"notify_all",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_owned",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"cannot wait on un-acquired lock\"",
")",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"update",
"(",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"self",
".",
"_waiters",
")",
"self",
".",
"_waiters",
".",
"clear",
"(",
")"
] | wake all waiting greenlets
:raises:
`RuntimeError` if the underlying lock hasn't been
:meth:`acquired <Lock.acquire>` | [
"wake",
"all",
"waiting",
"greenlets"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L323-L333 | train |
teepark/greenhouse | greenhouse/util.py | Semaphore.acquire | def acquire(self, blocking=True):
"""decrement the counter, waiting if it is already at 0
.. note::
if the counter is already at 0, this method will block the current
coroutine until a :meth:`release` increments it again.
:param blocking:
whether or not to block if the counter is already at 0 (default
``True``)
:type blocking: bool
:returns:
a bool, indicating whether the count was decremented (this can only
be ``False`` if ``blocking`` was ``False`` -- otherwise it would
have blocked until it could decrement the counter)
"""
if self._value:
self._value -= 1
return True
if not blocking:
return False
self._waiters.append(compat.getcurrent())
scheduler.state.mainloop.switch()
return True | python | def acquire(self, blocking=True):
"""decrement the counter, waiting if it is already at 0
.. note::
if the counter is already at 0, this method will block the current
coroutine until a :meth:`release` increments it again.
:param blocking:
whether or not to block if the counter is already at 0 (default
``True``)
:type blocking: bool
:returns:
a bool, indicating whether the count was decremented (this can only
be ``False`` if ``blocking`` was ``False`` -- otherwise it would
have blocked until it could decrement the counter)
"""
if self._value:
self._value -= 1
return True
if not blocking:
return False
self._waiters.append(compat.getcurrent())
scheduler.state.mainloop.switch()
return True | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
")",
":",
"if",
"self",
".",
"_value",
":",
"self",
".",
"_value",
"-=",
"1",
"return",
"True",
"if",
"not",
"blocking",
":",
"return",
"False",
"self",
".",
"_waiters",
".",
"append",
"(",
"compat",
".",
"getcurrent",
"(",
")",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"return",
"True"
] | decrement the counter, waiting if it is already at 0
.. note::
if the counter is already at 0, this method will block the current
coroutine until a :meth:`release` increments it again.
:param blocking:
whether or not to block if the counter is already at 0 (default
``True``)
:type blocking: bool
:returns:
a bool, indicating whether the count was decremented (this can only
be ``False`` if ``blocking`` was ``False`` -- otherwise it would
have blocked until it could decrement the counter) | [
"decrement",
"the",
"counter",
"waiting",
"if",
"it",
"is",
"already",
"at",
"0"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L351-L376 | train |
teepark/greenhouse | greenhouse/util.py | Semaphore.release | def release(self):
"increment the counter, waking up a waiter if there was any"
if self._waiters:
scheduler.state.awoken_from_events.add(self._waiters.popleft())
else:
self._value += 1 | python | def release(self):
"increment the counter, waking up a waiter if there was any"
if self._waiters:
scheduler.state.awoken_from_events.add(self._waiters.popleft())
else:
self._value += 1 | [
"def",
"release",
"(",
"self",
")",
":",
"if",
"self",
".",
"_waiters",
":",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"add",
"(",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
")",
"else",
":",
"self",
".",
"_value",
"+=",
"1"
] | increment the counter, waking up a waiter if there was any | [
"increment",
"the",
"counter",
"waking",
"up",
"a",
"waiter",
"if",
"there",
"was",
"any"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L378-L383 | train |
teepark/greenhouse | greenhouse/util.py | Thread.start | def start(self):
"""schedule to start the greenlet that runs this thread's function
:raises: `RuntimeError` if the thread has already been started
"""
if self._started:
raise RuntimeError("thread already started")
def run():
try:
self.run(*self._args, **self._kwargs)
except SystemExit:
# only shut down the thread, not the whole process
pass
finally:
self._deactivate()
self._glet = scheduler.greenlet(run)
self._ident = id(self._glet)
scheduler.schedule(self._glet)
self._activate() | python | def start(self):
"""schedule to start the greenlet that runs this thread's function
:raises: `RuntimeError` if the thread has already been started
"""
if self._started:
raise RuntimeError("thread already started")
def run():
try:
self.run(*self._args, **self._kwargs)
except SystemExit:
# only shut down the thread, not the whole process
pass
finally:
self._deactivate()
self._glet = scheduler.greenlet(run)
self._ident = id(self._glet)
scheduler.schedule(self._glet)
self._activate() | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"self",
".",
"_started",
":",
"raise",
"RuntimeError",
"(",
"\"thread already started\"",
")",
"def",
"run",
"(",
")",
":",
"try",
":",
"self",
".",
"run",
"(",
"*",
"self",
".",
"_args",
",",
"*",
"*",
"self",
".",
"_kwargs",
")",
"except",
"SystemExit",
":",
"# only shut down the thread, not the whole process",
"pass",
"finally",
":",
"self",
".",
"_deactivate",
"(",
")",
"self",
".",
"_glet",
"=",
"scheduler",
".",
"greenlet",
"(",
"run",
")",
"self",
".",
"_ident",
"=",
"id",
"(",
"self",
".",
"_glet",
")",
"scheduler",
".",
"schedule",
"(",
"self",
".",
"_glet",
")",
"self",
".",
"_activate",
"(",
")"
] | schedule to start the greenlet that runs this thread's function
:raises: `RuntimeError` if the thread has already been started | [
"schedule",
"to",
"start",
"the",
"greenlet",
"that",
"runs",
"this",
"thread",
"s",
"function"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L512-L532 | train |
teepark/greenhouse | greenhouse/util.py | Thread.join | def join(self, timeout=None):
"""block until this thread terminates
.. note::
this method can block the calling coroutine if the thread has not
yet completed.
:param timeout:
the maximum time to wait. with the default of ``None``, waits
indefinitely
:type timeout: int, float or None
:raises:
`RuntimeError` if called inside the thread, or it has not yet been
started
"""
if not self._started:
raise RuntimeError("cannot join thread before it is started")
if compat.getcurrent() is self._glet:
raise RuntimeError("cannot join current thread")
self._finished.wait(timeout) | python | def join(self, timeout=None):
"""block until this thread terminates
.. note::
this method can block the calling coroutine if the thread has not
yet completed.
:param timeout:
the maximum time to wait. with the default of ``None``, waits
indefinitely
:type timeout: int, float or None
:raises:
`RuntimeError` if called inside the thread, or it has not yet been
started
"""
if not self._started:
raise RuntimeError("cannot join thread before it is started")
if compat.getcurrent() is self._glet:
raise RuntimeError("cannot join current thread")
self._finished.wait(timeout) | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_started",
":",
"raise",
"RuntimeError",
"(",
"\"cannot join thread before it is started\"",
")",
"if",
"compat",
".",
"getcurrent",
"(",
")",
"is",
"self",
".",
"_glet",
":",
"raise",
"RuntimeError",
"(",
"\"cannot join current thread\"",
")",
"self",
".",
"_finished",
".",
"wait",
"(",
"timeout",
")"
] | block until this thread terminates
.. note::
this method can block the calling coroutine if the thread has not
yet completed.
:param timeout:
the maximum time to wait. with the default of ``None``, waits
indefinitely
:type timeout: int, float or None
:raises:
`RuntimeError` if called inside the thread, or it has not yet been
started | [
"block",
"until",
"this",
"thread",
"terminates"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L542-L563 | train |
teepark/greenhouse | greenhouse/util.py | Timer.cancel | def cancel(self):
"""attempt to prevent the timer from ever running its function
:returns:
``True`` if it was successful, ``False`` if the timer had already
run or been cancelled
"""
done = self.finished.is_set()
self.finished.set()
return not done | python | def cancel(self):
"""attempt to prevent the timer from ever running its function
:returns:
``True`` if it was successful, ``False`` if the timer had already
run or been cancelled
"""
done = self.finished.is_set()
self.finished.set()
return not done | [
"def",
"cancel",
"(",
"self",
")",
":",
"done",
"=",
"self",
".",
"finished",
".",
"is_set",
"(",
")",
"self",
".",
"finished",
".",
"set",
"(",
")",
"return",
"not",
"done"
] | attempt to prevent the timer from ever running its function
:returns:
``True`` if it was successful, ``False`` if the timer had already
run or been cancelled | [
"attempt",
"to",
"prevent",
"the",
"timer",
"from",
"ever",
"running",
"its",
"function"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L655-L664 | train |
teepark/greenhouse | greenhouse/util.py | Timer.wrap | def wrap(cls, secs, args=(), kwargs=None):
"""a classmethod decorator to immediately turn a function into a timer
.. note::
you won't find this on `threading.Timer`, it is an extension to
that API
this is a function *returning a decorator*, so it is used like so:
>>> @Timer.wrap(5, args=("world",))
>>> def say_hi_timer(name):
... print "hello, %s" % name
:param secs:
how far in the future to defer running the function in seconds
:type secs: int or float
:param args: positional arguments to pass to the function
:type args: tuple
:param kwargs: keyword arguments to pass to the function
:type kwargs: dict
:returns:
a decorator function which produces an unstarted :class:`Timer`
"""
def decorator(func):
return cls(secs, func, args, kwargs)
return decorator | python | def wrap(cls, secs, args=(), kwargs=None):
"""a classmethod decorator to immediately turn a function into a timer
.. note::
you won't find this on `threading.Timer`, it is an extension to
that API
this is a function *returning a decorator*, so it is used like so:
>>> @Timer.wrap(5, args=("world",))
>>> def say_hi_timer(name):
... print "hello, %s" % name
:param secs:
how far in the future to defer running the function in seconds
:type secs: int or float
:param args: positional arguments to pass to the function
:type args: tuple
:param kwargs: keyword arguments to pass to the function
:type kwargs: dict
:returns:
a decorator function which produces an unstarted :class:`Timer`
"""
def decorator(func):
return cls(secs, func, args, kwargs)
return decorator | [
"def",
"wrap",
"(",
"cls",
",",
"secs",
",",
"args",
"=",
"(",
")",
",",
"kwargs",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"return",
"cls",
"(",
"secs",
",",
"func",
",",
"args",
",",
"kwargs",
")",
"return",
"decorator"
] | a classmethod decorator to immediately turn a function into a timer
.. note::
you won't find this on `threading.Timer`, it is an extension to
that API
this is a function *returning a decorator*, so it is used like so:
>>> @Timer.wrap(5, args=("world",))
>>> def say_hi_timer(name):
... print "hello, %s" % name
:param secs:
how far in the future to defer running the function in seconds
:type secs: int or float
:param args: positional arguments to pass to the function
:type args: tuple
:param kwargs: keyword arguments to pass to the function
:type kwargs: dict
:returns:
a decorator function which produces an unstarted :class:`Timer` | [
"a",
"classmethod",
"decorator",
"to",
"immediately",
"turn",
"a",
"function",
"into",
"a",
"timer"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L673-L700 | train |
teepark/greenhouse | greenhouse/util.py | Queue.get | def get(self, block=True, timeout=None):
"""get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
whether to block if there is no data yet available (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting for data. with the
default of ``None``, can wait indefinitely. this is unused if
`block` is ``False``.
:type timeout: int, float or None
:raises:
:class:`Empty` if there is no data in the queue and block is
``False``, or `timeout` expires
:returns: something that was previously :meth:`put` in the queue
"""
if not self._data:
if not block:
raise Empty()
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
self._waiters.remove((current, waketime))
raise Empty()
if self.full() and self._waiters:
scheduler.schedule(self._waiters.popleft()[0])
return self._get() | python | def get(self, block=True, timeout=None):
"""get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
whether to block if there is no data yet available (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting for data. with the
default of ``None``, can wait indefinitely. this is unused if
`block` is ``False``.
:type timeout: int, float or None
:raises:
:class:`Empty` if there is no data in the queue and block is
``False``, or `timeout` expires
:returns: something that was previously :meth:`put` in the queue
"""
if not self._data:
if not block:
raise Empty()
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
self._waiters.remove((current, waketime))
raise Empty()
if self.full() and self._waiters:
scheduler.schedule(self._waiters.popleft()[0])
return self._get() | [
"def",
"get",
"(",
"self",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_data",
":",
"if",
"not",
"block",
":",
"raise",
"Empty",
"(",
")",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"waketime",
"=",
"None",
"if",
"timeout",
"is",
"None",
"else",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"scheduler",
".",
"schedule_at",
"(",
"waketime",
",",
"current",
")",
"self",
".",
"_waiters",
".",
"append",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"if",
"not",
"scheduler",
".",
"_remove_timer",
"(",
"waketime",
",",
"current",
")",
":",
"self",
".",
"_waiters",
".",
"remove",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"raise",
"Empty",
"(",
")",
"if",
"self",
".",
"full",
"(",
")",
"and",
"self",
".",
"_waiters",
":",
"scheduler",
".",
"schedule",
"(",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
"[",
"0",
"]",
")",
"return",
"self",
".",
"_get",
"(",
")"
] | get an item out of the queue
.. note::
if `block` is ``True`` (the default) and the queue is
:meth`empty`, this method will block the current coroutine until
something has been :meth:`put`.
:param block:
whether to block if there is no data yet available (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting for data. with the
default of ``None``, can wait indefinitely. this is unused if
`block` is ``False``.
:type timeout: int, float or None
:raises:
:class:`Empty` if there is no data in the queue and block is
``False``, or `timeout` expires
:returns: something that was previously :meth:`put` in the queue | [
"get",
"an",
"item",
"out",
"of",
"the",
"queue"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L743-L789 | train |
teepark/greenhouse | greenhouse/util.py | Queue.put | def put(self, item, block=True, timeout=None):
"""put an item into the queue
.. note::
if the queue was created with a `maxsize` and it is currently
:meth:`full`, this method will block the calling coroutine until
another coroutine :meth:`get`\ s an item.
:param item: the object to put into the queue, can be any type
:param block:
whether to block if the queue is already :meth:`full` (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting. with the default of
``None``, it can wait indefinitely. this is unused if `block` is
``False``.
:type timeout: int, float or None
:raises:
:class:`Full` if the queue is :meth:`full` and `block` is
``False``, or if `timeout` expires.
"""
if self.full():
if not block:
raise Full()
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
self._waiters.remove((current, waketime))
raise Full()
if self._waiters and not self.full():
scheduler.schedule(self._waiters.popleft()[0])
if not self._open_tasks:
self._jobs_done.clear()
self._open_tasks += 1
self._put(item) | python | def put(self, item, block=True, timeout=None):
"""put an item into the queue
.. note::
if the queue was created with a `maxsize` and it is currently
:meth:`full`, this method will block the calling coroutine until
another coroutine :meth:`get`\ s an item.
:param item: the object to put into the queue, can be any type
:param block:
whether to block if the queue is already :meth:`full` (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting. with the default of
``None``, it can wait indefinitely. this is unused if `block` is
``False``.
:type timeout: int, float or None
:raises:
:class:`Full` if the queue is :meth:`full` and `block` is
``False``, or if `timeout` expires.
"""
if self.full():
if not block:
raise Full()
current = compat.getcurrent()
waketime = None if timeout is None else time.time() + timeout
if timeout is not None:
scheduler.schedule_at(waketime, current)
self._waiters.append((current, waketime))
scheduler.state.mainloop.switch()
if timeout is not None:
if not scheduler._remove_timer(waketime, current):
self._waiters.remove((current, waketime))
raise Full()
if self._waiters and not self.full():
scheduler.schedule(self._waiters.popleft()[0])
if not self._open_tasks:
self._jobs_done.clear()
self._open_tasks += 1
self._put(item) | [
"def",
"put",
"(",
"self",
",",
"item",
",",
"block",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"full",
"(",
")",
":",
"if",
"not",
"block",
":",
"raise",
"Full",
"(",
")",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"waketime",
"=",
"None",
"if",
"timeout",
"is",
"None",
"else",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
":",
"scheduler",
".",
"schedule_at",
"(",
"waketime",
",",
"current",
")",
"self",
".",
"_waiters",
".",
"append",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"if",
"not",
"scheduler",
".",
"_remove_timer",
"(",
"waketime",
",",
"current",
")",
":",
"self",
".",
"_waiters",
".",
"remove",
"(",
"(",
"current",
",",
"waketime",
")",
")",
"raise",
"Full",
"(",
")",
"if",
"self",
".",
"_waiters",
"and",
"not",
"self",
".",
"full",
"(",
")",
":",
"scheduler",
".",
"schedule",
"(",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
"[",
"0",
"]",
")",
"if",
"not",
"self",
".",
"_open_tasks",
":",
"self",
".",
"_jobs_done",
".",
"clear",
"(",
")",
"self",
".",
"_open_tasks",
"+=",
"1",
"self",
".",
"_put",
"(",
"item",
")"
] | put an item into the queue
.. note::
if the queue was created with a `maxsize` and it is currently
:meth:`full`, this method will block the calling coroutine until
another coroutine :meth:`get`\ s an item.
:param item: the object to put into the queue, can be any type
:param block:
whether to block if the queue is already :meth:`full` (default
``True``)
:type block: bool
:param timeout:
the maximum time in seconds to block waiting. with the default of
``None``, it can wait indefinitely. this is unused if `block` is
``False``.
:type timeout: int, float or None
:raises:
:class:`Full` if the queue is :meth:`full` and `block` is
``False``, or if `timeout` expires. | [
"put",
"an",
"item",
"into",
"the",
"queue"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L803-L852 | train |
teepark/greenhouse | greenhouse/util.py | Counter.increment | def increment(self):
"increment the counter, and wake anyone waiting for the new value"
self._count += 1
waiters = self._waiters.pop(self._count, [])
if waiters:
scheduler.state.awoken_from_events.update(waiters) | python | def increment(self):
"increment the counter, and wake anyone waiting for the new value"
self._count += 1
waiters = self._waiters.pop(self._count, [])
if waiters:
scheduler.state.awoken_from_events.update(waiters) | [
"def",
"increment",
"(",
"self",
")",
":",
"self",
".",
"_count",
"+=",
"1",
"waiters",
"=",
"self",
".",
"_waiters",
".",
"pop",
"(",
"self",
".",
"_count",
",",
"[",
"]",
")",
"if",
"waiters",
":",
"scheduler",
".",
"state",
".",
"awoken_from_events",
".",
"update",
"(",
"waiters",
")"
] | increment the counter, and wake anyone waiting for the new value | [
"increment",
"the",
"counter",
"and",
"wake",
"anyone",
"waiting",
"for",
"the",
"new",
"value"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L952-L957 | train |
teepark/greenhouse | greenhouse/util.py | Counter.wait | def wait(self, until=0):
"""wait until the count has reached a particular number
.. note:: this method can block the current greenlet
:param until:
the number to wait for the count to get down (or up) to. default 0
:type until: int
"""
if self._count != until:
self._waiters.setdefault(until, []).append(compat.getcurrent())
scheduler.state.mainloop.switch() | python | def wait(self, until=0):
"""wait until the count has reached a particular number
.. note:: this method can block the current greenlet
:param until:
the number to wait for the count to get down (or up) to. default 0
:type until: int
"""
if self._count != until:
self._waiters.setdefault(until, []).append(compat.getcurrent())
scheduler.state.mainloop.switch() | [
"def",
"wait",
"(",
"self",
",",
"until",
"=",
"0",
")",
":",
"if",
"self",
".",
"_count",
"!=",
"until",
":",
"self",
".",
"_waiters",
".",
"setdefault",
"(",
"until",
",",
"[",
"]",
")",
".",
"append",
"(",
"compat",
".",
"getcurrent",
"(",
")",
")",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")"
] | wait until the count has reached a particular number
.. note:: this method can block the current greenlet
:param until:
the number to wait for the count to get down (or up) to. default 0
:type until: int | [
"wait",
"until",
"the",
"count",
"has",
"reached",
"a",
"particular",
"number"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L976-L987 | train |
teepark/greenhouse | greenhouse/ext/psycopg2.py | wait_callback | def wait_callback(connection):
"""callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the change and return to normal blocking operation, use
`psycopg2.extensions.set_wait_callback(None)``
"""
while 1:
state = connection.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
descriptor.wait_fds([(connection.fileno(), 1)])
elif state == extensions.POLL_WRITE:
descriptor.wait_fds([(connection.fileno(), 2)])
else:
raise psycopg2.OperationalError("Bad poll result: %r" % state) | python | def wait_callback(connection):
"""callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the change and return to normal blocking operation, use
`psycopg2.extensions.set_wait_callback(None)``
"""
while 1:
state = connection.poll()
if state == extensions.POLL_OK:
break
elif state == extensions.POLL_READ:
descriptor.wait_fds([(connection.fileno(), 1)])
elif state == extensions.POLL_WRITE:
descriptor.wait_fds([(connection.fileno(), 2)])
else:
raise psycopg2.OperationalError("Bad poll result: %r" % state) | [
"def",
"wait_callback",
"(",
"connection",
")",
":",
"while",
"1",
":",
"state",
"=",
"connection",
".",
"poll",
"(",
")",
"if",
"state",
"==",
"extensions",
".",
"POLL_OK",
":",
"break",
"elif",
"state",
"==",
"extensions",
".",
"POLL_READ",
":",
"descriptor",
".",
"wait_fds",
"(",
"[",
"(",
"connection",
".",
"fileno",
"(",
")",
",",
"1",
")",
"]",
")",
"elif",
"state",
"==",
"extensions",
".",
"POLL_WRITE",
":",
"descriptor",
".",
"wait_fds",
"(",
"[",
"(",
"connection",
".",
"fileno",
"(",
")",
",",
"2",
")",
"]",
")",
"else",
":",
"raise",
"psycopg2",
".",
"OperationalError",
"(",
"\"Bad poll result: %r\"",
"%",
"state",
")"
] | callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the change and return to normal blocking operation, use
`psycopg2.extensions.set_wait_callback(None)`` | [
"callback",
"function",
"suitable",
"for",
"psycopg2",
".",
"set_wait_callback"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/ext/psycopg2.py#L12-L32 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/dependency.py | Cdependency_extractor.get_path_to_root | def get_path_to_root(self,termid):
"""
Returns the dependency path from the term to the root
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of dependency relations
"""
# Get the sentence for the term
root = None
sentence = self.sentence_for_termid.get(termid)
if sentence is None: #try with the top node
top_node = self.top_relation_for_term.get(termid)
if top_node is not None:
root = top_node[1]
else:
return None
else:
if sentence in self.root_for_sentence:
root = self.root_for_sentence[sentence]
else:
##There is no root for this sentence
return None
# In this point top_node should be properly set
path = self.get_shortest_path(termid, root)
return path | python | def get_path_to_root(self,termid):
"""
Returns the dependency path from the term to the root
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of dependency relations
"""
# Get the sentence for the term
root = None
sentence = self.sentence_for_termid.get(termid)
if sentence is None: #try with the top node
top_node = self.top_relation_for_term.get(termid)
if top_node is not None:
root = top_node[1]
else:
return None
else:
if sentence in self.root_for_sentence:
root = self.root_for_sentence[sentence]
else:
##There is no root for this sentence
return None
# In this point top_node should be properly set
path = self.get_shortest_path(termid, root)
return path | [
"def",
"get_path_to_root",
"(",
"self",
",",
"termid",
")",
":",
"# Get the sentence for the term",
"root",
"=",
"None",
"sentence",
"=",
"self",
".",
"sentence_for_termid",
".",
"get",
"(",
"termid",
")",
"if",
"sentence",
"is",
"None",
":",
"#try with the top node",
"top_node",
"=",
"self",
".",
"top_relation_for_term",
".",
"get",
"(",
"termid",
")",
"if",
"top_node",
"is",
"not",
"None",
":",
"root",
"=",
"top_node",
"[",
"1",
"]",
"else",
":",
"return",
"None",
"else",
":",
"if",
"sentence",
"in",
"self",
".",
"root_for_sentence",
":",
"root",
"=",
"self",
".",
"root_for_sentence",
"[",
"sentence",
"]",
"else",
":",
"##There is no root for this sentence",
"return",
"None",
"# In this point top_node should be properly set",
"path",
"=",
"self",
".",
"get_shortest_path",
"(",
"termid",
",",
"root",
")",
"return",
"path"
] | Returns the dependency path from the term to the root
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of dependency relations | [
"Returns",
"the",
"dependency",
"path",
"from",
"the",
"term",
"to",
"the",
"root"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/dependency.py#L307-L333 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/dependency.py | Cdependency_extractor.get_full_dependents | def get_full_dependents(self, term_id, relations, counter = 0):
"""
Returns the complete list of dependents and embedded dependents of a certain term.
"""
counter += 1
deps = self.relations_for_term
if term_id in deps and len(deps.get(term_id)) > 0:
for dep in deps.get(term_id):
if not dep[1] in relations:
relations.append(dep[1])
if dep[1] in deps:
deprelations = self.get_full_dependents(dep[1], relations, counter)
for deprel in deprelations:
if not deprel in relations:
relations.append(deprel)
return relations | python | def get_full_dependents(self, term_id, relations, counter = 0):
"""
Returns the complete list of dependents and embedded dependents of a certain term.
"""
counter += 1
deps = self.relations_for_term
if term_id in deps and len(deps.get(term_id)) > 0:
for dep in deps.get(term_id):
if not dep[1] in relations:
relations.append(dep[1])
if dep[1] in deps:
deprelations = self.get_full_dependents(dep[1], relations, counter)
for deprel in deprelations:
if not deprel in relations:
relations.append(deprel)
return relations | [
"def",
"get_full_dependents",
"(",
"self",
",",
"term_id",
",",
"relations",
",",
"counter",
"=",
"0",
")",
":",
"counter",
"+=",
"1",
"deps",
"=",
"self",
".",
"relations_for_term",
"if",
"term_id",
"in",
"deps",
"and",
"len",
"(",
"deps",
".",
"get",
"(",
"term_id",
")",
")",
">",
"0",
":",
"for",
"dep",
"in",
"deps",
".",
"get",
"(",
"term_id",
")",
":",
"if",
"not",
"dep",
"[",
"1",
"]",
"in",
"relations",
":",
"relations",
".",
"append",
"(",
"dep",
"[",
"1",
"]",
")",
"if",
"dep",
"[",
"1",
"]",
"in",
"deps",
":",
"deprelations",
"=",
"self",
".",
"get_full_dependents",
"(",
"dep",
"[",
"1",
"]",
",",
"relations",
",",
"counter",
")",
"for",
"deprel",
"in",
"deprelations",
":",
"if",
"not",
"deprel",
"in",
"relations",
":",
"relations",
".",
"append",
"(",
"deprel",
")",
"return",
"relations"
] | Returns the complete list of dependents and embedded dependents of a certain term. | [
"Returns",
"the",
"complete",
"list",
"of",
"dependents",
"and",
"embedded",
"dependents",
"of",
"a",
"certain",
"term",
"."
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/dependency.py#L354-L370 | train |
nickpandolfi/Cyther | cyther/configuration.py | getDirsToInclude | def getDirsToInclude(string):
"""
Given a string of module names, it will return the 'include' directories
essential to their compilation as long as the module has the conventional
'get_include' function.
"""
dirs = []
a = string.strip()
obj = a.split('-')
if len(obj) == 1 and obj[0]:
for module in obj:
try:
exec('import {}'.format(module))
except ImportError:
raise FileNotFoundError("The module '{}' does not"
"exist".format(module))
try:
dirs.append('-I{}'.format(eval(module).get_include()))
except AttributeError:
print(NOT_NEEDED_MESSAGE.format(module))
return dirs | python | def getDirsToInclude(string):
"""
Given a string of module names, it will return the 'include' directories
essential to their compilation as long as the module has the conventional
'get_include' function.
"""
dirs = []
a = string.strip()
obj = a.split('-')
if len(obj) == 1 and obj[0]:
for module in obj:
try:
exec('import {}'.format(module))
except ImportError:
raise FileNotFoundError("The module '{}' does not"
"exist".format(module))
try:
dirs.append('-I{}'.format(eval(module).get_include()))
except AttributeError:
print(NOT_NEEDED_MESSAGE.format(module))
return dirs | [
"def",
"getDirsToInclude",
"(",
"string",
")",
":",
"dirs",
"=",
"[",
"]",
"a",
"=",
"string",
".",
"strip",
"(",
")",
"obj",
"=",
"a",
".",
"split",
"(",
"'-'",
")",
"if",
"len",
"(",
"obj",
")",
"==",
"1",
"and",
"obj",
"[",
"0",
"]",
":",
"for",
"module",
"in",
"obj",
":",
"try",
":",
"exec",
"(",
"'import {}'",
".",
"format",
"(",
"module",
")",
")",
"except",
"ImportError",
":",
"raise",
"FileNotFoundError",
"(",
"\"The module '{}' does not\"",
"\"exist\"",
".",
"format",
"(",
"module",
")",
")",
"try",
":",
"dirs",
".",
"append",
"(",
"'-I{}'",
".",
"format",
"(",
"eval",
"(",
"module",
")",
".",
"get_include",
"(",
")",
")",
")",
"except",
"AttributeError",
":",
"print",
"(",
"NOT_NEEDED_MESSAGE",
".",
"format",
"(",
"module",
")",
")",
"return",
"dirs"
] | Given a string of module names, it will return the 'include' directories
essential to their compilation as long as the module has the conventional
'get_include' function. | [
"Given",
"a",
"string",
"of",
"module",
"names",
"it",
"will",
"return",
"the",
"include",
"directories",
"essential",
"to",
"their",
"compilation",
"as",
"long",
"as",
"the",
"module",
"has",
"the",
"conventional",
"get_include",
"function",
"."
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L42-L63 | train |
nickpandolfi/Cyther | cyther/configuration.py | purge_configs | def purge_configs():
"""
These will delete any configs found in either the current directory or the
user's home directory
"""
user_config = path(CONFIG_FILE_NAME, root=USER)
inplace_config = path(CONFIG_FILE_NAME)
if os.path.isfile(user_config):
os.remove(user_config)
if os.path.isfile(inplace_config):
os.remove(inplace_config) | python | def purge_configs():
"""
These will delete any configs found in either the current directory or the
user's home directory
"""
user_config = path(CONFIG_FILE_NAME, root=USER)
inplace_config = path(CONFIG_FILE_NAME)
if os.path.isfile(user_config):
os.remove(user_config)
if os.path.isfile(inplace_config):
os.remove(inplace_config) | [
"def",
"purge_configs",
"(",
")",
":",
"user_config",
"=",
"path",
"(",
"CONFIG_FILE_NAME",
",",
"root",
"=",
"USER",
")",
"inplace_config",
"=",
"path",
"(",
"CONFIG_FILE_NAME",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"user_config",
")",
":",
"os",
".",
"remove",
"(",
"user_config",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"inplace_config",
")",
":",
"os",
".",
"remove",
"(",
"inplace_config",
")"
] | These will delete any configs found in either the current directory or the
user's home directory | [
"These",
"will",
"delete",
"any",
"configs",
"found",
"in",
"either",
"the",
"current",
"directory",
"or",
"the",
"user",
"s",
"home",
"directory"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L66-L78 | train |
nickpandolfi/Cyther | cyther/configuration.py | find_config_file | def find_config_file():
"""
Returns the path to the config file if found in either the current working
directory, or the user's home directory. If a config file is not found,
the function will return None.
"""
local_config_name = path(CONFIG_FILE_NAME)
if os.path.isfile(local_config_name):
return local_config_name
else:
user_config_name = path(CONFIG_FILE_NAME, root=USER)
if os.path.isfile(user_config_name):
return user_config_name
else:
return None | python | def find_config_file():
"""
Returns the path to the config file if found in either the current working
directory, or the user's home directory. If a config file is not found,
the function will return None.
"""
local_config_name = path(CONFIG_FILE_NAME)
if os.path.isfile(local_config_name):
return local_config_name
else:
user_config_name = path(CONFIG_FILE_NAME, root=USER)
if os.path.isfile(user_config_name):
return user_config_name
else:
return None | [
"def",
"find_config_file",
"(",
")",
":",
"local_config_name",
"=",
"path",
"(",
"CONFIG_FILE_NAME",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"local_config_name",
")",
":",
"return",
"local_config_name",
"else",
":",
"user_config_name",
"=",
"path",
"(",
"CONFIG_FILE_NAME",
",",
"root",
"=",
"USER",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"user_config_name",
")",
":",
"return",
"user_config_name",
"else",
":",
"return",
"None"
] | Returns the path to the config file if found in either the current working
directory, or the user's home directory. If a config file is not found,
the function will return None. | [
"Returns",
"the",
"path",
"to",
"the",
"config",
"file",
"if",
"found",
"in",
"either",
"the",
"current",
"working",
"directory",
"or",
"the",
"user",
"s",
"home",
"directory",
".",
"If",
"a",
"config",
"file",
"is",
"not",
"found",
"the",
"function",
"will",
"return",
"None",
"."
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L95-L109 | train |
nickpandolfi/Cyther | cyther/configuration.py | make_config_data | def make_config_data(*, guided):
"""
Makes the data necessary to construct a functional config file
"""
config_data = {}
config_data[INCLUDE_DIRS_KEY] = _make_include_dirs(guided=guided)
config_data[RUNTIME_DIRS_KEY] = _make_runtime_dirs(guided=guided)
config_data[RUNTIME_KEY] = _make_runtime()
return config_data | python | def make_config_data(*, guided):
"""
Makes the data necessary to construct a functional config file
"""
config_data = {}
config_data[INCLUDE_DIRS_KEY] = _make_include_dirs(guided=guided)
config_data[RUNTIME_DIRS_KEY] = _make_runtime_dirs(guided=guided)
config_data[RUNTIME_KEY] = _make_runtime()
return config_data | [
"def",
"make_config_data",
"(",
"*",
",",
"guided",
")",
":",
"config_data",
"=",
"{",
"}",
"config_data",
"[",
"INCLUDE_DIRS_KEY",
"]",
"=",
"_make_include_dirs",
"(",
"guided",
"=",
"guided",
")",
"config_data",
"[",
"RUNTIME_DIRS_KEY",
"]",
"=",
"_make_runtime_dirs",
"(",
"guided",
"=",
"guided",
")",
"config_data",
"[",
"RUNTIME_KEY",
"]",
"=",
"_make_runtime",
"(",
")",
"return",
"config_data"
] | Makes the data necessary to construct a functional config file | [
"Makes",
"the",
"data",
"necessary",
"to",
"construct",
"a",
"functional",
"config",
"file"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L308-L317 | train |
nickpandolfi/Cyther | cyther/configuration.py | generate_configurations | def generate_configurations(*, guided=False, fresh_start=False, save=False):
"""
If a config file is found in the standard locations, it will be loaded and
the config data would be retuned. If not found, then generate the data on
the fly, and return it
"""
if fresh_start:
purge_configs()
loaded_status, loaded_data = get_config()
if loaded_status != CONFIG_VALID:
if save:
make_config_file(guided=guided)
status, config_data = get_config()
else:
config_data = make_config_data(guided=guided)
else:
config_data = loaded_data
return config_data | python | def generate_configurations(*, guided=False, fresh_start=False, save=False):
"""
If a config file is found in the standard locations, it will be loaded and
the config data would be retuned. If not found, then generate the data on
the fly, and return it
"""
if fresh_start:
purge_configs()
loaded_status, loaded_data = get_config()
if loaded_status != CONFIG_VALID:
if save:
make_config_file(guided=guided)
status, config_data = get_config()
else:
config_data = make_config_data(guided=guided)
else:
config_data = loaded_data
return config_data | [
"def",
"generate_configurations",
"(",
"*",
",",
"guided",
"=",
"False",
",",
"fresh_start",
"=",
"False",
",",
"save",
"=",
"False",
")",
":",
"if",
"fresh_start",
":",
"purge_configs",
"(",
")",
"loaded_status",
",",
"loaded_data",
"=",
"get_config",
"(",
")",
"if",
"loaded_status",
"!=",
"CONFIG_VALID",
":",
"if",
"save",
":",
"make_config_file",
"(",
"guided",
"=",
"guided",
")",
"status",
",",
"config_data",
"=",
"get_config",
"(",
")",
"else",
":",
"config_data",
"=",
"make_config_data",
"(",
"guided",
"=",
"guided",
")",
"else",
":",
"config_data",
"=",
"loaded_data",
"return",
"config_data"
] | If a config file is found in the standard locations, it will be loaded and
the config data would be retuned. If not found, then generate the data on
the fly, and return it | [
"If",
"a",
"config",
"file",
"is",
"found",
"in",
"the",
"standard",
"locations",
"it",
"will",
"be",
"loaded",
"and",
"the",
"config",
"data",
"would",
"be",
"retuned",
".",
"If",
"not",
"found",
"then",
"generate",
"the",
"data",
"on",
"the",
"fly",
"and",
"return",
"it"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L333-L353 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.info | def info(self):
"""Execute an HTTP request to get details on a queue, and
return it.
"""
url = "queues/%s" % (self.name,)
result = self.client.get(url)
return result['body']['queue'] | python | def info(self):
"""Execute an HTTP request to get details on a queue, and
return it.
"""
url = "queues/%s" % (self.name,)
result = self.client.get(url)
return result['body']['queue'] | [
"def",
"info",
"(",
"self",
")",
":",
"url",
"=",
"\"queues/%s\"",
"%",
"(",
"self",
".",
"name",
",",
")",
"result",
"=",
"self",
".",
"client",
".",
"get",
"(",
"url",
")",
"return",
"result",
"[",
"'body'",
"]",
"[",
"'queue'",
"]"
] | Execute an HTTP request to get details on a queue, and
return it. | [
"Execute",
"an",
"HTTP",
"request",
"to",
"get",
"details",
"on",
"a",
"queue",
"and",
"return",
"it",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L33-L40 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.clear | def clear(self):
"""Executes an HTTP request to clear all contents of a queue."""
url = "queues/%s/messages" % self.name
result = self.client.delete(url = url,
body = json.dumps({}),
headers={'Content-Type': 'application/json'})
return result['body'] | python | def clear(self):
"""Executes an HTTP request to clear all contents of a queue."""
url = "queues/%s/messages" % self.name
result = self.client.delete(url = url,
body = json.dumps({}),
headers={'Content-Type': 'application/json'})
return result['body'] | [
"def",
"clear",
"(",
"self",
")",
":",
"url",
"=",
"\"queues/%s/messages\"",
"%",
"self",
".",
"name",
"result",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"url",
"=",
"url",
",",
"body",
"=",
"json",
".",
"dumps",
"(",
"{",
"}",
")",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"result",
"[",
"'body'",
"]"
] | Executes an HTTP request to clear all contents of a queue. | [
"Executes",
"an",
"HTTP",
"request",
"to",
"clear",
"all",
"contents",
"of",
"a",
"queue",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L54-L61 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.delete | def delete(self, message_id, reservation_id=None, subscriber_name=None):
"""Execute an HTTP request to delete a message from queue.
Arguments:
message_id -- The ID of the message to be deleted.
reservation_id -- Reservation Id of the message. Reserved message could not be deleted without reservation Id.
subscriber_name -- This is required to acknowledge push after long-processing of message is finished.
"""
url = "queues/%s/messages/%s" % (self.name, message_id)
qitems = {}
if reservation_id is not None:
qitems['reservation_id'] = reservation_id
if subscriber_name is not None:
qitems['subscriber_name'] = subscriber_name
body = json.dumps(qitems)
result = self.client.delete(url=url, body=body,
headers={'Content-Type': 'application/json'})
return result['body'] | python | def delete(self, message_id, reservation_id=None, subscriber_name=None):
"""Execute an HTTP request to delete a message from queue.
Arguments:
message_id -- The ID of the message to be deleted.
reservation_id -- Reservation Id of the message. Reserved message could not be deleted without reservation Id.
subscriber_name -- This is required to acknowledge push after long-processing of message is finished.
"""
url = "queues/%s/messages/%s" % (self.name, message_id)
qitems = {}
if reservation_id is not None:
qitems['reservation_id'] = reservation_id
if subscriber_name is not None:
qitems['subscriber_name'] = subscriber_name
body = json.dumps(qitems)
result = self.client.delete(url=url, body=body,
headers={'Content-Type': 'application/json'})
return result['body'] | [
"def",
"delete",
"(",
"self",
",",
"message_id",
",",
"reservation_id",
"=",
"None",
",",
"subscriber_name",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/messages/%s\"",
"%",
"(",
"self",
".",
"name",
",",
"message_id",
")",
"qitems",
"=",
"{",
"}",
"if",
"reservation_id",
"is",
"not",
"None",
":",
"qitems",
"[",
"'reservation_id'",
"]",
"=",
"reservation_id",
"if",
"subscriber_name",
"is",
"not",
"None",
":",
"qitems",
"[",
"'subscriber_name'",
"]",
"=",
"subscriber_name",
"body",
"=",
"json",
".",
"dumps",
"(",
"qitems",
")",
"result",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"url",
"=",
"url",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"result",
"[",
"'body'",
"]"
] | Execute an HTTP request to delete a message from queue.
Arguments:
message_id -- The ID of the message to be deleted.
reservation_id -- Reservation Id of the message. Reserved message could not be deleted without reservation Id.
subscriber_name -- This is required to acknowledge push after long-processing of message is finished. | [
"Execute",
"an",
"HTTP",
"request",
"to",
"delete",
"a",
"message",
"from",
"queue",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L63-L82 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.delete_multiple | def delete_multiple(self, ids=None, messages=None):
"""Execute an HTTP request to delete messages from queue.
Arguments:
ids -- A list of messages id to be deleted from the queue.
messages -- Response to message reserving.
"""
url = "queues/%s/messages" % self.name
items = None
if ids is None and messages is None:
raise Exception('Please, specify at least one parameter.')
if ids is not None:
items = [{'id': item} for item in ids]
if messages is not None:
items = [{'id': item['id'], 'reservation_id': item['reservation_id']} for item in
messages['messages']]
data = json.dumps({'ids': items})
result = self.client.delete(url=url, body=data,
headers={'Content-Type': 'application/json'})
return result['body'] | python | def delete_multiple(self, ids=None, messages=None):
"""Execute an HTTP request to delete messages from queue.
Arguments:
ids -- A list of messages id to be deleted from the queue.
messages -- Response to message reserving.
"""
url = "queues/%s/messages" % self.name
items = None
if ids is None and messages is None:
raise Exception('Please, specify at least one parameter.')
if ids is not None:
items = [{'id': item} for item in ids]
if messages is not None:
items = [{'id': item['id'], 'reservation_id': item['reservation_id']} for item in
messages['messages']]
data = json.dumps({'ids': items})
result = self.client.delete(url=url, body=data,
headers={'Content-Type': 'application/json'})
return result['body'] | [
"def",
"delete_multiple",
"(",
"self",
",",
"ids",
"=",
"None",
",",
"messages",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/messages\"",
"%",
"self",
".",
"name",
"items",
"=",
"None",
"if",
"ids",
"is",
"None",
"and",
"messages",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'Please, specify at least one parameter.'",
")",
"if",
"ids",
"is",
"not",
"None",
":",
"items",
"=",
"[",
"{",
"'id'",
":",
"item",
"}",
"for",
"item",
"in",
"ids",
"]",
"if",
"messages",
"is",
"not",
"None",
":",
"items",
"=",
"[",
"{",
"'id'",
":",
"item",
"[",
"'id'",
"]",
",",
"'reservation_id'",
":",
"item",
"[",
"'reservation_id'",
"]",
"}",
"for",
"item",
"in",
"messages",
"[",
"'messages'",
"]",
"]",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'ids'",
":",
"items",
"}",
")",
"result",
"=",
"self",
".",
"client",
".",
"delete",
"(",
"url",
"=",
"url",
",",
"body",
"=",
"data",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"result",
"[",
"'body'",
"]"
] | Execute an HTTP request to delete messages from queue.
Arguments:
ids -- A list of messages id to be deleted from the queue.
messages -- Response to message reserving. | [
"Execute",
"an",
"HTTP",
"request",
"to",
"delete",
"messages",
"from",
"queue",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L84-L106 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.post | def post(self, *messages):
"""Executes an HTTP request to create message on the queue.
Creates queue if not existed.
Arguments:
messages -- An array of messages to be added to the queue.
"""
url = "queues/%s/messages" % self.name
msgs = [{'body': msg} if isinstance(msg, basestring) else msg
for msg in messages]
data = json.dumps({'messages': msgs})
result = self.client.post(url=url, body=data,
headers={'Content-Type': 'application/json'})
return result['body'] | python | def post(self, *messages):
"""Executes an HTTP request to create message on the queue.
Creates queue if not existed.
Arguments:
messages -- An array of messages to be added to the queue.
"""
url = "queues/%s/messages" % self.name
msgs = [{'body': msg} if isinstance(msg, basestring) else msg
for msg in messages]
data = json.dumps({'messages': msgs})
result = self.client.post(url=url, body=data,
headers={'Content-Type': 'application/json'})
return result['body'] | [
"def",
"post",
"(",
"self",
",",
"*",
"messages",
")",
":",
"url",
"=",
"\"queues/%s/messages\"",
"%",
"self",
".",
"name",
"msgs",
"=",
"[",
"{",
"'body'",
":",
"msg",
"}",
"if",
"isinstance",
"(",
"msg",
",",
"basestring",
")",
"else",
"msg",
"for",
"msg",
"in",
"messages",
"]",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'messages'",
":",
"msgs",
"}",
")",
"result",
"=",
"self",
".",
"client",
".",
"post",
"(",
"url",
"=",
"url",
",",
"body",
"=",
"data",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"result",
"[",
"'body'",
"]"
] | Executes an HTTP request to create message on the queue.
Creates queue if not existed.
Arguments:
messages -- An array of messages to be added to the queue. | [
"Executes",
"an",
"HTTP",
"request",
"to",
"create",
"message",
"on",
"the",
"queue",
".",
"Creates",
"queue",
"if",
"not",
"existed",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L108-L124 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.reserve | def reserve(self, max=None, timeout=None, wait=None, delete=None):
"""Retrieves Messages from the queue and reserves it.
Arguments:
max -- The maximum number of messages to reserve. Defaults to 1.
timeout -- Timeout in seconds.
wait -- Time to long poll for messages, in seconds. Max is 30 seconds. Default 0.
delete -- If true, do not put each message back on to the queue after reserving. Default false.
"""
url = "queues/%s/reservations" % self.name
qitems = {}
if max is not None:
qitems['n'] = max
if timeout is not None:
qitems['timeout'] = timeout
if wait is not None:
qitems['wait'] = wait
if delete is not None:
qitems['delete'] = delete
body = json.dumps(qitems)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | python | def reserve(self, max=None, timeout=None, wait=None, delete=None):
"""Retrieves Messages from the queue and reserves it.
Arguments:
max -- The maximum number of messages to reserve. Defaults to 1.
timeout -- Timeout in seconds.
wait -- Time to long poll for messages, in seconds. Max is 30 seconds. Default 0.
delete -- If true, do not put each message back on to the queue after reserving. Default false.
"""
url = "queues/%s/reservations" % self.name
qitems = {}
if max is not None:
qitems['n'] = max
if timeout is not None:
qitems['timeout'] = timeout
if wait is not None:
qitems['wait'] = wait
if delete is not None:
qitems['delete'] = delete
body = json.dumps(qitems)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | [
"def",
"reserve",
"(",
"self",
",",
"max",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"wait",
"=",
"None",
",",
"delete",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/reservations\"",
"%",
"self",
".",
"name",
"qitems",
"=",
"{",
"}",
"if",
"max",
"is",
"not",
"None",
":",
"qitems",
"[",
"'n'",
"]",
"=",
"max",
"if",
"timeout",
"is",
"not",
"None",
":",
"qitems",
"[",
"'timeout'",
"]",
"=",
"timeout",
"if",
"wait",
"is",
"not",
"None",
":",
"qitems",
"[",
"'wait'",
"]",
"=",
"wait",
"if",
"delete",
"is",
"not",
"None",
":",
"qitems",
"[",
"'delete'",
"]",
"=",
"delete",
"body",
"=",
"json",
".",
"dumps",
"(",
"qitems",
")",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"url",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"response",
"[",
"'body'",
"]"
] | Retrieves Messages from the queue and reserves it.
Arguments:
max -- The maximum number of messages to reserve. Defaults to 1.
timeout -- Timeout in seconds.
wait -- Time to long poll for messages, in seconds. Max is 30 seconds. Default 0.
delete -- If true, do not put each message back on to the queue after reserving. Default false. | [
"Retrieves",
"Messages",
"from",
"the",
"queue",
"and",
"reserves",
"it",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L136-L160 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.touch | def touch(self, message_id, reservation_id, timeout=None):
"""Touching a reserved message extends its timeout to the duration specified when the message was created.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
timeout -- Optional. The timeout in seconds after which new reservation will expire.
"""
url = "queues/%s/messages/%s/touch" % (self.name, message_id)
qitems = {'reservation_id': reservation_id}
if timeout is not None:
qitems['timeout'] = timeout
body = json.dumps(qitems)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | python | def touch(self, message_id, reservation_id, timeout=None):
"""Touching a reserved message extends its timeout to the duration specified when the message was created.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
timeout -- Optional. The timeout in seconds after which new reservation will expire.
"""
url = "queues/%s/messages/%s/touch" % (self.name, message_id)
qitems = {'reservation_id': reservation_id}
if timeout is not None:
qitems['timeout'] = timeout
body = json.dumps(qitems)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | [
"def",
"touch",
"(",
"self",
",",
"message_id",
",",
"reservation_id",
",",
"timeout",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/messages/%s/touch\"",
"%",
"(",
"self",
".",
"name",
",",
"message_id",
")",
"qitems",
"=",
"{",
"'reservation_id'",
":",
"reservation_id",
"}",
"if",
"timeout",
"is",
"not",
"None",
":",
"qitems",
"[",
"'timeout'",
"]",
"=",
"timeout",
"body",
"=",
"json",
".",
"dumps",
"(",
"qitems",
")",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"url",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"response",
"[",
"'body'",
"]"
] | Touching a reserved message extends its timeout to the duration specified when the message was created.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
timeout -- Optional. The timeout in seconds after which new reservation will expire. | [
"Touching",
"a",
"reserved",
"message",
"extends",
"its",
"timeout",
"to",
"the",
"duration",
"specified",
"when",
"the",
"message",
"was",
"created",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L177-L194 | train |
iron-io/iron_mq_python | iron_mq.py | Queue.release | def release(self, message_id, reservation_id, delay=0):
"""Release locked message after specified time. If there is no message with such id on the queue.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
delay -- The time after which the message will be released.
"""
url = "queues/%s/messages/%s/release" % (self.name, message_id)
body = {'reservation_id': reservation_id}
if delay > 0:
body['delay'] = delay
body = json.dumps(body)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | python | def release(self, message_id, reservation_id, delay=0):
"""Release locked message after specified time. If there is no message with such id on the queue.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
delay -- The time after which the message will be released.
"""
url = "queues/%s/messages/%s/release" % (self.name, message_id)
body = {'reservation_id': reservation_id}
if delay > 0:
body['delay'] = delay
body = json.dumps(body)
response = self.client.post(url, body=body,
headers={'Content-Type': 'application/json'})
return response['body'] | [
"def",
"release",
"(",
"self",
",",
"message_id",
",",
"reservation_id",
",",
"delay",
"=",
"0",
")",
":",
"url",
"=",
"\"queues/%s/messages/%s/release\"",
"%",
"(",
"self",
".",
"name",
",",
"message_id",
")",
"body",
"=",
"{",
"'reservation_id'",
":",
"reservation_id",
"}",
"if",
"delay",
">",
"0",
":",
"body",
"[",
"'delay'",
"]",
"=",
"delay",
"body",
"=",
"json",
".",
"dumps",
"(",
"body",
")",
"response",
"=",
"self",
".",
"client",
".",
"post",
"(",
"url",
",",
"body",
"=",
"body",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"return",
"response",
"[",
"'body'",
"]"
] | Release locked message after specified time. If there is no message with such id on the queue.
Arguments:
message_id -- The ID of the message.
reservation_id -- Reservation Id of the message.
delay -- The time after which the message will be released. | [
"Release",
"locked",
"message",
"after",
"specified",
"time",
".",
"If",
"there",
"is",
"no",
"message",
"with",
"such",
"id",
"on",
"the",
"queue",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L196-L213 | train |
iron-io/iron_mq_python | iron_mq.py | IronMQ.queues | def queues(self, page=None, per_page=None, previous=None, prefix=None):
"""Execute an HTTP request to get a list of queues and return it.
Keyword arguments:
page -- The 0-based page to get queues from. Defaults to None, which
omits the parameter.
"""
options = {}
if page is not None:
raise Exception('page param is deprecated!')
if per_page is not None:
options['per_page'] = per_page
if previous is not None:
options['previous'] = previous
if prefix is not None:
options['prefix'] = prefix
query = urlencode(options)
url = 'queues'
if query != '':
url = "%s?%s" % (url, query)
result = self.client.get(url)
return [queue['name'] for queue in result['body']['queues']] | python | def queues(self, page=None, per_page=None, previous=None, prefix=None):
"""Execute an HTTP request to get a list of queues and return it.
Keyword arguments:
page -- The 0-based page to get queues from. Defaults to None, which
omits the parameter.
"""
options = {}
if page is not None:
raise Exception('page param is deprecated!')
if per_page is not None:
options['per_page'] = per_page
if previous is not None:
options['previous'] = previous
if prefix is not None:
options['prefix'] = prefix
query = urlencode(options)
url = 'queues'
if query != '':
url = "%s?%s" % (url, query)
result = self.client.get(url)
return [queue['name'] for queue in result['body']['queues']] | [
"def",
"queues",
"(",
"self",
",",
"page",
"=",
"None",
",",
"per_page",
"=",
"None",
",",
"previous",
"=",
"None",
",",
"prefix",
"=",
"None",
")",
":",
"options",
"=",
"{",
"}",
"if",
"page",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"'page param is deprecated!'",
")",
"if",
"per_page",
"is",
"not",
"None",
":",
"options",
"[",
"'per_page'",
"]",
"=",
"per_page",
"if",
"previous",
"is",
"not",
"None",
":",
"options",
"[",
"'previous'",
"]",
"=",
"previous",
"if",
"prefix",
"is",
"not",
"None",
":",
"options",
"[",
"'prefix'",
"]",
"=",
"prefix",
"query",
"=",
"urlencode",
"(",
"options",
")",
"url",
"=",
"'queues'",
"if",
"query",
"!=",
"''",
":",
"url",
"=",
"\"%s?%s\"",
"%",
"(",
"url",
",",
"query",
")",
"result",
"=",
"self",
".",
"client",
".",
"get",
"(",
"url",
")",
"return",
"[",
"queue",
"[",
"'name'",
"]",
"for",
"queue",
"in",
"result",
"[",
"'body'",
"]",
"[",
"'queues'",
"]",
"]"
] | Execute an HTTP request to get a list of queues and return it.
Keyword arguments:
page -- The 0-based page to get queues from. Defaults to None, which
omits the parameter. | [
"Execute",
"an",
"HTTP",
"request",
"to",
"get",
"a",
"list",
"of",
"queues",
"and",
"return",
"it",
"."
] | d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L318-L341 | train |
cltl/KafNafParserPy | KafNafParserPy/time_data.py | CtimeExpressions.get_timex | def get_timex(self, timex_id):
"""
Returns the timex object for the supplied identifier
@type timex_id: string
@param timex_id: timex identifier
"""
if timex_id in self.idx:
return Ctime(self.idx[timex_id])
else:
return None | python | def get_timex(self, timex_id):
"""
Returns the timex object for the supplied identifier
@type timex_id: string
@param timex_id: timex identifier
"""
if timex_id in self.idx:
return Ctime(self.idx[timex_id])
else:
return None | [
"def",
"get_timex",
"(",
"self",
",",
"timex_id",
")",
":",
"if",
"timex_id",
"in",
"self",
".",
"idx",
":",
"return",
"Ctime",
"(",
"self",
".",
"idx",
"[",
"timex_id",
"]",
")",
"else",
":",
"return",
"None"
] | Returns the timex object for the supplied identifier
@type timex_id: string
@param timex_id: timex identifier | [
"Returns",
"the",
"timex",
"object",
"for",
"the",
"supplied",
"identifier"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/time_data.py#L346-L355 | train |
cltl/KafNafParserPy | KafNafParserPy/time_data.py | CtimeExpressions.add_timex | def add_timex(self, timex_obj):
"""
Adds a timex object to the layer.
@type timex_obj: L{Ctime}
@param timex_obj: the timex object
"""
timex_id = timex_obj.get_id()
#check if id is not already present
if not timex_id in self.idx:
timex_node = timex_obj.get_node()
self.node.append(timex_node)
self.idx[timex_id] = timex_node
else:
#FIXME: what we want is that the element receives a new identifier that
#is not present in current element yet
print('Error: trying to add new element with existing identifier') | python | def add_timex(self, timex_obj):
"""
Adds a timex object to the layer.
@type timex_obj: L{Ctime}
@param timex_obj: the timex object
"""
timex_id = timex_obj.get_id()
#check if id is not already present
if not timex_id in self.idx:
timex_node = timex_obj.get_node()
self.node.append(timex_node)
self.idx[timex_id] = timex_node
else:
#FIXME: what we want is that the element receives a new identifier that
#is not present in current element yet
print('Error: trying to add new element with existing identifier') | [
"def",
"add_timex",
"(",
"self",
",",
"timex_obj",
")",
":",
"timex_id",
"=",
"timex_obj",
".",
"get_id",
"(",
")",
"#check if id is not already present",
"if",
"not",
"timex_id",
"in",
"self",
".",
"idx",
":",
"timex_node",
"=",
"timex_obj",
".",
"get_node",
"(",
")",
"self",
".",
"node",
".",
"append",
"(",
"timex_node",
")",
"self",
".",
"idx",
"[",
"timex_id",
"]",
"=",
"timex_node",
"else",
":",
"#FIXME: what we want is that the element receives a new identifier that",
"#is not present in current element yet",
"print",
"(",
"'Error: trying to add new element with existing identifier'",
")"
] | Adds a timex object to the layer.
@type timex_obj: L{Ctime}
@param timex_obj: the timex object | [
"Adds",
"a",
"timex",
"object",
"to",
"the",
"layer",
"."
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/time_data.py#L367-L383 | train |
sio2project/filetracker | filetracker/scripts/recover.py | ensure_storage_format | def ensure_storage_format(root_dir):
"""Checks if the directory looks like a filetracker storage.
Exits with error if it doesn't.
"""
if not os.path.isdir(os.path.join(root_dir, 'blobs')):
print('"blobs/" directory not found')
sys.exit(1)
if not os.path.isdir(os.path.join(root_dir, 'links')):
print('"links/" directory not found')
sys.exit(1)
if not os.path.isdir(os.path.join(root_dir, 'db')):
print('"db/" directory not found')
sys.exit(1) | python | def ensure_storage_format(root_dir):
"""Checks if the directory looks like a filetracker storage.
Exits with error if it doesn't.
"""
if not os.path.isdir(os.path.join(root_dir, 'blobs')):
print('"blobs/" directory not found')
sys.exit(1)
if not os.path.isdir(os.path.join(root_dir, 'links')):
print('"links/" directory not found')
sys.exit(1)
if not os.path.isdir(os.path.join(root_dir, 'db')):
print('"db/" directory not found')
sys.exit(1) | [
"def",
"ensure_storage_format",
"(",
"root_dir",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'blobs'",
")",
")",
":",
"print",
"(",
"'\"blobs/\" directory not found'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'links'",
")",
")",
":",
"print",
"(",
"'\"links/\" directory not found'",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root_dir",
",",
"'db'",
")",
")",
":",
"print",
"(",
"'\"db/\" directory not found'",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | Checks if the directory looks like a filetracker storage.
Exits with error if it doesn't. | [
"Checks",
"if",
"the",
"directory",
"looks",
"like",
"a",
"filetracker",
"storage",
".",
"Exits",
"with",
"error",
"if",
"it",
"doesn",
"t",
"."
] | 359b474850622e3d0c25ee2596d7242c02f84efb | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/scripts/recover.py#L132-L147 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | Cconstituency_extractor.get_deepest_phrase_for_termid | def get_deepest_phrase_for_termid(self,termid):
"""
Returns the deepest phrase type for the term identifier and the list of subsumed by the same element
@type termid: string
@param termid: term identifier
@rtype: (string,list)
@return: the label and list of terms subsumed
"""
terminal_id = self.terminal_for_term.get(termid)
label = None
subsumed = []
if terminal_id is not None:
first_path = self.paths_for_terminal[terminal_id][0]
first_phrase_id = first_path[1]
label = self.label_for_nonter.get(first_phrase_id)
subsumed = self.terms_subsumed_by_nonter.get(first_phrase_id,[])
return label,sorted(list(subsumed)) | python | def get_deepest_phrase_for_termid(self,termid):
"""
Returns the deepest phrase type for the term identifier and the list of subsumed by the same element
@type termid: string
@param termid: term identifier
@rtype: (string,list)
@return: the label and list of terms subsumed
"""
terminal_id = self.terminal_for_term.get(termid)
label = None
subsumed = []
if terminal_id is not None:
first_path = self.paths_for_terminal[terminal_id][0]
first_phrase_id = first_path[1]
label = self.label_for_nonter.get(first_phrase_id)
subsumed = self.terms_subsumed_by_nonter.get(first_phrase_id,[])
return label,sorted(list(subsumed)) | [
"def",
"get_deepest_phrase_for_termid",
"(",
"self",
",",
"termid",
")",
":",
"terminal_id",
"=",
"self",
".",
"terminal_for_term",
".",
"get",
"(",
"termid",
")",
"label",
"=",
"None",
"subsumed",
"=",
"[",
"]",
"if",
"terminal_id",
"is",
"not",
"None",
":",
"first_path",
"=",
"self",
".",
"paths_for_terminal",
"[",
"terminal_id",
"]",
"[",
"0",
"]",
"first_phrase_id",
"=",
"first_path",
"[",
"1",
"]",
"label",
"=",
"self",
".",
"label_for_nonter",
".",
"get",
"(",
"first_phrase_id",
")",
"subsumed",
"=",
"self",
".",
"terms_subsumed_by_nonter",
".",
"get",
"(",
"first_phrase_id",
",",
"[",
"]",
")",
"return",
"label",
",",
"sorted",
"(",
"list",
"(",
"subsumed",
")",
")"
] | Returns the deepest phrase type for the term identifier and the list of subsumed by the same element
@type termid: string
@param termid: term identifier
@rtype: (string,list)
@return: the label and list of terms subsumed | [
"Returns",
"the",
"deepest",
"phrase",
"type",
"for",
"the",
"term",
"identifier",
"and",
"the",
"list",
"of",
"subsumed",
"by",
"the",
"same",
"element"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L89-L105 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | Cconstituency_extractor.get_least_common_subsumer | def get_least_common_subsumer(self,from_tid,to_tid):
"""
Returns the deepest common subsumer among two terms
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: string
@return: the term identifier of the common subsumer
"""
termid_from = self.terminal_for_term.get(from_tid)
termid_to = self.terminal_for_term.get(to_tid)
path_from = self.paths_for_terminal[termid_from][0]
path_to = self.paths_for_terminal[termid_to][0]
common_nodes = set(path_from) & set(path_to)
if len(common_nodes) == 0:
return None
else:
indexes = []
for common_node in common_nodes:
index1 = path_from.index(common_node)
index2 = path_to.index(common_node)
indexes.append((common_node,index1+index2))
indexes.sort(key=itemgetter(1))
shortest_common = indexes[0][0]
return shortest_common | python | def get_least_common_subsumer(self,from_tid,to_tid):
"""
Returns the deepest common subsumer among two terms
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: string
@return: the term identifier of the common subsumer
"""
termid_from = self.terminal_for_term.get(from_tid)
termid_to = self.terminal_for_term.get(to_tid)
path_from = self.paths_for_terminal[termid_from][0]
path_to = self.paths_for_terminal[termid_to][0]
common_nodes = set(path_from) & set(path_to)
if len(common_nodes) == 0:
return None
else:
indexes = []
for common_node in common_nodes:
index1 = path_from.index(common_node)
index2 = path_to.index(common_node)
indexes.append((common_node,index1+index2))
indexes.sort(key=itemgetter(1))
shortest_common = indexes[0][0]
return shortest_common | [
"def",
"get_least_common_subsumer",
"(",
"self",
",",
"from_tid",
",",
"to_tid",
")",
":",
"termid_from",
"=",
"self",
".",
"terminal_for_term",
".",
"get",
"(",
"from_tid",
")",
"termid_to",
"=",
"self",
".",
"terminal_for_term",
".",
"get",
"(",
"to_tid",
")",
"path_from",
"=",
"self",
".",
"paths_for_terminal",
"[",
"termid_from",
"]",
"[",
"0",
"]",
"path_to",
"=",
"self",
".",
"paths_for_terminal",
"[",
"termid_to",
"]",
"[",
"0",
"]",
"common_nodes",
"=",
"set",
"(",
"path_from",
")",
"&",
"set",
"(",
"path_to",
")",
"if",
"len",
"(",
"common_nodes",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"indexes",
"=",
"[",
"]",
"for",
"common_node",
"in",
"common_nodes",
":",
"index1",
"=",
"path_from",
".",
"index",
"(",
"common_node",
")",
"index2",
"=",
"path_to",
".",
"index",
"(",
"common_node",
")",
"indexes",
".",
"append",
"(",
"(",
"common_node",
",",
"index1",
"+",
"index2",
")",
")",
"indexes",
".",
"sort",
"(",
"key",
"=",
"itemgetter",
"(",
"1",
")",
")",
"shortest_common",
"=",
"indexes",
"[",
"0",
"]",
"[",
"0",
"]",
"return",
"shortest_common"
] | Returns the deepest common subsumer among two terms
@type from_tid: string
@param from_tid: one term id
@type to_tid: string
@param to_tid: another term id
@rtype: string
@return: the term identifier of the common subsumer | [
"Returns",
"the",
"deepest",
"common",
"subsumer",
"among",
"two",
"terms"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L108-L134 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | Cconstituency_extractor.get_deepest_subsumer | def get_deepest_subsumer(self,list_terms):
'''
Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided
'''
#To store with how many terms every nonterminal appears
count_per_no_terminal = defaultdict(int)
#To store the total deep of each noter for all the term ides (as we want the deepest)
total_deep_per_no_terminal = defaultdict(int)
for term_id in list_terms:
terminal_id = self.terminal_for_term.get(term_id)
path = self.paths_for_terminal[terminal_id][0]
print(term_id, path)
for c,noter in enumerate(path):
count_per_no_terminal[noter] += 1
total_deep_per_no_terminal[noter] += c
deepest_and_common = None
deepest = 10000
for noterid, this_total in total_deep_per_no_terminal.items():
if count_per_no_terminal.get(noterid,-1) == len(list_terms): ##Only the nontarms that ocurr with all the term ids in the input
if this_total < deepest:
deepest = this_total
deepest_and_common = noterid
label = None
if deepest_and_common is not None:
label = self.label_for_nonter[deepest_and_common]
return deepest_and_common, label | python | def get_deepest_subsumer(self,list_terms):
'''
Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided
'''
#To store with how many terms every nonterminal appears
count_per_no_terminal = defaultdict(int)
#To store the total deep of each noter for all the term ides (as we want the deepest)
total_deep_per_no_terminal = defaultdict(int)
for term_id in list_terms:
terminal_id = self.terminal_for_term.get(term_id)
path = self.paths_for_terminal[terminal_id][0]
print(term_id, path)
for c,noter in enumerate(path):
count_per_no_terminal[noter] += 1
total_deep_per_no_terminal[noter] += c
deepest_and_common = None
deepest = 10000
for noterid, this_total in total_deep_per_no_terminal.items():
if count_per_no_terminal.get(noterid,-1) == len(list_terms): ##Only the nontarms that ocurr with all the term ids in the input
if this_total < deepest:
deepest = this_total
deepest_and_common = noterid
label = None
if deepest_and_common is not None:
label = self.label_for_nonter[deepest_and_common]
return deepest_and_common, label | [
"def",
"get_deepest_subsumer",
"(",
"self",
",",
"list_terms",
")",
":",
"#To store with how many terms every nonterminal appears",
"count_per_no_terminal",
"=",
"defaultdict",
"(",
"int",
")",
"#To store the total deep of each noter for all the term ides (as we want the deepest)",
"total_deep_per_no_terminal",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"term_id",
"in",
"list_terms",
":",
"terminal_id",
"=",
"self",
".",
"terminal_for_term",
".",
"get",
"(",
"term_id",
")",
"path",
"=",
"self",
".",
"paths_for_terminal",
"[",
"terminal_id",
"]",
"[",
"0",
"]",
"print",
"(",
"term_id",
",",
"path",
")",
"for",
"c",
",",
"noter",
"in",
"enumerate",
"(",
"path",
")",
":",
"count_per_no_terminal",
"[",
"noter",
"]",
"+=",
"1",
"total_deep_per_no_terminal",
"[",
"noter",
"]",
"+=",
"c",
"deepest_and_common",
"=",
"None",
"deepest",
"=",
"10000",
"for",
"noterid",
",",
"this_total",
"in",
"total_deep_per_no_terminal",
".",
"items",
"(",
")",
":",
"if",
"count_per_no_terminal",
".",
"get",
"(",
"noterid",
",",
"-",
"1",
")",
"==",
"len",
"(",
"list_terms",
")",
":",
"##Only the nontarms that ocurr with all the term ids in the input",
"if",
"this_total",
"<",
"deepest",
":",
"deepest",
"=",
"this_total",
"deepest_and_common",
"=",
"noterid",
"label",
"=",
"None",
"if",
"deepest_and_common",
"is",
"not",
"None",
":",
"label",
"=",
"self",
".",
"label_for_nonter",
"[",
"deepest_and_common",
"]",
"return",
"deepest_and_common",
",",
"label"
] | Returns the labels of the deepest node that subsumes all the terms in the list of terms id's provided | [
"Returns",
"the",
"labels",
"of",
"the",
"deepest",
"node",
"that",
"subsumes",
"all",
"the",
"terms",
"in",
"the",
"list",
"of",
"terms",
"id",
"s",
"provided"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L218-L248 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | Cconstituency_extractor.get_chunks | def get_chunks(self,chunk_type):
"""
Returns the chunks for a certain type
@type chunk_type: string
@param chunk_type: type of the chunk
@rtype: list
@return: the chunks for that type
"""
for nonter,this_type in self.label_for_nonter.items():
if this_type == chunk_type:
subsumed = self.terms_subsumed_by_nonter.get(nonter)
if subsumed is not None:
yield sorted(list(subsumed)) | python | def get_chunks(self,chunk_type):
"""
Returns the chunks for a certain type
@type chunk_type: string
@param chunk_type: type of the chunk
@rtype: list
@return: the chunks for that type
"""
for nonter,this_type in self.label_for_nonter.items():
if this_type == chunk_type:
subsumed = self.terms_subsumed_by_nonter.get(nonter)
if subsumed is not None:
yield sorted(list(subsumed)) | [
"def",
"get_chunks",
"(",
"self",
",",
"chunk_type",
")",
":",
"for",
"nonter",
",",
"this_type",
"in",
"self",
".",
"label_for_nonter",
".",
"items",
"(",
")",
":",
"if",
"this_type",
"==",
"chunk_type",
":",
"subsumed",
"=",
"self",
".",
"terms_subsumed_by_nonter",
".",
"get",
"(",
"nonter",
")",
"if",
"subsumed",
"is",
"not",
"None",
":",
"yield",
"sorted",
"(",
"list",
"(",
"subsumed",
")",
")"
] | Returns the chunks for a certain type
@type chunk_type: string
@param chunk_type: type of the chunk
@rtype: list
@return: the chunks for that type | [
"Returns",
"the",
"chunks",
"for",
"a",
"certain",
"type"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L270-L282 | train |
cltl/KafNafParserPy | KafNafParserPy/feature_extractor/constituency.py | Cconstituency_extractor.get_all_chunks_for_term | def get_all_chunks_for_term(self,termid):
"""
Returns all the chunks in which the term is contained
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of chunks
"""
terminal_id = self.terminal_for_term.get(termid)
paths = self.paths_for_terminal[terminal_id]
for path in paths:
for node in path:
this_type = self.label_for_nonter[node]
subsumed = self.terms_subsumed_by_nonter.get(node)
if subsumed is not None:
yield this_type,sorted(list(subsumed)) | python | def get_all_chunks_for_term(self,termid):
"""
Returns all the chunks in which the term is contained
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of chunks
"""
terminal_id = self.terminal_for_term.get(termid)
paths = self.paths_for_terminal[terminal_id]
for path in paths:
for node in path:
this_type = self.label_for_nonter[node]
subsumed = self.terms_subsumed_by_nonter.get(node)
if subsumed is not None:
yield this_type,sorted(list(subsumed)) | [
"def",
"get_all_chunks_for_term",
"(",
"self",
",",
"termid",
")",
":",
"terminal_id",
"=",
"self",
".",
"terminal_for_term",
".",
"get",
"(",
"termid",
")",
"paths",
"=",
"self",
".",
"paths_for_terminal",
"[",
"terminal_id",
"]",
"for",
"path",
"in",
"paths",
":",
"for",
"node",
"in",
"path",
":",
"this_type",
"=",
"self",
".",
"label_for_nonter",
"[",
"node",
"]",
"subsumed",
"=",
"self",
".",
"terms_subsumed_by_nonter",
".",
"get",
"(",
"node",
")",
"if",
"subsumed",
"is",
"not",
"None",
":",
"yield",
"this_type",
",",
"sorted",
"(",
"list",
"(",
"subsumed",
")",
")"
] | Returns all the chunks in which the term is contained
@type termid: string
@param termid: the term identifier
@rtype: list
@return: list of chunks | [
"Returns",
"all",
"the",
"chunks",
"in",
"which",
"the",
"term",
"is",
"contained"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L331-L346 | train |
polysquare/cmake-ast | cmakeast/ast.py | _lookup_enum_in_ns | def _lookup_enum_in_ns(namespace, value):
"""Return the attribute of namespace corresponding to value."""
for attribute in dir(namespace):
if getattr(namespace, attribute) == value:
return attribute | python | def _lookup_enum_in_ns(namespace, value):
"""Return the attribute of namespace corresponding to value."""
for attribute in dir(namespace):
if getattr(namespace, attribute) == value:
return attribute | [
"def",
"_lookup_enum_in_ns",
"(",
"namespace",
",",
"value",
")",
":",
"for",
"attribute",
"in",
"dir",
"(",
"namespace",
")",
":",
"if",
"getattr",
"(",
"namespace",
",",
"attribute",
")",
"==",
"value",
":",
"return",
"attribute"
] | Return the attribute of namespace corresponding to value. | [
"Return",
"the",
"attribute",
"of",
"namespace",
"corresponding",
"to",
"value",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L88-L92 | train |
polysquare/cmake-ast | cmakeast/ast.py | _is_word_type | def _is_word_type(token_type):
"""Return true if this is a word-type token."""
return token_type in [TokenType.Word,
TokenType.QuotedLiteral,
TokenType.UnquotedLiteral,
TokenType.Number,
TokenType.Deref] | python | def _is_word_type(token_type):
"""Return true if this is a word-type token."""
return token_type in [TokenType.Word,
TokenType.QuotedLiteral,
TokenType.UnquotedLiteral,
TokenType.Number,
TokenType.Deref] | [
"def",
"_is_word_type",
"(",
"token_type",
")",
":",
"return",
"token_type",
"in",
"[",
"TokenType",
".",
"Word",
",",
"TokenType",
".",
"QuotedLiteral",
",",
"TokenType",
".",
"UnquotedLiteral",
",",
"TokenType",
".",
"Number",
",",
"TokenType",
".",
"Deref",
"]"
] | Return true if this is a word-type token. | [
"Return",
"true",
"if",
"this",
"is",
"a",
"word",
"-",
"type",
"token",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L174-L180 | train |
polysquare/cmake-ast | cmakeast/ast.py | _is_in_comment_type | def _is_in_comment_type(token_type):
"""Return true if this kind of token can be inside a comment."""
return token_type in [TokenType.Comment,
TokenType.Newline,
TokenType.Whitespace,
TokenType.RST,
TokenType.BeginRSTComment,
TokenType.BeginInlineRST,
TokenType.EndInlineRST] | python | def _is_in_comment_type(token_type):
"""Return true if this kind of token can be inside a comment."""
return token_type in [TokenType.Comment,
TokenType.Newline,
TokenType.Whitespace,
TokenType.RST,
TokenType.BeginRSTComment,
TokenType.BeginInlineRST,
TokenType.EndInlineRST] | [
"def",
"_is_in_comment_type",
"(",
"token_type",
")",
":",
"return",
"token_type",
"in",
"[",
"TokenType",
".",
"Comment",
",",
"TokenType",
".",
"Newline",
",",
"TokenType",
".",
"Whitespace",
",",
"TokenType",
".",
"RST",
",",
"TokenType",
".",
"BeginRSTComment",
",",
"TokenType",
".",
"BeginInlineRST",
",",
"TokenType",
".",
"EndInlineRST",
"]"
] | Return true if this kind of token can be inside a comment. | [
"Return",
"true",
"if",
"this",
"kind",
"of",
"token",
"can",
"be",
"inside",
"a",
"comment",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L183-L191 | train |
polysquare/cmake-ast | cmakeast/ast.py | _get_string_type_from_token | def _get_string_type_from_token(token_type):
"""Return 'Single' or 'Double' depending on what kind of string this is."""
return_value = None
if token_type in [TokenType.BeginSingleQuotedLiteral,
TokenType.EndSingleQuotedLiteral]:
return_value = "Single"
elif token_type in [TokenType.BeginDoubleQuotedLiteral,
TokenType.EndDoubleQuotedLiteral]:
return_value = "Double"
assert return_value is not None
return return_value | python | def _get_string_type_from_token(token_type):
"""Return 'Single' or 'Double' depending on what kind of string this is."""
return_value = None
if token_type in [TokenType.BeginSingleQuotedLiteral,
TokenType.EndSingleQuotedLiteral]:
return_value = "Single"
elif token_type in [TokenType.BeginDoubleQuotedLiteral,
TokenType.EndDoubleQuotedLiteral]:
return_value = "Double"
assert return_value is not None
return return_value | [
"def",
"_get_string_type_from_token",
"(",
"token_type",
")",
":",
"return_value",
"=",
"None",
"if",
"token_type",
"in",
"[",
"TokenType",
".",
"BeginSingleQuotedLiteral",
",",
"TokenType",
".",
"EndSingleQuotedLiteral",
"]",
":",
"return_value",
"=",
"\"Single\"",
"elif",
"token_type",
"in",
"[",
"TokenType",
".",
"BeginDoubleQuotedLiteral",
",",
"TokenType",
".",
"EndDoubleQuotedLiteral",
"]",
":",
"return_value",
"=",
"\"Double\"",
"assert",
"return_value",
"is",
"not",
"None",
"return",
"return_value"
] | Return 'Single' or 'Double' depending on what kind of string this is. | [
"Return",
"Single",
"or",
"Double",
"depending",
"on",
"what",
"kind",
"of",
"string",
"this",
"is",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L212-L223 | train |
polysquare/cmake-ast | cmakeast/ast.py | _make_header_body_handler | def _make_header_body_handler(end_body_regex,
node_factory,
has_footer=True):
"""Utility function to make a handler for header-body node.
A header-body node is any node which has a single function-call
header and a body of statements inside of it
"""
def handler(tokens, tokens_len, body_index, function_call):
"""Handler function."""
def _end_header_body_definition(token_index, tokens):
"""Header body termination function."""
if end_body_regex.match(tokens[token_index].content):
try:
if tokens[token_index + 1].type == TokenType.LeftParen:
return True
except IndexError:
raise RuntimeError("Syntax Error")
return False
token_index, body = _ast_worker(tokens, tokens_len, body_index,
_end_header_body_definition)
extra_kwargs = {}
if has_footer:
# Handle footer
token_index, footer = _handle_function_call(tokens,
tokens_len,
token_index)
extra_kwargs = {"footer": footer}
return (token_index,
node_factory(header=function_call,
body=body.statements,
line=tokens[body_index].line,
col=tokens[body_index].col,
index=body_index,
**extra_kwargs))
return handler | python | def _make_header_body_handler(end_body_regex,
node_factory,
has_footer=True):
"""Utility function to make a handler for header-body node.
A header-body node is any node which has a single function-call
header and a body of statements inside of it
"""
def handler(tokens, tokens_len, body_index, function_call):
"""Handler function."""
def _end_header_body_definition(token_index, tokens):
"""Header body termination function."""
if end_body_regex.match(tokens[token_index].content):
try:
if tokens[token_index + 1].type == TokenType.LeftParen:
return True
except IndexError:
raise RuntimeError("Syntax Error")
return False
token_index, body = _ast_worker(tokens, tokens_len, body_index,
_end_header_body_definition)
extra_kwargs = {}
if has_footer:
# Handle footer
token_index, footer = _handle_function_call(tokens,
tokens_len,
token_index)
extra_kwargs = {"footer": footer}
return (token_index,
node_factory(header=function_call,
body=body.statements,
line=tokens[body_index].line,
col=tokens[body_index].col,
index=body_index,
**extra_kwargs))
return handler | [
"def",
"_make_header_body_handler",
"(",
"end_body_regex",
",",
"node_factory",
",",
"has_footer",
"=",
"True",
")",
":",
"def",
"handler",
"(",
"tokens",
",",
"tokens_len",
",",
"body_index",
",",
"function_call",
")",
":",
"\"\"\"Handler function.\"\"\"",
"def",
"_end_header_body_definition",
"(",
"token_index",
",",
"tokens",
")",
":",
"\"\"\"Header body termination function.\"\"\"",
"if",
"end_body_regex",
".",
"match",
"(",
"tokens",
"[",
"token_index",
"]",
".",
"content",
")",
":",
"try",
":",
"if",
"tokens",
"[",
"token_index",
"+",
"1",
"]",
".",
"type",
"==",
"TokenType",
".",
"LeftParen",
":",
"return",
"True",
"except",
"IndexError",
":",
"raise",
"RuntimeError",
"(",
"\"Syntax Error\"",
")",
"return",
"False",
"token_index",
",",
"body",
"=",
"_ast_worker",
"(",
"tokens",
",",
"tokens_len",
",",
"body_index",
",",
"_end_header_body_definition",
")",
"extra_kwargs",
"=",
"{",
"}",
"if",
"has_footer",
":",
"# Handle footer",
"token_index",
",",
"footer",
"=",
"_handle_function_call",
"(",
"tokens",
",",
"tokens_len",
",",
"token_index",
")",
"extra_kwargs",
"=",
"{",
"\"footer\"",
":",
"footer",
"}",
"return",
"(",
"token_index",
",",
"node_factory",
"(",
"header",
"=",
"function_call",
",",
"body",
"=",
"body",
".",
"statements",
",",
"line",
"=",
"tokens",
"[",
"body_index",
"]",
".",
"line",
",",
"col",
"=",
"tokens",
"[",
"body_index",
"]",
".",
"col",
",",
"index",
"=",
"body_index",
",",
"*",
"*",
"extra_kwargs",
")",
")",
"return",
"handler"
] | Utility function to make a handler for header-body node.
A header-body node is any node which has a single function-call
header and a body of statements inside of it | [
"Utility",
"function",
"to",
"make",
"a",
"handler",
"for",
"header",
"-",
"body",
"node",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L248-L289 | train |
polysquare/cmake-ast | cmakeast/ast.py | _handle_if_block | def _handle_if_block(tokens, tokens_len, body_index, function_call):
"""Special handler for if-blocks.
If blocks are special because they can have multiple bodies and have
multiple terminating keywords for each of those sub-bodies
"""
# First handle the if statement and body
next_index, if_statement = _IF_BLOCK_IF_HANDLER(tokens,
tokens_len,
body_index,
function_call)
elseif_statements = []
else_statement = None
footer = None
# Keep going until we hit endif
while True:
# Back up a bit until we found out what terminated the if statement
# body
assert _RE_END_IF_BODY.match(tokens[next_index].content)
terminator = tokens[next_index].content.lower()
if terminator == "endif":
next_index, footer = _handle_function_call(tokens,
tokens_len,
next_index)
break
next_index, header = _handle_function_call(tokens,
tokens_len,
next_index)
if terminator == "elseif":
next_index, elseif_stmnt = _ELSEIF_BLOCK_HANDLER(tokens,
tokens_len,
next_index + 1,
header)
elseif_statements.append(elseif_stmnt)
elif terminator == "else":
next_index, else_statement = _ELSE_BLOCK_HANDLER(tokens,
tokens_len,
next_index + 1,
header)
assert footer is not None
return next_index, IfBlock(if_statement=if_statement,
elseif_statements=elseif_statements,
else_statement=else_statement,
footer=footer,
line=if_statement.line,
col=if_statement.col,
index=body_index) | python | def _handle_if_block(tokens, tokens_len, body_index, function_call):
"""Special handler for if-blocks.
If blocks are special because they can have multiple bodies and have
multiple terminating keywords for each of those sub-bodies
"""
# First handle the if statement and body
next_index, if_statement = _IF_BLOCK_IF_HANDLER(tokens,
tokens_len,
body_index,
function_call)
elseif_statements = []
else_statement = None
footer = None
# Keep going until we hit endif
while True:
# Back up a bit until we found out what terminated the if statement
# body
assert _RE_END_IF_BODY.match(tokens[next_index].content)
terminator = tokens[next_index].content.lower()
if terminator == "endif":
next_index, footer = _handle_function_call(tokens,
tokens_len,
next_index)
break
next_index, header = _handle_function_call(tokens,
tokens_len,
next_index)
if terminator == "elseif":
next_index, elseif_stmnt = _ELSEIF_BLOCK_HANDLER(tokens,
tokens_len,
next_index + 1,
header)
elseif_statements.append(elseif_stmnt)
elif terminator == "else":
next_index, else_statement = _ELSE_BLOCK_HANDLER(tokens,
tokens_len,
next_index + 1,
header)
assert footer is not None
return next_index, IfBlock(if_statement=if_statement,
elseif_statements=elseif_statements,
else_statement=else_statement,
footer=footer,
line=if_statement.line,
col=if_statement.col,
index=body_index) | [
"def",
"_handle_if_block",
"(",
"tokens",
",",
"tokens_len",
",",
"body_index",
",",
"function_call",
")",
":",
"# First handle the if statement and body",
"next_index",
",",
"if_statement",
"=",
"_IF_BLOCK_IF_HANDLER",
"(",
"tokens",
",",
"tokens_len",
",",
"body_index",
",",
"function_call",
")",
"elseif_statements",
"=",
"[",
"]",
"else_statement",
"=",
"None",
"footer",
"=",
"None",
"# Keep going until we hit endif",
"while",
"True",
":",
"# Back up a bit until we found out what terminated the if statement",
"# body",
"assert",
"_RE_END_IF_BODY",
".",
"match",
"(",
"tokens",
"[",
"next_index",
"]",
".",
"content",
")",
"terminator",
"=",
"tokens",
"[",
"next_index",
"]",
".",
"content",
".",
"lower",
"(",
")",
"if",
"terminator",
"==",
"\"endif\"",
":",
"next_index",
",",
"footer",
"=",
"_handle_function_call",
"(",
"tokens",
",",
"tokens_len",
",",
"next_index",
")",
"break",
"next_index",
",",
"header",
"=",
"_handle_function_call",
"(",
"tokens",
",",
"tokens_len",
",",
"next_index",
")",
"if",
"terminator",
"==",
"\"elseif\"",
":",
"next_index",
",",
"elseif_stmnt",
"=",
"_ELSEIF_BLOCK_HANDLER",
"(",
"tokens",
",",
"tokens_len",
",",
"next_index",
"+",
"1",
",",
"header",
")",
"elseif_statements",
".",
"append",
"(",
"elseif_stmnt",
")",
"elif",
"terminator",
"==",
"\"else\"",
":",
"next_index",
",",
"else_statement",
"=",
"_ELSE_BLOCK_HANDLER",
"(",
"tokens",
",",
"tokens_len",
",",
"next_index",
"+",
"1",
",",
"header",
")",
"assert",
"footer",
"is",
"not",
"None",
"return",
"next_index",
",",
"IfBlock",
"(",
"if_statement",
"=",
"if_statement",
",",
"elseif_statements",
"=",
"elseif_statements",
",",
"else_statement",
"=",
"else_statement",
",",
"footer",
"=",
"footer",
",",
"line",
"=",
"if_statement",
".",
"line",
",",
"col",
"=",
"if_statement",
".",
"col",
",",
"index",
"=",
"body_index",
")"
] | Special handler for if-blocks.
If blocks are special because they can have multiple bodies and have
multiple terminating keywords for each of those sub-bodies | [
"Special",
"handler",
"for",
"if",
"-",
"blocks",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L302-L355 | train |
polysquare/cmake-ast | cmakeast/ast.py | _handle_function_call | def _handle_function_call(tokens, tokens_len, index):
"""Handle function calls, which could include a control statement.
In CMake, all control flow statements are also function calls, so handle
the function call first and then direct tree construction to the
appropriate control flow statement constructor found in
_FUNCTION_CALL_DISAMBIGUATE
"""
def _end_function_call(token_index, tokens):
"""Function call termination detector."""
return tokens[token_index].type == TokenType.RightParen
# First handle the "function call"
next_index, call_body = _ast_worker(tokens, tokens_len,
index + 2,
_end_function_call)
function_call = FunctionCall(name=tokens[index].content,
arguments=call_body.arguments,
line=tokens[index].line,
col=tokens[index].col,
index=index)
# Next find a handler for the body and pass control to that
try:
handler = _FUNCTION_CALL_DISAMBIGUATE[tokens[index].content.lower()]
except KeyError:
handler = None
if handler:
return handler(tokens, tokens_len, next_index, function_call)
else:
return (next_index, function_call) | python | def _handle_function_call(tokens, tokens_len, index):
"""Handle function calls, which could include a control statement.
In CMake, all control flow statements are also function calls, so handle
the function call first and then direct tree construction to the
appropriate control flow statement constructor found in
_FUNCTION_CALL_DISAMBIGUATE
"""
def _end_function_call(token_index, tokens):
"""Function call termination detector."""
return tokens[token_index].type == TokenType.RightParen
# First handle the "function call"
next_index, call_body = _ast_worker(tokens, tokens_len,
index + 2,
_end_function_call)
function_call = FunctionCall(name=tokens[index].content,
arguments=call_body.arguments,
line=tokens[index].line,
col=tokens[index].col,
index=index)
# Next find a handler for the body and pass control to that
try:
handler = _FUNCTION_CALL_DISAMBIGUATE[tokens[index].content.lower()]
except KeyError:
handler = None
if handler:
return handler(tokens, tokens_len, next_index, function_call)
else:
return (next_index, function_call) | [
"def",
"_handle_function_call",
"(",
"tokens",
",",
"tokens_len",
",",
"index",
")",
":",
"def",
"_end_function_call",
"(",
"token_index",
",",
"tokens",
")",
":",
"\"\"\"Function call termination detector.\"\"\"",
"return",
"tokens",
"[",
"token_index",
"]",
".",
"type",
"==",
"TokenType",
".",
"RightParen",
"# First handle the \"function call\"",
"next_index",
",",
"call_body",
"=",
"_ast_worker",
"(",
"tokens",
",",
"tokens_len",
",",
"index",
"+",
"2",
",",
"_end_function_call",
")",
"function_call",
"=",
"FunctionCall",
"(",
"name",
"=",
"tokens",
"[",
"index",
"]",
".",
"content",
",",
"arguments",
"=",
"call_body",
".",
"arguments",
",",
"line",
"=",
"tokens",
"[",
"index",
"]",
".",
"line",
",",
"col",
"=",
"tokens",
"[",
"index",
"]",
".",
"col",
",",
"index",
"=",
"index",
")",
"# Next find a handler for the body and pass control to that",
"try",
":",
"handler",
"=",
"_FUNCTION_CALL_DISAMBIGUATE",
"[",
"tokens",
"[",
"index",
"]",
".",
"content",
".",
"lower",
"(",
")",
"]",
"except",
"KeyError",
":",
"handler",
"=",
"None",
"if",
"handler",
":",
"return",
"handler",
"(",
"tokens",
",",
"tokens_len",
",",
"next_index",
",",
"function_call",
")",
"else",
":",
"return",
"(",
"next_index",
",",
"function_call",
")"
] | Handle function calls, which could include a control statement.
In CMake, all control flow statements are also function calls, so handle
the function call first and then direct tree construction to the
appropriate control flow statement constructor found in
_FUNCTION_CALL_DISAMBIGUATE | [
"Handle",
"function",
"calls",
"which",
"could",
"include",
"a",
"control",
"statement",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L368-L400 | train |
polysquare/cmake-ast | cmakeast/ast.py | _ast_worker | def _ast_worker(tokens, tokens_len, index, term):
"""The main collector for all AST functions.
This function is called recursively to find both variable use and function
calls and returns a GenericBody with both those variables and function
calls hanging off of it. The caller can figure out what to do with both of
those
"""
statements = []
arguments = []
while index < tokens_len:
if term:
if term(index, tokens):
break
# Function call
if tokens[index].type == TokenType.Word and \
index + 1 < tokens_len and \
tokens[index + 1].type == TokenType.LeftParen:
index, statement = _handle_function_call(tokens,
tokens_len,
index)
statements.append(statement)
# Argument
elif _is_word_type(tokens[index].type):
arguments.append(Word(type=_word_type(tokens[index].type),
contents=tokens[index].content,
line=tokens[index].line,
col=tokens[index].col,
index=index))
index = index + 1
return (index, GenericBody(statements=statements,
arguments=arguments)) | python | def _ast_worker(tokens, tokens_len, index, term):
"""The main collector for all AST functions.
This function is called recursively to find both variable use and function
calls and returns a GenericBody with both those variables and function
calls hanging off of it. The caller can figure out what to do with both of
those
"""
statements = []
arguments = []
while index < tokens_len:
if term:
if term(index, tokens):
break
# Function call
if tokens[index].type == TokenType.Word and \
index + 1 < tokens_len and \
tokens[index + 1].type == TokenType.LeftParen:
index, statement = _handle_function_call(tokens,
tokens_len,
index)
statements.append(statement)
# Argument
elif _is_word_type(tokens[index].type):
arguments.append(Word(type=_word_type(tokens[index].type),
contents=tokens[index].content,
line=tokens[index].line,
col=tokens[index].col,
index=index))
index = index + 1
return (index, GenericBody(statements=statements,
arguments=arguments)) | [
"def",
"_ast_worker",
"(",
"tokens",
",",
"tokens_len",
",",
"index",
",",
"term",
")",
":",
"statements",
"=",
"[",
"]",
"arguments",
"=",
"[",
"]",
"while",
"index",
"<",
"tokens_len",
":",
"if",
"term",
":",
"if",
"term",
"(",
"index",
",",
"tokens",
")",
":",
"break",
"# Function call",
"if",
"tokens",
"[",
"index",
"]",
".",
"type",
"==",
"TokenType",
".",
"Word",
"and",
"index",
"+",
"1",
"<",
"tokens_len",
"and",
"tokens",
"[",
"index",
"+",
"1",
"]",
".",
"type",
"==",
"TokenType",
".",
"LeftParen",
":",
"index",
",",
"statement",
"=",
"_handle_function_call",
"(",
"tokens",
",",
"tokens_len",
",",
"index",
")",
"statements",
".",
"append",
"(",
"statement",
")",
"# Argument",
"elif",
"_is_word_type",
"(",
"tokens",
"[",
"index",
"]",
".",
"type",
")",
":",
"arguments",
".",
"append",
"(",
"Word",
"(",
"type",
"=",
"_word_type",
"(",
"tokens",
"[",
"index",
"]",
".",
"type",
")",
",",
"contents",
"=",
"tokens",
"[",
"index",
"]",
".",
"content",
",",
"line",
"=",
"tokens",
"[",
"index",
"]",
".",
"line",
",",
"col",
"=",
"tokens",
"[",
"index",
"]",
".",
"col",
",",
"index",
"=",
"index",
")",
")",
"index",
"=",
"index",
"+",
"1",
"return",
"(",
"index",
",",
"GenericBody",
"(",
"statements",
"=",
"statements",
",",
"arguments",
"=",
"arguments",
")",
")"
] | The main collector for all AST functions.
This function is called recursively to find both variable use and function
calls and returns a GenericBody with both those variables and function
calls hanging off of it. The caller can figure out what to do with both of
those | [
"The",
"main",
"collector",
"for",
"all",
"AST",
"functions",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L403-L438 | train |
polysquare/cmake-ast | cmakeast/ast.py | _scan_for_tokens | def _scan_for_tokens(contents):
"""Scan a string for tokens and return immediate form tokens."""
# Regexes are in priority order. Changing the order may alter the
# behavior of the lexer
scanner = re.Scanner([
# Things inside quotes
(r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])",
lambda s, t: (TokenType.QuotedLiteral, t)),
# Numbers on their own
(r"(?<![^\s\(])-?[0-9]+(?![^\s\)\(])", lambda s, t: (TokenType.Number,
t)),
# Left Paren
(r"\(", lambda s, t: (TokenType.LeftParen, t)),
# Right Paren
(r"\)", lambda s, t: (TokenType.RightParen, t)),
# Either a valid function name or variable name.
(r"(?<![^\s\(])[a-zA-z_][a-zA-Z0-9_]*(?![^\s\)\(])",
lambda s, t: (TokenType.Word, t)),
# Variable dereference.
(r"(?<![^\s\(])\${[a-zA-z_][a-zA-Z0-9_]*}(?![^\s\)])",
lambda s, t: (TokenType.Deref, t)),
# Newline
(r"\n", lambda s, t: (TokenType.Newline, t)),
# Whitespace
(r"\s+", lambda s, t: (TokenType.Whitespace, t)),
# The beginning of a double-quoted string, terminating at end of line
(r"(?<![^\s\(\\])[\"]([^\"]|\\[\"])*$",
lambda s, t: (TokenType.BeginDoubleQuotedLiteral, t)),
# The end of a double-quoted string
(r"[^\s]*(?<!\\)[\"](?![^\s\)])",
lambda s, t: (TokenType.EndDoubleQuotedLiteral, t)),
# The beginning of a single-quoted string, terminating at end of line
(r"(?<![^\s\(\\])[\']([^\']|\\[\'])*$",
lambda s, t: (TokenType.BeginSingleQuotedLiteral, t)),
# The end of a single-quoted string
(r"[^\s]*(?<!\\)[\'](?![^\s\)])",
lambda s, t: (TokenType.EndSingleQuotedLiteral, t)),
# Begin-RST Comment Block
(r"#.rst:$", lambda s, t: (TokenType.BeginRSTComment, t)),
# Begin Inline RST
(r"#\[=*\[.rst:$", lambda s, t: (TokenType.BeginInlineRST, t)),
# End Inline RST
(r"#\]=*\]$", lambda s, t: (TokenType.EndInlineRST, t)),
# Comment
(r"#", lambda s, t: (TokenType.Comment, t)),
# Catch-all for literals which are compound statements.
(r"([^\s\(\)]+|[^\s\(]*[^\)]|[^\(][^\s\)]*)",
lambda s, t: (TokenType.UnquotedLiteral, t))
])
tokens_return = []
lines = contents.splitlines(True)
lineno = 0
for line in lines:
lineno += 1
col = 1
tokens, remaining = scanner.scan(line)
if remaining != "":
msg = "Unknown tokens found on line {0}: {1}".format(lineno,
remaining)
raise RuntimeError(msg)
for token_type, token_contents in tokens:
tokens_return.append(Token(type=token_type,
content=token_contents,
line=lineno,
col=col))
col += len(token_contents)
return tokens_return | python | def _scan_for_tokens(contents):
"""Scan a string for tokens and return immediate form tokens."""
# Regexes are in priority order. Changing the order may alter the
# behavior of the lexer
scanner = re.Scanner([
# Things inside quotes
(r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])",
lambda s, t: (TokenType.QuotedLiteral, t)),
# Numbers on their own
(r"(?<![^\s\(])-?[0-9]+(?![^\s\)\(])", lambda s, t: (TokenType.Number,
t)),
# Left Paren
(r"\(", lambda s, t: (TokenType.LeftParen, t)),
# Right Paren
(r"\)", lambda s, t: (TokenType.RightParen, t)),
# Either a valid function name or variable name.
(r"(?<![^\s\(])[a-zA-z_][a-zA-Z0-9_]*(?![^\s\)\(])",
lambda s, t: (TokenType.Word, t)),
# Variable dereference.
(r"(?<![^\s\(])\${[a-zA-z_][a-zA-Z0-9_]*}(?![^\s\)])",
lambda s, t: (TokenType.Deref, t)),
# Newline
(r"\n", lambda s, t: (TokenType.Newline, t)),
# Whitespace
(r"\s+", lambda s, t: (TokenType.Whitespace, t)),
# The beginning of a double-quoted string, terminating at end of line
(r"(?<![^\s\(\\])[\"]([^\"]|\\[\"])*$",
lambda s, t: (TokenType.BeginDoubleQuotedLiteral, t)),
# The end of a double-quoted string
(r"[^\s]*(?<!\\)[\"](?![^\s\)])",
lambda s, t: (TokenType.EndDoubleQuotedLiteral, t)),
# The beginning of a single-quoted string, terminating at end of line
(r"(?<![^\s\(\\])[\']([^\']|\\[\'])*$",
lambda s, t: (TokenType.BeginSingleQuotedLiteral, t)),
# The end of a single-quoted string
(r"[^\s]*(?<!\\)[\'](?![^\s\)])",
lambda s, t: (TokenType.EndSingleQuotedLiteral, t)),
# Begin-RST Comment Block
(r"#.rst:$", lambda s, t: (TokenType.BeginRSTComment, t)),
# Begin Inline RST
(r"#\[=*\[.rst:$", lambda s, t: (TokenType.BeginInlineRST, t)),
# End Inline RST
(r"#\]=*\]$", lambda s, t: (TokenType.EndInlineRST, t)),
# Comment
(r"#", lambda s, t: (TokenType.Comment, t)),
# Catch-all for literals which are compound statements.
(r"([^\s\(\)]+|[^\s\(]*[^\)]|[^\(][^\s\)]*)",
lambda s, t: (TokenType.UnquotedLiteral, t))
])
tokens_return = []
lines = contents.splitlines(True)
lineno = 0
for line in lines:
lineno += 1
col = 1
tokens, remaining = scanner.scan(line)
if remaining != "":
msg = "Unknown tokens found on line {0}: {1}".format(lineno,
remaining)
raise RuntimeError(msg)
for token_type, token_contents in tokens:
tokens_return.append(Token(type=token_type,
content=token_contents,
line=lineno,
col=col))
col += len(token_contents)
return tokens_return | [
"def",
"_scan_for_tokens",
"(",
"contents",
")",
":",
"# Regexes are in priority order. Changing the order may alter the",
"# behavior of the lexer",
"scanner",
"=",
"re",
".",
"Scanner",
"(",
"[",
"# Things inside quotes",
"(",
"r\"(?<![^\\s\\(])([\\\"\\'])(?:(?=(\\\\?))\\2.)*?\\1(?![^\\s\\)])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"QuotedLiteral",
",",
"t",
")",
")",
",",
"# Numbers on their own",
"(",
"r\"(?<![^\\s\\(])-?[0-9]+(?![^\\s\\)\\(])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Number",
",",
"t",
")",
")",
",",
"# Left Paren",
"(",
"r\"\\(\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"LeftParen",
",",
"t",
")",
")",
",",
"# Right Paren",
"(",
"r\"\\)\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"RightParen",
",",
"t",
")",
")",
",",
"# Either a valid function name or variable name.",
"(",
"r\"(?<![^\\s\\(])[a-zA-z_][a-zA-Z0-9_]*(?![^\\s\\)\\(])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Word",
",",
"t",
")",
")",
",",
"# Variable dereference.",
"(",
"r\"(?<![^\\s\\(])\\${[a-zA-z_][a-zA-Z0-9_]*}(?![^\\s\\)])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Deref",
",",
"t",
")",
")",
",",
"# Newline",
"(",
"r\"\\n\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Newline",
",",
"t",
")",
")",
",",
"# Whitespace",
"(",
"r\"\\s+\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Whitespace",
",",
"t",
")",
")",
",",
"# The beginning of a double-quoted string, terminating at end of line",
"(",
"r\"(?<![^\\s\\(\\\\])[\\\"]([^\\\"]|\\\\[\\\"])*$\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"BeginDoubleQuotedLiteral",
",",
"t",
")",
")",
",",
"# The end of a double-quoted string",
"(",
"r\"[^\\s]*(?<!\\\\)[\\\"](?![^\\s\\)])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"EndDoubleQuotedLiteral",
",",
"t",
")",
")",
",",
"# The beginning of a single-quoted string, terminating at end of line",
"(",
"r\"(?<![^\\s\\(\\\\])[\\']([^\\']|\\\\[\\'])*$\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"BeginSingleQuotedLiteral",
",",
"t",
")",
")",
",",
"# The end of a single-quoted string",
"(",
"r\"[^\\s]*(?<!\\\\)[\\'](?![^\\s\\)])\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"EndSingleQuotedLiteral",
",",
"t",
")",
")",
",",
"# Begin-RST Comment Block",
"(",
"r\"#.rst:$\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"BeginRSTComment",
",",
"t",
")",
")",
",",
"# Begin Inline RST",
"(",
"r\"#\\[=*\\[.rst:$\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"BeginInlineRST",
",",
"t",
")",
")",
",",
"# End Inline RST",
"(",
"r\"#\\]=*\\]$\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"EndInlineRST",
",",
"t",
")",
")",
",",
"# Comment",
"(",
"r\"#\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"Comment",
",",
"t",
")",
")",
",",
"# Catch-all for literals which are compound statements.",
"(",
"r\"([^\\s\\(\\)]+|[^\\s\\(]*[^\\)]|[^\\(][^\\s\\)]*)\"",
",",
"lambda",
"s",
",",
"t",
":",
"(",
"TokenType",
".",
"UnquotedLiteral",
",",
"t",
")",
")",
"]",
")",
"tokens_return",
"=",
"[",
"]",
"lines",
"=",
"contents",
".",
"splitlines",
"(",
"True",
")",
"lineno",
"=",
"0",
"for",
"line",
"in",
"lines",
":",
"lineno",
"+=",
"1",
"col",
"=",
"1",
"tokens",
",",
"remaining",
"=",
"scanner",
".",
"scan",
"(",
"line",
")",
"if",
"remaining",
"!=",
"\"\"",
":",
"msg",
"=",
"\"Unknown tokens found on line {0}: {1}\"",
".",
"format",
"(",
"lineno",
",",
"remaining",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"for",
"token_type",
",",
"token_contents",
"in",
"tokens",
":",
"tokens_return",
".",
"append",
"(",
"Token",
"(",
"type",
"=",
"token_type",
",",
"content",
"=",
"token_contents",
",",
"line",
"=",
"lineno",
",",
"col",
"=",
"col",
")",
")",
"col",
"+=",
"len",
"(",
"token_contents",
")",
"return",
"tokens_return"
] | Scan a string for tokens and return immediate form tokens. | [
"Scan",
"a",
"string",
"for",
"tokens",
"and",
"return",
"immediate",
"form",
"tokens",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L441-L513 | train |
polysquare/cmake-ast | cmakeast/ast.py | _replace_token_range | def _replace_token_range(tokens, start, end, replacement):
"""For a range indicated from start to end, replace with replacement."""
tokens = tokens[:start] + replacement + tokens[end:]
return tokens | python | def _replace_token_range(tokens, start, end, replacement):
"""For a range indicated from start to end, replace with replacement."""
tokens = tokens[:start] + replacement + tokens[end:]
return tokens | [
"def",
"_replace_token_range",
"(",
"tokens",
",",
"start",
",",
"end",
",",
"replacement",
")",
":",
"tokens",
"=",
"tokens",
"[",
":",
"start",
"]",
"+",
"replacement",
"+",
"tokens",
"[",
"end",
":",
"]",
"return",
"tokens"
] | For a range indicated from start to end, replace with replacement. | [
"For",
"a",
"range",
"indicated",
"from",
"start",
"to",
"end",
"replace",
"with",
"replacement",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L516-L519 | train |
polysquare/cmake-ast | cmakeast/ast.py | _is_really_comment | def _is_really_comment(tokens, index):
"""Return true if the token at index is really a comment."""
if tokens[index].type == TokenType.Comment:
return True
# Really a comment in disguise!
try:
if tokens[index].content.lstrip()[0] == "#":
return True
except IndexError:
return False | python | def _is_really_comment(tokens, index):
"""Return true if the token at index is really a comment."""
if tokens[index].type == TokenType.Comment:
return True
# Really a comment in disguise!
try:
if tokens[index].content.lstrip()[0] == "#":
return True
except IndexError:
return False | [
"def",
"_is_really_comment",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"tokens",
"[",
"index",
"]",
".",
"type",
"==",
"TokenType",
".",
"Comment",
":",
"return",
"True",
"# Really a comment in disguise!",
"try",
":",
"if",
"tokens",
"[",
"index",
"]",
".",
"content",
".",
"lstrip",
"(",
")",
"[",
"0",
"]",
"==",
"\"#\"",
":",
"return",
"True",
"except",
"IndexError",
":",
"return",
"False"
] | Return true if the token at index is really a comment. | [
"Return",
"true",
"if",
"the",
"token",
"at",
"index",
"is",
"really",
"a",
"comment",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L522-L532 | train |
polysquare/cmake-ast | cmakeast/ast.py | _paste_tokens_line_by_line | def _paste_tokens_line_by_line(tokens, token_type, begin, end):
"""Return lines of tokens pasted together, line by line."""
block_index = begin
while block_index < end:
rst_line = tokens[block_index].line
line_traversal_index = block_index
pasted = ""
try:
while tokens[line_traversal_index].line == rst_line:
pasted += tokens[line_traversal_index].content
line_traversal_index += 1
except IndexError:
assert line_traversal_index == end
last_tokens_len = len(tokens)
tokens = _replace_token_range(tokens,
block_index,
line_traversal_index,
[Token(type=token_type,
content=pasted,
line=tokens[block_index].line,
col=tokens[block_index].col)])
end -= last_tokens_len - len(tokens)
block_index += 1
return (block_index, len(tokens), tokens) | python | def _paste_tokens_line_by_line(tokens, token_type, begin, end):
"""Return lines of tokens pasted together, line by line."""
block_index = begin
while block_index < end:
rst_line = tokens[block_index].line
line_traversal_index = block_index
pasted = ""
try:
while tokens[line_traversal_index].line == rst_line:
pasted += tokens[line_traversal_index].content
line_traversal_index += 1
except IndexError:
assert line_traversal_index == end
last_tokens_len = len(tokens)
tokens = _replace_token_range(tokens,
block_index,
line_traversal_index,
[Token(type=token_type,
content=pasted,
line=tokens[block_index].line,
col=tokens[block_index].col)])
end -= last_tokens_len - len(tokens)
block_index += 1
return (block_index, len(tokens), tokens) | [
"def",
"_paste_tokens_line_by_line",
"(",
"tokens",
",",
"token_type",
",",
"begin",
",",
"end",
")",
":",
"block_index",
"=",
"begin",
"while",
"block_index",
"<",
"end",
":",
"rst_line",
"=",
"tokens",
"[",
"block_index",
"]",
".",
"line",
"line_traversal_index",
"=",
"block_index",
"pasted",
"=",
"\"\"",
"try",
":",
"while",
"tokens",
"[",
"line_traversal_index",
"]",
".",
"line",
"==",
"rst_line",
":",
"pasted",
"+=",
"tokens",
"[",
"line_traversal_index",
"]",
".",
"content",
"line_traversal_index",
"+=",
"1",
"except",
"IndexError",
":",
"assert",
"line_traversal_index",
"==",
"end",
"last_tokens_len",
"=",
"len",
"(",
"tokens",
")",
"tokens",
"=",
"_replace_token_range",
"(",
"tokens",
",",
"block_index",
",",
"line_traversal_index",
",",
"[",
"Token",
"(",
"type",
"=",
"token_type",
",",
"content",
"=",
"pasted",
",",
"line",
"=",
"tokens",
"[",
"block_index",
"]",
".",
"line",
",",
"col",
"=",
"tokens",
"[",
"block_index",
"]",
".",
"col",
")",
"]",
")",
"end",
"-=",
"last_tokens_len",
"-",
"len",
"(",
"tokens",
")",
"block_index",
"+=",
"1",
"return",
"(",
"block_index",
",",
"len",
"(",
"tokens",
")",
",",
"tokens",
")"
] | Return lines of tokens pasted together, line by line. | [
"Return",
"lines",
"of",
"tokens",
"pasted",
"together",
"line",
"by",
"line",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L585-L611 | train |
polysquare/cmake-ast | cmakeast/ast.py | _find_recorder | def _find_recorder(recorder, tokens, index):
"""Given a current recorder and a token index, try to find a recorder."""
if recorder is None:
# See if we can start recording something
for recorder_factory in _RECORDERS:
recorder = recorder_factory.maybe_start_recording(tokens,
index)
if recorder is not None:
return recorder
return recorder | python | def _find_recorder(recorder, tokens, index):
"""Given a current recorder and a token index, try to find a recorder."""
if recorder is None:
# See if we can start recording something
for recorder_factory in _RECORDERS:
recorder = recorder_factory.maybe_start_recording(tokens,
index)
if recorder is not None:
return recorder
return recorder | [
"def",
"_find_recorder",
"(",
"recorder",
",",
"tokens",
",",
"index",
")",
":",
"if",
"recorder",
"is",
"None",
":",
"# See if we can start recording something",
"for",
"recorder_factory",
"in",
"_RECORDERS",
":",
"recorder",
"=",
"recorder_factory",
".",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
"if",
"recorder",
"is",
"not",
"None",
":",
"return",
"recorder",
"return",
"recorder"
] | Given a current recorder and a token index, try to find a recorder. | [
"Given",
"a",
"current",
"recorder",
"and",
"a",
"token",
"index",
"try",
"to",
"find",
"a",
"recorder",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L814-L824 | train |
polysquare/cmake-ast | cmakeast/ast.py | _compress_tokens | def _compress_tokens(tokens):
"""Paste multi-line strings, comments, RST etc together.
This function works by iterating over each over the _RECORDERS to determine
if we should start recording a token sequence for pasting together. If
it finds one, then we keep recording until that recorder is done and
returns a pasted together token sequence. Keep going until we reach
the end of the sequence.
The sequence is modified in place, so any function that modifies it
must return its new length. This is also why we use a while loop here.
"""
recorder = None
def _edge_case_stray_end_quoted(tokens, index):
"""Convert stray end_quoted_literals to unquoted_literals."""
# In this case, "tokenize" the matched token into what it would
# have looked like had the last quote not been there. Put the
# last quote on the end of the final token and call it an
# unquoted_literal
tokens[index] = Token(type=TokenType.UnquotedLiteral,
content=tokens[index].content,
line=tokens[index].line,
col=tokens[index].col)
tokens_len = len(tokens)
index = 0
with _EdgeCaseStrayParens() as edge_case_stray_parens:
edge_cases = [
(_is_paren_type, edge_case_stray_parens),
(_is_end_quoted_type, _edge_case_stray_end_quoted),
]
while index < tokens_len:
recorder = _find_recorder(recorder, tokens, index)
if recorder is not None:
# Do recording
result = recorder.consume_token(tokens, index, tokens_len)
if result is not None:
(index, tokens_len, tokens) = result
recorder = None
else:
# Handle edge cases
for matcher, handler in edge_cases:
if matcher(tokens[index].type):
handler(tokens, index)
index += 1
return tokens | python | def _compress_tokens(tokens):
"""Paste multi-line strings, comments, RST etc together.
This function works by iterating over each over the _RECORDERS to determine
if we should start recording a token sequence for pasting together. If
it finds one, then we keep recording until that recorder is done and
returns a pasted together token sequence. Keep going until we reach
the end of the sequence.
The sequence is modified in place, so any function that modifies it
must return its new length. This is also why we use a while loop here.
"""
recorder = None
def _edge_case_stray_end_quoted(tokens, index):
"""Convert stray end_quoted_literals to unquoted_literals."""
# In this case, "tokenize" the matched token into what it would
# have looked like had the last quote not been there. Put the
# last quote on the end of the final token and call it an
# unquoted_literal
tokens[index] = Token(type=TokenType.UnquotedLiteral,
content=tokens[index].content,
line=tokens[index].line,
col=tokens[index].col)
tokens_len = len(tokens)
index = 0
with _EdgeCaseStrayParens() as edge_case_stray_parens:
edge_cases = [
(_is_paren_type, edge_case_stray_parens),
(_is_end_quoted_type, _edge_case_stray_end_quoted),
]
while index < tokens_len:
recorder = _find_recorder(recorder, tokens, index)
if recorder is not None:
# Do recording
result = recorder.consume_token(tokens, index, tokens_len)
if result is not None:
(index, tokens_len, tokens) = result
recorder = None
else:
# Handle edge cases
for matcher, handler in edge_cases:
if matcher(tokens[index].type):
handler(tokens, index)
index += 1
return tokens | [
"def",
"_compress_tokens",
"(",
"tokens",
")",
":",
"recorder",
"=",
"None",
"def",
"_edge_case_stray_end_quoted",
"(",
"tokens",
",",
"index",
")",
":",
"\"\"\"Convert stray end_quoted_literals to unquoted_literals.\"\"\"",
"# In this case, \"tokenize\" the matched token into what it would",
"# have looked like had the last quote not been there. Put the",
"# last quote on the end of the final token and call it an",
"# unquoted_literal",
"tokens",
"[",
"index",
"]",
"=",
"Token",
"(",
"type",
"=",
"TokenType",
".",
"UnquotedLiteral",
",",
"content",
"=",
"tokens",
"[",
"index",
"]",
".",
"content",
",",
"line",
"=",
"tokens",
"[",
"index",
"]",
".",
"line",
",",
"col",
"=",
"tokens",
"[",
"index",
"]",
".",
"col",
")",
"tokens_len",
"=",
"len",
"(",
"tokens",
")",
"index",
"=",
"0",
"with",
"_EdgeCaseStrayParens",
"(",
")",
"as",
"edge_case_stray_parens",
":",
"edge_cases",
"=",
"[",
"(",
"_is_paren_type",
",",
"edge_case_stray_parens",
")",
",",
"(",
"_is_end_quoted_type",
",",
"_edge_case_stray_end_quoted",
")",
",",
"]",
"while",
"index",
"<",
"tokens_len",
":",
"recorder",
"=",
"_find_recorder",
"(",
"recorder",
",",
"tokens",
",",
"index",
")",
"if",
"recorder",
"is",
"not",
"None",
":",
"# Do recording",
"result",
"=",
"recorder",
".",
"consume_token",
"(",
"tokens",
",",
"index",
",",
"tokens_len",
")",
"if",
"result",
"is",
"not",
"None",
":",
"(",
"index",
",",
"tokens_len",
",",
"tokens",
")",
"=",
"result",
"recorder",
"=",
"None",
"else",
":",
"# Handle edge cases",
"for",
"matcher",
",",
"handler",
"in",
"edge_cases",
":",
"if",
"matcher",
"(",
"tokens",
"[",
"index",
"]",
".",
"type",
")",
":",
"handler",
"(",
"tokens",
",",
"index",
")",
"index",
"+=",
"1",
"return",
"tokens"
] | Paste multi-line strings, comments, RST etc together.
This function works by iterating over each over the _RECORDERS to determine
if we should start recording a token sequence for pasting together. If
it finds one, then we keep recording until that recorder is done and
returns a pasted together token sequence. Keep going until we reach
the end of the sequence.
The sequence is modified in place, so any function that modifies it
must return its new length. This is also why we use a while loop here. | [
"Paste",
"multi",
"-",
"line",
"strings",
"comments",
"RST",
"etc",
"together",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L827-L880 | train |
polysquare/cmake-ast | cmakeast/ast.py | tokenize | def tokenize(contents):
"""Parse a string called contents for CMake tokens."""
tokens = _scan_for_tokens(contents)
tokens = _compress_tokens(tokens)
tokens = [token for token in tokens if token.type != TokenType.Whitespace]
return tokens | python | def tokenize(contents):
"""Parse a string called contents for CMake tokens."""
tokens = _scan_for_tokens(contents)
tokens = _compress_tokens(tokens)
tokens = [token for token in tokens if token.type != TokenType.Whitespace]
return tokens | [
"def",
"tokenize",
"(",
"contents",
")",
":",
"tokens",
"=",
"_scan_for_tokens",
"(",
"contents",
")",
"tokens",
"=",
"_compress_tokens",
"(",
"tokens",
")",
"tokens",
"=",
"[",
"token",
"for",
"token",
"in",
"tokens",
"if",
"token",
".",
"type",
"!=",
"TokenType",
".",
"Whitespace",
"]",
"return",
"tokens"
] | Parse a string called contents for CMake tokens. | [
"Parse",
"a",
"string",
"called",
"contents",
"for",
"CMake",
"tokens",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L883-L888 | train |
polysquare/cmake-ast | cmakeast/ast.py | parse | def parse(contents, tokens=None):
"""Parse a string called contents for an AST and return it."""
# Shortcut for users who are interested in tokens
if tokens is None:
tokens = [t for t in tokenize(contents)]
token_index, body = _ast_worker(tokens, len(tokens), 0, None)
assert token_index == len(tokens)
assert body.arguments == []
return ToplevelBody(statements=body.statements) | python | def parse(contents, tokens=None):
"""Parse a string called contents for an AST and return it."""
# Shortcut for users who are interested in tokens
if tokens is None:
tokens = [t for t in tokenize(contents)]
token_index, body = _ast_worker(tokens, len(tokens), 0, None)
assert token_index == len(tokens)
assert body.arguments == []
return ToplevelBody(statements=body.statements) | [
"def",
"parse",
"(",
"contents",
",",
"tokens",
"=",
"None",
")",
":",
"# Shortcut for users who are interested in tokens",
"if",
"tokens",
"is",
"None",
":",
"tokens",
"=",
"[",
"t",
"for",
"t",
"in",
"tokenize",
"(",
"contents",
")",
"]",
"token_index",
",",
"body",
"=",
"_ast_worker",
"(",
"tokens",
",",
"len",
"(",
"tokens",
")",
",",
"0",
",",
"None",
")",
"assert",
"token_index",
"==",
"len",
"(",
"tokens",
")",
"assert",
"body",
".",
"arguments",
"==",
"[",
"]",
"return",
"ToplevelBody",
"(",
"statements",
"=",
"body",
".",
"statements",
")"
] | Parse a string called contents for an AST and return it. | [
"Parse",
"a",
"string",
"called",
"contents",
"for",
"an",
"AST",
"and",
"return",
"it",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L891-L902 | train |
polysquare/cmake-ast | cmakeast/ast.py | _CommentedLineRecorder.maybe_start_recording | def maybe_start_recording(tokens, index):
"""Return a new _CommentedLineRecorder when it is time to record."""
if _is_really_comment(tokens, index):
return _CommentedLineRecorder(index, tokens[index].line)
return None | python | def maybe_start_recording(tokens, index):
"""Return a new _CommentedLineRecorder when it is time to record."""
if _is_really_comment(tokens, index):
return _CommentedLineRecorder(index, tokens[index].line)
return None | [
"def",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"_is_really_comment",
"(",
"tokens",
",",
"index",
")",
":",
"return",
"_CommentedLineRecorder",
"(",
"index",
",",
"tokens",
"[",
"index",
"]",
".",
"line",
")",
"return",
"None"
] | Return a new _CommentedLineRecorder when it is time to record. | [
"Return",
"a",
"new",
"_CommentedLineRecorder",
"when",
"it",
"is",
"time",
"to",
"record",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L545-L550 | train |
polysquare/cmake-ast | cmakeast/ast.py | _RSTCommentBlockRecorder.maybe_start_recording | def maybe_start_recording(tokens, index):
"""Return a new _RSTCommentBlockRecorder when its time to record."""
if tokens[index].type == TokenType.BeginRSTComment:
return _RSTCommentBlockRecorder(index, tokens[index].line)
return None | python | def maybe_start_recording(tokens, index):
"""Return a new _RSTCommentBlockRecorder when its time to record."""
if tokens[index].type == TokenType.BeginRSTComment:
return _RSTCommentBlockRecorder(index, tokens[index].line)
return None | [
"def",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"tokens",
"[",
"index",
"]",
".",
"type",
"==",
"TokenType",
".",
"BeginRSTComment",
":",
"return",
"_RSTCommentBlockRecorder",
"(",
"index",
",",
"tokens",
"[",
"index",
"]",
".",
"line",
")",
"return",
"None"
] | Return a new _RSTCommentBlockRecorder when its time to record. | [
"Return",
"a",
"new",
"_RSTCommentBlockRecorder",
"when",
"its",
"time",
"to",
"record",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L624-L629 | train |
polysquare/cmake-ast | cmakeast/ast.py | _InlineRSTRecorder.maybe_start_recording | def maybe_start_recording(tokens, index):
"""Return a new _InlineRSTRecorder when its time to record."""
if tokens[index].type == TokenType.BeginInlineRST:
return _InlineRSTRecorder(index) | python | def maybe_start_recording(tokens, index):
"""Return a new _InlineRSTRecorder when its time to record."""
if tokens[index].type == TokenType.BeginInlineRST:
return _InlineRSTRecorder(index) | [
"def",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"tokens",
"[",
"index",
"]",
".",
"type",
"==",
"TokenType",
".",
"BeginInlineRST",
":",
"return",
"_InlineRSTRecorder",
"(",
"index",
")"
] | Return a new _InlineRSTRecorder when its time to record. | [
"Return",
"a",
"new",
"_InlineRSTRecorder",
"when",
"its",
"time",
"to",
"record",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L666-L669 | train |
polysquare/cmake-ast | cmakeast/ast.py | _MultilineStringRecorder.maybe_start_recording | def maybe_start_recording(tokens, index):
"""Return a new _MultilineStringRecorder when its time to record."""
if _is_begin_quoted_type(tokens[index].type):
string_type = _get_string_type_from_token(tokens[index].type)
return _MultilineStringRecorder(index, string_type)
return None | python | def maybe_start_recording(tokens, index):
"""Return a new _MultilineStringRecorder when its time to record."""
if _is_begin_quoted_type(tokens[index].type):
string_type = _get_string_type_from_token(tokens[index].type)
return _MultilineStringRecorder(index, string_type)
return None | [
"def",
"maybe_start_recording",
"(",
"tokens",
",",
"index",
")",
":",
"if",
"_is_begin_quoted_type",
"(",
"tokens",
"[",
"index",
"]",
".",
"type",
")",
":",
"string_type",
"=",
"_get_string_type_from_token",
"(",
"tokens",
"[",
"index",
"]",
".",
"type",
")",
"return",
"_MultilineStringRecorder",
"(",
"index",
",",
"string_type",
")",
"return",
"None"
] | Return a new _MultilineStringRecorder when its time to record. | [
"Return",
"a",
"new",
"_MultilineStringRecorder",
"when",
"its",
"time",
"to",
"record",
"."
] | 431a32d595d76f1f8f993eb6ddcc79effbadff9d | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L696-L702 | train |
vmonaco/pohmm | examples/keystroke.py | stratified_kfold | def stratified_kfold(df, n_folds):
"""
Create stratified k-folds from an indexed dataframe
"""
sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique())
sessions.apply(lambda x: np.random.shuffle(x))
folds = []
for i in range(n_folds):
idx = sessions.apply(lambda x: pd.Series(x[i * (len(x) / n_folds):(i + 1) * (len(x) / n_folds)]))
idx = pd.DataFrame(idx.stack().reset_index(level=1, drop=True)).set_index(0, append=True).index.values
folds.append(df.loc[idx])
return folds | python | def stratified_kfold(df, n_folds):
"""
Create stratified k-folds from an indexed dataframe
"""
sessions = pd.DataFrame.from_records(list(df.index.unique())).groupby(0).apply(lambda x: x[1].unique())
sessions.apply(lambda x: np.random.shuffle(x))
folds = []
for i in range(n_folds):
idx = sessions.apply(lambda x: pd.Series(x[i * (len(x) / n_folds):(i + 1) * (len(x) / n_folds)]))
idx = pd.DataFrame(idx.stack().reset_index(level=1, drop=True)).set_index(0, append=True).index.values
folds.append(df.loc[idx])
return folds | [
"def",
"stratified_kfold",
"(",
"df",
",",
"n_folds",
")",
":",
"sessions",
"=",
"pd",
".",
"DataFrame",
".",
"from_records",
"(",
"list",
"(",
"df",
".",
"index",
".",
"unique",
"(",
")",
")",
")",
".",
"groupby",
"(",
"0",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
".",
"unique",
"(",
")",
")",
"sessions",
".",
"apply",
"(",
"lambda",
"x",
":",
"np",
".",
"random",
".",
"shuffle",
"(",
"x",
")",
")",
"folds",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n_folds",
")",
":",
"idx",
"=",
"sessions",
".",
"apply",
"(",
"lambda",
"x",
":",
"pd",
".",
"Series",
"(",
"x",
"[",
"i",
"*",
"(",
"len",
"(",
"x",
")",
"/",
"n_folds",
")",
":",
"(",
"i",
"+",
"1",
")",
"*",
"(",
"len",
"(",
"x",
")",
"/",
"n_folds",
")",
"]",
")",
")",
"idx",
"=",
"pd",
".",
"DataFrame",
"(",
"idx",
".",
"stack",
"(",
")",
".",
"reset_index",
"(",
"level",
"=",
"1",
",",
"drop",
"=",
"True",
")",
")",
".",
"set_index",
"(",
"0",
",",
"append",
"=",
"True",
")",
".",
"index",
".",
"values",
"folds",
".",
"append",
"(",
"df",
".",
"loc",
"[",
"idx",
"]",
")",
"return",
"folds"
] | Create stratified k-folds from an indexed dataframe | [
"Create",
"stratified",
"k",
"-",
"folds",
"from",
"an",
"indexed",
"dataframe"
] | c00f8a62d3005a171d424549a55d46c421859ae9 | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/examples/keystroke.py#L15-L26 | train |
vmonaco/pohmm | examples/keystroke.py | keystroke_model | def keystroke_model():
"""Generates a 2-state model with lognormal emissions and frequency smoothing"""
model = Pohmm(n_hidden_states=2,
init_spread=2,
emissions=['lognormal', 'lognormal'],
smoothing='freq',
init_method='obs',
thresh=1)
return model | python | def keystroke_model():
"""Generates a 2-state model with lognormal emissions and frequency smoothing"""
model = Pohmm(n_hidden_states=2,
init_spread=2,
emissions=['lognormal', 'lognormal'],
smoothing='freq',
init_method='obs',
thresh=1)
return model | [
"def",
"keystroke_model",
"(",
")",
":",
"model",
"=",
"Pohmm",
"(",
"n_hidden_states",
"=",
"2",
",",
"init_spread",
"=",
"2",
",",
"emissions",
"=",
"[",
"'lognormal'",
",",
"'lognormal'",
"]",
",",
"smoothing",
"=",
"'freq'",
",",
"init_method",
"=",
"'obs'",
",",
"thresh",
"=",
"1",
")",
"return",
"model"
] | Generates a 2-state model with lognormal emissions and frequency smoothing | [
"Generates",
"a",
"2",
"-",
"state",
"model",
"with",
"lognormal",
"emissions",
"and",
"frequency",
"smoothing"
] | c00f8a62d3005a171d424549a55d46c421859ae9 | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/examples/keystroke.py#L123-L131 | train |
teepark/greenhouse | greenhouse/backdoor.py | run_backdoor | def run_backdoor(address, namespace=None):
"""start a server that runs python interpreters on connections made to it
.. note::
this function blocks effectively indefinitely -- it runs the listening
socket loop in the current greenlet. to keep the current greenlet free,
:func:`schedule<greenhouse.scheduler.schedule>` this function.
:param address:
the address on which to listen for backdoor connections, in the form of
a two-tuple ``(host, port)``
:type address: tuple
:param namespace:
the local namespace dict for the interpreter, or None to have each
connection create its own empty namespace
:type namespace: dict or None
"""
log.info("starting on %r" % (address,))
serversock = io.Socket()
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind(address)
serversock.listen(socket.SOMAXCONN)
while 1:
clientsock, address = serversock.accept()
log.info("connection received from %r" % (address,))
scheduler.schedule(backdoor_handler, args=(clientsock, namespace)) | python | def run_backdoor(address, namespace=None):
"""start a server that runs python interpreters on connections made to it
.. note::
this function blocks effectively indefinitely -- it runs the listening
socket loop in the current greenlet. to keep the current greenlet free,
:func:`schedule<greenhouse.scheduler.schedule>` this function.
:param address:
the address on which to listen for backdoor connections, in the form of
a two-tuple ``(host, port)``
:type address: tuple
:param namespace:
the local namespace dict for the interpreter, or None to have each
connection create its own empty namespace
:type namespace: dict or None
"""
log.info("starting on %r" % (address,))
serversock = io.Socket()
serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serversock.bind(address)
serversock.listen(socket.SOMAXCONN)
while 1:
clientsock, address = serversock.accept()
log.info("connection received from %r" % (address,))
scheduler.schedule(backdoor_handler, args=(clientsock, namespace)) | [
"def",
"run_backdoor",
"(",
"address",
",",
"namespace",
"=",
"None",
")",
":",
"log",
".",
"info",
"(",
"\"starting on %r\"",
"%",
"(",
"address",
",",
")",
")",
"serversock",
"=",
"io",
".",
"Socket",
"(",
")",
"serversock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_REUSEADDR",
",",
"1",
")",
"serversock",
".",
"bind",
"(",
"address",
")",
"serversock",
".",
"listen",
"(",
"socket",
".",
"SOMAXCONN",
")",
"while",
"1",
":",
"clientsock",
",",
"address",
"=",
"serversock",
".",
"accept",
"(",
")",
"log",
".",
"info",
"(",
"\"connection received from %r\"",
"%",
"(",
"address",
",",
")",
")",
"scheduler",
".",
"schedule",
"(",
"backdoor_handler",
",",
"args",
"=",
"(",
"clientsock",
",",
"namespace",
")",
")"
] | start a server that runs python interpreters on connections made to it
.. note::
this function blocks effectively indefinitely -- it runs the listening
socket loop in the current greenlet. to keep the current greenlet free,
:func:`schedule<greenhouse.scheduler.schedule>` this function.
:param address:
the address on which to listen for backdoor connections, in the form of
a two-tuple ``(host, port)``
:type address: tuple
:param namespace:
the local namespace dict for the interpreter, or None to have each
connection create its own empty namespace
:type namespace: dict or None | [
"start",
"a",
"server",
"that",
"runs",
"python",
"interpreters",
"on",
"connections",
"made",
"to",
"it"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/backdoor.py#L40-L67 | train |
teepark/greenhouse | greenhouse/backdoor.py | backdoor_handler | def backdoor_handler(clientsock, namespace=None):
"""start an interactive python interpreter on an existing connection
.. note::
this function will block for as long as the connection remains alive.
:param sock: the socket on which to serve the interpreter
:type sock: :class:`Socket<greenhouse.io.sockets.Socket>`
:param namespace:
the local namespace dict for the interpreter, or None to have the
function create its own empty namespace
:type namespace: dict or None
"""
namespace = {} if namespace is None else namespace.copy()
console = code.InteractiveConsole(namespace)
multiline_statement = []
stdout, stderr = StringIO(), StringIO()
clientsock.sendall(PREAMBLE + "\n" + PS1)
for input_line in _produce_lines(clientsock):
input_line = input_line.rstrip()
if input_line:
input_line = '\n' + input_line
source = '\n'.join(multiline_statement) + input_line
response = ''
with _wrap_stdio(stdout, stderr):
result = console.runsource(source)
response += stdout.getvalue()
err = stderr.getvalue()
if err:
response += err
if err or not result:
multiline_statement = []
response += PS1
else:
multiline_statement.append(input_line)
response += PS2
clientsock.sendall(response) | python | def backdoor_handler(clientsock, namespace=None):
"""start an interactive python interpreter on an existing connection
.. note::
this function will block for as long as the connection remains alive.
:param sock: the socket on which to serve the interpreter
:type sock: :class:`Socket<greenhouse.io.sockets.Socket>`
:param namespace:
the local namespace dict for the interpreter, or None to have the
function create its own empty namespace
:type namespace: dict or None
"""
namespace = {} if namespace is None else namespace.copy()
console = code.InteractiveConsole(namespace)
multiline_statement = []
stdout, stderr = StringIO(), StringIO()
clientsock.sendall(PREAMBLE + "\n" + PS1)
for input_line in _produce_lines(clientsock):
input_line = input_line.rstrip()
if input_line:
input_line = '\n' + input_line
source = '\n'.join(multiline_statement) + input_line
response = ''
with _wrap_stdio(stdout, stderr):
result = console.runsource(source)
response += stdout.getvalue()
err = stderr.getvalue()
if err:
response += err
if err or not result:
multiline_statement = []
response += PS1
else:
multiline_statement.append(input_line)
response += PS2
clientsock.sendall(response) | [
"def",
"backdoor_handler",
"(",
"clientsock",
",",
"namespace",
"=",
"None",
")",
":",
"namespace",
"=",
"{",
"}",
"if",
"namespace",
"is",
"None",
"else",
"namespace",
".",
"copy",
"(",
")",
"console",
"=",
"code",
".",
"InteractiveConsole",
"(",
"namespace",
")",
"multiline_statement",
"=",
"[",
"]",
"stdout",
",",
"stderr",
"=",
"StringIO",
"(",
")",
",",
"StringIO",
"(",
")",
"clientsock",
".",
"sendall",
"(",
"PREAMBLE",
"+",
"\"\\n\"",
"+",
"PS1",
")",
"for",
"input_line",
"in",
"_produce_lines",
"(",
"clientsock",
")",
":",
"input_line",
"=",
"input_line",
".",
"rstrip",
"(",
")",
"if",
"input_line",
":",
"input_line",
"=",
"'\\n'",
"+",
"input_line",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"multiline_statement",
")",
"+",
"input_line",
"response",
"=",
"''",
"with",
"_wrap_stdio",
"(",
"stdout",
",",
"stderr",
")",
":",
"result",
"=",
"console",
".",
"runsource",
"(",
"source",
")",
"response",
"+=",
"stdout",
".",
"getvalue",
"(",
")",
"err",
"=",
"stderr",
".",
"getvalue",
"(",
")",
"if",
"err",
":",
"response",
"+=",
"err",
"if",
"err",
"or",
"not",
"result",
":",
"multiline_statement",
"=",
"[",
"]",
"response",
"+=",
"PS1",
"else",
":",
"multiline_statement",
".",
"append",
"(",
"input_line",
")",
"response",
"+=",
"PS2",
"clientsock",
".",
"sendall",
"(",
"response",
")"
] | start an interactive python interpreter on an existing connection
.. note::
this function will block for as long as the connection remains alive.
:param sock: the socket on which to serve the interpreter
:type sock: :class:`Socket<greenhouse.io.sockets.Socket>`
:param namespace:
the local namespace dict for the interpreter, or None to have the
function create its own empty namespace
:type namespace: dict or None | [
"start",
"an",
"interactive",
"python",
"interpreter",
"on",
"an",
"existing",
"connection"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/backdoor.py#L70-L112 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.prepare_params | def prepare_params(self):
"""
Prepare the parameters passed to the templatetag
"""
if self.options.resolve_fragment:
self.fragment_name = self.node.fragment_name.resolve(self.context)
else:
self.fragment_name = str(self.node.fragment_name)
# Remove quotes that surround the name
for char in '\'\"':
if self.fragment_name.startswith(char) or self.fragment_name.endswith(char):
if self.fragment_name.startswith(char) and self.fragment_name.endswith(char):
self.fragment_name = self.fragment_name[1:-1]
break
else:
raise ValueError('Number of quotes around the fragment name is incoherent')
self.expire_time = self.get_expire_time()
if self.options.versioning:
self.version = force_bytes(self.get_version())
self.vary_on = [template.Variable(var).resolve(self.context) for var in self.node.vary_on] | python | def prepare_params(self):
"""
Prepare the parameters passed to the templatetag
"""
if self.options.resolve_fragment:
self.fragment_name = self.node.fragment_name.resolve(self.context)
else:
self.fragment_name = str(self.node.fragment_name)
# Remove quotes that surround the name
for char in '\'\"':
if self.fragment_name.startswith(char) or self.fragment_name.endswith(char):
if self.fragment_name.startswith(char) and self.fragment_name.endswith(char):
self.fragment_name = self.fragment_name[1:-1]
break
else:
raise ValueError('Number of quotes around the fragment name is incoherent')
self.expire_time = self.get_expire_time()
if self.options.versioning:
self.version = force_bytes(self.get_version())
self.vary_on = [template.Variable(var).resolve(self.context) for var in self.node.vary_on] | [
"def",
"prepare_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
".",
"resolve_fragment",
":",
"self",
".",
"fragment_name",
"=",
"self",
".",
"node",
".",
"fragment_name",
".",
"resolve",
"(",
"self",
".",
"context",
")",
"else",
":",
"self",
".",
"fragment_name",
"=",
"str",
"(",
"self",
".",
"node",
".",
"fragment_name",
")",
"# Remove quotes that surround the name",
"for",
"char",
"in",
"'\\'\\\"'",
":",
"if",
"self",
".",
"fragment_name",
".",
"startswith",
"(",
"char",
")",
"or",
"self",
".",
"fragment_name",
".",
"endswith",
"(",
"char",
")",
":",
"if",
"self",
".",
"fragment_name",
".",
"startswith",
"(",
"char",
")",
"and",
"self",
".",
"fragment_name",
".",
"endswith",
"(",
"char",
")",
":",
"self",
".",
"fragment_name",
"=",
"self",
".",
"fragment_name",
"[",
"1",
":",
"-",
"1",
"]",
"break",
"else",
":",
"raise",
"ValueError",
"(",
"'Number of quotes around the fragment name is incoherent'",
")",
"self",
".",
"expire_time",
"=",
"self",
".",
"get_expire_time",
"(",
")",
"if",
"self",
".",
"options",
".",
"versioning",
":",
"self",
".",
"version",
"=",
"force_bytes",
"(",
"self",
".",
"get_version",
"(",
")",
")",
"self",
".",
"vary_on",
"=",
"[",
"template",
".",
"Variable",
"(",
"var",
")",
".",
"resolve",
"(",
"self",
".",
"context",
")",
"for",
"var",
"in",
"self",
".",
"node",
".",
"vary_on",
"]"
] | Prepare the parameters passed to the templatetag | [
"Prepare",
"the",
"parameters",
"passed",
"to",
"the",
"templatetag"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L234-L256 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.get_expire_time | def get_expire_time(self):
"""
Return the expire time passed to the templatetag.
Must be None or an integer.
"""
try:
expire_time = self.node.expire_time.resolve(self.context)
except template.VariableDoesNotExist:
raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' %
(self.node.nodename, self.node.expire_time.var))
try:
if expire_time is not None:
expire_time = str(expire_time)
if not expire_time.isdigit():
raise TypeError
expire_time = int(expire_time)
except (ValueError, TypeError):
raise template.TemplateSyntaxError(
'"%s" tag got a non-integer (or None) timeout value: %r' % (
self.node.nodename, expire_time
)
)
return expire_time | python | def get_expire_time(self):
"""
Return the expire time passed to the templatetag.
Must be None or an integer.
"""
try:
expire_time = self.node.expire_time.resolve(self.context)
except template.VariableDoesNotExist:
raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' %
(self.node.nodename, self.node.expire_time.var))
try:
if expire_time is not None:
expire_time = str(expire_time)
if not expire_time.isdigit():
raise TypeError
expire_time = int(expire_time)
except (ValueError, TypeError):
raise template.TemplateSyntaxError(
'"%s" tag got a non-integer (or None) timeout value: %r' % (
self.node.nodename, expire_time
)
)
return expire_time | [
"def",
"get_expire_time",
"(",
"self",
")",
":",
"try",
":",
"expire_time",
"=",
"self",
".",
"node",
".",
"expire_time",
".",
"resolve",
"(",
"self",
".",
"context",
")",
"except",
"template",
".",
"VariableDoesNotExist",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"'\"%s\" tag got an unknown variable: %r'",
"%",
"(",
"self",
".",
"node",
".",
"nodename",
",",
"self",
".",
"node",
".",
"expire_time",
".",
"var",
")",
")",
"try",
":",
"if",
"expire_time",
"is",
"not",
"None",
":",
"expire_time",
"=",
"str",
"(",
"expire_time",
")",
"if",
"not",
"expire_time",
".",
"isdigit",
"(",
")",
":",
"raise",
"TypeError",
"expire_time",
"=",
"int",
"(",
"expire_time",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"'\"%s\" tag got a non-integer (or None) timeout value: %r'",
"%",
"(",
"self",
".",
"node",
".",
"nodename",
",",
"expire_time",
")",
")",
"return",
"expire_time"
] | Return the expire time passed to the templatetag.
Must be None or an integer. | [
"Return",
"the",
"expire",
"time",
"passed",
"to",
"the",
"templatetag",
".",
"Must",
"be",
"None",
"or",
"an",
"integer",
"."
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L258-L281 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.get_version | def get_version(self):
"""
Return the stringified version passed to the templatetag.
"""
if not self.node.version:
return None
try:
version = smart_str('%s' % self.node.version.resolve(self.context))
except template.VariableDoesNotExist:
raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' %
(self.node.nodename, self.node.version.var))
return '%s' % version | python | def get_version(self):
"""
Return the stringified version passed to the templatetag.
"""
if not self.node.version:
return None
try:
version = smart_str('%s' % self.node.version.resolve(self.context))
except template.VariableDoesNotExist:
raise template.TemplateSyntaxError('"%s" tag got an unknown variable: %r' %
(self.node.nodename, self.node.version.var))
return '%s' % version | [
"def",
"get_version",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"node",
".",
"version",
":",
"return",
"None",
"try",
":",
"version",
"=",
"smart_str",
"(",
"'%s'",
"%",
"self",
".",
"node",
".",
"version",
".",
"resolve",
"(",
"self",
".",
"context",
")",
")",
"except",
"template",
".",
"VariableDoesNotExist",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"'\"%s\" tag got an unknown variable: %r'",
"%",
"(",
"self",
".",
"node",
".",
"nodename",
",",
"self",
".",
"node",
".",
"version",
".",
"var",
")",
")",
"return",
"'%s'",
"%",
"version"
] | Return the stringified version passed to the templatetag. | [
"Return",
"the",
"stringified",
"version",
"passed",
"to",
"the",
"templatetag",
"."
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L283-L295 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.hash_args | def hash_args(self):
"""
Take all the arguments passed after the fragment name and return a
hashed version which will be used in the cache key
"""
return hashlib.md5(force_bytes(':'.join([urlquote(force_bytes(var)) for var in self.vary_on]))).hexdigest() | python | def hash_args(self):
"""
Take all the arguments passed after the fragment name and return a
hashed version which will be used in the cache key
"""
return hashlib.md5(force_bytes(':'.join([urlquote(force_bytes(var)) for var in self.vary_on]))).hexdigest() | [
"def",
"hash_args",
"(",
"self",
")",
":",
"return",
"hashlib",
".",
"md5",
"(",
"force_bytes",
"(",
"':'",
".",
"join",
"(",
"[",
"urlquote",
"(",
"force_bytes",
"(",
"var",
")",
")",
"for",
"var",
"in",
"self",
".",
"vary_on",
"]",
")",
")",
")",
".",
"hexdigest",
"(",
")"
] | Take all the arguments passed after the fragment name and return a
hashed version which will be used in the cache key | [
"Take",
"all",
"the",
"arguments",
"passed",
"after",
"the",
"fragment",
"name",
"and",
"return",
"a",
"hashed",
"version",
"which",
"will",
"be",
"used",
"in",
"the",
"cache",
"key"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L297-L302 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.get_cache_key_args | def get_cache_key_args(self):
"""
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
"""
cache_key_args = dict(
nodename=self.node.nodename,
name=self.fragment_name,
hash=self.hash_args(),
)
if self.options.include_pk:
cache_key_args['pk'] = self.get_pk()
return cache_key_args | python | def get_cache_key_args(self):
"""
Return the arguments to be passed to the base cache key returned by `get_base_cache_key`.
"""
cache_key_args = dict(
nodename=self.node.nodename,
name=self.fragment_name,
hash=self.hash_args(),
)
if self.options.include_pk:
cache_key_args['pk'] = self.get_pk()
return cache_key_args | [
"def",
"get_cache_key_args",
"(",
"self",
")",
":",
"cache_key_args",
"=",
"dict",
"(",
"nodename",
"=",
"self",
".",
"node",
".",
"nodename",
",",
"name",
"=",
"self",
".",
"fragment_name",
",",
"hash",
"=",
"self",
".",
"hash_args",
"(",
")",
",",
")",
"if",
"self",
".",
"options",
".",
"include_pk",
":",
"cache_key_args",
"[",
"'pk'",
"]",
"=",
"self",
".",
"get_pk",
"(",
")",
"return",
"cache_key_args"
] | Return the arguments to be passed to the base cache key returned by `get_base_cache_key`. | [
"Return",
"the",
"arguments",
"to",
"be",
"passed",
"to",
"the",
"base",
"cache",
"key",
"returned",
"by",
"get_base_cache_key",
"."
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L326-L338 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.cache_set | def cache_set(self, to_cache):
"""
Set content into the cache
"""
self.cache.set(self.cache_key, to_cache, self.expire_time) | python | def cache_set(self, to_cache):
"""
Set content into the cache
"""
self.cache.set(self.cache_key, to_cache, self.expire_time) | [
"def",
"cache_set",
"(",
"self",
",",
"to_cache",
")",
":",
"self",
".",
"cache",
".",
"set",
"(",
"self",
".",
"cache_key",
",",
"to_cache",
",",
"self",
".",
"expire_time",
")"
] | Set content into the cache | [
"Set",
"content",
"into",
"the",
"cache"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L362-L366 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.render_node | def render_node(self):
"""
Render the template and save the generated content
"""
self.content = self.node.nodelist.render(self.context) | python | def render_node(self):
"""
Render the template and save the generated content
"""
self.content = self.node.nodelist.render(self.context) | [
"def",
"render_node",
"(",
"self",
")",
":",
"self",
".",
"content",
"=",
"self",
".",
"node",
".",
"nodelist",
".",
"render",
"(",
"self",
".",
"context",
")"
] | Render the template and save the generated content | [
"Render",
"the",
"template",
"and",
"save",
"the",
"generated",
"content"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L421-L425 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.create_content | def create_content(self):
"""
Render the template, apply options on it, and save it to the cache.
"""
self.render_node()
if self.options.compress_spaces:
self.content = self.RE_SPACELESS.sub(' ', self.content)
if self.options.compress:
to_cache = self.encode_content()
else:
to_cache = self.content
to_cache = self.join_content_version(to_cache)
try:
self.cache_set(to_cache)
except Exception:
if is_template_debug_activated():
raise
logger.exception('Error when saving the cached template fragment') | python | def create_content(self):
"""
Render the template, apply options on it, and save it to the cache.
"""
self.render_node()
if self.options.compress_spaces:
self.content = self.RE_SPACELESS.sub(' ', self.content)
if self.options.compress:
to_cache = self.encode_content()
else:
to_cache = self.content
to_cache = self.join_content_version(to_cache)
try:
self.cache_set(to_cache)
except Exception:
if is_template_debug_activated():
raise
logger.exception('Error when saving the cached template fragment') | [
"def",
"create_content",
"(",
"self",
")",
":",
"self",
".",
"render_node",
"(",
")",
"if",
"self",
".",
"options",
".",
"compress_spaces",
":",
"self",
".",
"content",
"=",
"self",
".",
"RE_SPACELESS",
".",
"sub",
"(",
"' '",
",",
"self",
".",
"content",
")",
"if",
"self",
".",
"options",
".",
"compress",
":",
"to_cache",
"=",
"self",
".",
"encode_content",
"(",
")",
"else",
":",
"to_cache",
"=",
"self",
".",
"content",
"to_cache",
"=",
"self",
".",
"join_content_version",
"(",
"to_cache",
")",
"try",
":",
"self",
".",
"cache_set",
"(",
"to_cache",
")",
"except",
"Exception",
":",
"if",
"is_template_debug_activated",
"(",
")",
":",
"raise",
"logger",
".",
"exception",
"(",
"'Error when saving the cached template fragment'",
")"
] | Render the template, apply options on it, and save it to the cache. | [
"Render",
"the",
"template",
"apply",
"options",
"on",
"it",
"and",
"save",
"it",
"to",
"the",
"cache",
"."
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L427-L448 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.get_templatetag_module | def get_templatetag_module(cls):
"""
Return the templatetags module name for which the current class is used.
It's used to render the nocache blocks by loading the correct module
"""
if cls not in CacheTag._templatetags_modules:
# find the library including the main templatetag of the current class
all_tags = cls.get_all_tags_and_filters_by_function()['tags']
CacheTag._templatetags_modules[cls] = all_tags[CacheTag._templatetags[cls]['cache']][0]
return CacheTag._templatetags_modules[cls] | python | def get_templatetag_module(cls):
"""
Return the templatetags module name for which the current class is used.
It's used to render the nocache blocks by loading the correct module
"""
if cls not in CacheTag._templatetags_modules:
# find the library including the main templatetag of the current class
all_tags = cls.get_all_tags_and_filters_by_function()['tags']
CacheTag._templatetags_modules[cls] = all_tags[CacheTag._templatetags[cls]['cache']][0]
return CacheTag._templatetags_modules[cls] | [
"def",
"get_templatetag_module",
"(",
"cls",
")",
":",
"if",
"cls",
"not",
"in",
"CacheTag",
".",
"_templatetags_modules",
":",
"# find the library including the main templatetag of the current class",
"all_tags",
"=",
"cls",
".",
"get_all_tags_and_filters_by_function",
"(",
")",
"[",
"'tags'",
"]",
"CacheTag",
".",
"_templatetags_modules",
"[",
"cls",
"]",
"=",
"all_tags",
"[",
"CacheTag",
".",
"_templatetags",
"[",
"cls",
"]",
"[",
"'cache'",
"]",
"]",
"[",
"0",
"]",
"return",
"CacheTag",
".",
"_templatetags_modules",
"[",
"cls",
"]"
] | Return the templatetags module name for which the current class is used.
It's used to render the nocache blocks by loading the correct module | [
"Return",
"the",
"templatetags",
"module",
"name",
"for",
"which",
"the",
"current",
"class",
"is",
"used",
".",
"It",
"s",
"used",
"to",
"render",
"the",
"nocache",
"blocks",
"by",
"loading",
"the",
"correct",
"module"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L562-L571 | train |
twidi/django-adv-cache-tag | adv_cache_tag/tag.py | CacheTag.render_nocache | def render_nocache(self):
"""
Render the `nocache` blocks of the content and return the whole
html
"""
tmpl = template.Template(''.join([
# start by loading the cache library
template.BLOCK_TAG_START,
'load %s' % self.get_templatetag_module(),
template.BLOCK_TAG_END,
# and surround the cached template by "raw" tags
self.RAW_TOKEN_START,
self.content,
self.RAW_TOKEN_END,
]))
return tmpl.render(self.context) | python | def render_nocache(self):
"""
Render the `nocache` blocks of the content and return the whole
html
"""
tmpl = template.Template(''.join([
# start by loading the cache library
template.BLOCK_TAG_START,
'load %s' % self.get_templatetag_module(),
template.BLOCK_TAG_END,
# and surround the cached template by "raw" tags
self.RAW_TOKEN_START,
self.content,
self.RAW_TOKEN_END,
]))
return tmpl.render(self.context) | [
"def",
"render_nocache",
"(",
"self",
")",
":",
"tmpl",
"=",
"template",
".",
"Template",
"(",
"''",
".",
"join",
"(",
"[",
"# start by loading the cache library",
"template",
".",
"BLOCK_TAG_START",
",",
"'load %s'",
"%",
"self",
".",
"get_templatetag_module",
"(",
")",
",",
"template",
".",
"BLOCK_TAG_END",
",",
"# and surround the cached template by \"raw\" tags",
"self",
".",
"RAW_TOKEN_START",
",",
"self",
".",
"content",
",",
"self",
".",
"RAW_TOKEN_END",
",",
"]",
")",
")",
"return",
"tmpl",
".",
"render",
"(",
"self",
".",
"context",
")"
] | Render the `nocache` blocks of the content and return the whole
html | [
"Render",
"the",
"nocache",
"blocks",
"of",
"the",
"content",
"and",
"return",
"the",
"whole",
"html"
] | 811f8db4dac73667c7d2fe0ea97a24969593eb8a | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L573-L588 | train |
marchete/django-adldap-sync | adldap_sync/callbacks.py | user_active_directory_deactivate | def user_active_directory_deactivate(user, attributes, created, updated):
"""
Deactivate user accounts based on Active Directory's
userAccountControl flags. Requires 'userAccountControl'
to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES.
"""
try:
user_account_control = int(attributes['userAccountControl'][0])
if user_account_control & 2:
user.is_active = False
except KeyError:
pass | python | def user_active_directory_deactivate(user, attributes, created, updated):
"""
Deactivate user accounts based on Active Directory's
userAccountControl flags. Requires 'userAccountControl'
to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES.
"""
try:
user_account_control = int(attributes['userAccountControl'][0])
if user_account_control & 2:
user.is_active = False
except KeyError:
pass | [
"def",
"user_active_directory_deactivate",
"(",
"user",
",",
"attributes",
",",
"created",
",",
"updated",
")",
":",
"try",
":",
"user_account_control",
"=",
"int",
"(",
"attributes",
"[",
"'userAccountControl'",
"]",
"[",
"0",
"]",
")",
"if",
"user_account_control",
"&",
"2",
":",
"user",
".",
"is_active",
"=",
"False",
"except",
"KeyError",
":",
"pass"
] | Deactivate user accounts based on Active Directory's
userAccountControl flags. Requires 'userAccountControl'
to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES. | [
"Deactivate",
"user",
"accounts",
"based",
"on",
"Active",
"Directory",
"s",
"userAccountControl",
"flags",
".",
"Requires",
"userAccountControl",
"to",
"be",
"included",
"in",
"LDAP_SYNC_USER_EXTRA_ATTRIBUTES",
"."
] | f6be226a4fb2a433d22e95043bd656ce902f8254 | https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/callbacks.py#L1-L12 | train |
nickpandolfi/Cyther | cyther/parser.py | _get_contents_between | def _get_contents_between(string, opener, closer):
"""
Get the contents of a string between two characters
"""
opener_location = string.index(opener)
closer_location = string.index(closer)
content = string[opener_location + 1:closer_location]
return content | python | def _get_contents_between(string, opener, closer):
"""
Get the contents of a string between two characters
"""
opener_location = string.index(opener)
closer_location = string.index(closer)
content = string[opener_location + 1:closer_location]
return content | [
"def",
"_get_contents_between",
"(",
"string",
",",
"opener",
",",
"closer",
")",
":",
"opener_location",
"=",
"string",
".",
"index",
"(",
"opener",
")",
"closer_location",
"=",
"string",
".",
"index",
"(",
"closer",
")",
"content",
"=",
"string",
"[",
"opener_location",
"+",
"1",
":",
"closer_location",
"]",
"return",
"content"
] | Get the contents of a string between two characters | [
"Get",
"the",
"contents",
"of",
"a",
"string",
"between",
"two",
"characters"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L29-L36 | train |
nickpandolfi/Cyther | cyther/parser.py | _check_whitespace | def _check_whitespace(string):
"""
Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected
"""
if string.count(' ') + string.count('\t') + string.count('\n') > 0:
raise ValueError(INSTRUCTION_HAS_WHITESPACE) | python | def _check_whitespace(string):
"""
Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected
"""
if string.count(' ') + string.count('\t') + string.count('\n') > 0:
raise ValueError(INSTRUCTION_HAS_WHITESPACE) | [
"def",
"_check_whitespace",
"(",
"string",
")",
":",
"if",
"string",
".",
"count",
"(",
"' '",
")",
"+",
"string",
".",
"count",
"(",
"'\\t'",
")",
"+",
"string",
".",
"count",
"(",
"'\\n'",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"INSTRUCTION_HAS_WHITESPACE",
")"
] | Make sure thre is no whitespace in the given string. Will raise a
ValueError if whitespace is detected | [
"Make",
"sure",
"thre",
"is",
"no",
"whitespace",
"in",
"the",
"given",
"string",
".",
"Will",
"raise",
"a",
"ValueError",
"if",
"whitespace",
"is",
"detected"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L39-L45 | train |
nickpandolfi/Cyther | cyther/parser.py | _check_parameters | def _check_parameters(parameters, symbols):
"""
Checks that the parameters given are not empty. Ones with prefix symbols
can be denoted by including the prefix in symbols
"""
for param in parameters:
if not param:
raise ValueError(EMPTY_PARAMETER)
elif (param[0] in symbols) and (not param[1:]):
print(param)
raise ValueError(EMPTY_KEYWORD_PARAMETER) | python | def _check_parameters(parameters, symbols):
"""
Checks that the parameters given are not empty. Ones with prefix symbols
can be denoted by including the prefix in symbols
"""
for param in parameters:
if not param:
raise ValueError(EMPTY_PARAMETER)
elif (param[0] in symbols) and (not param[1:]):
print(param)
raise ValueError(EMPTY_KEYWORD_PARAMETER) | [
"def",
"_check_parameters",
"(",
"parameters",
",",
"symbols",
")",
":",
"for",
"param",
"in",
"parameters",
":",
"if",
"not",
"param",
":",
"raise",
"ValueError",
"(",
"EMPTY_PARAMETER",
")",
"elif",
"(",
"param",
"[",
"0",
"]",
"in",
"symbols",
")",
"and",
"(",
"not",
"param",
"[",
"1",
":",
"]",
")",
":",
"print",
"(",
"param",
")",
"raise",
"ValueError",
"(",
"EMPTY_KEYWORD_PARAMETER",
")"
] | Checks that the parameters given are not empty. Ones with prefix symbols
can be denoted by including the prefix in symbols | [
"Checks",
"that",
"the",
"parameters",
"given",
"are",
"not",
"empty",
".",
"Ones",
"with",
"prefix",
"symbols",
"can",
"be",
"denoted",
"by",
"including",
"the",
"prefix",
"in",
"symbols"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L71-L81 | train |
nickpandolfi/Cyther | cyther/parser.py | _check_dependencies | def _check_dependencies(string):
"""
Checks the dependencies constructor. Looks to make sure that the
dependencies are the first things defined
"""
opener, closer = '(', ')'
_check_enclosing_characters(string, opener, closer)
if opener in string:
if string[0] != opener:
raise ValueError(DEPENDENCIES_NOT_FIRST)
ret = True
else:
ret = False
return ret | python | def _check_dependencies(string):
"""
Checks the dependencies constructor. Looks to make sure that the
dependencies are the first things defined
"""
opener, closer = '(', ')'
_check_enclosing_characters(string, opener, closer)
if opener in string:
if string[0] != opener:
raise ValueError(DEPENDENCIES_NOT_FIRST)
ret = True
else:
ret = False
return ret | [
"def",
"_check_dependencies",
"(",
"string",
")",
":",
"opener",
",",
"closer",
"=",
"'('",
",",
"')'",
"_check_enclosing_characters",
"(",
"string",
",",
"opener",
",",
"closer",
")",
"if",
"opener",
"in",
"string",
":",
"if",
"string",
"[",
"0",
"]",
"!=",
"opener",
":",
"raise",
"ValueError",
"(",
"DEPENDENCIES_NOT_FIRST",
")",
"ret",
"=",
"True",
"else",
":",
"ret",
"=",
"False",
"return",
"ret"
] | Checks the dependencies constructor. Looks to make sure that the
dependencies are the first things defined | [
"Checks",
"the",
"dependencies",
"constructor",
".",
"Looks",
"to",
"make",
"sure",
"that",
"the",
"dependencies",
"are",
"the",
"first",
"things",
"defined"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L84-L97 | train |
nickpandolfi/Cyther | cyther/parser.py | _check_building_options | def _check_building_options(string):
"""
Checks the building options to make sure that they are defined last,
after the task name and the dependencies
"""
opener, closer = '{', '}'
_check_enclosing_characters(string, opener, closer)
if opener in string:
if string[-1] != closer:
raise ValueError(OPTIONS_NOT_LAST)
ret = True
else:
ret = False
return ret | python | def _check_building_options(string):
"""
Checks the building options to make sure that they are defined last,
after the task name and the dependencies
"""
opener, closer = '{', '}'
_check_enclosing_characters(string, opener, closer)
if opener in string:
if string[-1] != closer:
raise ValueError(OPTIONS_NOT_LAST)
ret = True
else:
ret = False
return ret | [
"def",
"_check_building_options",
"(",
"string",
")",
":",
"opener",
",",
"closer",
"=",
"'{'",
",",
"'}'",
"_check_enclosing_characters",
"(",
"string",
",",
"opener",
",",
"closer",
")",
"if",
"opener",
"in",
"string",
":",
"if",
"string",
"[",
"-",
"1",
"]",
"!=",
"closer",
":",
"raise",
"ValueError",
"(",
"OPTIONS_NOT_LAST",
")",
"ret",
"=",
"True",
"else",
":",
"ret",
"=",
"False",
"return",
"ret"
] | Checks the building options to make sure that they are defined last,
after the task name and the dependencies | [
"Checks",
"the",
"building",
"options",
"to",
"make",
"sure",
"that",
"they",
"are",
"defined",
"last",
"after",
"the",
"task",
"name",
"and",
"the",
"dependencies"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L100-L113 | train |
nickpandolfi/Cyther | cyther/parser.py | _parse_dependencies | def _parse_dependencies(string):
"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""
contents = _get_contents_between(string, '(', ')')
unsorted_dependencies = contents.split(',')
_check_parameters(unsorted_dependencies, ('?',))
buildable_dependencies = []
given_dependencies = []
for dependency in unsorted_dependencies:
if dependency[0] == '?':
given_dependencies.append(dependency[1:])
else:
buildable_dependencies.append(dependency)
string = string[string.index(')') + 1:]
return buildable_dependencies, given_dependencies, string | python | def _parse_dependencies(string):
"""
This function actually parses the dependencies are sorts them into
the buildable and given dependencies
"""
contents = _get_contents_between(string, '(', ')')
unsorted_dependencies = contents.split(',')
_check_parameters(unsorted_dependencies, ('?',))
buildable_dependencies = []
given_dependencies = []
for dependency in unsorted_dependencies:
if dependency[0] == '?':
given_dependencies.append(dependency[1:])
else:
buildable_dependencies.append(dependency)
string = string[string.index(')') + 1:]
return buildable_dependencies, given_dependencies, string | [
"def",
"_parse_dependencies",
"(",
"string",
")",
":",
"contents",
"=",
"_get_contents_between",
"(",
"string",
",",
"'('",
",",
"')'",
")",
"unsorted_dependencies",
"=",
"contents",
".",
"split",
"(",
"','",
")",
"_check_parameters",
"(",
"unsorted_dependencies",
",",
"(",
"'?'",
",",
")",
")",
"buildable_dependencies",
"=",
"[",
"]",
"given_dependencies",
"=",
"[",
"]",
"for",
"dependency",
"in",
"unsorted_dependencies",
":",
"if",
"dependency",
"[",
"0",
"]",
"==",
"'?'",
":",
"given_dependencies",
".",
"append",
"(",
"dependency",
"[",
"1",
":",
"]",
")",
"else",
":",
"buildable_dependencies",
".",
"append",
"(",
"dependency",
")",
"string",
"=",
"string",
"[",
"string",
".",
"index",
"(",
"')'",
")",
"+",
"1",
":",
"]",
"return",
"buildable_dependencies",
",",
"given_dependencies",
",",
"string"
] | This function actually parses the dependencies are sorts them into
the buildable and given dependencies | [
"This",
"function",
"actually",
"parses",
"the",
"dependencies",
"are",
"sorts",
"them",
"into",
"the",
"buildable",
"and",
"given",
"dependencies"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L135-L153 | train |
nickpandolfi/Cyther | cyther/parser.py | parseString | def parseString(string):
"""
This function takes an entire instruction in the form of a string, and
will parse the entire string and return a dictionary of the fields
gathered from the parsing
"""
buildable_dependencies = []
given_dependencies = []
output_directory = None
output_format = None
building_directory = None
output_name = None
_check_whitespace(string)
there_are_dependencies = _check_dependencies(string)
if there_are_dependencies:
buildable_dependencies, \
given_dependencies, \
string = _parse_dependencies(string)
there_are_options = _check_building_options(string)
if there_are_options:
output_directory, \
output_format, \
building_directory, string = _parse_building_options(string)
if string[0] == '>':
string = string[1:]
if string[-1] == '>':
string = string[:-1]
is_a_flow_operator = _check_flow_operator(string)
if is_a_flow_operator:
greater_than_location = string.index('>')
output_name = string[greater_than_location + 1:]
string = string[:greater_than_location]
ret = object()
ret.input_name = string
ret.output_name = output_name
ret.buildable_dependencies = buildable_dependencies
ret.given_dependencies = given_dependencies
ret.output_format = output_format
ret.building_directory = building_directory
ret.output_directory = output_directory
return ret | python | def parseString(string):
"""
This function takes an entire instruction in the form of a string, and
will parse the entire string and return a dictionary of the fields
gathered from the parsing
"""
buildable_dependencies = []
given_dependencies = []
output_directory = None
output_format = None
building_directory = None
output_name = None
_check_whitespace(string)
there_are_dependencies = _check_dependencies(string)
if there_are_dependencies:
buildable_dependencies, \
given_dependencies, \
string = _parse_dependencies(string)
there_are_options = _check_building_options(string)
if there_are_options:
output_directory, \
output_format, \
building_directory, string = _parse_building_options(string)
if string[0] == '>':
string = string[1:]
if string[-1] == '>':
string = string[:-1]
is_a_flow_operator = _check_flow_operator(string)
if is_a_flow_operator:
greater_than_location = string.index('>')
output_name = string[greater_than_location + 1:]
string = string[:greater_than_location]
ret = object()
ret.input_name = string
ret.output_name = output_name
ret.buildable_dependencies = buildable_dependencies
ret.given_dependencies = given_dependencies
ret.output_format = output_format
ret.building_directory = building_directory
ret.output_directory = output_directory
return ret | [
"def",
"parseString",
"(",
"string",
")",
":",
"buildable_dependencies",
"=",
"[",
"]",
"given_dependencies",
"=",
"[",
"]",
"output_directory",
"=",
"None",
"output_format",
"=",
"None",
"building_directory",
"=",
"None",
"output_name",
"=",
"None",
"_check_whitespace",
"(",
"string",
")",
"there_are_dependencies",
"=",
"_check_dependencies",
"(",
"string",
")",
"if",
"there_are_dependencies",
":",
"buildable_dependencies",
",",
"given_dependencies",
",",
"string",
"=",
"_parse_dependencies",
"(",
"string",
")",
"there_are_options",
"=",
"_check_building_options",
"(",
"string",
")",
"if",
"there_are_options",
":",
"output_directory",
",",
"output_format",
",",
"building_directory",
",",
"string",
"=",
"_parse_building_options",
"(",
"string",
")",
"if",
"string",
"[",
"0",
"]",
"==",
"'>'",
":",
"string",
"=",
"string",
"[",
"1",
":",
"]",
"if",
"string",
"[",
"-",
"1",
"]",
"==",
"'>'",
":",
"string",
"=",
"string",
"[",
":",
"-",
"1",
"]",
"is_a_flow_operator",
"=",
"_check_flow_operator",
"(",
"string",
")",
"if",
"is_a_flow_operator",
":",
"greater_than_location",
"=",
"string",
".",
"index",
"(",
"'>'",
")",
"output_name",
"=",
"string",
"[",
"greater_than_location",
"+",
"1",
":",
"]",
"string",
"=",
"string",
"[",
":",
"greater_than_location",
"]",
"ret",
"=",
"object",
"(",
")",
"ret",
".",
"input_name",
"=",
"string",
"ret",
".",
"output_name",
"=",
"output_name",
"ret",
".",
"buildable_dependencies",
"=",
"buildable_dependencies",
"ret",
".",
"given_dependencies",
"=",
"given_dependencies",
"ret",
".",
"output_format",
"=",
"output_format",
"ret",
".",
"building_directory",
"=",
"building_directory",
"ret",
".",
"output_directory",
"=",
"output_directory",
"return",
"ret"
] | This function takes an entire instruction in the form of a string, and
will parse the entire string and return a dictionary of the fields
gathered from the parsing | [
"This",
"function",
"takes",
"an",
"entire",
"instruction",
"in",
"the",
"form",
"of",
"a",
"string",
"and",
"will",
"parse",
"the",
"entire",
"string",
"and",
"return",
"a",
"dictionary",
"of",
"the",
"fields",
"gathered",
"from",
"the",
"parsing"
] | 9fb0bd77af594008aa6ee8af460aa8c953abf5bc | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L195-L241 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/account.py | Account.GetAlias | def GetAlias(session=None):
"""Return specified alias or if none the alias associated with the provided credentials.
>>> clc.v2.Account.GetAlias()
u'BTDI'
"""
if session is not None:
return session['alias']
if not clc.ALIAS: clc.v2.API._Login()
return(clc.ALIAS) | python | def GetAlias(session=None):
"""Return specified alias or if none the alias associated with the provided credentials.
>>> clc.v2.Account.GetAlias()
u'BTDI'
"""
if session is not None:
return session['alias']
if not clc.ALIAS: clc.v2.API._Login()
return(clc.ALIAS) | [
"def",
"GetAlias",
"(",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"return",
"session",
"[",
"'alias'",
"]",
"if",
"not",
"clc",
".",
"ALIAS",
":",
"clc",
".",
"v2",
".",
"API",
".",
"_Login",
"(",
")",
"return",
"(",
"clc",
".",
"ALIAS",
")"
] | Return specified alias or if none the alias associated with the provided credentials.
>>> clc.v2.Account.GetAlias()
u'BTDI' | [
"Return",
"specified",
"alias",
"or",
"if",
"none",
"the",
"alias",
"associated",
"with",
"the",
"provided",
"credentials",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L35-L45 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/account.py | Account.GetLocation | def GetLocation(session=None):
"""Return specified location or if none the default location associated with the provided credentials and alias.
>>> clc.v2.Account.GetLocation()
u'WA1'
"""
if session is not None:
return session['location']
if not clc.LOCATION: clc.v2.API._Login()
return(clc.LOCATION) | python | def GetLocation(session=None):
"""Return specified location or if none the default location associated with the provided credentials and alias.
>>> clc.v2.Account.GetLocation()
u'WA1'
"""
if session is not None:
return session['location']
if not clc.LOCATION: clc.v2.API._Login()
return(clc.LOCATION) | [
"def",
"GetLocation",
"(",
"session",
"=",
"None",
")",
":",
"if",
"session",
"is",
"not",
"None",
":",
"return",
"session",
"[",
"'location'",
"]",
"if",
"not",
"clc",
".",
"LOCATION",
":",
"clc",
".",
"v2",
".",
"API",
".",
"_Login",
"(",
")",
"return",
"(",
"clc",
".",
"LOCATION",
")"
] | Return specified location or if none the default location associated with the provided credentials and alias.
>>> clc.v2.Account.GetLocation()
u'WA1' | [
"Return",
"specified",
"location",
"or",
"if",
"none",
"the",
"default",
"location",
"associated",
"with",
"the",
"provided",
"credentials",
"and",
"alias",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L49-L59 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/account.py | Account.PrimaryDatacenter | def PrimaryDatacenter(self):
"""Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1
"""
return(clc.v2.Datacenter(alias=self.alias,location=self.data['primaryDataCenter'], session=self.session)) | python | def PrimaryDatacenter(self):
"""Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1
"""
return(clc.v2.Datacenter(alias=self.alias,location=self.data['primaryDataCenter'], session=self.session)) | [
"def",
"PrimaryDatacenter",
"(",
"self",
")",
":",
"return",
"(",
"clc",
".",
"v2",
".",
"Datacenter",
"(",
"alias",
"=",
"self",
".",
"alias",
",",
"location",
"=",
"self",
".",
"data",
"[",
"'primaryDataCenter'",
"]",
",",
"session",
"=",
"self",
".",
"session",
")",
")"
] | Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1 | [
"Returns",
"the",
"primary",
"datacenter",
"object",
"associated",
"with",
"the",
"account",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L94-L104 | train |
sio2project/filetracker | filetracker/client/data_store.py | DataStore.add_file | def add_file(self, name, filename, compress_hint=True):
"""Saves the actual file in the store.
``compress_hint`` suggests whether the file should be compressed
before transfer
Works like :meth:`add_stream`, but ``filename`` is the name of
an existing file in the filesystem.
"""
return self.add_stream(name, open(filename, 'rb')) | python | def add_file(self, name, filename, compress_hint=True):
"""Saves the actual file in the store.
``compress_hint`` suggests whether the file should be compressed
before transfer
Works like :meth:`add_stream`, but ``filename`` is the name of
an existing file in the filesystem.
"""
return self.add_stream(name, open(filename, 'rb')) | [
"def",
"add_file",
"(",
"self",
",",
"name",
",",
"filename",
",",
"compress_hint",
"=",
"True",
")",
":",
"return",
"self",
".",
"add_stream",
"(",
"name",
",",
"open",
"(",
"filename",
",",
"'rb'",
")",
")"
] | Saves the actual file in the store.
``compress_hint`` suggests whether the file should be compressed
before transfer
Works like :meth:`add_stream`, but ``filename`` is the name of
an existing file in the filesystem. | [
"Saves",
"the",
"actual",
"file",
"in",
"the",
"store",
"."
] | 359b474850622e3d0c25ee2596d7242c02f84efb | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L38-L47 | train |
sio2project/filetracker | filetracker/client/data_store.py | DataStore.get_file | def get_file(self, name, filename):
"""Saves the content of file named ``name`` to ``filename``.
Works like :meth:`get_stream`, but ``filename`` is the name of
a file which will be created (or overwritten).
Returns the full versioned name of the retrieved file.
"""
stream, vname = self.get_stream(name)
path, version = split_name(vname)
dir_path = os.path.dirname(filename)
if dir_path:
mkdir(dir_path)
with open(filename, 'wb') as f:
shutil.copyfileobj(stream, f)
return vname | python | def get_file(self, name, filename):
"""Saves the content of file named ``name`` to ``filename``.
Works like :meth:`get_stream`, but ``filename`` is the name of
a file which will be created (or overwritten).
Returns the full versioned name of the retrieved file.
"""
stream, vname = self.get_stream(name)
path, version = split_name(vname)
dir_path = os.path.dirname(filename)
if dir_path:
mkdir(dir_path)
with open(filename, 'wb') as f:
shutil.copyfileobj(stream, f)
return vname | [
"def",
"get_file",
"(",
"self",
",",
"name",
",",
"filename",
")",
":",
"stream",
",",
"vname",
"=",
"self",
".",
"get_stream",
"(",
"name",
")",
"path",
",",
"version",
"=",
"split_name",
"(",
"vname",
")",
"dir_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"dir_path",
":",
"mkdir",
"(",
"dir_path",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"shutil",
".",
"copyfileobj",
"(",
"stream",
",",
"f",
")",
"return",
"vname"
] | Saves the content of file named ``name`` to ``filename``.
Works like :meth:`get_stream`, but ``filename`` is the name of
a file which will be created (or overwritten).
Returns the full versioned name of the retrieved file. | [
"Saves",
"the",
"content",
"of",
"file",
"named",
"name",
"to",
"filename",
"."
] | 359b474850622e3d0c25ee2596d7242c02f84efb | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L80-L98 | train |
cltl/KafNafParserPy | KafNafParserPy/temporal_data.py | CtemporalRelations.remove_this_tlink | def remove_this_tlink(self,tlink_id):
"""
Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed
"""
for tlink in self.get_tlinks():
if tlink.get_id() == tlink_id:
self.node.remove(tlink.get_node())
break | python | def remove_this_tlink(self,tlink_id):
"""
Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed
"""
for tlink in self.get_tlinks():
if tlink.get_id() == tlink_id:
self.node.remove(tlink.get_node())
break | [
"def",
"remove_this_tlink",
"(",
"self",
",",
"tlink_id",
")",
":",
"for",
"tlink",
"in",
"self",
".",
"get_tlinks",
"(",
")",
":",
"if",
"tlink",
".",
"get_id",
"(",
")",
"==",
"tlink_id",
":",
"self",
".",
"node",
".",
"remove",
"(",
"tlink",
".",
"get_node",
"(",
")",
")",
"break"
] | Removes the tlink for the given tlink identifier
@type tlink_id: string
@param tlink_id: the tlink identifier to be removed | [
"Removes",
"the",
"tlink",
"for",
"the",
"given",
"tlink",
"identifier"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/temporal_data.py#L344-L353 | train |
cltl/KafNafParserPy | KafNafParserPy/temporal_data.py | CtemporalRelations.remove_this_predicateAnchor | def remove_this_predicateAnchor(self,predAnch_id):
"""
Removes the predicate anchor for the given predicate anchor identifier
@type predAnch_id: string
@param predAnch_id: the predicate anchor identifier to be removed
"""
for predAnch in self.get_predicateAnchors():
if predAnch.get_id() == predAnch_id:
self.node.remove(predAnch.get_node())
break | python | def remove_this_predicateAnchor(self,predAnch_id):
"""
Removes the predicate anchor for the given predicate anchor identifier
@type predAnch_id: string
@param predAnch_id: the predicate anchor identifier to be removed
"""
for predAnch in self.get_predicateAnchors():
if predAnch.get_id() == predAnch_id:
self.node.remove(predAnch.get_node())
break | [
"def",
"remove_this_predicateAnchor",
"(",
"self",
",",
"predAnch_id",
")",
":",
"for",
"predAnch",
"in",
"self",
".",
"get_predicateAnchors",
"(",
")",
":",
"if",
"predAnch",
".",
"get_id",
"(",
")",
"==",
"predAnch_id",
":",
"self",
".",
"node",
".",
"remove",
"(",
"predAnch",
".",
"get_node",
"(",
")",
")",
"break"
] | Removes the predicate anchor for the given predicate anchor identifier
@type predAnch_id: string
@param predAnch_id: the predicate anchor identifier to be removed | [
"Removes",
"the",
"predicate",
"anchor",
"for",
"the",
"given",
"predicate",
"anchor",
"identifier"
] | 9bc32e803c176404b255ba317479b8780ed5f569 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/temporal_data.py#L363-L372 | train |
teepark/greenhouse | greenhouse/io/descriptor.py | wait_fds | def wait_fds(fd_events, inmask=1, outmask=2, timeout=None):
"""wait for the first of a number of file descriptors to have activity
.. note:: this method can block
it will return once there is relevant activity on the file descriptors,
or the timeout expires
:param fd_events:
two-tuples, each one a file descriptor and a mask made up of the inmask
and/or the outmask bitwise-ORd together
:type fd_events: list
:param inmask: the mask to use for readable events (default 1)
:type inmask: int
:param outmask: the mask to use for writable events (default 2)
:type outmask: int
:param timeout:
the maximum time to wait before raising an exception (default None)
:type timeout: int, float or None
:returns:
a list of two-tuples, each is a file descriptor and an event mask (made
up of inmask and/or outmask bitwise-ORd together) representing readable
and writable events
"""
current = compat.getcurrent()
activated = {}
poll_regs = {}
callback_refs = {}
def activate(fd, event):
if not activated and timeout != 0:
# this is the first invocation of `activated` for a blocking
# `wait_fds` call, so re-schedule the blocked coroutine
scheduler.schedule(current)
# if there was a timeout then also have to pull
# the coroutine from the timed_paused structure
if timeout:
scheduler._remove_timer(waketime, current)
# in any case, set the event information
activated.setdefault(fd, 0)
activated[fd] |= event
for fd, events in fd_events:
readable = None
writable = None
if events & inmask:
readable = functools.partial(activate, fd, inmask)
if events & outmask:
writable = functools.partial(activate, fd, outmask)
callback_refs[fd] = (readable, writable)
poll_regs[fd] = scheduler._register_fd(fd, readable, writable)
if timeout:
# real timeout value, schedule ourself `timeout` seconds in the future
waketime = time.time() + timeout
scheduler.pause_until(waketime)
elif timeout == 0:
# timeout == 0, only pause for 1 loop iteration
scheduler.pause()
else:
# timeout is None, it's up to _hit_poller->activate to bring us back
scheduler.state.mainloop.switch()
for fd, reg in poll_regs.iteritems():
readable, writable = callback_refs[fd]
scheduler._unregister_fd(fd, readable, writable, reg)
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call")
return activated.items() | python | def wait_fds(fd_events, inmask=1, outmask=2, timeout=None):
"""wait for the first of a number of file descriptors to have activity
.. note:: this method can block
it will return once there is relevant activity on the file descriptors,
or the timeout expires
:param fd_events:
two-tuples, each one a file descriptor and a mask made up of the inmask
and/or the outmask bitwise-ORd together
:type fd_events: list
:param inmask: the mask to use for readable events (default 1)
:type inmask: int
:param outmask: the mask to use for writable events (default 2)
:type outmask: int
:param timeout:
the maximum time to wait before raising an exception (default None)
:type timeout: int, float or None
:returns:
a list of two-tuples, each is a file descriptor and an event mask (made
up of inmask and/or outmask bitwise-ORd together) representing readable
and writable events
"""
current = compat.getcurrent()
activated = {}
poll_regs = {}
callback_refs = {}
def activate(fd, event):
if not activated and timeout != 0:
# this is the first invocation of `activated` for a blocking
# `wait_fds` call, so re-schedule the blocked coroutine
scheduler.schedule(current)
# if there was a timeout then also have to pull
# the coroutine from the timed_paused structure
if timeout:
scheduler._remove_timer(waketime, current)
# in any case, set the event information
activated.setdefault(fd, 0)
activated[fd] |= event
for fd, events in fd_events:
readable = None
writable = None
if events & inmask:
readable = functools.partial(activate, fd, inmask)
if events & outmask:
writable = functools.partial(activate, fd, outmask)
callback_refs[fd] = (readable, writable)
poll_regs[fd] = scheduler._register_fd(fd, readable, writable)
if timeout:
# real timeout value, schedule ourself `timeout` seconds in the future
waketime = time.time() + timeout
scheduler.pause_until(waketime)
elif timeout == 0:
# timeout == 0, only pause for 1 loop iteration
scheduler.pause()
else:
# timeout is None, it's up to _hit_poller->activate to bring us back
scheduler.state.mainloop.switch()
for fd, reg in poll_regs.iteritems():
readable, writable = callback_refs[fd]
scheduler._unregister_fd(fd, readable, writable, reg)
if scheduler.state.interrupted:
raise IOError(errno.EINTR, "interrupted system call")
return activated.items() | [
"def",
"wait_fds",
"(",
"fd_events",
",",
"inmask",
"=",
"1",
",",
"outmask",
"=",
"2",
",",
"timeout",
"=",
"None",
")",
":",
"current",
"=",
"compat",
".",
"getcurrent",
"(",
")",
"activated",
"=",
"{",
"}",
"poll_regs",
"=",
"{",
"}",
"callback_refs",
"=",
"{",
"}",
"def",
"activate",
"(",
"fd",
",",
"event",
")",
":",
"if",
"not",
"activated",
"and",
"timeout",
"!=",
"0",
":",
"# this is the first invocation of `activated` for a blocking",
"# `wait_fds` call, so re-schedule the blocked coroutine",
"scheduler",
".",
"schedule",
"(",
"current",
")",
"# if there was a timeout then also have to pull",
"# the coroutine from the timed_paused structure",
"if",
"timeout",
":",
"scheduler",
".",
"_remove_timer",
"(",
"waketime",
",",
"current",
")",
"# in any case, set the event information",
"activated",
".",
"setdefault",
"(",
"fd",
",",
"0",
")",
"activated",
"[",
"fd",
"]",
"|=",
"event",
"for",
"fd",
",",
"events",
"in",
"fd_events",
":",
"readable",
"=",
"None",
"writable",
"=",
"None",
"if",
"events",
"&",
"inmask",
":",
"readable",
"=",
"functools",
".",
"partial",
"(",
"activate",
",",
"fd",
",",
"inmask",
")",
"if",
"events",
"&",
"outmask",
":",
"writable",
"=",
"functools",
".",
"partial",
"(",
"activate",
",",
"fd",
",",
"outmask",
")",
"callback_refs",
"[",
"fd",
"]",
"=",
"(",
"readable",
",",
"writable",
")",
"poll_regs",
"[",
"fd",
"]",
"=",
"scheduler",
".",
"_register_fd",
"(",
"fd",
",",
"readable",
",",
"writable",
")",
"if",
"timeout",
":",
"# real timeout value, schedule ourself `timeout` seconds in the future",
"waketime",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"scheduler",
".",
"pause_until",
"(",
"waketime",
")",
"elif",
"timeout",
"==",
"0",
":",
"# timeout == 0, only pause for 1 loop iteration",
"scheduler",
".",
"pause",
"(",
")",
"else",
":",
"# timeout is None, it's up to _hit_poller->activate to bring us back",
"scheduler",
".",
"state",
".",
"mainloop",
".",
"switch",
"(",
")",
"for",
"fd",
",",
"reg",
"in",
"poll_regs",
".",
"iteritems",
"(",
")",
":",
"readable",
",",
"writable",
"=",
"callback_refs",
"[",
"fd",
"]",
"scheduler",
".",
"_unregister_fd",
"(",
"fd",
",",
"readable",
",",
"writable",
",",
"reg",
")",
"if",
"scheduler",
".",
"state",
".",
"interrupted",
":",
"raise",
"IOError",
"(",
"errno",
".",
"EINTR",
",",
"\"interrupted system call\"",
")",
"return",
"activated",
".",
"items",
"(",
")"
] | wait for the first of a number of file descriptors to have activity
.. note:: this method can block
it will return once there is relevant activity on the file descriptors,
or the timeout expires
:param fd_events:
two-tuples, each one a file descriptor and a mask made up of the inmask
and/or the outmask bitwise-ORd together
:type fd_events: list
:param inmask: the mask to use for readable events (default 1)
:type inmask: int
:param outmask: the mask to use for writable events (default 2)
:type outmask: int
:param timeout:
the maximum time to wait before raising an exception (default None)
:type timeout: int, float or None
:returns:
a list of two-tuples, each is a file descriptor and an event mask (made
up of inmask and/or outmask bitwise-ORd together) representing readable
and writable events | [
"wait",
"for",
"the",
"first",
"of",
"a",
"number",
"of",
"file",
"descriptors",
"to",
"have",
"activity"
] | 8fd1be4f5443ba090346b5ec82fdbeb0a060d956 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/descriptor.py#L13-L87 | train |
EVEprosper/ProsperCommon | setup.py | hack_find_packages | def hack_find_packages(include_str):
"""patches setuptools.find_packages issue
setuptools.find_packages(path='') doesn't work as intended
Returns:
list: append <include_str>. onto every element of setuptools.find_pacakges() call
"""
new_list = [include_str]
for element in find_packages(include_str):
new_list.append(include_str + '.' + element)
return new_list | python | def hack_find_packages(include_str):
"""patches setuptools.find_packages issue
setuptools.find_packages(path='') doesn't work as intended
Returns:
list: append <include_str>. onto every element of setuptools.find_pacakges() call
"""
new_list = [include_str]
for element in find_packages(include_str):
new_list.append(include_str + '.' + element)
return new_list | [
"def",
"hack_find_packages",
"(",
"include_str",
")",
":",
"new_list",
"=",
"[",
"include_str",
"]",
"for",
"element",
"in",
"find_packages",
"(",
"include_str",
")",
":",
"new_list",
".",
"append",
"(",
"include_str",
"+",
"'.'",
"+",
"element",
")",
"return",
"new_list"
] | patches setuptools.find_packages issue
setuptools.find_packages(path='') doesn't work as intended
Returns:
list: append <include_str>. onto every element of setuptools.find_pacakges() call | [
"patches",
"setuptools",
".",
"find_packages",
"issue"
] | bcada3b25420099e1f204db8d55eb268e7b4dc27 | https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/setup.py#L30-L43 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/queue.py | Requests.WaitUntilComplete | def WaitUntilComplete(self,poll_freq=2,timeout=None):
"""Poll until all request objects have completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' then success
Else log as error
poll_freq option is in seconds
Returns an Int the number of unsuccessful requests. This behavior is subject to change.
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntilComplete()
0
"""
start_time = time.time()
while len(self.requests):
cur_requests = []
for request in self.requests:
status = request.Status()
if status in ('notStarted','executing','resumed','queued','running'): cur_requests.append(request)
elif status == 'succeeded': self.success_requests.append(request)
elif status in ("failed", "unknown"): self.error_requests.append(request)
self.requests = cur_requests
if self.requests > 0 and clc.v2.time_utils.TimeoutExpired(start_time, timeout):
raise clc.RequestTimeoutException('Timeout waiting for Requests: {0}'.format(self.requests[0].id),
self.requests[0].Status())
time.sleep(poll_freq) # alternately - sleep for the delta between start time and 2s
# Is this the best approach? Non-zero indicates some error. Exception seems the wrong approach for
# a partial failure
return(len(self.error_requests)) | python | def WaitUntilComplete(self,poll_freq=2,timeout=None):
"""Poll until all request objects have completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' then success
Else log as error
poll_freq option is in seconds
Returns an Int the number of unsuccessful requests. This behavior is subject to change.
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntilComplete()
0
"""
start_time = time.time()
while len(self.requests):
cur_requests = []
for request in self.requests:
status = request.Status()
if status in ('notStarted','executing','resumed','queued','running'): cur_requests.append(request)
elif status == 'succeeded': self.success_requests.append(request)
elif status in ("failed", "unknown"): self.error_requests.append(request)
self.requests = cur_requests
if self.requests > 0 and clc.v2.time_utils.TimeoutExpired(start_time, timeout):
raise clc.RequestTimeoutException('Timeout waiting for Requests: {0}'.format(self.requests[0].id),
self.requests[0].Status())
time.sleep(poll_freq) # alternately - sleep for the delta between start time and 2s
# Is this the best approach? Non-zero indicates some error. Exception seems the wrong approach for
# a partial failure
return(len(self.error_requests)) | [
"def",
"WaitUntilComplete",
"(",
"self",
",",
"poll_freq",
"=",
"2",
",",
"timeout",
"=",
"None",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"len",
"(",
"self",
".",
"requests",
")",
":",
"cur_requests",
"=",
"[",
"]",
"for",
"request",
"in",
"self",
".",
"requests",
":",
"status",
"=",
"request",
".",
"Status",
"(",
")",
"if",
"status",
"in",
"(",
"'notStarted'",
",",
"'executing'",
",",
"'resumed'",
",",
"'queued'",
",",
"'running'",
")",
":",
"cur_requests",
".",
"append",
"(",
"request",
")",
"elif",
"status",
"==",
"'succeeded'",
":",
"self",
".",
"success_requests",
".",
"append",
"(",
"request",
")",
"elif",
"status",
"in",
"(",
"\"failed\"",
",",
"\"unknown\"",
")",
":",
"self",
".",
"error_requests",
".",
"append",
"(",
"request",
")",
"self",
".",
"requests",
"=",
"cur_requests",
"if",
"self",
".",
"requests",
">",
"0",
"and",
"clc",
".",
"v2",
".",
"time_utils",
".",
"TimeoutExpired",
"(",
"start_time",
",",
"timeout",
")",
":",
"raise",
"clc",
".",
"RequestTimeoutException",
"(",
"'Timeout waiting for Requests: {0}'",
".",
"format",
"(",
"self",
".",
"requests",
"[",
"0",
"]",
".",
"id",
")",
",",
"self",
".",
"requests",
"[",
"0",
"]",
".",
"Status",
"(",
")",
")",
"time",
".",
"sleep",
"(",
"poll_freq",
")",
"# alternately - sleep for the delta between start time and 2s",
"# Is this the best approach? Non-zero indicates some error. Exception seems the wrong approach for",
"# a partial failure",
"return",
"(",
"len",
"(",
"self",
".",
"error_requests",
")",
")"
] | Poll until all request objects have completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' then success
Else log as error
poll_freq option is in seconds
Returns an Int the number of unsuccessful requests. This behavior is subject to change.
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntilComplete()
0 | [
"Poll",
"until",
"all",
"request",
"objects",
"have",
"completed",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L119-L153 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/queue.py | Request.WaitUntilComplete | def WaitUntilComplete(self,poll_freq=2,timeout=None):
"""Poll until status is completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' return
Else raise exception
poll_freq option is in seconds
"""
start_time = time.time()
while not self.time_completed:
status = self.Status()
if status == 'executing':
if not self.time_executed: self.time_executed = time.time()
if clc.v2.time_utils.TimeoutExpired(start_time, timeout):
raise clc.RequestTimeoutException('Timeout waiting for Request: {0}'.format(self.id), status)
elif status == 'succeeded':
self.time_completed = time.time()
elif status in ("failed", "resumed" or "unknown"):
# TODO - need to ID best reaction for resumed status (e.g. manual intervention)
self.time_completed = time.time()
raise(clc.CLCException("%s %s execution %s" % (self.context_key,self.context_val,status)))
time.sleep(poll_freq) | python | def WaitUntilComplete(self,poll_freq=2,timeout=None):
"""Poll until status is completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' return
Else raise exception
poll_freq option is in seconds
"""
start_time = time.time()
while not self.time_completed:
status = self.Status()
if status == 'executing':
if not self.time_executed: self.time_executed = time.time()
if clc.v2.time_utils.TimeoutExpired(start_time, timeout):
raise clc.RequestTimeoutException('Timeout waiting for Request: {0}'.format(self.id), status)
elif status == 'succeeded':
self.time_completed = time.time()
elif status in ("failed", "resumed" or "unknown"):
# TODO - need to ID best reaction for resumed status (e.g. manual intervention)
self.time_completed = time.time()
raise(clc.CLCException("%s %s execution %s" % (self.context_key,self.context_val,status)))
time.sleep(poll_freq) | [
"def",
"WaitUntilComplete",
"(",
"self",
",",
"poll_freq",
"=",
"2",
",",
"timeout",
"=",
"None",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"not",
"self",
".",
"time_completed",
":",
"status",
"=",
"self",
".",
"Status",
"(",
")",
"if",
"status",
"==",
"'executing'",
":",
"if",
"not",
"self",
".",
"time_executed",
":",
"self",
".",
"time_executed",
"=",
"time",
".",
"time",
"(",
")",
"if",
"clc",
".",
"v2",
".",
"time_utils",
".",
"TimeoutExpired",
"(",
"start_time",
",",
"timeout",
")",
":",
"raise",
"clc",
".",
"RequestTimeoutException",
"(",
"'Timeout waiting for Request: {0}'",
".",
"format",
"(",
"self",
".",
"id",
")",
",",
"status",
")",
"elif",
"status",
"==",
"'succeeded'",
":",
"self",
".",
"time_completed",
"=",
"time",
".",
"time",
"(",
")",
"elif",
"status",
"in",
"(",
"\"failed\"",
",",
"\"resumed\"",
"or",
"\"unknown\"",
")",
":",
"# TODO - need to ID best reaction for resumed status (e.g. manual intervention)",
"self",
".",
"time_completed",
"=",
"time",
".",
"time",
"(",
")",
"raise",
"(",
"clc",
".",
"CLCException",
"(",
"\"%s %s execution %s\"",
"%",
"(",
"self",
".",
"context_key",
",",
"self",
".",
"context_val",
",",
"status",
")",
")",
")",
"time",
".",
"sleep",
"(",
"poll_freq",
")"
] | Poll until status is completed.
If status is 'notStarted' or 'executing' continue polling.
If status is 'succeeded' return
Else raise exception
poll_freq option is in seconds | [
"Poll",
"until",
"status",
"is",
"completed",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L197-L222 | train |
CenturyLinkCloud/clc-python-sdk | src/clc/APIv2/queue.py | Request.Server | def Server(self):
"""Return server associated with this request.
>>> d = clc.v2.Datacenter()
>>> q = clc.v2.Server.Create(name="api2",cpu=1,memory=1,group_id=d.Groups().Get("Default Group").id,template=d.Templates().Search("centos-6-64")[0].id,network_id=d.Networks().networks[0].id,ttl=4000)
>>> q.WaitUntilComplete()
0
>>> q.success_requests[0].Server()
<clc.APIv2.server.Server object at 0x1095a8390>
>>> print _
VA1BTDIAPI214
"""
if self.context_key == 'newserver':
server_id = clc.v2.API.Call('GET', self.context_val,session=self.session)['id']
return(clc.v2.Server(id=server_id,alias=self.alias,session=self.session))
elif self.context_key == 'server':
return(clc.v2.Server(id=self.context_val,alias=self.alias,session=self.session))
else: raise(clc.CLCException("%s object not server" % self.context_key)) | python | def Server(self):
"""Return server associated with this request.
>>> d = clc.v2.Datacenter()
>>> q = clc.v2.Server.Create(name="api2",cpu=1,memory=1,group_id=d.Groups().Get("Default Group").id,template=d.Templates().Search("centos-6-64")[0].id,network_id=d.Networks().networks[0].id,ttl=4000)
>>> q.WaitUntilComplete()
0
>>> q.success_requests[0].Server()
<clc.APIv2.server.Server object at 0x1095a8390>
>>> print _
VA1BTDIAPI214
"""
if self.context_key == 'newserver':
server_id = clc.v2.API.Call('GET', self.context_val,session=self.session)['id']
return(clc.v2.Server(id=server_id,alias=self.alias,session=self.session))
elif self.context_key == 'server':
return(clc.v2.Server(id=self.context_val,alias=self.alias,session=self.session))
else: raise(clc.CLCException("%s object not server" % self.context_key)) | [
"def",
"Server",
"(",
"self",
")",
":",
"if",
"self",
".",
"context_key",
"==",
"'newserver'",
":",
"server_id",
"=",
"clc",
".",
"v2",
".",
"API",
".",
"Call",
"(",
"'GET'",
",",
"self",
".",
"context_val",
",",
"session",
"=",
"self",
".",
"session",
")",
"[",
"'id'",
"]",
"return",
"(",
"clc",
".",
"v2",
".",
"Server",
"(",
"id",
"=",
"server_id",
",",
"alias",
"=",
"self",
".",
"alias",
",",
"session",
"=",
"self",
".",
"session",
")",
")",
"elif",
"self",
".",
"context_key",
"==",
"'server'",
":",
"return",
"(",
"clc",
".",
"v2",
".",
"Server",
"(",
"id",
"=",
"self",
".",
"context_val",
",",
"alias",
"=",
"self",
".",
"alias",
",",
"session",
"=",
"self",
".",
"session",
")",
")",
"else",
":",
"raise",
"(",
"clc",
".",
"CLCException",
"(",
"\"%s object not server\"",
"%",
"self",
".",
"context_key",
")",
")"
] | Return server associated with this request.
>>> d = clc.v2.Datacenter()
>>> q = clc.v2.Server.Create(name="api2",cpu=1,memory=1,group_id=d.Groups().Get("Default Group").id,template=d.Templates().Search("centos-6-64")[0].id,network_id=d.Networks().networks[0].id,ttl=4000)
>>> q.WaitUntilComplete()
0
>>> q.success_requests[0].Server()
<clc.APIv2.server.Server object at 0x1095a8390>
>>> print _
VA1BTDIAPI214 | [
"Return",
"server",
"associated",
"with",
"this",
"request",
"."
] | f4dba40c627cb08dd4b7d0d277e8d67578010b05 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L225-L243 | train |
thilux/tvdb_client | tvdb_client/clients/ApiV2Client.py | ApiV2Client.login | def login(self):
"""
This method performs the login on TheTVDB given the api key, user name and account identifier.
:return: None
"""
auth_data = dict()
auth_data['apikey'] = self.api_key
auth_data['username'] = self.username
auth_data['userkey'] = self.account_identifier
auth_resp = requests_util.run_request('post', self.API_BASE_URL + '/login', data=json.dumps(auth_data),
headers=self.__get_header())
if auth_resp.status_code == 200:
auth_resp_data = self.parse_raw_response(auth_resp)
self.__token = auth_resp_data['token']
self.__auth_time = datetime.now()
self.is_authenticated = True
else:
raise AuthenticationFailedException('Authentication failed!') | python | def login(self):
"""
This method performs the login on TheTVDB given the api key, user name and account identifier.
:return: None
"""
auth_data = dict()
auth_data['apikey'] = self.api_key
auth_data['username'] = self.username
auth_data['userkey'] = self.account_identifier
auth_resp = requests_util.run_request('post', self.API_BASE_URL + '/login', data=json.dumps(auth_data),
headers=self.__get_header())
if auth_resp.status_code == 200:
auth_resp_data = self.parse_raw_response(auth_resp)
self.__token = auth_resp_data['token']
self.__auth_time = datetime.now()
self.is_authenticated = True
else:
raise AuthenticationFailedException('Authentication failed!') | [
"def",
"login",
"(",
"self",
")",
":",
"auth_data",
"=",
"dict",
"(",
")",
"auth_data",
"[",
"'apikey'",
"]",
"=",
"self",
".",
"api_key",
"auth_data",
"[",
"'username'",
"]",
"=",
"self",
".",
"username",
"auth_data",
"[",
"'userkey'",
"]",
"=",
"self",
".",
"account_identifier",
"auth_resp",
"=",
"requests_util",
".",
"run_request",
"(",
"'post'",
",",
"self",
".",
"API_BASE_URL",
"+",
"'/login'",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"auth_data",
")",
",",
"headers",
"=",
"self",
".",
"__get_header",
"(",
")",
")",
"if",
"auth_resp",
".",
"status_code",
"==",
"200",
":",
"auth_resp_data",
"=",
"self",
".",
"parse_raw_response",
"(",
"auth_resp",
")",
"self",
".",
"__token",
"=",
"auth_resp_data",
"[",
"'token'",
"]",
"self",
".",
"__auth_time",
"=",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"is_authenticated",
"=",
"True",
"else",
":",
"raise",
"AuthenticationFailedException",
"(",
"'Authentication failed!'",
")"
] | This method performs the login on TheTVDB given the api key, user name and account identifier.
:return: None | [
"This",
"method",
"performs",
"the",
"login",
"on",
"TheTVDB",
"given",
"the",
"api",
"key",
"user",
"name",
"and",
"account",
"identifier",
"."
] | 2d5106f260367c0abe1284683697874df6343f78 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L79-L99 | train |
thilux/tvdb_client | tvdb_client/clients/ApiV2Client.py | ApiV2Client.search_series | def search_series(self, name=None, imdb_id=None, zap2it_id=None):
"""
Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id.
:param name: the name of the series to look for
:param imdb_id: the IMDB id of the series to look for
:param zap2it_id: the zap2it id of the series to look for.
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
arguments = locals()
optional_parameters = {'name': 'name', 'imdb_id': 'imdbId', 'zap2it_id': 'zap2itId'}
query_string = utils.query_param_string_from_option_args(optional_parameters, arguments)
raw_response = requests_util.run_request('get', '%s%s?%s' % (self.API_BASE_URL, '/search/series',
query_string),
headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | python | def search_series(self, name=None, imdb_id=None, zap2it_id=None):
"""
Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id.
:param name: the name of the series to look for
:param imdb_id: the IMDB id of the series to look for
:param zap2it_id: the zap2it id of the series to look for.
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
arguments = locals()
optional_parameters = {'name': 'name', 'imdb_id': 'imdbId', 'zap2it_id': 'zap2itId'}
query_string = utils.query_param_string_from_option_args(optional_parameters, arguments)
raw_response = requests_util.run_request('get', '%s%s?%s' % (self.API_BASE_URL, '/search/series',
query_string),
headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | [
"def",
"search_series",
"(",
"self",
",",
"name",
"=",
"None",
",",
"imdb_id",
"=",
"None",
",",
"zap2it_id",
"=",
"None",
")",
":",
"arguments",
"=",
"locals",
"(",
")",
"optional_parameters",
"=",
"{",
"'name'",
":",
"'name'",
",",
"'imdb_id'",
":",
"'imdbId'",
",",
"'zap2it_id'",
":",
"'zap2itId'",
"}",
"query_string",
"=",
"utils",
".",
"query_param_string_from_option_args",
"(",
"optional_parameters",
",",
"arguments",
")",
"raw_response",
"=",
"requests_util",
".",
"run_request",
"(",
"'get'",
",",
"'%s%s?%s'",
"%",
"(",
"self",
".",
"API_BASE_URL",
",",
"'/search/series'",
",",
"query_string",
")",
",",
"headers",
"=",
"self",
".",
"__get_header_with_auth",
"(",
")",
")",
"return",
"self",
".",
"parse_raw_response",
"(",
"raw_response",
")"
] | Searchs for a series in TheTVDB by either its name, imdb_id or zap2it_id.
:param name: the name of the series to look for
:param imdb_id: the IMDB id of the series to look for
:param zap2it_id: the zap2it id of the series to look for.
:return: a python dictionary with either the result of the search or an error from TheTVDB. | [
"Searchs",
"for",
"a",
"series",
"in",
"TheTVDB",
"by",
"either",
"its",
"name",
"imdb_id",
"or",
"zap2it_id",
"."
] | 2d5106f260367c0abe1284683697874df6343f78 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L102-L120 | train |
thilux/tvdb_client | tvdb_client/clients/ApiV2Client.py | ApiV2Client.get_series_actors | def get_series_actors(self, series_id):
"""
Retrieves the information on the actors of a particular series, given its TheTVDB id.
:param series_id: the TheTVDB id of the series
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
raw_response = requests_util.run_request('get', self.API_BASE_URL + '/series/%d/actors' % series_id,
headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | python | def get_series_actors(self, series_id):
"""
Retrieves the information on the actors of a particular series, given its TheTVDB id.
:param series_id: the TheTVDB id of the series
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
raw_response = requests_util.run_request('get', self.API_BASE_URL + '/series/%d/actors' % series_id,
headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | [
"def",
"get_series_actors",
"(",
"self",
",",
"series_id",
")",
":",
"raw_response",
"=",
"requests_util",
".",
"run_request",
"(",
"'get'",
",",
"self",
".",
"API_BASE_URL",
"+",
"'/series/%d/actors'",
"%",
"series_id",
",",
"headers",
"=",
"self",
".",
"__get_header_with_auth",
"(",
")",
")",
"return",
"self",
".",
"parse_raw_response",
"(",
"raw_response",
")"
] | Retrieves the information on the actors of a particular series, given its TheTVDB id.
:param series_id: the TheTVDB id of the series
:return: a python dictionary with either the result of the search or an error from TheTVDB. | [
"Retrieves",
"the",
"information",
"on",
"the",
"actors",
"of",
"a",
"particular",
"series",
"given",
"its",
"TheTVDB",
"id",
"."
] | 2d5106f260367c0abe1284683697874df6343f78 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L137-L148 | train |
thilux/tvdb_client | tvdb_client/clients/ApiV2Client.py | ApiV2Client.get_series_episodes | def get_series_episodes(self, series_id, page=1):
"""
Retrieves all episodes for a particular series given its TheTVDB id. It retrieves a maximum of 100 results per
page.
:param series_id: The TheTVDB id of the series.
:param page: The page number. If none is provided, 1 is used by default.
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
raw_response = requests_util.run_request('get', self.API_BASE_URL + '/series/%d/episodes?page=%d' %
(series_id, page), headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | python | def get_series_episodes(self, series_id, page=1):
"""
Retrieves all episodes for a particular series given its TheTVDB id. It retrieves a maximum of 100 results per
page.
:param series_id: The TheTVDB id of the series.
:param page: The page number. If none is provided, 1 is used by default.
:return: a python dictionary with either the result of the search or an error from TheTVDB.
"""
raw_response = requests_util.run_request('get', self.API_BASE_URL + '/series/%d/episodes?page=%d' %
(series_id, page), headers=self.__get_header_with_auth())
return self.parse_raw_response(raw_response) | [
"def",
"get_series_episodes",
"(",
"self",
",",
"series_id",
",",
"page",
"=",
"1",
")",
":",
"raw_response",
"=",
"requests_util",
".",
"run_request",
"(",
"'get'",
",",
"self",
".",
"API_BASE_URL",
"+",
"'/series/%d/episodes?page=%d'",
"%",
"(",
"series_id",
",",
"page",
")",
",",
"headers",
"=",
"self",
".",
"__get_header_with_auth",
"(",
")",
")",
"return",
"self",
".",
"parse_raw_response",
"(",
"raw_response",
")"
] | Retrieves all episodes for a particular series given its TheTVDB id. It retrieves a maximum of 100 results per
page.
:param series_id: The TheTVDB id of the series.
:param page: The page number. If none is provided, 1 is used by default.
:return: a python dictionary with either the result of the search or an error from TheTVDB. | [
"Retrieves",
"all",
"episodes",
"for",
"a",
"particular",
"series",
"given",
"its",
"TheTVDB",
"id",
".",
"It",
"retrieves",
"a",
"maximum",
"of",
"100",
"results",
"per",
"page",
"."
] | 2d5106f260367c0abe1284683697874df6343f78 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L151-L164 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.