partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | JsonStreamListener.on_exception | An exception occurred in the streaming thread | twitter_monitor/listener.py | def on_exception(self, exception):
"""An exception occurred in the streaming thread"""
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception | def on_exception(self, exception):
"""An exception occurred in the streaming thread"""
logger.error('Exception from stream!', exc_info=True)
self.streaming_exception = exception | [
"An",
"exception",
"occurred",
"in",
"the",
"streaming",
"thread"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/listener.py#L121-L124 | [
"def",
"on_exception",
"(",
"self",
",",
"exception",
")",
":",
"logger",
".",
"error",
"(",
"'Exception from stream!'",
",",
"exc_info",
"=",
"True",
")",
"self",
".",
"streaming_exception",
"=",
"exception"
] | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | TermChecker.check | Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False. | twitter_monitor/checker.py | def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... | def check(self):
"""
Checks if the list of tracked terms has changed.
Returns True if changed, otherwise False.
"""
new_tracking_terms = self.update_tracking_terms()
terms_changed = False
# any deleted terms?
if self._tracking_terms_set > new_tracking_t... | [
"Checks",
"if",
"the",
"list",
"of",
"tracked",
"terms",
"has",
"changed",
".",
"Returns",
"True",
"if",
"changed",
"otherwise",
"False",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L33-L57 | [
"def",
"check",
"(",
"self",
")",
":",
"new_tracking_terms",
"=",
"self",
".",
"update_tracking_terms",
"(",
")",
"terms_changed",
"=",
"False",
"# any deleted terms?",
"if",
"self",
".",
"_tracking_terms_set",
">",
"new_tracking_terms",
":",
"logging",
".",
"debu... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | FileTermChecker.update_tracking_terms | Terms must be one-per-line.
Blank lines will be skipped. | twitter_monitor/checker.py | def update_tracking_terms(self):
"""
Terms must be one-per-line.
Blank lines will be skipped.
"""
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set... | def update_tracking_terms(self):
"""
Terms must be one-per-line.
Blank lines will be skipped.
"""
import codecs
with codecs.open(self.filename,"r", encoding='utf8') as input:
# read all the lines
lines = input.readlines()
# build a set... | [
"Terms",
"must",
"be",
"one",
"-",
"per",
"-",
"line",
".",
"Blank",
"lines",
"will",
"be",
"skipped",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/checker.py#L75-L92 | [
"def",
"update_tracking_terms",
"(",
"self",
")",
":",
"import",
"codecs",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"filename",
",",
"\"r\"",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"input",
":",
"# read all the lines",
"lines",
"=",
"input",
".... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | launch_debugger | Interrupt running process, and provide a python prompt for
interactive debugging. | twitter_monitor/basic_stream.py | def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | def launch_debugger(frame, stream=None):
"""
Interrupt running process, and provide a python prompt for
interactive debugging.
"""
d = {'_frame': frame} # Allow access to frame object.
d.update(frame.f_globals) # Unless shadowed by global
d.update(frame.f_locals)
import code, traceba... | [
"Interrupt",
"running",
"process",
"and",
"provide",
"a",
"python",
"prompt",
"for",
"interactive",
"debugging",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L75-L90 | [
"def",
"launch_debugger",
"(",
"frame",
",",
"stream",
"=",
"None",
")",
":",
"d",
"=",
"{",
"'_frame'",
":",
"frame",
"}",
"# Allow access to frame object.",
"d",
".",
"update",
"(",
"frame",
".",
"f_globals",
")",
"# Unless shadowed by global",
"d",
".",
"... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | set_debug_listener | Break into a debugger if receives the SIGUSR1 signal | twitter_monitor/basic_stream.py | def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal"""
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode... | def set_debug_listener(stream):
"""Break into a debugger if receives the SIGUSR1 signal"""
def debugger(sig, frame):
launch_debugger(frame, stream)
if hasattr(signal, 'SIGUSR1'):
signal.signal(signal.SIGUSR1, debugger)
else:
logger.warn("Cannot set SIGUSR1 signal for debug mode... | [
"Break",
"into",
"a",
"debugger",
"if",
"receives",
"the",
"SIGUSR1",
"signal"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L93-L102 | [
"def",
"set_debug_listener",
"(",
"stream",
")",
":",
"def",
"debugger",
"(",
"sig",
",",
"frame",
")",
":",
"launch_debugger",
"(",
"frame",
",",
"stream",
")",
"if",
"hasattr",
"(",
"signal",
",",
"'SIGUSR1'",
")",
":",
"signal",
".",
"signal",
"(",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | set_terminate_listeners | Die on SIGTERM or SIGINT | twitter_monitor/basic_stream.py | def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | def set_terminate_listeners(stream):
"""Die on SIGTERM or SIGINT"""
def stop(signum, frame):
terminate(stream.listener)
# Installs signal handlers for handling SIGINT and SIGTERM
# gracefully.
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | [
"Die",
"on",
"SIGTERM",
"or",
"SIGINT"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L115-L124 | [
"def",
"set_terminate_listeners",
"(",
"stream",
")",
":",
"def",
"stop",
"(",
"signum",
",",
"frame",
")",
":",
"terminate",
"(",
"stream",
".",
"listener",
")",
"# Installs signal handlers for handling SIGINT and SIGTERM",
"# gracefully.",
"signal",
".",
"signal",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | get_tweepy_auth | Make a tweepy auth object | twitter_monitor/basic_stream.py | def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | [
"Make",
"a",
"tweepy",
"auth",
"object"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L127-L134 | [
"def",
"get_tweepy_auth",
"(",
"twitter_api_key",
",",
"twitter_api_secret",
",",
"twitter_access_token",
",",
"twitter_access_token_secret",
")",
":",
"auth",
"=",
"tweepy",
".",
"OAuthHandler",
"(",
"twitter_api_key",
",",
"twitter_api_secret",
")",
"auth",
".",
"se... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | construct_listener | Create the listener that prints tweets | twitter_monitor/basic_stream.py | def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) | def construct_listener(outfile=None):
"""Create the listener that prints tweets"""
if outfile is not None:
if os.path.exists(outfile):
raise IOError("File %s already exists" % outfile)
outfile = open(outfile, 'wb')
return PrintingListener(out=outfile) | [
"Create",
"the",
"listener",
"that",
"prints",
"tweets"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L137-L145 | [
"def",
"construct_listener",
"(",
"outfile",
"=",
"None",
")",
":",
"if",
"outfile",
"is",
"not",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"outfile",
")",
":",
"raise",
"IOError",
"(",
"\"File %s already exists\"",
"%",
"outfile",
")",
"... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | begin_stream_loop | Start and maintain the streaming connection... | twitter_monitor/basic_stream.py | def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... | def begin_stream_loop(stream, poll_interval):
"""Start and maintain the streaming connection..."""
while should_continue():
try:
stream.start_polling(poll_interval)
except Exception as e:
# Infinite restart
logger.error("Exception while polling. Restarting in ... | [
"Start",
"and",
"maintain",
"the",
"streaming",
"connection",
"..."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L150-L158 | [
"def",
"begin_stream_loop",
"(",
"stream",
",",
"poll_interval",
")",
":",
"while",
"should_continue",
"(",
")",
":",
"try",
":",
"stream",
".",
"start_polling",
"(",
"poll_interval",
")",
"except",
"Exception",
"as",
"e",
":",
"# Infinite restart",
"logger",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | start | Start the stream. | twitter_monitor/basic_stream.py | def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... | def start(track_file,
twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret,
poll_interval=15,
unfiltered=False,
languages=None,
debug=False,
outfile=None):
"""Start the stream."""
listener... | [
"Start",
"the",
"stream",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L161-L186 | [
"def",
"start",
"(",
"track_file",
",",
"twitter_api_key",
",",
"twitter_api_secret",
",",
"twitter_access_token",
",",
"twitter_access_token_secret",
",",
"poll_interval",
"=",
"15",
",",
"unfiltered",
"=",
"False",
",",
"languages",
"=",
"None",
",",
"debug",
"=... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | PrintingListener.on_status | Print out some tweets | twitter_monitor/basic_stream.py | def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | def on_status(self, status):
"""Print out some tweets"""
self.out.write(json.dumps(status))
self.out.write(os.linesep)
self.received += 1
return not self.terminate | [
"Print",
"out",
"some",
"tweets"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L38-L44 | [
"def",
"on_status",
"(",
"self",
",",
"status",
")",
":",
"self",
".",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"status",
")",
")",
"self",
".",
"out",
".",
"write",
"(",
"os",
".",
"linesep",
")",
"self",
".",
"received",
"+=",
"1",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | PrintingListener.print_status | Print out the current tweet rate and reset the counter | twitter_monitor/basic_stream.py | def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... | def print_status(self):
"""Print out the current tweet rate and reset the counter"""
tweets = self.received
now = time.time()
diff = now - self.since
self.since = now
self.received = 0
if diff > 0:
logger.info("Receiving tweets at %s tps", tweets / dif... | [
"Print",
"out",
"the",
"current",
"tweet",
"rate",
"and",
"reset",
"the",
"counter"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/basic_stream.py#L50-L58 | [
"def",
"print_status",
"(",
"self",
")",
":",
"tweets",
"=",
"self",
".",
"received",
"now",
"=",
"time",
".",
"time",
"(",
")",
"diff",
"=",
"now",
"-",
"self",
".",
"since",
"self",
".",
"since",
"=",
"now",
"self",
".",
"received",
"=",
"0",
"... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | DynamicTwitterStream.start_polling | Start polling for term updates and streaming. | twitter_monitor/stream.py | def start_polling(self, interval):
"""
Start polling for term updates and streaming.
"""
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for... | def start_polling(self, interval):
"""
Start polling for term updates and streaming.
"""
interval = float(interval)
self.polling = True
# clear the stored list of terms - we aren't tracking any
self.term_checker.reset()
logger.info("Starting polling for... | [
"Start",
"polling",
"for",
"term",
"updates",
"and",
"streaming",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L33-L56 | [
"def",
"start_polling",
"(",
"self",
",",
"interval",
")",
":",
"interval",
"=",
"float",
"(",
"interval",
")",
"self",
".",
"polling",
"=",
"True",
"# clear the stored list of terms - we aren't tracking any",
"self",
".",
"term_checker",
".",
"reset",
"(",
")",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | DynamicTwitterStream.update_stream | Restarts the stream with the current list of tracking terms. | twitter_monitor/stream.py | def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... | def update_stream(self):
"""
Restarts the stream with the current list of tracking terms.
"""
need_to_restart = False
# If we think we are running, but something has gone wrong in the streaming thread
# Restart it.
if self.stream is not None and not self.stream.... | [
"Restarts",
"the",
"stream",
"with",
"the",
"current",
"list",
"of",
"tracking",
"terms",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L65-L98 | [
"def",
"update_stream",
"(",
"self",
")",
":",
"need_to_restart",
"=",
"False",
"# If we think we are running, but something has gone wrong in the streaming thread",
"# Restart it.",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"stream",
... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | DynamicTwitterStream.start_stream | Starts a stream with teh current tracking terms | twitter_monitor/stream.py | def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | [
"Starts",
"a",
"stream",
"with",
"teh",
"current",
"tracking",
"terms"
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L100-L120 | [
"def",
"start_stream",
"(",
"self",
")",
":",
"tracking_terms",
"=",
"self",
".",
"term_checker",
".",
"tracking_terms",
"(",
")",
"if",
"len",
"(",
"tracking_terms",
")",
">",
"0",
"or",
"self",
".",
"unfiltered",
":",
"# we have terms to track, so build a new ... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | DynamicTwitterStream.stop_stream | Stops the current stream. Blocks until this is done. | twitter_monitor/stream.py | def stop_stream(self):
"""
Stops the current stream. Blocks until this is done.
"""
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
... | def stop_stream(self):
"""
Stops the current stream. Blocks until this is done.
"""
if self.stream is not None:
# There is a streaming thread
logger.warning("Stopping twitter stream...")
self.stream.disconnect()
self.stream = None
... | [
"Stops",
"the",
"current",
"stream",
".",
"Blocks",
"until",
"this",
"is",
"done",
"."
] | michaelbrooks/twitter-monitor | python | https://github.com/michaelbrooks/twitter-monitor/blob/3f99cea8492d3bdaa16f28a038bc8cf6022222ba/twitter_monitor/stream.py#L122-L136 | [
"def",
"stop_stream",
"(",
"self",
")",
":",
"if",
"self",
".",
"stream",
"is",
"not",
"None",
":",
"# There is a streaming thread",
"logger",
".",
"warning",
"(",
"\"Stopping twitter stream...\"",
")",
"self",
".",
"stream",
".",
"disconnect",
"(",
")",
"self... | 3f99cea8492d3bdaa16f28a038bc8cf6022222ba |
train | BaseTwitterTag.enrich | Apply the local presentation logic to the fetched data. | twitter_tag/templatetags/twitter_tag.py | def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %... | def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %... | [
"Apply",
"the",
"local",
"presentation",
"logic",
"to",
"the",
"fetched",
"data",
"."
] | coagulant/django-twitter-tag | python | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/templatetags/twitter_tag.py#L37-L47 | [
"def",
"enrich",
"(",
"self",
",",
"tweet",
")",
":",
"tweet",
"=",
"urlize_tweet",
"(",
"expand_tweet_urls",
"(",
"tweet",
")",
")",
"# parses created_at \"Wed Aug 27 13:08:45 +0000 2008\"",
"if",
"settings",
".",
"USE_TZ",
":",
"tweet",
"[",
"'datetime'",
"]",
... | 2cb0f46837279e12b1ac250794a71611bac1acdc |
train | get_user_cache_key | Generate suitable key to cache twitter tag context | twitter_tag/utils.py | def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... | def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... | [
"Generate",
"suitable",
"key",
"to",
"cache",
"twitter",
"tag",
"context"
] | coagulant/django-twitter-tag | python | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L9-L15 | [
"def",
"get_user_cache_key",
"(",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"'get_tweets_%s'",
"%",
"(",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"kwargs",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
")",
"if",
"kwargs",
"["... | 2cb0f46837279e12b1ac250794a71611bac1acdc |
train | get_search_cache_key | Generate suitable key to cache twitter tag context | twitter_tag/utils.py | def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | [
"Generate",
"suitable",
"key",
"to",
"cache",
"twitter",
"tag",
"context"
] | coagulant/django-twitter-tag | python | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L18-L24 | [
"def",
"get_search_cache_key",
"(",
"prefix",
",",
"*",
"args",
")",
":",
"key",
"=",
"'%s_%s'",
"%",
"(",
"prefix",
",",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"if",
"arg",
"]",
")",
")",
"not_allowed",
... | 2cb0f46837279e12b1ac250794a71611bac1acdc |
train | urlize_tweet | Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django. | twitter_tag/utils.py | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
"""
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %... | def urlize_tweet(tweet):
""" Turn #hashtag and @username in a text to Twitter hyperlinks,
similar to the ``urlize()`` function in Django.
"""
text = tweet.get('html', tweet['text'])
for hash in tweet['entities']['hashtags']:
text = text.replace('#%s' % hash['text'], TWITTER_HASHTAG_URL %... | [
"Turn",
"#hashtag",
"and"
] | coagulant/django-twitter-tag | python | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L31-L41 | [
"def",
"urlize_tweet",
"(",
"tweet",
")",
":",
"text",
"=",
"tweet",
".",
"get",
"(",
"'html'",
",",
"tweet",
"[",
"'text'",
"]",
")",
"for",
"hash",
"in",
"tweet",
"[",
"'entities'",
"]",
"[",
"'hashtags'",
"]",
":",
"text",
"=",
"text",
".",
"rep... | 2cb0f46837279e12b1ac250794a71611bac1acdc |
train | expand_tweet_urls | Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet | twitter_tag/utils.py | def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... | def expand_tweet_urls(tweet):
""" Replace shortened URLs with long URLs in the twitter status, and add the "RT" flag.
Should be used before urlize_tweet
"""
if 'retweeted_status' in tweet:
text = 'RT @{user}: {text}'.format(user=tweet['retweeted_status']['user']['screen_name'],
... | [
"Replace",
"shortened",
"URLs",
"with",
"long",
"URLs",
"in",
"the",
"twitter",
"status",
"and",
"add",
"the",
"RT",
"flag",
".",
"Should",
"be",
"used",
"before",
"urlize_tweet"
] | coagulant/django-twitter-tag | python | https://github.com/coagulant/django-twitter-tag/blob/2cb0f46837279e12b1ac250794a71611bac1acdc/twitter_tag/utils.py#L44-L59 | [
"def",
"expand_tweet_urls",
"(",
"tweet",
")",
":",
"if",
"'retweeted_status'",
"in",
"tweet",
":",
"text",
"=",
"'RT @{user}: {text}'",
".",
"format",
"(",
"user",
"=",
"tweet",
"[",
"'retweeted_status'",
"]",
"[",
"'user'",
"]",
"[",
"'screen_name'",
"]",
... | 2cb0f46837279e12b1ac250794a71611bac1acdc |
train | safe_power | Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b | rolldice/rolldice.py | def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | def safe_power(a, b):
"""
Same power of a ^ b
:param a: Number a
:param b: Number b
:return: a ^ b
"""
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
raise ValueError('Number too high!')
return a ** b | [
"Same",
"power",
"of",
"a",
"^",
"b",
":",
"param",
"a",
":",
"Number",
"a",
":",
"param",
"b",
":",
"Number",
"b",
":",
"return",
":",
"a",
"^",
"b"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L55-L64 | [
"def",
"safe_power",
"(",
"a",
",",
"b",
")",
":",
"if",
"abs",
"(",
"a",
")",
">",
"MAX_POWER",
"or",
"abs",
"(",
"b",
")",
">",
"MAX_POWER",
":",
"raise",
"ValueError",
"(",
"'Number too high!'",
")",
"return",
"a",
"**",
"b"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | rabin_miller | Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime | rolldice/rolldice.py | def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... | def rabin_miller(p):
"""
Performs a rabin-miller primality test
:param p: Number to test
:return: Bool of whether num is prime
"""
# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function
if p < 2:
return False
if p != 2 ... | [
"Performs",
"a",
"rabin",
"-",
"miller",
"primality",
"test"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L67-L91 | [
"def",
"rabin_miller",
"(",
"p",
")",
":",
"# From this stackoverflow answer: https://codegolf.stackexchange.com/questions/26739/super-speedy-totient-function",
"if",
"p",
"<",
"2",
":",
"return",
"False",
"if",
"p",
"!=",
"2",
"and",
"p",
"&",
"1",
"==",
"0",
":",
... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | zero_width_split | Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array | rolldice/rolldice.py | def zero_width_split(pattern, string):
"""
Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array
"""
splits = list((m.start(), m.end()) for m in regex.finditer(patt... | def zero_width_split(pattern, string):
"""
Split a string on a regex that only matches zero-width strings
:param pattern: Regex pattern that matches zero-width strings
:param string: String to split on.
:return: Split array
"""
splits = list((m.start(), m.end()) for m in regex.finditer(patt... | [
"Split",
"a",
"string",
"on",
"a",
"regex",
"that",
"only",
"matches",
"zero",
"-",
"width",
"strings"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L308-L319 | [
"def",
"zero_width_split",
"(",
"pattern",
",",
"string",
")",
":",
"splits",
"=",
"list",
"(",
"(",
"m",
".",
"start",
"(",
")",
",",
"m",
".",
"end",
"(",
")",
")",
"for",
"m",
"in",
"regex",
".",
"finditer",
"(",
"pattern",
",",
"string",
",",... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | roll_group | Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results | rolldice/rolldice.py | def roll_group(group):
"""
Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results
"""
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2... | def roll_group(group):
"""
Rolls a group of dice in 2d6, 3d10, d12, etc. format
:param group: String of dice group
:return: Array of results
"""
group = regex.match(r'^(\d*)d(\d+)$', group, regex.IGNORECASE)
num_of_dice = int(group[1]) if group[1] != '' else 1
type_of_dice = int(group[2... | [
"Rolls",
"a",
"group",
"of",
"dice",
"in",
"2d6",
"3d10",
"d12",
"etc",
".",
"format"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L322-L337 | [
"def",
"roll_group",
"(",
"group",
")",
":",
"group",
"=",
"regex",
".",
"match",
"(",
"r'^(\\d*)d(\\d+)$'",
",",
"group",
",",
"regex",
".",
"IGNORECASE",
")",
"num_of_dice",
"=",
"int",
"(",
"group",
"[",
"1",
"]",
")",
"if",
"group",
"[",
"1",
"]"... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | num_equal | Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
:return: | rolldice/rolldice.py | def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... | def num_equal(result, operator, comparator):
"""
Returns the number of elements in a list that pass a comparison
:param result: The list of results of a dice roll
:param operator: Operator in string to perform comparison on:
Either '+', '-', or '*'
:param comparator: The value to compare
... | [
"Returns",
"the",
"number",
"of",
"elements",
"in",
"a",
"list",
"that",
"pass",
"a",
"comparison"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L340-L357 | [
"def",
"num_equal",
"(",
"result",
",",
"operator",
",",
"comparator",
")",
":",
"if",
"operator",
"==",
"'<'",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"result",
"if",
"x",
"<",
"comparator",
"]",
")",
"elif",
"operator",
"==",
"'>'",
... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | roll_dice | Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string | rolldice/rolldice.py | def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... | def roll_dice(roll, *, functions=True, floats=True):
"""
Rolls dice in dice notation with advanced syntax used according to tinyurl.com/pydice
:param roll: Roll in dice notation
:return: Result of roll, and an explanation string
"""
roll = ''.join(roll.split())
roll = regex.sub(r'(?<=d)%', ... | [
"Rolls",
"dice",
"in",
"dice",
"notation",
"with",
"advanced",
"syntax",
"used",
"according",
"to",
"tinyurl",
".",
"com",
"/",
"pydice"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L360-L875 | [
"def",
"roll_dice",
"(",
"roll",
",",
"*",
",",
"functions",
"=",
"True",
",",
"floats",
"=",
"True",
")",
":",
"roll",
"=",
"''",
".",
"join",
"(",
"roll",
".",
"split",
"(",
")",
")",
"roll",
"=",
"regex",
".",
"sub",
"(",
"r'(?<=d)%'",
",",
... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval.eval | Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression | rolldice/rolldice.py | def eval(self, expr):
"""
Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression
"""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.pa... | def eval(self, expr):
"""
Evaluates an expression
:param expr: Expression to evaluate
:return: Result of expression
"""
# set a copy of the expression aside, so we can give nice errors...
self.expr = expr
# and evaluate:
return self._eval(ast.pa... | [
"Evaluates",
"an",
"expression"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L139-L151 | [
"def",
"eval",
"(",
"self",
",",
"expr",
")",
":",
"# set a copy of the expression aside, so we can give nice errors...",
"self",
".",
"expr",
"=",
"expr",
"# and evaluate:",
"return",
"self",
".",
"_eval",
"(",
"ast",
".",
"parse",
"(",
"expr",
".",
"strip",
"(... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval._eval | Evaluate a node
:param node: Node to eval
:return: Result of node | rolldice/rolldice.py | def _eval(self, node):
"""
Evaluate a node
:param node: Node to eval
:return: Result of node
"""
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na... | def _eval(self, node):
"""
Evaluate a node
:param node: Node to eval
:return: Result of node
"""
try:
handler = self.nodes[type(node)]
except KeyError:
raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__na... | [
"Evaluate",
"a",
"node"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L153-L165 | [
"def",
"_eval",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"handler",
"=",
"self",
".",
"nodes",
"[",
"type",
"(",
"node",
")",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Sorry, {0} is not available in this evaluator\"",
".",
"format... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval._eval_num | Evaluate a numerical node
:param node: Node to eval
:return: Result of node | rolldice/rolldice.py | def _eval_num(self, node):
"""
Evaluate a numerical node
:param node: Node to eval
:return: Result of node
"""
if self.floats:
return node.n
else:
return int(node.n) | def _eval_num(self, node):
"""
Evaluate a numerical node
:param node: Node to eval
:return: Result of node
"""
if self.floats:
return node.n
else:
return int(node.n) | [
"Evaluate",
"a",
"numerical",
"node"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L167-L177 | [
"def",
"_eval_num",
"(",
"self",
",",
"node",
")",
":",
"if",
"self",
".",
"floats",
":",
"return",
"node",
".",
"n",
"else",
":",
"return",
"int",
"(",
"node",
".",
"n",
")"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval._eval_unaryop | Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node | rolldice/rolldice.py | def _eval_unaryop(self, node):
"""
Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.operand)) | def _eval_unaryop(self, node):
"""
Evaluate a unary operator node (ie. -2, +3)
Currently just supports positive and negative
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.operand)) | [
"Evaluate",
"a",
"unary",
"operator",
"node",
"(",
"ie",
".",
"-",
"2",
"+",
"3",
")",
"Currently",
"just",
"supports",
"positive",
"and",
"negative"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L179-L187 | [
"def",
"_eval_unaryop",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"operators",
"[",
"type",
"(",
"node",
".",
"op",
")",
"]",
"(",
"self",
".",
"_eval",
"(",
"node",
".",
"operand",
")",
")"
] | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval._eval_binop | Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node | rolldice/rolldice.py | def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) | def _eval_binop(self, node):
"""
Evaluate a binary operator node (ie. 2+3, 5*6, 3 ** 4)
:param node: Node to eval
:return: Result of node
"""
return self.operators[type(node.op)](self._eval(node.left),
self._eval(node.right)) | [
"Evaluate",
"a",
"binary",
"operator",
"node",
"(",
"ie",
".",
"2",
"+",
"3",
"5",
"*",
"6",
"3",
"**",
"4",
")"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L189-L197 | [
"def",
"_eval_binop",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"operators",
"[",
"type",
"(",
"node",
".",
"op",
")",
"]",
"(",
"self",
".",
"_eval",
"(",
"node",
".",
"left",
")",
",",
"self",
".",
"_eval",
"(",
"node",
".",
... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | SimpleEval._eval_call | Evaluate a function call
:param node: Node to eval
:return: Result of node | rolldice/rolldice.py | def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | def _eval_call(self, node):
"""
Evaluate a function call
:param node: Node to eval
:return: Result of node
"""
try:
func = self.functions[node.func.id]
except KeyError:
raise NameError(node.func.id)
value = func(
*(sel... | [
"Evaluate",
"a",
"function",
"call"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L199-L221 | [
"def",
"_eval_call",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"func",
"=",
"self",
".",
"functions",
"[",
"node",
".",
"func",
".",
"id",
"]",
"except",
"KeyError",
":",
"raise",
"NameError",
"(",
"node",
".",
"func",
".",
"id",
")",
"value"... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | DiceBag.roll_dice | Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results. | rolldice/rolldice.py | def roll_dice(self): # Roll dice with current roll
"""
Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results.
"""
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._las... | def roll_dice(self): # Roll dice with current roll
"""
Rolls dicebag and sets last_roll and last_explanation to roll results
:return: Roll results.
"""
roll = roll_dice(self.roll, floats=self.floats, functions=self.functions)
self._last_roll = roll[0]
self._las... | [
"Rolls",
"dicebag",
"and",
"sets",
"last_roll",
"and",
"last_explanation",
"to",
"roll",
"results"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L242-L253 | [
"def",
"roll_dice",
"(",
"self",
")",
":",
"# Roll dice with current roll",
"roll",
"=",
"roll_dice",
"(",
"self",
".",
"roll",
",",
"floats",
"=",
"self",
".",
"floats",
",",
"functions",
"=",
"self",
".",
"functions",
")",
"self",
".",
"_last_roll",
"=",... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | DiceBag.roll | Setter for roll, verifies the roll is valid
:param value: Roll
:return: None | rolldice/rolldice.py | def roll(self, value):
"""
Setter for roll, verifies the roll is valid
:param value: Roll
:return: None
"""
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dic... | def roll(self, value):
"""
Setter for roll, verifies the roll is valid
:param value: Roll
:return: None
"""
if type(value) != str: # Make sure dice roll is a str
raise TypeError('Dice roll must be a string in dice notation')
try:
roll_dic... | [
"Setter",
"for",
"roll",
"verifies",
"the",
"roll",
"is",
"valid"
] | ThePlasmaRailgun/py-rolldice | python | https://github.com/ThePlasmaRailgun/py-rolldice/blob/dc46d1d3e765592e76c52fd812b4f3b7425db552/rolldice/rolldice.py#L273-L287 | [
"def",
"roll",
"(",
"self",
",",
"value",
")",
":",
"if",
"type",
"(",
"value",
")",
"!=",
"str",
":",
"# Make sure dice roll is a str",
"raise",
"TypeError",
"(",
"'Dice roll must be a string in dice notation'",
")",
"try",
":",
"roll_dice",
"(",
"value",
")",
... | dc46d1d3e765592e76c52fd812b4f3b7425db552 |
train | run | Look for pdb.set_trace() commands in python files. | captainhook/checkers/pdb_checker.py | def run(files, temp_folder, arg=''):
"Look for pdb.set_trace() commands in python files."
parser = get_parser()
args = parser.parse_args(arg.split())
py_files = filter_python_files(files)
if args.ignore:
orig_file_list = original_files(py_files, temp_folder)
py_files = set(orig_file... | def run(files, temp_folder, arg=''):
"Look for pdb.set_trace() commands in python files."
parser = get_parser()
args = parser.parse_args(arg.split())
py_files = filter_python_files(files)
if args.ignore:
orig_file_list = original_files(py_files, temp_folder)
py_files = set(orig_file... | [
"Look",
"for",
"pdb",
".",
"set_trace",
"()",
"commands",
"in",
"python",
"files",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pdb_checker.py#L15-L26 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"''",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"arg",
".",
"split",
"(",
")",
")",
"py_files",
"=",
"filter_python_files",
"(",
"f... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | checks | An iterator of valid checks that are in the installed checkers package.
yields check name, check module | captainhook/pre_commit.py | def checks():
"""
An iterator of valid checks that are in the installed checkers package.
yields check name, check module
"""
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = impo... | def checks():
"""
An iterator of valid checks that are in the installed checkers package.
yields check name, check module
"""
checkers_dir = os.path.dirname(checkers.__file__)
mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])]
for name in mod_names:
mod = impo... | [
"An",
"iterator",
"of",
"valid",
"checks",
"that",
"are",
"in",
"the",
"installed",
"checkers",
"package",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L40-L54 | [
"def",
"checks",
"(",
")",
":",
"checkers_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"checkers",
".",
"__file__",
")",
"mod_names",
"=",
"[",
"name",
"for",
"_",
",",
"name",
",",
"_",
"in",
"pkgutil",
".",
"iter_modules",
"(",
"[",
"checkers... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | files_to_check | Validate the commit diff.
Make copies of the staged changes for analysis. | captainhook/pre_commit.py | def files_to_check(commit_only):
"""
Validate the commit diff.
Make copies of the staged changes for analysis.
"""
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
... | def files_to_check(commit_only):
"""
Validate the commit diff.
Make copies of the staged changes for analysis.
"""
global TEMP_FOLDER
safe_directory = tempfile.mkdtemp()
TEMP_FOLDER = safe_directory
files = get_files(commit_only=commit_only, copy_dest=safe_directory)
try:
... | [
"Validate",
"the",
"commit",
"diff",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L66-L81 | [
"def",
"files_to_check",
"(",
"commit_only",
")",
":",
"global",
"TEMP_FOLDER",
"safe_directory",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"TEMP_FOLDER",
"=",
"safe_directory",
"files",
"=",
"get_files",
"(",
"commit_only",
"=",
"commit_only",
",",
"copy_dest",
... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | main | Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit | captainhook/pre_commit.py | def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... | def main(commit_only=True):
"""
Run the configured code checks.
Return system exit code.
1 - reject commit
0 - accept commit
"""
global TEMP_FOLDER
exit_code = 0
hook_checks = HookConfig(get_config_file())
with files_to_check(commit_only) as files:
for name, mod ... | [
"Run",
"the",
"configured",
"code",
"checks",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/pre_commit.py#L84-L123 | [
"def",
"main",
"(",
"commit_only",
"=",
"True",
")",
":",
"global",
"TEMP_FOLDER",
"exit_code",
"=",
"0",
"hook_checks",
"=",
"HookConfig",
"(",
"get_config_file",
"(",
")",
")",
"with",
"files_to_check",
"(",
"commit_only",
")",
"as",
"files",
":",
"for",
... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | get_files | Get copies of files for analysis. | captainhook/checkers/utils.py | def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash... | def get_files(commit_only=True, copy_dest=None):
"Get copies of files for analysis."
if commit_only:
real_files = bash(
"git diff --cached --name-status | "
"grep -v -E '^D' | "
"awk '{ print ( $(NF) ) }' "
).value().strip()
else:
real_files = bash... | [
"Get",
"copies",
"of",
"files",
"for",
"analysis",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L34-L49 | [
"def",
"get_files",
"(",
"commit_only",
"=",
"True",
",",
"copy_dest",
"=",
"None",
")",
":",
"if",
"commit_only",
":",
"real_files",
"=",
"bash",
"(",
"\"git diff --cached --name-status | \"",
"\"grep -v -E '^D' | \"",
"\"awk '{ print ( $(NF) ) }' \"",
")",
".",
"val... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | create_fake_copies | Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files. | captainhook/checkers/utils.py | def create_fake_copies(files, destination):
"""
Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files.
"""
dest_files = []
for filename in files:
leaf_d... | def create_fake_copies(files, destination):
"""
Create copies of the given list of files in the destination given.
Creates copies of the actual files to be committed using
git show :<filename>
Return a list of destination files.
"""
dest_files = []
for filename in files:
leaf_d... | [
"Create",
"copies",
"of",
"the",
"given",
"list",
"of",
"files",
"in",
"the",
"destination",
"given",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L52-L72 | [
"def",
"create_fake_copies",
"(",
"files",
",",
"destination",
")",
":",
"dest_files",
"=",
"[",
"]",
"for",
"filename",
"in",
"files",
":",
"leaf_dest_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"os",
".",
"path",
".",
"dirnam... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | filter_python_files | Get all python files from the list of files. | captainhook/checkers/utils.py | def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | [
"Get",
"all",
"python",
"files",
"from",
"the",
"list",
"of",
"files",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L75-L91 | [
"def",
"filter_python_files",
"(",
"files",
")",
":",
"py_files",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"# If we end in .py, or if we don't have an extension and file says that",
"# we are a python script, then add us to the list",
"extension",
"=",
"os",
".",
"pat... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | HookConfig.configuration | Get plugin configuration.
Return a tuple of (on|off|default, args) | captainhook/checkers/utils.py | def configuration(self, plugin):
"""
Get plugin configuration.
Return a tuple of (on|off|default, args)
"""
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) | def configuration(self, plugin):
"""
Get plugin configuration.
Return a tuple of (on|off|default, args)
"""
conf = self.config.get(plugin, "default;").split(';')
if len(conf) == 1:
conf.append('')
return tuple(conf) | [
"Get",
"plugin",
"configuration",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/utils.py#L121-L130 | [
"def",
"configuration",
"(",
"self",
",",
"plugin",
")",
":",
"conf",
"=",
"self",
".",
"config",
".",
"get",
"(",
"plugin",
",",
"\"default;\"",
")",
".",
"split",
"(",
"';'",
")",
"if",
"len",
"(",
"conf",
")",
"==",
"1",
":",
"conf",
".",
"app... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check frosted errors in the code base. | captainhook/checkers/frosted_checker.py | def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() | def run(files, temp_folder):
"Check frosted errors in the code base."
try:
import frosted # NOQA
except ImportError:
return NO_FROSTED_MSG
py_files = filter_python_files(files)
cmd = 'frosted {0}'.format(' '.join(py_files))
return bash(cmd).value() | [
"Check",
"frosted",
"errors",
"in",
"the",
"code",
"base",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/frosted_checker.py#L14-L24 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"frosted",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_FROSTED_MSG",
"py_files",
"=",
"filter_python_files",
"(",
"files",
")",
"cmd",
"=",
"'frosted {0}'",
".",
"format"... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411 | captainhook/checkers/isort_checker.py | def run(files, temp_folder):
"""Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
"""
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_... | def run(files, temp_folder):
"""Check isort errors in the code base.
For the --quiet option, at least isort >= 4.1.1 is required.
https://github.com/timothycrosley/isort/blob/develop/CHANGELOG.md#411
"""
try:
import isort # NOQA
except ImportError:
return NO_ISORT_MSG
py_... | [
"Check",
"isort",
"errors",
"in",
"the",
"code",
"base",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/isort_checker.py#L13-L28 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"isort",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_ISORT_MSG",
"py_files",
"=",
"filter_python_files",
"(",
"files",
")",
"# --quiet because isort >= 4.1 outputs its logo in th... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check we're not committing to a blocked branch | captainhook/checkers/block_branches.py | def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in arg... | def run(files, temp_folder, arg=None):
"Check we're not committing to a blocked branch"
parser = get_parser()
argos = parser.parse_args(arg.split())
current_branch = bash('git symbolic-ref HEAD').value()
current_branch = current_branch.replace('refs/heads/', '').strip()
if current_branch in arg... | [
"Check",
"we",
"re",
"not",
"committing",
"to",
"a",
"blocked",
"branch"
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/block_branches.py#L11-L20 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"None",
")",
":",
"parser",
"=",
"get_parser",
"(",
")",
"argos",
"=",
"parser",
".",
"parse_args",
"(",
"arg",
".",
"split",
"(",
")",
")",
"current_branch",
"=",
"bash",
"(",
"'git sy... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check coding convention of the code base. | captainhook/checkers/pylint_checker.py | def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
... | def run(files, temp_folder, arg=None):
"Check coding convention of the code base."
try:
import pylint
except ImportError:
return NO_PYLINT_MSG
# set default level of threshold
arg = arg or SCORE
py_files = filter_python_files(files)
if not py_files:
return False
... | [
"Check",
"coding",
"convention",
"of",
"the",
"code",
"base",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/pylint_checker.py#L17-L42 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
",",
"arg",
"=",
"None",
")",
":",
"try",
":",
"import",
"pylint",
"except",
"ImportError",
":",
"return",
"NO_PYLINT_MSG",
"# set default level of threshold",
"arg",
"=",
"arg",
"or",
"SCORE",
"py_files",
"=",
... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check to see if python files are py3 compatible | captainhook/checkers/python3.py | def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py... | def run(files, temp_folder):
"Check to see if python files are py3 compatible"
errors = []
for py_file in filter_python_files(files):
# We only want to show errors if we CAN'T compile to py3.
# but we want to show all the errors at once.
b = bash('python3 -m py_compile {0}'.format(py... | [
"Check",
"to",
"see",
"if",
"python",
"files",
"are",
"py3",
"compatible"
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/python3.py#L9-L19 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"py_file",
"in",
"filter_python_files",
"(",
"files",
")",
":",
"# We only want to show errors if we CAN'T compile to py3.",
"# but we want to show all the errors at once.",
"b",
"... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | run | Check flake8 errors in the code base. | captainhook/checkers/flake8_checker.py | def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy... | def run(files, temp_folder):
"Check flake8 errors in the code base."
try:
import flake8 # NOQA
except ImportError:
return NO_FLAKE_MSG
try:
from flake8.engine import get_style_guide
except ImportError:
# We're on a new version of flake8
from flake8.api.legacy... | [
"Check",
"flake8",
"errors",
"in",
"the",
"code",
"base",
"."
] | alexcouper/captainhook | python | https://github.com/alexcouper/captainhook/blob/5593ee8756dfa06959adb4320b4f6308277bb9d3/captainhook/checkers/flake8_checker.py#L45-L67 | [
"def",
"run",
"(",
"files",
",",
"temp_folder",
")",
":",
"try",
":",
"import",
"flake8",
"# NOQA",
"except",
"ImportError",
":",
"return",
"NO_FLAKE_MSG",
"try",
":",
"from",
"flake8",
".",
"engine",
"import",
"get_style_guide",
"except",
"ImportError",
":",
... | 5593ee8756dfa06959adb4320b4f6308277bb9d3 |
train | tictactoe | Put two strategies to a classic battle of wits. | examples/tttplaybitboard.py | def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... | def tictactoe(w, i, player, opponent, grid=None):
"Put two strategies to a classic battle of wits."
grid = grid or empty_grid
while True:
w.render_to_terminal(w.array_from_text(view(grid)))
if is_won(grid):
print(whose_move(grid), "wins.")
break
if not success... | [
"Put",
"two",
"strategies",
"to",
"a",
"classic",
"battle",
"of",
"wits",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L40-L52 | [
"def",
"tictactoe",
"(",
"w",
",",
"i",
",",
"player",
",",
"opponent",
",",
"grid",
"=",
"None",
")",
":",
"grid",
"=",
"grid",
"or",
"empty_grid",
"while",
"True",
":",
"w",
".",
"render_to_terminal",
"(",
"w",
".",
"array_from_text",
"(",
"view",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | memo | Return a function like f that remembers and reuses results of past calls. | examples/tttplaybitboard.py | def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f | def memo(f):
"Return a function like f that remembers and reuses results of past calls."
table = {}
def memo_f(*args):
try:
return table[args]
except KeyError:
table[args] = value = f(*args)
return value
return memo_f | [
"Return",
"a",
"function",
"like",
"f",
"that",
"remembers",
"and",
"reuses",
"results",
"of",
"past",
"calls",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L60-L69 | [
"def",
"memo",
"(",
"f",
")",
":",
"table",
"=",
"{",
"}",
"def",
"memo_f",
"(",
"*",
"args",
")",
":",
"try",
":",
"return",
"table",
"[",
"args",
"]",
"except",
"KeyError",
":",
"table",
"[",
"args",
"]",
"=",
"value",
"=",
"f",
"(",
"*",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | human_play | Just ask for a move. | examples/tttplaybitboard.py | def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
... | def human_play(w, i, grid):
"Just ask for a move."
plaint = ''
prompt = whose_move(grid) + " move? [1-9] "
while True:
w.render_to_terminal(w.array_from_text(view(grid)
+ '\n\n' + plaint + prompt))
key = c = i.next()
try:
... | [
"Just",
"ask",
"for",
"a",
"move",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L74-L94 | [
"def",
"human_play",
"(",
"w",
",",
"i",
",",
"grid",
")",
":",
"plaint",
"=",
"''",
"prompt",
"=",
"whose_move",
"(",
"grid",
")",
"+",
"\" move? [1-9] \"",
"while",
"True",
":",
"w",
".",
"render_to_terminal",
"(",
"w",
".",
"array_from_text",
"(",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | max_play | Play like Spock, except breaking ties by drunk_value. | examples/tttplaybitboard.py | def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) | def max_play(w, i, grid):
"Play like Spock, except breaking ties by drunk_value."
return min(successors(grid),
key=lambda succ: (evaluate(succ), drunk_value(succ))) | [
"Play",
"like",
"Spock",
"except",
"breaking",
"ties",
"by",
"drunk_value",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L106-L109 | [
"def",
"max_play",
"(",
"w",
",",
"i",
",",
"grid",
")",
":",
"return",
"min",
"(",
"successors",
"(",
"grid",
")",
",",
"key",
"=",
"lambda",
"succ",
":",
"(",
"evaluate",
"(",
"succ",
")",
",",
"drunk_value",
"(",
"succ",
")",
")",
")"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | drunk_value | Return the expected value to the player if both players play at random. | examples/tttplaybitboard.py | def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 | def drunk_value(grid):
"Return the expected value to the player if both players play at random."
if is_won(grid): return -1
succs = successors(grid)
return -average(map(drunk_value, succs)) if succs else 0 | [
"Return",
"the",
"expected",
"value",
"to",
"the",
"player",
"if",
"both",
"players",
"play",
"at",
"random",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L112-L116 | [
"def",
"drunk_value",
"(",
"grid",
")",
":",
"if",
"is_won",
"(",
"grid",
")",
":",
"return",
"-",
"1",
"succs",
"=",
"successors",
"(",
"grid",
")",
"return",
"-",
"average",
"(",
"map",
"(",
"drunk_value",
",",
"succs",
")",
")",
"if",
"succs",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | evaluate | Return the value for the player to move, assuming perfect play. | examples/tttplaybitboard.py | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | def evaluate(grid):
"Return the value for the player to move, assuming perfect play."
if is_won(grid): return -1
succs = successors(grid)
return -min(map(evaluate, succs)) if succs else 0 | [
"Return",
"the",
"value",
"for",
"the",
"player",
"to",
"move",
"assuming",
"perfect",
"play",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L119-L123 | [
"def",
"evaluate",
"(",
"grid",
")",
":",
"if",
"is_won",
"(",
"grid",
")",
":",
"return",
"-",
"1",
"succs",
"=",
"successors",
"(",
"grid",
")",
"return",
"-",
"min",
"(",
"map",
"(",
"evaluate",
",",
"succs",
")",
")",
"if",
"succs",
"else",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | is_won | Did the latest move win the game? | examples/tttplaybitboard.py | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | def is_won(grid):
"Did the latest move win the game?"
p, q = grid
return any(way == (way & q) for way in ways_to_win) | [
"Did",
"the",
"latest",
"move",
"win",
"the",
"game?"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L139-L142 | [
"def",
"is_won",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"any",
"(",
"way",
"==",
"(",
"way",
"&",
"q",
")",
"for",
"way",
"in",
"ways_to_win",
")"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | apply_move | Try to move: return a new grid, or None if illegal. | examples/tttplaybitboard.py | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | def apply_move(grid, move):
"Try to move: return a new grid, or None if illegal."
p, q = grid
bit = 1 << move
return (q, p | bit) if 0 == (bit & (p | q)) else None | [
"Try",
"to",
"move",
":",
"return",
"a",
"new",
"grid",
"or",
"None",
"if",
"illegal",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L161-L165 | [
"def",
"apply_move",
"(",
"grid",
",",
"move",
")",
":",
"p",
",",
"q",
"=",
"grid",
"bit",
"=",
"1",
"<<",
"move",
"return",
"(",
"q",
",",
"p",
"|",
"bit",
")",
"if",
"0",
"==",
"(",
"bit",
"&",
"(",
"p",
"|",
"q",
")",
")",
"else",
"No... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | player_marks | Return two results: the player's mark and their opponent's. | examples/tttplaybitboard.py | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | def player_marks(grid):
"Return two results: the player's mark and their opponent's."
p, q = grid
return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX' | [
"Return",
"two",
"results",
":",
"the",
"player",
"s",
"mark",
"and",
"their",
"opponent",
"s",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L181-L184 | [
"def",
"player_marks",
"(",
"grid",
")",
":",
"p",
",",
"q",
"=",
"grid",
"return",
"'XO'",
"if",
"sum",
"(",
"player_bits",
"(",
"p",
")",
")",
"==",
"sum",
"(",
"player_bits",
"(",
"q",
")",
")",
"else",
"'OX'"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | view | Show a grid human-readably. | examples/tttplaybitboard.py | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | def view(grid):
"Show a grid human-readably."
p_mark, q_mark = player_marks(grid)
return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.'
for by_p, by_q in zip(*map(player_bits, grid))) | [
"Show",
"a",
"grid",
"human",
"-",
"readably",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/tttplaybitboard.py#L189-L193 | [
"def",
"view",
"(",
"grid",
")",
":",
"p_mark",
",",
"q_mark",
"=",
"player_marks",
"(",
"grid",
")",
"return",
"grid_format",
"%",
"tuple",
"(",
"p_mark",
"if",
"by_p",
"else",
"q_mark",
"if",
"by_q",
"else",
"'.'",
"for",
"by_p",
",",
"by_q",
"in",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | read_sdpa_out | Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solutionmatrix: bool.
:param status: Optional parameter for retrieving the status.
:type status:... | ncpol2sdpa/sdpa_utils.py | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | def read_sdpa_out(filename, solutionmatrix=False, status=False,
sdp=None):
"""Helper function to parse the output file of SDPA.
:param filename: The name of the SDPA output file.
:type filename: str.
:param solutionmatrix: Optional parameter for retrieving the solution.
:type solu... | [
"Helper",
"function",
"to",
"parse",
"the",
"output",
"file",
"of",
"SDPA",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L47-L119 | [
"def",
"read_sdpa_out",
"(",
"filename",
",",
"solutionmatrix",
"=",
"False",
",",
"status",
"=",
"False",
",",
"sdp",
"=",
"None",
")",
":",
"primal",
"=",
"None",
"dual",
"=",
"None",
"x_mat",
"=",
"None",
"y_mat",
"=",
"None",
"status_string",
"=",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | solve_with_sdpa | Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:type solverparameters: dict of str.
:returns: tuple of... | ncpol2sdpa/sdpa_utils.py | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | def solve_with_sdpa(sdp, solverparameters=None):
"""Helper function to write out the SDP problem to a temporary
file, call the solver, and parse the output.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param solverparameters: Optional parameters to SDPA.
:ty... | [
"Helper",
"function",
"to",
"write",
"out",
"the",
"SDP",
"problem",
"to",
"a",
"temporary",
"file",
"call",
"the",
"solver",
"and",
"parse",
"the",
"output",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L148-L191 | [
"def",
"solve_with_sdpa",
"(",
"sdp",
",",
"solverparameters",
"=",
"None",
")",
":",
"solverexecutable",
"=",
"detect_sdpa",
"(",
"solverparameters",
")",
"if",
"solverexecutable",
"is",
"None",
":",
"raise",
"OSError",
"(",
"\"SDPA is not in the path or the executab... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | convert_row_to_sdpa_index | Helper function to map to sparse SDPA index values. | ncpol2sdpa/sdpa_utils.py | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | def convert_row_to_sdpa_index(block_struct, row_offsets, row):
"""Helper function to map to sparse SDPA index values.
"""
block_index = bisect_left(row_offsets[1:], row + 1)
width = block_struct[block_index]
row = row - row_offsets[block_index]
i, j = divmod(row, width)
return block_index, i... | [
"Helper",
"function",
"to",
"map",
"to",
"sparse",
"SDPA",
"index",
"values",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L194-L201 | [
"def",
"convert_row_to_sdpa_index",
"(",
"block_struct",
",",
"row_offsets",
",",
"row",
")",
":",
"block_index",
"=",
"bisect_left",
"(",
"row_offsets",
"[",
"1",
":",
"]",
",",
"row",
"+",
"1",
")",
"width",
"=",
"block_struct",
"[",
"block_index",
"]",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | write_to_sdpa | Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str. | ncpol2sdpa/sdpa_utils.py | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | def write_to_sdpa(sdp, filename):
"""Write the SDP relaxation to SDPA format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file. It must have the suffix ".dat-s"
:type filename: str.
"""
# Coefficient matrices
row_offsets ... | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"SDPA",
"format",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L204-L273 | [
"def",
"write_to_sdpa",
"(",
"sdp",
",",
"filename",
")",
":",
"# Coefficient matrices",
"row_offsets",
"=",
"[",
"0",
"]",
"cumulative_sum",
"=",
"0",
"for",
"block_size",
"in",
"sdp",
".",
"block_struct",
":",
"cumulative_sum",
"+=",
"block_size",
"**",
"2",... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | convert_to_human_readable | Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the moment matrix | ncpol2sdpa/sdpa_utils.py | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | def convert_to_human_readable(sdp):
"""Convert the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:returns: tuple of the objective function in a string and a matrix of
strings as the symbolic representation of the mo... | [
"Convert",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L276-L341 | [
"def",
"convert_to_human_readable",
"(",
"sdp",
")",
":",
"objective",
"=",
"\"\"",
"indices_in_objective",
"=",
"[",
"]",
"for",
"i",
",",
"tmp",
"in",
"enumerate",
"(",
"sdp",
".",
"obj_facvar",
")",
":",
"candidates",
"=",
"[",
"key",
"for",
"key",
",... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | write_to_human_readable | Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str. | ncpol2sdpa/sdpa_utils.py | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | def write_to_human_readable(sdp, filename):
"""Write the SDP relaxation to a human-readable format.
:param sdp: The SDP relaxation to write.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param filename: The name of the file.
:type filename: str.
"""
objective, matrix = convert_to_human_readable(sdp)... | [
"Write",
"the",
"SDP",
"relaxation",
"to",
"a",
"human",
"-",
"readable",
"format",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdpa_utils.py#L344-L359 | [
"def",
"write_to_human_readable",
"(",
"sdp",
",",
"filename",
")",
":",
"objective",
",",
"matrix",
"=",
"convert_to_human_readable",
"(",
"sdp",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"Objective:\"",
"+",
"obje... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | main | Ideally we shouldn't lose the first second of events | examples/initial_input_with_cursor.py | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | def main():
"""Ideally we shouldn't lose the first second of events"""
with Input() as input_generator:
def extra_bytes_callback(string):
print('got extra bytes', repr(string))
print('type:', type(string))
input_generator.unget_bytes(string)
time.sleep(1)
... | [
"Ideally",
"we",
"shouldn",
"t",
"lose",
"the",
"first",
"second",
"of",
"events"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/initial_input_with_cursor.py#L5-L16 | [
"def",
"main",
"(",
")",
":",
"with",
"Input",
"(",
")",
"as",
"input_generator",
":",
"def",
"extra_bytes_callback",
"(",
"string",
")",
":",
"print",
"(",
"'got extra bytes'",
",",
"repr",
"(",
"string",
")",
")",
"print",
"(",
"'type:'",
",",
"type",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | make_header | create request header function
:param url: URL for the new :class:`Request` object. | coincheck/utils.py | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | def make_header(url,
access_key=None,
secret_key=None):
''' create request header function
:param url: URL for the new :class:`Request` object.
'''
nonce = nounce()
url = url
message = nonce + url
signature = hmac.new(secret_key.encode('utf-8'), message.enc... | [
"create",
"request",
"header",
"function",
":",
"param",
"url",
":",
"URL",
"for",
"the",
"new",
":",
"class",
":",
"Request",
"object",
"."
] | kmn/coincheck | python | https://github.com/kmn/coincheck/blob/4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc/coincheck/utils.py#L14-L29 | [
"def",
"make_header",
"(",
"url",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"nonce",
"=",
"nounce",
"(",
")",
"url",
"=",
"url",
"message",
"=",
"nonce",
"+",
"url",
"signature",
"=",
"hmac",
".",
"new",
"(",
"secret_k... | 4e1062f1e564cddceec2f6fb4d70fe3a3ab645bc |
train | Input.unget_bytes | Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object | curtsies/input.py | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | def unget_bytes(self, string):
"""Adds bytes to be internal buffer to be read
This method is for reporting bytes from an in_stream read
not initiated by this Input object"""
self.unprocessed_bytes.extend(string[i:i + 1]
for i in range(len(string))) | [
"Adds",
"bytes",
"to",
"be",
"internal",
"buffer",
"to",
"be",
"read"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L120-L127 | [
"def",
"unget_bytes",
"(",
"self",
",",
"string",
")",
":",
"self",
".",
"unprocessed_bytes",
".",
"extend",
"(",
"string",
"[",
"i",
":",
"i",
"+",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
")"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input._wait_for_read_ready_or_timeout | Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a SIGTSTP
triggered by dsusp has been received | curtsies/input.py | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | def _wait_for_read_ready_or_timeout(self, timeout):
"""Returns tuple of whether stdin is ready to read and an event.
If an event is returned, that event is more pressing than reading
bytes on stdin to create a keyboard input event.
If stdin is ready, either there are bytes to read or a ... | [
"Returns",
"tuple",
"of",
"whether",
"stdin",
"is",
"ready",
"to",
"read",
"and",
"an",
"event",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L129-L162 | [
"def",
"_wait_for_read_ready_or_timeout",
"(",
"self",
",",
"timeout",
")",
":",
"remaining_timeout",
"=",
"timeout",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"try",
":",
"(",
"rs",
",",
"_",
",",
"_",
")",
"=",
"select",
".",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input.send | Returns an event or None if no events occur before timeout. | curtsies/input.py | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | def send(self, timeout=None):
"""Returns an event or None if no events occur before timeout."""
if self.sigint_event and is_main_thread():
with ReplacedSigIntHandler(self.sigint_handler):
return self._send(timeout)
else:
return self._send(timeout) | [
"Returns",
"an",
"event",
"or",
"None",
"if",
"no",
"events",
"occur",
"before",
"timeout",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L164-L170 | [
"def",
"send",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"sigint_event",
"and",
"is_main_thread",
"(",
")",
":",
"with",
"ReplacedSigIntHandler",
"(",
"self",
".",
"sigint_handler",
")",
":",
"return",
"self",
".",
"_send",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input._nonblocking_read | Returns the number of characters read and adds them to self.unprocessed_bytes | curtsies/input.py | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | def _nonblocking_read(self):
"""Returns the number of characters read and adds them to self.unprocessed_bytes"""
with Nonblocking(self.in_stream):
if PY3:
try:
data = os.read(self.in_stream.fileno(), READ_SIZE)
except BlockingIOError:
... | [
"Returns",
"the",
"number",
"of",
"characters",
"read",
"and",
"adds",
"them",
"to",
"self",
".",
"unprocessed_bytes"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L245-L265 | [
"def",
"_nonblocking_read",
"(",
"self",
")",
":",
"with",
"Nonblocking",
"(",
"self",
".",
"in_stream",
")",
":",
"if",
"PY3",
":",
"try",
":",
"data",
"=",
"os",
".",
"read",
"(",
"self",
".",
"in_stream",
".",
"fileno",
"(",
")",
",",
"READ_SIZE",... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input.event_trigger | Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | curtsies/input.py | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | def event_trigger(self, event_type):
"""Returns a callback that creates events.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(**kwargs):
self.queued_events.append(event_ty... | [
"Returns",
"a",
"callback",
"that",
"creates",
"events",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L267-L274 | [
"def",
"event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_events",
".",
"append",
"(",
"event_type",
"(",
"*",
"*",
"kwargs",
")",
")",
"return",
"callback"
] | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input.scheduled_event_trigger | Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested. | curtsies/input.py | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | def scheduled_event_trigger(self, event_type):
"""Returns a callback that schedules events for the future.
Returned callback function will add an event of type event_type
to a queue which will be checked the next time an event is requested."""
def callback(when, **kwargs):
s... | [
"Returns",
"a",
"callback",
"that",
"schedules",
"events",
"for",
"the",
"future",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L276-L283 | [
"def",
"scheduled_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"def",
"callback",
"(",
"when",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"queued_scheduled_events",
".",
"append",
"(",
"(",
"when",
",",
"event_type",
"(",
"when",
"=",
"... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Input.threadsafe_event_trigger | Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the event to a queue
that will be checked on the next eve... | curtsies/input.py | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | def threadsafe_event_trigger(self, event_type):
"""Returns a callback to creates events, interrupting current event requests.
Returned callback function will create an event of type event_type
which will interrupt an event request if one
is concurrently occuring, otherwise adding the ev... | [
"Returns",
"a",
"callback",
"to",
"creates",
"events",
"interrupting",
"current",
"event",
"requests",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/input.py#L285-L299 | [
"def",
"threadsafe_event_trigger",
"(",
"self",
",",
"event_type",
")",
":",
"readfd",
",",
"writefd",
"=",
"os",
".",
"pipe",
"(",
")",
"self",
".",
"readers",
".",
"append",
"(",
"readfd",
")",
"def",
"callback",
"(",
"*",
"*",
"kwargs",
")",
":",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | solve_sdp | Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.
:param solver: The solver to be called, eit... | ncpol2sdpa/solver_common.py | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | def solve_sdp(sdp, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices.
:param sdpRelaxation: The SDP relaxation to be solved.
:type sdpRelaxation: :class:`ncpol2sdpa.... | [
"Call",
"a",
"solver",
"on",
"the",
"SDP",
"relaxation",
".",
"Upon",
"successful",
"solution",
"it",
"returns",
"the",
"primal",
"and",
"dual",
"objective",
"values",
"along",
"with",
"the",
"solution",
"matrices",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L46-L140 | [
"def",
"solve_sdp",
"(",
"sdp",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"solvers",
"=",
"autodetect_solvers",
"(",
"solverparameters",
")",
"solver",
"=",
"solver",
".",
"lower",
"(",
")",
"if",
"solver",
"is",
"not",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | find_solution_ranks | Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided, the solution is extracted
from the sdp ob... | ncpol2sdpa/solver_common.py | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | def find_solution_ranks(sdp, xmat=None, baselevel=0):
"""Helper function to detect rank loop in the solution matrix.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param x_mat: Optional parameter providing the primal solution of the
moment matrix. If not provided... | [
"Helper",
"function",
"to",
"detect",
"rank",
"loop",
"in",
"the",
"solution",
"matrix",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L143-L181 | [
"def",
"find_solution_ranks",
"(",
"sdp",
",",
"xmat",
"=",
"None",
",",
"baselevel",
"=",
"0",
")",
":",
"if",
"sdp",
".",
"status",
"==",
"\"unsolved\"",
"and",
"xmat",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"The SDP relaxation is unsolved and no pr... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | get_sos_decomposition | Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
moment matrix. If not provided, the solution is extracted
... | ncpol2sdpa/solver_common.py | def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
... | def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
"""Given a solution of the dual problem, it returns the SOS
decomposition.
:param sdp: The SDP relaxation to be solved.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param y_mat: Optional parameter providing the dual solution of the
... | [
"Given",
"a",
"solution",
"of",
"the",
"dual",
"problem",
"it",
"returns",
"the",
"SOS",
"decomposition",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L184-L236 | [
"def",
"get_sos_decomposition",
"(",
"sdp",
",",
"y_mat",
"=",
"None",
",",
"threshold",
"=",
"0.0",
")",
":",
"if",
"len",
"(",
"sdp",
".",
"monomial_sets",
")",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"\"Cannot automatically match primal and dual \"",
"+"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | extract_dual_value | Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sdpa.sdp`.
:param monomial: The monomial for which the va... | ncpol2sdpa/solver_common.py | def extract_dual_value(sdp, monomial, blocks=None):
"""Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sd... | def extract_dual_value(sdp, monomial, blocks=None):
"""Given a solution of the dual problem and a monomial, it returns the
inner product of the corresponding coefficient matrix and the dual
solution. It can be restricted to certain blocks.
:param sdp: The SDP relaxation.
:type sdp: :class:`ncpol2sd... | [
"Given",
"a",
"solution",
"of",
"the",
"dual",
"problem",
"and",
"a",
"monomial",
"it",
"returns",
"the",
"inner",
"product",
"of",
"the",
"corresponding",
"coefficient",
"matrix",
"and",
"the",
"dual",
"solution",
".",
"It",
"can",
"be",
"restricted",
"to",... | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/solver_common.py#L344-L386 | [
"def",
"extract_dual_value",
"(",
"sdp",
",",
"monomial",
",",
"blocks",
"=",
"None",
")",
":",
"if",
"sdp",
".",
"status",
"==",
"\"unsolved\"",
":",
"raise",
"Exception",
"(",
"\"The SDP relaxation is unsolved!\"",
")",
"if",
"blocks",
"is",
"None",
":",
"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | completed_number | 'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16 | barnum/gencc.py | def completed_number(prefix, length):
"""
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
"""
ccnumber = prefix
# generate digits
while len(ccnumber) < (length - 1):
digit = random.choic... | def completed_number(prefix, length):
"""
'prefix' is the start of the CC number as a string, any number of digits.
'length' is the length of the CC number to generate. Typically 13 or 16
"""
ccnumber = prefix
# generate digits
while len(ccnumber) < (length - 1):
digit = random.choic... | [
"prefix",
"is",
"the",
"start",
"of",
"the",
"CC",
"number",
"as",
"a",
"string",
"any",
"number",
"of",
"digits",
".",
"length",
"is",
"the",
"length",
"of",
"the",
"CC",
"number",
"to",
"generate",
".",
"Typically",
"13",
"or",
"16"
] | chris1610/barnum-proj | python | https://github.com/chris1610/barnum-proj/blob/0a38f24bde66373553d02fbf67b733c1d55ada33/barnum/gencc.py#L63-L90 | [
"def",
"completed_number",
"(",
"prefix",
",",
"length",
")",
":",
"ccnumber",
"=",
"prefix",
"# generate digits",
"while",
"len",
"(",
"ccnumber",
")",
"<",
"(",
"length",
"-",
"1",
")",
":",
"digit",
"=",
"random",
".",
"choice",
"(",
"[",
"'0'",
","... | 0a38f24bde66373553d02fbf67b733c1d55ada33 |
train | JsonLoader.load_module | load_module is always called with the same argument as finder's
find_module, see "How Import Works" | ezcf/type_json.py | def load_module(self, fullname):
"""
load_module is always called with the same argument as finder's
find_module, see "How Import Works"
"""
mod = super(JsonLoader, self).load_module(fullname)
try:
with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
... | def load_module(self, fullname):
"""
load_module is always called with the same argument as finder's
find_module, see "How Import Works"
"""
mod = super(JsonLoader, self).load_module(fullname)
try:
with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
... | [
"load_module",
"is",
"always",
"called",
"with",
"the",
"same",
"argument",
"as",
"finder",
"s",
"find_module",
"see",
"How",
"Import",
"Works"
] | laike9m/ezcf | python | https://github.com/laike9m/ezcf/blob/30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12/ezcf/type_json.py#L32-L53 | [
"def",
"load_module",
"(",
"self",
",",
"fullname",
")",
":",
"mod",
"=",
"super",
"(",
"JsonLoader",
",",
"self",
")",
".",
"load_module",
"(",
"fullname",
")",
"try",
":",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"cfg_file",
",",
"'r'",
","... | 30b0f7ecfd4062e9b9a2f8f13ae1f2fd9f21fa12 |
train | World.process_event | Returns a message from tick() to be displayed if game is over | examples/gameexample.py | def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == "":
sys.exit()
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
else:
return "try arrow keys,... | def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == "":
sys.exit()
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
else:
return "try arrow keys,... | [
"Returns",
"a",
"message",
"from",
"tick",
"()",
"to",
"be",
"displayed",
"if",
"game",
"is",
"over"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L57-L65 | [
"def",
"process_event",
"(",
"self",
",",
"c",
")",
":",
"if",
"c",
"==",
"\"\u0004\"",
":",
"sys",
".",
"exit",
"(",
")",
"elif",
"c",
"in",
"key_directions",
":",
"self",
".",
"move_entity",
"(",
"self",
".",
"player",
",",
"*",
"vscale",
"(",
"s... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | World.tick | Returns a message to be displayed if game is over, else None | examples/gameexample.py | def tick(self):
"""Returns a message to be displayed if game is over, else None"""
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):... | def tick(self):
"""Returns a message to be displayed if game is over, else None"""
for npc in self.npcs:
self.move_entity(npc, *npc.towards(self.player))
for entity1, entity2 in itertools.combinations(self.entities, 2):
if (entity1.x, entity1.y) == (entity2.x, entity2.y):... | [
"Returns",
"a",
"message",
"to",
"be",
"displayed",
"if",
"game",
"is",
"over",
"else",
"None"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/examples/gameexample.py#L67-L83 | [
"def",
"tick",
"(",
"self",
")",
":",
"for",
"npc",
"in",
"self",
".",
"npcs",
":",
"self",
".",
"move_entity",
"(",
"npc",
",",
"*",
"npc",
".",
"towards",
"(",
"self",
".",
"player",
")",
")",
"for",
"entity1",
",",
"entity2",
"in",
"itertools",
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | BaseWindow.array_from_text | Returns a FSArray of the size of the window containing msg | curtsies/window.py | def array_from_text(self, msg):
"""Returns a FSArray of the size of the window containing msg"""
rows, columns = self.t.height, self.t.width
return self.array_from_text_rc(msg, rows, columns) | def array_from_text(self, msg):
"""Returns a FSArray of the size of the window containing msg"""
rows, columns = self.t.height, self.t.width
return self.array_from_text_rc(msg, rows, columns) | [
"Returns",
"a",
"FSArray",
"of",
"the",
"size",
"of",
"the",
"window",
"containing",
"msg"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L76-L79 | [
"def",
"array_from_text",
"(",
"self",
",",
"msg",
")",
":",
"rows",
",",
"columns",
"=",
"self",
".",
"t",
".",
"height",
",",
"self",
".",
"t",
".",
"width",
"return",
"self",
".",
"array_from_text_rc",
"(",
"msg",
",",
"rows",
",",
"columns",
")"
... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | FullscreenWindow.render_to_terminal | Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width too large,
* render the renderable portion
* If array... | curtsies/window.py | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width to... | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal and places (0-indexed) cursor
Args:
array (FSArray): Grid of styled characters to be rendered.
* If array received is of width too small, render it anyway
* If array received is of width to... | [
"Renders",
"array",
"to",
"terminal",
"and",
"places",
"(",
"0",
"-",
"indexed",
")",
"cursor"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L144-L204 | [
"def",
"render_to_terminal",
"(",
"self",
",",
"array",
",",
"cursor_pos",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"# TODO there's a race condition here - these height and widths are",
"# super fresh - they might change between the array being constructed",
"# and rendered",
"#... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | CursorAwareWindow.get_cursor_position | Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions | curtsies/window.py | def get_cursor_position(self):
"""Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions"""
# TODO would this be cleaner as a parameter?
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
... | def get_cursor_position(self):
"""Returns the terminal (row, column) of the cursor
0-indexed, like blessings cursor positions"""
# TODO would this be cleaner as a parameter?
in_stream = self.in_stream
query_cursor_position = u"\x1b[6n"
self.write(query_cursor_position)
... | [
"Returns",
"the",
"terminal",
"(",
"row",
"column",
")",
"of",
"the",
"cursor"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L271-L318 | [
"def",
"get_cursor_position",
"(",
"self",
")",
":",
"# TODO would this be cleaner as a parameter?",
"in_stream",
"=",
"self",
".",
"in_stream",
"query_cursor_position",
"=",
"u\"\\x1b[6n\"",
"self",
".",
"write",
"(",
"query_cursor_position",
")",
"def",
"retrying_read",... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | CursorAwareWindow.get_cursor_vertical_diff | Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a SIGWINCH signal
handler, since sig... | curtsies/window.py | def get_cursor_vertical_diff(self):
"""Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a... | def get_cursor_vertical_diff(self):
"""Returns the how far down the cursor moved since last render.
Note:
If another get_cursor_vertical_diff call is already in progress,
immediately returns zero. (This situation is likely if
get_cursor_vertical_diff is called from a... | [
"Returns",
"the",
"how",
"far",
"down",
"the",
"cursor",
"moved",
"since",
"last",
"render",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L320-L347 | [
"def",
"get_cursor_vertical_diff",
"(",
"self",
")",
":",
"# Probably called by a SIGWINCH handler, and therefore",
"# will do cursor querying until a SIGWINCH doesn't happen during",
"# the query. Calls to the function from a signal handler COULD STILL",
"# HAPPEN out of order -",
"# they just ... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | CursorAwareWindow._get_cursor_vertical_diff_once | Returns the how far down the cursor moved. | curtsies/window.py | def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cur... | def _get_cursor_vertical_diff_once(self):
"""Returns the how far down the cursor moved."""
old_top_usable_row = self.top_usable_row
row, col = self.get_cursor_position()
if self._last_cursor_row is None:
cursor_dy = 0
else:
cursor_dy = row - self._last_cur... | [
"Returns",
"the",
"how",
"far",
"down",
"the",
"cursor",
"moved",
"."
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L349-L368 | [
"def",
"_get_cursor_vertical_diff_once",
"(",
"self",
")",
":",
"old_top_usable_row",
"=",
"self",
".",
"top_usable_row",
"row",
",",
"col",
"=",
"self",
".",
"get_cursor_position",
"(",
")",
"if",
"self",
".",
"_last_cursor_row",
"is",
"None",
":",
"cursor_dy",... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | CursorAwareWindow.render_to_terminal | Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of width too small, render it anyway
if array received is of... | curtsies/window.py | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of wid... | def render_to_terminal(self, array, cursor_pos=(0, 0)):
"""Renders array to terminal, returns the number of lines scrolled offscreen
Returns:
Number of times scrolled
Args:
array (FSArray): Grid of styled characters to be rendered.
If array received is of wid... | [
"Renders",
"array",
"to",
"terminal",
"returns",
"the",
"number",
"of",
"lines",
"scrolled",
"offscreen"
] | bpython/curtsies | python | https://github.com/bpython/curtsies/blob/223e42b97fbf6c86b479ed4f0963a067333c5a63/curtsies/window.py#L370-L461 | [
"def",
"render_to_terminal",
"(",
"self",
",",
"array",
",",
"cursor_pos",
"=",
"(",
"0",
",",
"0",
")",
")",
":",
"for_stdout",
"=",
"self",
".",
"fmtstr_to_stdout_xform",
"(",
")",
"# caching of write and tc (avoiding the self. lookups etc) made",
"# no significant ... | 223e42b97fbf6c86b479ed4f0963a067333c5a63 |
train | Relaxation.solve | Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status information.
:param sdpRelaxation: The SDP relaxation to be so... | ncpol2sdpa/sdp_relaxation.py | def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status informa... | def solve(self, solver=None, solverparameters=None):
"""Call a solver on the SDP relaxation. Upon successful solution, it
returns the primal and dual objective values along with the solution
matrices. It also sets these values in the `sdpRelaxation` object,
along with some status informa... | [
"Call",
"a",
"solver",
"on",
"the",
"SDP",
"relaxation",
".",
"Upon",
"successful",
"solution",
"it",
"returns",
"the",
"primal",
"and",
"dual",
"objective",
"values",
"along",
"with",
"the",
"solution",
"matrices",
".",
"It",
"also",
"sets",
"these",
"value... | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L65-L109 | [
"def",
"solve",
"(",
"self",
",",
"solver",
"=",
"None",
",",
"solverparameters",
"=",
"None",
")",
":",
"if",
"self",
".",
"F",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Relaxation is not generated yet. Call \"",
"\"'SdpRelaxation.get_relaxation' first\"",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation._process_monomial | Process a single monomial when building the moment matrix. | ncpol2sdpa/sdp_relaxation.py | def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
processed_monomial, coeff = separate_scalar_factor(monomial)
# Are we substituting this moment?
try:
substitute = self.moment_substitutions[processed_monom... | def _process_monomial(self, monomial, n_vars):
"""Process a single monomial when building the moment matrix.
"""
processed_monomial, coeff = separate_scalar_factor(monomial)
# Are we substituting this moment?
try:
substitute = self.moment_substitutions[processed_monom... | [
"Process",
"a",
"single",
"monomial",
"when",
"building",
"the",
"moment",
"matrix",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L269-L322 | [
"def",
"_process_monomial",
"(",
"self",
",",
"monomial",
",",
"n_vars",
")",
":",
"processed_monomial",
",",
"coeff",
"=",
"separate_scalar_factor",
"(",
"monomial",
")",
"# Are we substituting this moment?",
"try",
":",
"substitute",
"=",
"self",
".",
"moment_subs... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation._generate_moment_matrix | Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix
monomials -- |W_d| set of words of length up to the relaxation level | ncpol2sdpa/sdp_relaxation.py | def _generate_moment_matrix(self, n_vars, block_index, processed_entries,
monomialsA, monomialsB, ppt=False):
"""Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix... | def _generate_moment_matrix(self, n_vars, block_index, processed_entries,
monomialsA, monomialsB, ppt=False):
"""Generate the moment matrix of monomials.
Arguments:
n_vars -- current number of variables
block_index -- current block index in the SDP matrix... | [
"Generate",
"the",
"moment",
"matrix",
"of",
"monomials",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L359-L433 | [
"def",
"_generate_moment_matrix",
"(",
"self",
",",
"n_vars",
",",
"block_index",
",",
"processed_entries",
",",
"monomialsA",
",",
"monomialsB",
",",
"ppt",
"=",
"False",
")",
":",
"row_offset",
"=",
"0",
"if",
"block_index",
">",
"0",
":",
"for",
"block_si... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation._get_index_of_monomial | Returns the index of a monomial. | ncpol2sdpa/sdp_relaxation.py | def _get_index_of_monomial(self, element, enablesubstitution=True,
daggered=False):
"""Returns the index of a monomial.
"""
result = []
processed_element, coeff1 = separate_scalar_factor(element)
if processed_element in self.moment_substitutions:
... | def _get_index_of_monomial(self, element, enablesubstitution=True,
daggered=False):
"""Returns the index of a monomial.
"""
result = []
processed_element, coeff1 = separate_scalar_factor(element)
if processed_element in self.moment_substitutions:
... | [
"Returns",
"the",
"index",
"of",
"a",
"monomial",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L463-L511 | [
"def",
"_get_index_of_monomial",
"(",
"self",
",",
"element",
",",
"enablesubstitution",
"=",
"True",
",",
"daggered",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"processed_element",
",",
"coeff1",
"=",
"separate_scalar_factor",
"(",
"element",
")",
"if"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.__push_facvar_sparse | Calculate the sparse vector representation of a polynomial
and pushes it to the F structure. | ncpol2sdpa/sdp_relaxation.py | def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
"""Calculate the sparse vector representation of a polynomial
and pushes it to the F structure.
"""
width = self.block_struct[block_index - 1]
# Preprocess the polynomial for uniform handling later
... | def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
"""Calculate the sparse vector representation of a polynomial
and pushes it to the F structure.
"""
width = self.block_struct[block_index - 1]
# Preprocess the polynomial for uniform handling later
... | [
"Calculate",
"the",
"sparse",
"vector",
"representation",
"of",
"a",
"polynomial",
"and",
"pushes",
"it",
"to",
"the",
"F",
"structure",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L513-L534 | [
"def",
"__push_facvar_sparse",
"(",
"self",
",",
"polynomial",
",",
"block_index",
",",
"row_offset",
",",
"i",
",",
"j",
")",
":",
"width",
"=",
"self",
".",
"block_struct",
"[",
"block_index",
"-",
"1",
"]",
"# Preprocess the polynomial for uniform handling late... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation._get_facvar | Return dense vector representation of a polynomial. This function is
nearly identical to __push_facvar_sparse, but instead of pushing
sparse entries to the constraint matrices, it returns a dense
vector. | ncpol2sdpa/sdp_relaxation.py | def _get_facvar(self, polynomial):
"""Return dense vector representation of a polynomial. This function is
nearly identical to __push_facvar_sparse, but instead of pushing
sparse entries to the constraint matrices, it returns a dense
vector.
"""
facvar = [0] * (self.n_var... | def _get_facvar(self, polynomial):
"""Return dense vector representation of a polynomial. This function is
nearly identical to __push_facvar_sparse, but instead of pushing
sparse entries to the constraint matrices, it returns a dense
vector.
"""
facvar = [0] * (self.n_var... | [
"Return",
"dense",
"vector",
"representation",
"of",
"a",
"polynomial",
".",
"This",
"function",
"is",
"nearly",
"identical",
"to",
"__push_facvar_sparse",
"but",
"instead",
"of",
"pushing",
"sparse",
"entries",
"to",
"the",
"constraint",
"matrices",
"it",
"return... | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L536-L556 | [
"def",
"_get_facvar",
"(",
"self",
",",
"polynomial",
")",
":",
"facvar",
"=",
"[",
"0",
"]",
"*",
"(",
"self",
".",
"n_vars",
"+",
"1",
")",
"# Preprocess the polynomial for uniform handling later",
"if",
"is_number_type",
"(",
"polynomial",
")",
":",
"facvar... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.__process_inequalities | Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxation | ncpol2sdpa/sdp_relaxation.py | def __process_inequalities(self, block_index):
"""Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxatio... | def __process_inequalities(self, block_index):
"""Generate localizing matrices
Arguments:
inequalities -- list of inequality constraints
monomials -- localizing monomials
block_index -- the current block index in constraint matrices of the
SDP relaxatio... | [
"Generate",
"localizing",
"matrices"
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L558-L620 | [
"def",
"__process_inequalities",
"(",
"self",
",",
"block_index",
")",
":",
"initial_block_index",
"=",
"block_index",
"row_offsets",
"=",
"[",
"0",
"]",
"for",
"block",
",",
"block_size",
"in",
"enumerate",
"(",
"self",
".",
"block_struct",
")",
":",
"row_off... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.__process_equalities | Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints | ncpol2sdpa/sdp_relaxation.py | def __process_equalities(self, equalities, momentequalities):
"""Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints
"""
monomial_sets = []
n_rows = 0
le = 0
if equal... | def __process_equalities(self, equalities, momentequalities):
"""Generate localizing matrices
Arguments:
equalities -- list of equality constraints
equalities -- list of moment equality constraints
"""
monomial_sets = []
n_rows = 0
le = 0
if equal... | [
"Generate",
"localizing",
"matrices"
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L622-L694 | [
"def",
"__process_equalities",
"(",
"self",
",",
"equalities",
",",
"momentequalities",
")",
":",
"monomial_sets",
"=",
"[",
"]",
"n_rows",
"=",
"0",
"le",
"=",
"0",
"if",
"equalities",
"is",
"not",
"None",
":",
"for",
"equality",
"in",
"equalities",
":",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.__remove_equalities | Attempt to remove equalities by solving the linear equations. | ncpol2sdpa/sdp_relaxation.py | def __remove_equalities(self, equalities, momentequalities):
"""Attempt to remove equalities by solving the linear equations.
"""
A = self.__process_equalities(equalities, momentequalities)
if min(A.shape != np.linalg.matrix_rank(A)):
print("Warning: equality constraints are ... | def __remove_equalities(self, equalities, momentequalities):
"""Attempt to remove equalities by solving the linear equations.
"""
A = self.__process_equalities(equalities, momentequalities)
if min(A.shape != np.linalg.matrix_rank(A)):
print("Warning: equality constraints are ... | [
"Attempt",
"to",
"remove",
"equalities",
"by",
"solving",
"the",
"linear",
"equations",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L696-L729 | [
"def",
"__remove_equalities",
"(",
"self",
",",
"equalities",
",",
"momentequalities",
")",
":",
"A",
"=",
"self",
".",
"__process_equalities",
"(",
"equalities",
",",
"momentequalities",
")",
"if",
"min",
"(",
"A",
".",
"shape",
"!=",
"np",
".",
"linalg",
... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation._calculate_block_structure | Calculates the block_struct array for the output file. | ncpol2sdpa/sdp_relaxation.py | def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | def _calculate_block_structure(self, inequalities, equalities,
momentinequalities, momentequalities,
extramomentmatrix, removeequalities,
block_struct=None):
"""Calculates the block_struct array for the outp... | [
"Calculates",
"the",
"block_struct",
"array",
"for",
"the",
"output",
"file",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L843-L935 | [
"def",
"_calculate_block_structure",
"(",
"self",
",",
"inequalities",
",",
"equalities",
",",
"momentinequalities",
",",
"momentequalities",
",",
"extramomentmatrix",
",",
"removeequalities",
",",
"block_struct",
"=",
"None",
")",
":",
"if",
"block_struct",
"is",
"... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.process_constraints | Process the constraints and generate localizing matrices. Useful
only if the moment matrix already exists. Call it if you want to
replace your constraints. The number of the respective types of
constraints and the maximum degree of each constraint must remain the
same.
:param in... | ncpol2sdpa/sdp_relaxation.py | def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful
only if the moment matrix ... | def process_constraints(self, inequalities=None, equalities=None,
momentinequalities=None, momentequalities=None,
block_index=0, removeequalities=False):
"""Process the constraints and generate localizing matrices. Useful
only if the moment matrix ... | [
"Process",
"the",
"constraints",
"and",
"generate",
"localizing",
"matrices",
".",
"Useful",
"only",
"if",
"the",
"moment",
"matrix",
"already",
"exists",
".",
"Call",
"it",
"if",
"you",
"want",
"to",
"replace",
"your",
"constraints",
".",
"The",
"number",
"... | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1007-L1074 | [
"def",
"process_constraints",
"(",
"self",
",",
"inequalities",
"=",
"None",
",",
"equalities",
"=",
"None",
",",
"momentinequalities",
"=",
"None",
",",
"momentequalities",
"=",
"None",
",",
"block_index",
"=",
"0",
",",
"removeequalities",
"=",
"False",
")",... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
train | SdpRelaxation.set_objective | Set or change the objective function of the polynomial optimization
problem.
:param objective: Describes the objective function.
:type objective: :class:`sympy.core.expr.Expr`
:param extraobjexpr: Optional parameter of a string expression of a
linear combina... | ncpol2sdpa/sdp_relaxation.py | def set_objective(self, objective, extraobjexpr=None):
"""Set or change the objective function of the polynomial optimization
problem.
:param objective: Describes the objective function.
:type objective: :class:`sympy.core.expr.Expr`
:param extraobjexpr: Optional parameter of a ... | def set_objective(self, objective, extraobjexpr=None):
"""Set or change the objective function of the polynomial optimization
problem.
:param objective: Describes the objective function.
:type objective: :class:`sympy.core.expr.Expr`
:param extraobjexpr: Optional parameter of a ... | [
"Set",
"or",
"change",
"the",
"objective",
"function",
"of",
"the",
"polynomial",
"optimization",
"problem",
"."
] | peterwittek/ncpol2sdpa | python | https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/sdp_relaxation.py#L1076-L1120 | [
"def",
"set_objective",
"(",
"self",
",",
"objective",
",",
"extraobjexpr",
"=",
"None",
")",
":",
"if",
"objective",
"is",
"not",
"None",
":",
"facvar",
"=",
"self",
".",
"_get_facvar",
"(",
"simplify_polynomial",
"(",
"objective",
",",
"self",
".",
"subs... | bce75d524d0b9d0093f32e3a0a5611f8589351a7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.