repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
20c/facsimile | facsimile/codec.py | find_datafile | def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... | python | def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... | [
"def",
"find_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
"=",
"get_codecs",
"(",
")",
")",
":",
"return",
"munge",
".",
"find_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
")"
] | find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename) | [
"find",
"all",
"matching",
"data",
"files",
"in",
"search_path",
"search_path",
":",
"path",
"of",
"directories",
"to",
"load",
"from",
"codecs",
":",
"allow",
"to",
"override",
"from",
"list",
"of",
"installed",
"returns",
"array",
"of",
"tuples",
"(",
"cod... | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/codec.py#L14-L21 | train |
20c/facsimile | facsimile/codec.py | load_datafile | def load_datafile(name, search_path, codecs=get_codecs(), **kwargs):
"""
find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing
"""
return munge.load_datafile(name, search_path, codecs, **kwargs) | python | def load_datafile(name, search_path, codecs=get_codecs(), **kwargs):
"""
find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing
"""
return munge.load_datafile(name, search_path, codecs, **kwargs) | [
"def",
"load_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
"=",
"get_codecs",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"munge",
".",
"load_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
",",
"*",
"*",
"kwargs",
")... | find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing | [
"find",
"datafile",
"and",
"load",
"them",
"from",
"codec",
"TODO",
"only",
"does",
"the",
"first",
"one",
"kwargs",
":",
"default",
"=",
"if",
"passed",
"will",
"return",
"that",
"on",
"failure",
"instead",
"of",
"throwing"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/codec.py#L23-L30 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.cred_init | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
"""
Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log:... | python | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
"""
Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log:... | [
"def",
"cred_init",
"(",
"self",
",",
"*",
",",
"secrets_dir",
":",
"str",
",",
"log",
":",
"Logger",
",",
"bot_name",
":",
"str",
",",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"secrets_dir",
"=",
"secrets_dir",
",",
"log",
... | Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log: logger to use for log output.
:param bot_name: name of this bot,
used for various kinds of labelling.
:returns: none. | [
"Initialize",
"what",
"requires",
"credentials",
"/",
"secret",
"files",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L23-L69 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.send | def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... | python | def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... | [
"def",
"send",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"try",
":",
"status",
"=",
"self",
".",
"api",
".",
"update_status",
"(",
"text",
")",
"self",
".",
"ldebug",
"(",
"f\"Status obje... | Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error. | [
"Send",
"birdsite",
"message",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L71-L93 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.send_with_media | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
... | python | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
... | [
"def",
"send_with_media",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
"files",
":",
"List",
"[",
"str",
"]",
",",
"captions",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"# upload media",
... | Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each... | [
"Upload",
"media",
"to",
"birdsite",
"and",
"send",
"status",
"and",
"media",
"and",
"captions",
"if",
"present",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L95-L144 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.perform_batch_reply | def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... | python | def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... | [
"def",
"perform_batch_reply",
"(",
"self",
",",
"*",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"str",
"]",
",",
"lookback_limit",
":",
"int",
",",
"target_handle",
":",
"str",
",",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"self",
".",... | Performs batch reply on target account.
Looks up the recent messages of the target user,
applies the callback,
and replies with
what the callback generates.
:param callback: a callback taking a message id,
message contents,
and optional extra keys,
... | [
"Performs",
"batch",
"reply",
"on",
"target",
"account",
".",
"Looks",
"up",
"the",
"recent",
"messages",
"of",
"the",
"target",
"user",
"applies",
"the",
"callback",
"and",
"replies",
"with",
"what",
"the",
"callback",
"generates",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L146-L223 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.send_dm_sos | def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
"""
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
... | python | def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
"""
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
... | [
"def",
"send_dm_sos",
"(",
"self",
",",
"message",
":",
"str",
")",
"->",
"None",
":",
"if",
"self",
".",
"owner_handle",
":",
"try",
":",
"# twitter changed the DM API and tweepy (as of 2019-03-08)",
"# has not adapted.",
"# fixing with",
"# https://github.com/tweepy/twe... | Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None. | [
"Send",
"DM",
"to",
"owner",
"if",
"something",
"happens",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L226-L260 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton.handle_error | def handle_error(
self,
*,
message: str,
error: tweepy.TweepError,
) -> OutputRecord:
"""
Handle error while trying to do something.
:param message: message to send in DM regarding error.
:param e: tweepy error object.
:returns... | python | def handle_error(
self,
*,
message: str,
error: tweepy.TweepError,
) -> OutputRecord:
"""
Handle error while trying to do something.
:param message: message to send in DM regarding error.
:param e: tweepy error object.
:returns... | [
"def",
"handle_error",
"(",
"self",
",",
"*",
",",
"message",
":",
"str",
",",
"error",
":",
"tweepy",
".",
"TweepError",
",",
")",
"->",
"OutputRecord",
":",
"self",
".",
"lerror",
"(",
"f\"Got an error! {error}\"",
")",
"# Handle errors if we know how.",
"tr... | Handle error while trying to do something.
:param message: message to send in DM regarding error.
:param e: tweepy error object.
:returns: OutputRecord containing an error. | [
"Handle",
"error",
"while",
"trying",
"to",
"do",
"something",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L262-L288 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton._handle_caption_upload | def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attac... | python | def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attac... | [
"def",
"_handle_caption_upload",
"(",
"self",
",",
"*",
",",
"media_ids",
":",
"List",
"[",
"str",
"]",
",",
"captions",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
",",
")",
"->",
"None",
":",
"if",
"captions",
"is",
"None",
":",
"captions",... | Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attached to those media ids.
:returns: None. | [
"Handle",
"uploading",
"all",
"captions",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L298-L319 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_birdsite.py | BirdsiteSkeleton._send_direct_message_new | def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... | python | def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... | [
"def",
"_send_direct_message_new",
"(",
"self",
",",
"messageobject",
":",
"Dict",
"[",
"str",
",",
"Dict",
"]",
")",
"->",
"Any",
":",
"headers",
",",
"post_data",
"=",
"_buildmessageobject",
"(",
"messageobject",
")",
"newdm_path",
"=",
"\"/direct_messages/eve... | :reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html | [
":",
"reference",
":",
"https",
":",
"//",
"developer",
".",
"twitter",
".",
"com",
"/",
"en",
"/",
"docs",
"/",
"direct",
"-",
"messages",
"/",
"sending",
"-",
"and",
"-",
"receiving",
"/",
"api",
"-",
"reference",
"/",
"new",
"-",
"event",
".",
"... | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_birdsite.py#L343-L355 | train |
willkg/socorro-siggen | siggen/cmd_signify.py | main | def main():
"""Takes crash data via stdin and generates a Socorro signature"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenera... | python | def main():
"""Takes crash data via stdin and generates a Socorro signature"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenera... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"DESCRIPTION",
")",
"parser",
".",
"add_argument",
"(",
"'-v'",
",",
"'--verbose'",
",",
"help",
"=",
"'increase output verbosity'",
",",
"action",
"=",
... | Takes crash data via stdin and generates a Socorro signature | [
"Takes",
"crash",
"data",
"via",
"stdin",
"and",
"generates",
"a",
"Socorro",
"signature"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_signify.py#L19-L33 | train |
20c/facsimile | facsimile/base.py | Base.add_config | def add_config(self, config):
"""
Update internel configuration dict with config and recheck
"""
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('s... | python | def add_config(self, config):
"""
Update internel configuration dict with config and recheck
"""
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('s... | [
"def",
"add_config",
"(",
"self",
",",
"config",
")",
":",
"for",
"attr",
"in",
"self",
".",
"__fixed_attrs",
":",
"if",
"attr",
"in",
"config",
":",
"raise",
"Exception",
"(",
"\"cannot set '%s' outside of init\"",
",",
"attr",
")",
"# pre checkout",
"stages"... | Update internel configuration dict with config and recheck | [
"Update",
"internel",
"configuration",
"dict",
"with",
"config",
"and",
"recheck"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L234-L292 | train |
20c/facsimile | facsimile/base.py | Base.check_config | def check_config(self):
"""
called after config was modified to sanity check
raises on error
"""
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
#... | python | def check_config(self):
"""
called after config was modified to sanity check
raises on error
"""
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
#... | [
"def",
"check_config",
"(",
"self",
")",
":",
"# sanity checks - no config access past here",
"if",
"not",
"getattr",
"(",
"self",
",",
"'stages'",
",",
"None",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"member variable 'stages' must be defined\"",
")",
"# start ... | called after config was modified to sanity check
raises on error | [
"called",
"after",
"config",
"was",
"modified",
"to",
"sanity",
"check",
"raises",
"on",
"error"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L294-L376 | train |
20c/facsimile | facsimile/base.py | Base.check_definition | def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
"""
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets... | python | def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
"""
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets... | [
"def",
"check_definition",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"write_codec",
":",
"self",
".",
"__write_codec",
"=",
"self",
".",
"defined",
".",
"data_ext",
"# TODO need to add back a class scope target limited for subprojects with sub target sets",
"target... | called after Defintion was loaded to sanity check
raises on error | [
"called",
"after",
"Defintion",
"was",
"loaded",
"to",
"sanity",
"check",
"raises",
"on",
"error"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L378-L394 | train |
20c/facsimile | facsimile/base.py | Base.find_datafile | def find_datafile(self, name, search_path=None):
"""
find all matching data files in search_path
returns array of tuples (codec_object, filename)
"""
if not search_path:
search_path = self.define_dir
return codec.find_datafile(name, search_path) | python | def find_datafile(self, name, search_path=None):
"""
find all matching data files in search_path
returns array of tuples (codec_object, filename)
"""
if not search_path:
search_path = self.define_dir
return codec.find_datafile(name, search_path) | [
"def",
"find_datafile",
"(",
"self",
",",
"name",
",",
"search_path",
"=",
"None",
")",
":",
"if",
"not",
"search_path",
":",
"search_path",
"=",
"self",
".",
"define_dir",
"return",
"codec",
".",
"find_datafile",
"(",
"name",
",",
"search_path",
")"
] | find all matching data files in search_path
returns array of tuples (codec_object, filename) | [
"find",
"all",
"matching",
"data",
"files",
"in",
"search_path",
"returns",
"array",
"of",
"tuples",
"(",
"codec_object",
"filename",
")"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L457-L465 | train |
20c/facsimile | facsimile/base.py | Base.load_datafile | def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
"""
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(nam... | python | def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
"""
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(nam... | [
"def",
"load_datafile",
"(",
"self",
",",
"name",
",",
"search_path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"search_path",
":",
"search_path",
"=",
"self",
".",
"define_dir",
"self",
".",
"debug_msg",
"(",
"'loading datafile %s from %s... | find datafile and load them from codec | [
"find",
"datafile",
"and",
"load",
"them",
"from",
"codec"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L467-L475 | train |
20c/facsimile | facsimile/base.py | Base.run | def run(self):
""" run all configured stages """
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = t... | python | def run(self):
""" run all configured stages """
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = t... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"sanity_check",
"(",
")",
"# TODO - check for devel",
"# if not self.version:",
"# raise Exception(\"no version\")",
"# XXX check attr exist",
"if",
"not",
"self",
".",
"release_environment",
":",
"raise",
... | run all configured stages | [
"run",
"all",
"configured",
"stages"
] | 570e28568475d5be1b1a2c95b8e941fbfbc167eb | https://github.com/20c/facsimile/blob/570e28568475d5be1b1a2c95b8e941fbfbc167eb/facsimile/base.py#L695-L753 | train |
jaraco/backports.datetime_timestamp | backports/datetime_timestamp/__init__.py | timestamp | def timestamp(dt):
"""
Return POSIX timestamp as float.
>>> timestamp(datetime.datetime.now()) > 1494638812
True
>>> timestamp(datetime.datetime.now()) % 1 > 0
True
"""
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond... | python | def timestamp(dt):
"""
Return POSIX timestamp as float.
>>> timestamp(datetime.datetime.now()) > 1494638812
True
>>> timestamp(datetime.datetime.now()) % 1 > 0
True
"""
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond... | [
"def",
"timestamp",
"(",
"dt",
")",
":",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"return",
"time",
".",
"mktime",
"(",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
",",
"dt",
".",
"hour",
",",
"dt",
".",
"minu... | Return POSIX timestamp as float.
>>> timestamp(datetime.datetime.now()) > 1494638812
True
>>> timestamp(datetime.datetime.now()) % 1 > 0
True | [
"Return",
"POSIX",
"timestamp",
"as",
"float",
"."
] | 914d3f75b3f8818b8dd4ac1863698917be2354ca | https://github.com/jaraco/backports.datetime_timestamp/blob/914d3f75b3f8818b8dd4ac1863698917be2354ca/backports/datetime_timestamp/__init__.py#L24-L40 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | rate_limited | def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) | python | def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) | [
"def",
"rate_limited",
"(",
"max_per_hour",
":",
"int",
",",
"*",
"args",
":",
"Any",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"return",
"util",
".",
"rate_limited",
"(",
"max_per_hour",
",",
"*",
"args",
")"
] | Rate limit a function. | [
"Rate",
"limit",
"a",
"function",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L492-L494 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | _repair | def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... | python | def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... | [
"def",
"_repair",
"(",
"record",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"output_records",
"=",
"record",
".",
"get",
"(",
"\"output_records\"",
")",
"if",
"record",
".",
"get",
"(",
"\"_type\"",... | Repair a corrupted IterationRecord with a specific known issue. | [
"Repair",
"a",
"corrupted",
"IterationRecord",
"with",
"a",
"specific",
"known",
"issue",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L510-L554 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | IterationRecord.from_dict | def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord":
"""Get object back from dict."""
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = item
return obj | python | def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord":
"""Get object back from dict."""
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = item
return obj | [
"def",
"from_dict",
"(",
"cls",
",",
"obj_dict",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"\"IterationRecord\"",
":",
"obj",
"=",
"cls",
"(",
")",
"for",
"key",
",",
"item",
"in",
"obj_dict",
".",
"items",
"(",
")",
":",
"obj",
".",
"... | Get object back from dict. | [
"Get",
"object",
"back",
"from",
"dict",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L48-L54 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.send | def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
... | python | def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
... | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
":",
"str",
",",
"text",
":",
"str",
"=",
"None",
",",
")",
"->",
"IterationRecord",
":",
"if",
"text",
"is",
"not",
"None",
":",
"final_text",
"=",
"text",
"else",
":",
"if",
"len",
"(",
"args",
")",... | Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
:param text: text to send as message in post.
:returns: new record of iteration | [
"Post",
"text",
"-",
"only",
"to",
"all",
"outputs",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L102-L140 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.send_with_one_media | def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:par... | python | def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:par... | [
"def",
"send_with_one_media",
"(",
"self",
",",
"*",
"args",
":",
"str",
",",
"text",
":",
"str",
"=",
"None",
",",
"file",
":",
"str",
"=",
"None",
",",
"caption",
":",
"str",
"=",
"None",
",",
")",
"->",
"IterationRecord",
":",
"final_text",
"=",
... | Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:param args: positional arguments.
expected:
text to send as message in post.
file to be uploaded.
caption to be paired with file.
k... | [
"Post",
"with",
"one",
"media",
"item",
"to",
"all",
"outputs",
".",
"Provide",
"filename",
"so",
"outputs",
"can",
"handle",
"their",
"own",
"uploads",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L142-L208 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.send_with_many_media | def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs can handle their own uploads.
:param... | python | def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs can handle their own uploads.
:param... | [
"def",
"send_with_many_media",
"(",
"self",
",",
"*",
"args",
":",
"str",
",",
"text",
":",
"str",
"=",
"None",
",",
"files",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"captions",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
",",
")",
"->... | Post with several media.
Provide filenames so outputs can handle their own uploads.
:param args: positional arguments.
expected:
text to send as message in post.
files to be uploaded.
captions to be paired with files.
keyword argum... | [
"Post",
"with",
"several",
"media",
".",
"Provide",
"filenames",
"so",
"outputs",
"can",
"handle",
"their",
"own",
"uploads",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L210-L269 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.perform_batch_reply | def perform_batch_reply(
self,
*,
callback: Callable[..., str]=None,
target_handles: Dict[str, str]=None,
lookback_limit: int=20,
per_service_lookback_limit: Dict[str, int]=None,
) -> IterationRecord:
"""
Performs batch reply on... | python | def perform_batch_reply(
self,
*,
callback: Callable[..., str]=None,
target_handles: Dict[str, str]=None,
lookback_limit: int=20,
per_service_lookback_limit: Dict[str, int]=None,
) -> IterationRecord:
"""
Performs batch reply on... | [
"def",
"perform_batch_reply",
"(",
"self",
",",
"*",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"str",
"]",
"=",
"None",
",",
"target_handles",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"lookback_limit",
":",
"int",
"=",
"20... | Performs batch reply on target accounts.
Looks up the recent messages of the target user,
applies the callback,
and replies with
what the callback generates.
:param callback: a callback taking a message id,
message contents,
and optional extra keys,
... | [
"Performs",
"batch",
"reply",
"on",
"target",
"accounts",
".",
"Looks",
"up",
"the",
"recent",
"messages",
"of",
"the",
"target",
"user",
"applies",
"the",
"callback",
"and",
"replies",
"with",
"what",
"the",
"callback",
"generates",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L271-L341 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.nap | def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
"""
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) | python | def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
"""
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) | [
"def",
"nap",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"log",
".",
"info",
"(",
"f\"Sleeping for {self.delay} seconds.\"",
")",
"for",
"_",
"in",
"progress",
".",
"bar",
"(",
"range",
"(",
"self",
".",
"delay",
")",
")",
":",
"time",
".",
"s... | Go to sleep for the duration of self.delay.
:returns: None | [
"Go",
"to",
"sleep",
"for",
"the",
"duration",
"of",
"self",
".",
"delay",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L343-L351 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.store_extra_info | def store_extra_info(self, key: str, value: Any) -> None:
"""
Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None
"""
self.extra_keys[key] = value | python | def store_extra_info(self, key: str, value: Any) -> None:
"""
Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None
"""
self.extra_keys[key] = value | [
"def",
"store_extra_info",
"(",
"self",
",",
"key",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"extra_keys",
"[",
"key",
"]",
"=",
"value"
] | Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None | [
"Store",
"some",
"extra",
"value",
"in",
"the",
"messaging",
"storage",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L353-L361 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.store_extra_keys | def store_extra_keys(self, d: Dict[str, Any]) -> None:
"""
Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None
"""
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.c... | python | def store_extra_keys(self, d: Dict[str, Any]) -> None:
"""
Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None
"""
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.c... | [
"def",
"store_extra_keys",
"(",
"self",
",",
"d",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"new_dict",
"=",
"dict",
"(",
"self",
".",
"extra_keys",
",",
"*",
"*",
"d",
")",
"self",
".",
"extra_keys",
"=",
"new_dict",
".",
... | Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None | [
"Store",
"several",
"extra",
"values",
"in",
"the",
"messaging",
"storage",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L363-L371 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.update_history | def update_history(self) -> None:
"""
Update messaging history on disk.
:returns: None
"""
self.log.debug(f"Saving history. History is: \n{self.history}")
jsons = []
for item in self.history:
json_item = item.__dict__
# Convert sub-entri... | python | def update_history(self) -> None:
"""
Update messaging history on disk.
:returns: None
"""
self.log.debug(f"Saving history. History is: \n{self.history}")
jsons = []
for item in self.history:
json_item = item.__dict__
# Convert sub-entri... | [
"def",
"update_history",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"log",
".",
"debug",
"(",
"f\"Saving history. History is: \\n{self.history}\"",
")",
"jsons",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"history",
":",
"json_item",
"=",
"item"... | Update messaging history on disk.
:returns: None | [
"Update",
"messaging",
"history",
"on",
"disk",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L373-L395 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton.load_history | def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
"""
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
... | python | def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
"""
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
... | [
"def",
"load_history",
"(",
"self",
")",
"->",
"List",
"[",
"\"IterationRecord\"",
"]",
":",
"if",
"path",
".",
"isfile",
"(",
"self",
".",
"history_filename",
")",
":",
"with",
"open",
"(",
"self",
".",
"history_filename",
",",
"\"r\"",
")",
"as",
"f",
... | Load messaging history from disk to self.
:returns: List of iteration records comprising history. | [
"Load",
"messaging",
"history",
"from",
"disk",
"to",
"self",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L397-L447 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton._setup_all_outputs | def _setup_all_outputs(self) -> None:
"""Set up all output methods. Provide them credentials and anything else they need."""
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.key... | python | def _setup_all_outputs(self) -> None:
"""Set up all output methods. Provide them credentials and anything else they need."""
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.key... | [
"def",
"_setup_all_outputs",
"(",
"self",
")",
"->",
"None",
":",
"# The way this is gonna work is that we assume an output should be set up iff it has a",
"# credentials_ directory under our secrets dir.",
"for",
"key",
"in",
"self",
".",
"outputs",
".",
"keys",
"(",
")",
":... | Set up all output methods. Provide them credentials and anything else they need. | [
"Set",
"up",
"all",
"output",
"methods",
".",
"Provide",
"them",
"credentials",
"and",
"anything",
"else",
"they",
"need",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L452-L475 | train |
alixnovosi/botskeleton | botskeleton/botskeleton.py | BotSkeleton._parse_output_records | def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]:
"""Parse output records into dicts ready for JSON."""
output_records = {}
for key, sub_item in item.output_records.items():
if isinstance(sub_item, dict) or isinstance(sub_item, list):
output_re... | python | def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]:
"""Parse output records into dicts ready for JSON."""
output_records = {}
for key, sub_item in item.output_records.items():
if isinstance(sub_item, dict) or isinstance(sub_item, list):
output_re... | [
"def",
"_parse_output_records",
"(",
"self",
",",
"item",
":",
"IterationRecord",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"output_records",
"=",
"{",
"}",
"for",
"key",
",",
"sub_item",
"in",
"item",
".",
"output_records",
".",
"items",
"(",... | Parse output records into dicts ready for JSON. | [
"Parse",
"output",
"records",
"into",
"dicts",
"ready",
"for",
"JSON",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/botskeleton.py#L477-L486 | train |
pmacosta/pmisc | pmisc/file.py | make_dir | def make_dir(fname):
"""
Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
... | python | def make_dir(fname):
"""
Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
... | [
"def",
"make_dir",
"(",
"fname",
")",
":",
"file_path",
",",
"fname",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"fname",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",... | Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
$ mkdir -p "${dir}"
:param ... | [
"Create",
"the",
"directory",
"of",
"a",
"fully",
"qualified",
"file",
"name",
"if",
"it",
"does",
"not",
"exist",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/file.py#L14-L34 | train |
pmacosta/pmisc | pmisc/file.py | normalize_windows_fname | def normalize_windows_fname(fname, _force=False):
r"""
Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are
converted to their equivalent (presumably correct and intended)
representation, for example :code:`r'\\\\x07pps'`... | python | def normalize_windows_fname(fname, _force=False):
r"""
Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are
converted to their equivalent (presumably correct and intended)
representation, for example :code:`r'\\\\x07pps'`... | [
"def",
"normalize_windows_fname",
"(",
"fname",
",",
"_force",
"=",
"False",
")",
":",
"if",
"(",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"!=",
"\"windows\"",
")",
"and",
"(",
"not",
"_force",
")",
":",
"# pragma: no cover",
"return"... | r"""
Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are
converted to their equivalent (presumably correct and intended)
representation, for example :code:`r'\\\\x07pps'` is transformed to
:code:`r'\\\\\\\\apps'`. A file... | [
"r",
"Fix",
"potential",
"problems",
"with",
"a",
"Microsoft",
"Windows",
"file",
"name",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/file.py#L37-L79 | train |
pmacosta/pmisc | pmisc/rst.py | _homogenize_linesep | def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) | python | def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) | [
"def",
"_homogenize_linesep",
"(",
"line",
")",
":",
"token",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"line",
"=",
"line",
".",
"replace",
"(",
"os",
".",
"linesep",
",",
"token",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",... | Enforce line separators to be the right one depending on platform. | [
"Enforce",
"line",
"separators",
"to",
"be",
"the",
"right",
"one",
"depending",
"on",
"platform",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/rst.py#L25-L29 | train |
pmacosta/pmisc | pmisc/rst.py | _proc_token | def _proc_token(spec, mlines):
"""Process line range tokens."""
spec = spec.strip().replace(" ", "")
regexp = re.compile(r".*[^0123456789\-,]+.*")
tokens = spec.split(",")
cond = any([not item for item in tokens])
if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec... | python | def _proc_token(spec, mlines):
"""Process line range tokens."""
spec = spec.strip().replace(" ", "")
regexp = re.compile(r".*[^0123456789\-,]+.*")
tokens = spec.split(",")
cond = any([not item for item in tokens])
if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec... | [
"def",
"_proc_token",
"(",
"spec",
",",
"mlines",
")",
":",
"spec",
"=",
"spec",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
"regexp",
"=",
"re",
".",
"compile",
"(",
"r\".*[^0123456789\\-,]+.*\"",
")",
"tokens",
"=",
"spec"... | Process line range tokens. | [
"Process",
"line",
"range",
"tokens",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/rst.py#L32-L56 | train |
pmacosta/pmisc | pmisc/rst.py | incfile | def incfile(fname, fpointer, lrange=None, sdir=None):
r"""
Return a Python source file formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param fname: File name, relative to environment variable
:bash:`PKG_DOC_DIR`
:type fname: string
:param fpoint... | python | def incfile(fname, fpointer, lrange=None, sdir=None):
r"""
Return a Python source file formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param fname: File name, relative to environment variable
:bash:`PKG_DOC_DIR`
:type fname: string
:param fpoint... | [
"def",
"incfile",
"(",
"fname",
",",
"fpointer",
",",
"lrange",
"=",
"None",
",",
"sdir",
"=",
"None",
")",
":",
"# pylint: disable=R0914",
"# Read file",
"file_dir",
"=",
"(",
"sdir",
"if",
"sdir",
"else",
"os",
".",
"environ",
".",
"get",
"(",
"\"PKG_D... | r"""
Return a Python source file formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param fname: File name, relative to environment variable
:bash:`PKG_DOC_DIR`
:type fname: string
:param fpointer: Output function pointer. Normally is :code:`cog.out` b... | [
"r",
"Return",
"a",
"Python",
"source",
"file",
"formatted",
"in",
"reStructuredText",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/rst.py#L59-L133 | train |
pmacosta/pmisc | pmisc/rst.py | ste | def ste(command, nindent, mdir, fpointer, env=None):
"""
Print STDOUT of a shell command formatted in reStructuredText.
This is a simplified version of :py:func:`pmisc.term_echo`.
:param command: Shell command (relative to **mdir** if **env** is not given)
:type command: string
:param ninden... | python | def ste(command, nindent, mdir, fpointer, env=None):
"""
Print STDOUT of a shell command formatted in reStructuredText.
This is a simplified version of :py:func:`pmisc.term_echo`.
:param command: Shell command (relative to **mdir** if **env** is not given)
:type command: string
:param ninden... | [
"def",
"ste",
"(",
"command",
",",
"nindent",
",",
"mdir",
",",
"fpointer",
",",
"env",
"=",
"None",
")",
":",
"sdir",
"=",
"LDELIM",
"+",
"\"PKG_BIN_DIR\"",
"+",
"RDELIM",
"command",
"=",
"(",
"sdir",
"+",
"(",
"\"{sep}{cmd}\"",
".",
"format",
"(",
... | Print STDOUT of a shell command formatted in reStructuredText.
This is a simplified version of :py:func:`pmisc.term_echo`.
:param command: Shell command (relative to **mdir** if **env** is not given)
:type command: string
:param nindent: Indentation level
:type nindent: integer
:param mdir... | [
"Print",
"STDOUT",
"of",
"a",
"shell",
"command",
"formatted",
"in",
"reStructuredText",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/rst.py#L136-L192 | train |
pmacosta/pmisc | pmisc/rst.py | term_echo | def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
"""
Print STDOUT of a shell command formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param command: Shell command
:type command: string
:param nindent: Indentation level
:type nindent: integ... | python | def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
"""
Print STDOUT of a shell command formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param command: Shell command
:type command: string
:param nindent: Indentation level
:type nindent: integ... | [
"def",
"term_echo",
"(",
"command",
",",
"nindent",
"=",
"0",
",",
"env",
"=",
"None",
",",
"fpointer",
"=",
"None",
",",
"cols",
"=",
"60",
")",
":",
"# pylint: disable=R0204",
"# Set argparse width so that output does not need horizontal scroll",
"# bar in narrow wi... | Print STDOUT of a shell command formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param command: Shell command
:type command: string
:param nindent: Indentation level
:type nindent: integer
:param env: Environment variable replacement dictionary. The
... | [
"Print",
"STDOUT",
"of",
"a",
"shell",
"command",
"formatted",
"in",
"reStructuredText",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/rst.py#L195-L258 | train |
theno/utlz | fabfile.py | flo | def flo(string):
'''Return the string given by param formatted with the callers locals.'''
callers_locals = {}
frame = inspect.currentframe()
try:
outerframe = frame.f_back
callers_locals = outerframe.f_locals
finally:
del frame
return string.format(**callers_locals) | python | def flo(string):
'''Return the string given by param formatted with the callers locals.'''
callers_locals = {}
frame = inspect.currentframe()
try:
outerframe = frame.f_back
callers_locals = outerframe.f_locals
finally:
del frame
return string.format(**callers_locals) | [
"def",
"flo",
"(",
"string",
")",
":",
"callers_locals",
"=",
"{",
"}",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"try",
":",
"outerframe",
"=",
"frame",
".",
"f_back",
"callers_locals",
"=",
"outerframe",
".",
"f_locals",
"finally",
":",
"... | Return the string given by param formatted with the callers locals. | [
"Return",
"the",
"string",
"given",
"by",
"param",
"formatted",
"with",
"the",
"callers",
"locals",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L10-L19 | train |
theno/utlz | fabfile.py | _wrap_with | def _wrap_with(color_code):
'''Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m
'''
def inner(text, bold=False):
'''Inner color function.'''
code = color_code
if bold:
code = flo("1;{code}")
... | python | def _wrap_with(color_code):
'''Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m
'''
def inner(text, bold=False):
'''Inner color function.'''
code = color_code
if bold:
code = flo("1;{code}")
... | [
"def",
"_wrap_with",
"(",
"color_code",
")",
":",
"def",
"inner",
"(",
"text",
",",
"bold",
"=",
"False",
")",
":",
"'''Inner color function.'''",
"code",
"=",
"color_code",
"if",
"bold",
":",
"code",
"=",
"flo",
"(",
"\"1;{code}\"",
")",
"return",
"flo",
... | Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m | [
"Color",
"wrapper",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L22-L36 | train |
theno/utlz | fabfile.py | clean | def clean(deltox=False):
'''Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox
'''
basedir = dirname(__file__)
print(cyan('delete temp files and dirs for packaging'))
local(flo(
'rm -rf '
'{basedir}/.eggs/ ... | python | def clean(deltox=False):
'''Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox
'''
basedir = dirname(__file__)
print(cyan('delete temp files and dirs for packaging'))
local(flo(
'rm -rf '
'{basedir}/.eggs/ ... | [
"def",
"clean",
"(",
"deltox",
"=",
"False",
")",
":",
"basedir",
"=",
"dirname",
"(",
"__file__",
")",
"print",
"(",
"cyan",
"(",
"'delete temp files and dirs for packaging'",
")",
")",
"local",
"(",
"flo",
"(",
"'rm -rf '",
"'{basedir}/.eggs/ '",
"'{basedir}... | Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox | [
"Delete",
"temporary",
"files",
"not",
"under",
"version",
"control",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L76-L112 | train |
theno/utlz | fabfile.py | pythons | def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... | python | def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... | [
"def",
"pythons",
"(",
")",
":",
"if",
"not",
"_pyenv_exists",
"(",
")",
":",
"print",
"(",
"'\\npyenv is not installed. You can install it with fabsetup '",
"'(https://github.com/theno/fabsetup):\\n\\n '",
"+",
"cyan",
"(",
"'mkdir ~/repos && cd ~/repos\\n '",
"'git clon... | Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions. | [
"Install",
"latest",
"pythons",
"with",
"pyenv",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L135-L167 | train |
theno/utlz | fabfile.py | tox | def tox(args=''):
'''Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r'
'''
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_mino... | python | def tox(args=''):
'''Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r'
'''
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_mino... | [
"def",
"tox",
"(",
"args",
"=",
"''",
")",
":",
"basedir",
"=",
"dirname",
"(",
"__file__",
")",
"latest_pythons",
"=",
"_determine_latest_pythons",
"(",
")",
"# e.g. highest_minor_python: '3.6'",
"highest_minor_python",
"=",
"_highest_minor",
"(",
"latest_pythons",
... | Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r' | [
"Run",
"tox",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L182-L200 | train |
theno/utlz | fabfile.py | pypi | def pypi():
'''Build package and upload to pypi.'''
if query_yes_no('version updated in setup.py?'):
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_minor: '3.6'
highest_minor... | python | def pypi():
'''Build package and upload to pypi.'''
if query_yes_no('version updated in setup.py?'):
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_minor: '3.6'
highest_minor... | [
"def",
"pypi",
"(",
")",
":",
"if",
"query_yes_no",
"(",
"'version updated in setup.py?'",
")",
":",
"print",
"(",
"cyan",
"(",
"'\\n## clean-up\\n'",
")",
")",
"execute",
"(",
"clean",
")",
"basedir",
"=",
"dirname",
"(",
"__file__",
")",
"latest_pythons",
... | Build package and upload to pypi. | [
"Build",
"package",
"and",
"upload",
"to",
"pypi",
"."
] | bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389 | https://github.com/theno/utlz/blob/bf7d2b53f3e0d35c6f8ded81f3f774a74fcd3389/fabfile.py#L235-L253 | train |
greenelab/django-genes | genes/management/commands/genes_load_gene_history.py | chk_col_numbers | def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col):
"""
Check that none of the input column numbers is out of range.
(Instead of defining this function, we could depend on Python's built-in
IndexError exception for this issue, but the IndexError exception wouldn't
include line n... | python | def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col):
"""
Check that none of the input column numbers is out of range.
(Instead of defining this function, we could depend on Python's built-in
IndexError exception for this issue, but the IndexError exception wouldn't
include line n... | [
"def",
"chk_col_numbers",
"(",
"line_num",
",",
"num_cols",
",",
"tax_id_col",
",",
"id_col",
",",
"symbol_col",
")",
":",
"bad_col",
"=",
"''",
"if",
"tax_id_col",
">=",
"num_cols",
":",
"bad_col",
"=",
"'tax_id_col'",
"elif",
"id_col",
">=",
"num_cols",
":... | Check that none of the input column numbers is out of range.
(Instead of defining this function, we could depend on Python's built-in
IndexError exception for this issue, but the IndexError exception wouldn't
include line number information, which is helpful for users to find exactly
which line is the c... | [
"Check",
"that",
"none",
"of",
"the",
"input",
"column",
"numbers",
"is",
"out",
"of",
"range",
".",
"(",
"Instead",
"of",
"defining",
"this",
"function",
"we",
"could",
"depend",
"on",
"Python",
"s",
"built",
"-",
"in",
"IndexError",
"exception",
"for",
... | 298939adcb115031acfc11cfcef60ea0b596fae5 | https://github.com/greenelab/django-genes/blob/298939adcb115031acfc11cfcef60ea0b596fae5/genes/management/commands/genes_load_gene_history.py#L104-L124 | train |
greenelab/django-genes | genes/management/commands/genes_load_gene_history.py | import_gene_history | def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
"""
Read input gene history file into the database.
Note that the arguments tax_id_col, id_col and symbol_col have been
converted into 0-based column indexes.
"""
# Make sure that tax_id is not "" or " "
if not t... | python | def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
"""
Read input gene history file into the database.
Note that the arguments tax_id_col, id_col and symbol_col have been
converted into 0-based column indexes.
"""
# Make sure that tax_id is not "" or " "
if not t... | [
"def",
"import_gene_history",
"(",
"file_handle",
",",
"tax_id",
",",
"tax_id_col",
",",
"id_col",
",",
"symbol_col",
")",
":",
"# Make sure that tax_id is not \"\" or \" \"",
"if",
"not",
"tax_id",
"or",
"tax_id",
".",
"isspace",
"(",
")",
":",
"raise",
"Excepti... | Read input gene history file into the database.
Note that the arguments tax_id_col, id_col and symbol_col have been
converted into 0-based column indexes. | [
"Read",
"input",
"gene",
"history",
"file",
"into",
"the",
"database",
".",
"Note",
"that",
"the",
"arguments",
"tax_id_col",
"id_col",
"and",
"symbol_col",
"have",
"been",
"converted",
"into",
"0",
"-",
"based",
"column",
"indexes",
"."
] | 298939adcb115031acfc11cfcef60ea0b596fae5 | https://github.com/greenelab/django-genes/blob/298939adcb115031acfc11cfcef60ea0b596fae5/genes/management/commands/genes_load_gene_history.py#L127-L173 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_mastodon.py | MastodonSkeleton.cred_init | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str="",
) -> None:
"""Initialize what requires credentials/secret files."""
super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name)
self.ldebug("Retriev... | python | def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str="",
) -> None:
"""Initialize what requires credentials/secret files."""
super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name)
self.ldebug("Retriev... | [
"def",
"cred_init",
"(",
"self",
",",
"*",
",",
"secrets_dir",
":",
"str",
",",
"log",
":",
"Logger",
",",
"bot_name",
":",
"str",
"=",
"\"\"",
",",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"secrets_dir",
"=",
"secrets_dir",
... | Initialize what requires credentials/secret files. | [
"Initialize",
"what",
"requires",
"credentials",
"/",
"secret",
"files",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_mastodon.py#L18-L44 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_mastodon.py | MastodonSkeleton.send | def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... | python | def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... | [
"def",
"send",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"try",
":",
"status",
"=",
"self",
".",
"api",
".",
"status_post",
"(",
"status",
"=",
"text",
")",
"return",
"[",
"TootRecord",
... | Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error. | [
"Send",
"mastodon",
"message",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_mastodon.py#L46-L70 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_mastodon.py | MastodonSkeleton.send_with_media | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
"""
Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
... | python | def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
"""
Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
... | [
"def",
"send_with_media",
"(",
"self",
",",
"*",
",",
"text",
":",
"str",
",",
"files",
":",
"List",
"[",
"str",
"]",
",",
"captions",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
",",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"try",
":... | Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
:param files: list of files to upload with post.
:param captions: list of captions to include as alt-text with files.
:returns: list of output records,
each ... | [
"Upload",
"media",
"to",
"mastodon",
"and",
"send",
"status",
"and",
"media",
"and",
"captions",
"if",
"present",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_mastodon.py#L72-L125 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_mastodon.py | MastodonSkeleton.perform_batch_reply | def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... | python | def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... | [
"def",
"perform_batch_reply",
"(",
"self",
",",
"*",
",",
"callback",
":",
"Callable",
"[",
"...",
",",
"str",
"]",
",",
"lookback_limit",
":",
"int",
",",
"target_handle",
":",
"str",
",",
")",
"->",
"List",
"[",
"OutputRecord",
"]",
":",
"self",
".",... | Performs batch reply on target account.
Looks up the recent messages of the target user,
applies the callback,
and replies with
what the callback generates.
:param callback: a callback taking a message id,
message contents,
and optional extra keys,
... | [
"Performs",
"batch",
"reply",
"on",
"target",
"account",
".",
"Looks",
"up",
"the",
"recent",
"messages",
"of",
"the",
"target",
"user",
"applies",
"the",
"callback",
"and",
"replies",
"with",
"what",
"the",
"callback",
"generates",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_mastodon.py#L127-L208 | train |
alixnovosi/botskeleton | botskeleton/outputs/output_mastodon.py | MastodonSkeleton.handle_error | def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord:
"""Handle error while trying to do something."""
self.lerror(f"Got an error! {e}")
# Handle errors if we know how.
try:
code = e[0]["code"]
if code in self.handled_errors:
... | python | def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord:
"""Handle error while trying to do something."""
self.lerror(f"Got an error! {e}")
# Handle errors if we know how.
try:
code = e[0]["code"]
if code in self.handled_errors:
... | [
"def",
"handle_error",
"(",
"self",
",",
"message",
":",
"str",
",",
"e",
":",
"mastodon",
".",
"MastodonError",
")",
"->",
"OutputRecord",
":",
"self",
".",
"lerror",
"(",
"f\"Got an error! {e}\"",
")",
"# Handle errors if we know how.",
"try",
":",
"code",
"... | Handle error while trying to do something. | [
"Handle",
"error",
"while",
"trying",
"to",
"do",
"something",
"."
] | 55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9 | https://github.com/alixnovosi/botskeleton/blob/55bfc1b8a3623c10437e4ab2cd0b0ec8d35907a9/botskeleton/outputs/output_mastodon.py#L214-L229 | train |
dongying/dear | dear/spectrum/_base.py | SpectrogramFile._read_header | def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... | python | def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... | [
"def",
"_read_header",
"(",
"self",
")",
":",
"self",
".",
"_fh",
".",
"seek",
"(",
"0",
")",
"buf",
"=",
"self",
".",
"_fh",
".",
"read",
"(",
"4",
"*",
"2",
")",
"fc",
",",
"dc",
"=",
"struct",
".",
"unpack",
"(",
"\"<II\"",
",",
"buf",
")"... | Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count | | [
"Little",
"-",
"endian",
"|",
"...",
"4",
"bytes",
"unsigned",
"int",
"...",
"|",
"...",
"4",
"bytes",
"unsigned",
"int",
"...",
"|",
"|",
"frames",
"count",
"|",
"dimensions",
"count",
"|"
] | 6f9a4f63bf3ee197dc03d7d2bd0451a83906d2ba | https://github.com/dongying/dear/blob/6f9a4f63bf3ee197dc03d7d2bd0451a83906d2ba/dear/spectrum/_base.py#L33-L42 | train |
limix/optimix | optimix/_types.py | Scalar.listen | def listen(self, you):
"""
Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute.
"""
self._listeners.append(you)
self.raw.talk_to(you) | python | def listen(self, you):
"""
Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute.
"""
self._listeners.append(you)
self.raw.talk_to(you) | [
"def",
"listen",
"(",
"self",
",",
"you",
")",
":",
"self",
".",
"_listeners",
".",
"append",
"(",
"you",
")",
"self",
".",
"raw",
".",
"talk_to",
"(",
"you",
")"
] | Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute. | [
"Request",
"a",
"callback",
"for",
"value",
"modification",
"."
] | d7b1356df259c9f6ee0d658258fb47d0074fc416 | https://github.com/limix/optimix/blob/d7b1356df259c9f6ee0d658258fb47d0074fc416/optimix/_types.py#L96-L106 | train |
koenedaele/skosprovider_oe | skosprovider_oe/providers.py | OnroerendErfgoedProvider._get_term_by_id | def _get_term_by_id(self, id):
'''Simple utility function to load a term.
'''
url = (self.url + '/%s.json') % id
r = self.session.get(url)
return r.json() | python | def _get_term_by_id(self, id):
'''Simple utility function to load a term.
'''
url = (self.url + '/%s.json') % id
r = self.session.get(url)
return r.json() | [
"def",
"_get_term_by_id",
"(",
"self",
",",
"id",
")",
":",
"url",
"=",
"(",
"self",
".",
"url",
"+",
"'/%s.json'",
")",
"%",
"id",
"r",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"return",
"r",
".",
"json",
"(",
")"
] | Simple utility function to load a term. | [
"Simple",
"utility",
"function",
"to",
"load",
"a",
"term",
"."
] | 099b23cccd3884b06354102955dbc71f59d8fdb0 | https://github.com/koenedaele/skosprovider_oe/blob/099b23cccd3884b06354102955dbc71f59d8fdb0/skosprovider_oe/providers.py#L167-L172 | train |
koenedaele/skosprovider_oe | skosprovider_oe/providers.py | OnroerendErfgoedProvider.get_top_display | def get_top_display(self, **kwargs):
'''
Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and... | python | def get_top_display(self, **kwargs):
'''
Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and... | [
"def",
"get_top_display",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"language",
"=",
"self",
".",
"_get_language",
"(",
"*",
"*",
"kwargs",
")",
"url",
"=",
"self",
".",
"url",
"+",
"'/lijst.json'",
"args",
"=",
"{",
"'type[]'",
":",
"[",
"'HR'... | Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and collections. For each an
id is present and a... | [
"Returns",
"all",
"concepts",
"or",
"collections",
"that",
"form",
"the",
"top",
"-",
"level",
"of",
"a",
"display",
"hierarchy",
"."
] | 099b23cccd3884b06354102955dbc71f59d8fdb0 | https://github.com/koenedaele/skosprovider_oe/blob/099b23cccd3884b06354102955dbc71f59d8fdb0/skosprovider_oe/providers.py#L246-L275 | train |
koenedaele/skosprovider_oe | skosprovider_oe/providers.py | OnroerendErfgoedProvider.get_children_display | def get_children_display(self, id, **kwargs):
'''
Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a la... | python | def get_children_display(self, id, **kwargs):
'''
Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a la... | [
"def",
"get_children_display",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"language",
"=",
"self",
".",
"_get_language",
"(",
"*",
"*",
"kwargs",
")",
"item",
"=",
"self",
".",
"get_by_id",
"(",
"id",
")",
"res",
"=",
"[",
"]",
"if"... | Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a label. The label is determined by looking at
the `**kwar... | [
"Return",
"a",
"list",
"of",
"concepts",
"or",
"collections",
"that",
"should",
"be",
"displayed",
"under",
"this",
"concept",
"or",
"collection",
"."
] | 099b23cccd3884b06354102955dbc71f59d8fdb0 | https://github.com/koenedaele/skosprovider_oe/blob/099b23cccd3884b06354102955dbc71f59d8fdb0/skosprovider_oe/providers.py#L277-L306 | train |
greenelab/django-genes | genes/utils.py | translate_genes | def translate_genes(id_list=None, from_id=None, to_id=None, organism=None):
"""
Pass a list of identifiers (id_list), the name of the database ('Entrez',
'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference
database) that you wish to translate from, and the name of the database
th... | python | def translate_genes(id_list=None, from_id=None, to_id=None, organism=None):
"""
Pass a list of identifiers (id_list), the name of the database ('Entrez',
'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference
database) that you wish to translate from, and the name of the database
th... | [
"def",
"translate_genes",
"(",
"id_list",
"=",
"None",
",",
"from_id",
"=",
"None",
",",
"to_id",
"=",
"None",
",",
"organism",
"=",
"None",
")",
":",
"ids",
"=",
"set",
"(",
"id_list",
")",
"# Initialize set of identifiers not found by this translate_genes method... | Pass a list of identifiers (id_list), the name of the database ('Entrez',
'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference
database) that you wish to translate from, and the name of the database
that you wish to translate to. | [
"Pass",
"a",
"list",
"of",
"identifiers",
"(",
"id_list",
")",
"the",
"name",
"of",
"the",
"database",
"(",
"Entrez",
"Symbol",
"Standard",
"name",
"Systematic",
"name",
"or",
"a",
"loaded",
"crossreference",
"database",
")",
"that",
"you",
"wish",
"to",
"... | 298939adcb115031acfc11cfcef60ea0b596fae5 | https://github.com/greenelab/django-genes/blob/298939adcb115031acfc11cfcef60ea0b596fae5/genes/utils.py#L5-L99 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | _inner_func_anot | def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface"""
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func | python | def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface"""
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func | [
"def",
"_inner_func_anot",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"new_func",
"(",
"*",
"args",
")",
":",
"return",
"func",
"(",
"*",
"_lmap",
"(",
"_wrap_surface",
",",
"args",
")",
")",
"return",
"new_func"
] | must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface | [
"must",
"be",
"applied",
"to",
"all",
"inner",
"functions",
"that",
"return",
"contexts",
".",
"Wraps",
"all",
"instances",
"of",
"pygame",
".",
"Surface",
"in",
"the",
"input",
"in",
"Surface"
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L23-L30 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | Cross | def Cross(width=3, color=0):
"""Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color
"""
return Overlay(Line("h", width, color), Line("v", width, color)) | python | def Cross(width=3, color=0):
"""Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color
"""
return Overlay(Line("h", width, color), Line("v", width, color)) | [
"def",
"Cross",
"(",
"width",
"=",
"3",
",",
"color",
"=",
"0",
")",
":",
"return",
"Overlay",
"(",
"Line",
"(",
"\"h\"",
",",
"width",
",",
"color",
")",
",",
"Line",
"(",
"\"v\"",
",",
"width",
",",
"color",
")",
")"
] | Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color | [
"Draws",
"a",
"cross",
"centered",
"in",
"the",
"target",
"area"
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L381-L389 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | compose | def compose(target, root=None):
"""Top level function to create a surface.
:param target: the pygame.Surface to blit on. Or a (width, height) tuple
in which case a new surface will be created
:type target: -
"""
if type(root) == Surface:
raise ValueError("A Surface may not be u... | python | def compose(target, root=None):
"""Top level function to create a surface.
:param target: the pygame.Surface to blit on. Or a (width, height) tuple
in which case a new surface will be created
:type target: -
"""
if type(root) == Surface:
raise ValueError("A Surface may not be u... | [
"def",
"compose",
"(",
"target",
",",
"root",
"=",
"None",
")",
":",
"if",
"type",
"(",
"root",
")",
"==",
"Surface",
":",
"raise",
"ValueError",
"(",
"\"A Surface may not be used as root, please add \"",
"+",
"\"it as a single child i.e. compose(...)(Surface(...))\"",
... | Top level function to create a surface.
:param target: the pygame.Surface to blit on. Or a (width, height) tuple
in which case a new surface will be created
:type target: - | [
"Top",
"level",
"function",
"to",
"create",
"a",
"surface",
".",
":",
"param",
"target",
":",
"the",
"pygame",
".",
"Surface",
"to",
"blit",
"on",
".",
"Or",
"a",
"(",
"width",
"height",
")",
"tuple",
"in",
"which",
"case",
"a",
"new",
"surface",
"wi... | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L483-L511 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | Font | def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: ... | python | def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: ... | [
"def",
"Font",
"(",
"name",
"=",
"None",
",",
"source",
"=",
"\"sys\"",
",",
"italic",
"=",
"False",
",",
"bold",
"=",
"False",
",",
"size",
"=",
"20",
")",
":",
"assert",
"source",
"in",
"[",
"\"sys\"",
",",
"\"file\"",
"]",
"if",
"not",
"name",
... | Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: str | [
"Unifies",
"loading",
"of",
"fonts",
"."
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L515-L536 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | Text | def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"):
"""Renders a text. Supports multiline text, the background will be transparent.
:param align: text-alignment must be "center", "left", or "righ"
:type align: str
:return: the input text
:rtype: pygame.Surface
... | python | def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"):
"""Renders a text. Supports multiline text, the background will be transparent.
:param align: text-alignment must be "center", "left", or "righ"
:type align: str
:return: the input text
:rtype: pygame.Surface
... | [
"def",
"Text",
"(",
"text",
",",
"font",
",",
"color",
"=",
"pygame",
".",
"Color",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"antialias",
"=",
"False",
",",
"align",
"=",
"\"center\"",
")",
":",
"assert",
"align",
"in",
"[",
"\"center\"",
",",
"\"... | Renders a text. Supports multiline text, the background will be transparent.
:param align: text-alignment must be "center", "left", or "righ"
:type align: str
:return: the input text
:rtype: pygame.Surface | [
"Renders",
"a",
"text",
".",
"Supports",
"multiline",
"text",
"the",
"background",
"will",
"be",
"transparent",
".",
":",
"param",
"align",
":",
"text",
"-",
"alignment",
"must",
"be",
"center",
"left",
"or",
"righ",
":",
"type",
"align",
":",
"str",
":"... | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L543-L566 | train |
KnorrFG/pyparadigm | pyparadigm/surface_composition.py | Padding.from_scale | def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not b... | python | def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not b... | [
"def",
"from_scale",
"(",
"scale_w",
",",
"scale_h",
"=",
"None",
")",
":",
"if",
"not",
"scale_h",
":",
"scale_h",
"=",
"scale_w",
"w_padding",
"=",
"[",
"(",
"1",
"-",
"scale_w",
")",
"*",
"0.5",
"]",
"*",
"2",
"h_padding",
"=",
"[",
"(",
"1",
... | Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not be scaled (since scale_h=1) and therefore
t... | [
"Creates",
"a",
"padding",
"by",
"the",
"remaining",
"space",
"after",
"scaling",
"the",
"content",
"."
] | 69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3 | https://github.com/KnorrFG/pyparadigm/blob/69944cdf3ce2f6414ae1aa1d27a0d8c6e5fb3fd3/pyparadigm/surface_composition.py#L264-L282 | train |
kfdm/wanikani | wanikani/core.py | WaniKani.radicals | def radicals(self, levels=None):
"""
:param levels string: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
http://www.wanikani.com/api/v1.2#... | python | def radicals(self, levels=None):
"""
:param levels string: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
http://www.wanikani.com/api/v1.2#... | [
"def",
"radicals",
"(",
"self",
",",
"levels",
"=",
"None",
")",
":",
"url",
"=",
"WANIKANI_BASE",
".",
"format",
"(",
"self",
".",
"api_key",
",",
"'radicals'",
")",
"if",
"levels",
":",
"url",
"+=",
"'/{0}'",
".",
"format",
"(",
"levels",
")",
"dat... | :param levels string: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
http://www.wanikani.com/api/v1.2#radicals-list | [
":",
"param",
"levels",
"string",
":",
"An",
"optional",
"argument",
"of",
"declaring",
"a",
"single",
"or",
"comma",
"-",
"delimited",
"list",
"of",
"levels",
"is",
"available",
"as",
"seen",
"in",
"the",
"example",
"as",
"1",
".",
"An",
"example",
"of"... | 209f9b34b2832c2b9c9b12077f4a4382c047f710 | https://github.com/kfdm/wanikani/blob/209f9b34b2832c2b9c9b12077f4a4382c047f710/wanikani/core.py#L168-L182 | train |
kfdm/wanikani | wanikani/core.py | WaniKani.kanji | def kanji(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://ww... | python | def kanji(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://ww... | [
"def",
"kanji",
"(",
"self",
",",
"levels",
"=",
"None",
")",
":",
"url",
"=",
"WANIKANI_BASE",
".",
"format",
"(",
"self",
".",
"api_key",
",",
"'kanji'",
")",
"if",
"levels",
":",
"url",
"+=",
"'/{0}'",
".",
"format",
"(",
"levels",
")",
"data",
... | :param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://www.wanikani.com/api/v1.2#kanji-list | [
":",
"param",
"levels",
":",
"An",
"optional",
"argument",
"of",
"declaring",
"a",
"single",
"or",
"comma",
"-",
"delimited",
"list",
"of",
"levels",
"is",
"available",
"as",
"seen",
"in",
"the",
"example",
"as",
"1",
".",
"An",
"example",
"of",
"a",
"... | 209f9b34b2832c2b9c9b12077f4a4382c047f710 | https://github.com/kfdm/wanikani/blob/209f9b34b2832c2b9c9b12077f4a4382c047f710/wanikani/core.py#L184-L199 | train |
kfdm/wanikani | wanikani/core.py | WaniKani.vocabulary | def vocabulary(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http... | python | def vocabulary(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http... | [
"def",
"vocabulary",
"(",
"self",
",",
"levels",
"=",
"None",
")",
":",
"url",
"=",
"WANIKANI_BASE",
".",
"format",
"(",
"self",
".",
"api_key",
",",
"'vocabulary'",
")",
"if",
"levels",
":",
"url",
"+=",
"'/{0}'",
".",
"format",
"(",
"levels",
")",
... | :param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://www.wanikani.com/api/v1.2#vocabulary-list | [
":",
"param",
"levels",
":",
"An",
"optional",
"argument",
"of",
"declaring",
"a",
"single",
"or",
"comma",
"-",
"delimited",
"list",
"of",
"levels",
"is",
"available",
"as",
"seen",
"in",
"the",
"example",
"as",
"1",
".",
"An",
"example",
"of",
"a",
"... | 209f9b34b2832c2b9c9b12077f4a4382c047f710 | https://github.com/kfdm/wanikani/blob/209f9b34b2832c2b9c9b12077f4a4382c047f710/wanikani/core.py#L202-L222 | train |
pmacosta/pmisc | pmisc/member.py | ishex | def ishex(obj):
"""
Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) | python | def ishex(obj):
"""
Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) | [
"def",
"ishex",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"str",
")",
"and",
"(",
"len",
"(",
"obj",
")",
"==",
"1",
")",
"and",
"(",
"obj",
"in",
"string",
".",
"hexdigits",
")"
] | Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean | [
"Test",
"if",
"the",
"argument",
"is",
"a",
"string",
"representing",
"a",
"valid",
"hexadecimal",
"digit",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/member.py#L40-L49 | train |
pmacosta/pmisc | pmisc/member.py | isnumber | def isnumber(obj):
"""
Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float, complex))
) | python | def isnumber(obj):
"""
Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float, complex))
) | [
"def",
"isnumber",
"(",
"obj",
")",
":",
"return",
"(",
"(",
"obj",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"obj",
",",
"bool",
")",
")",
"and",
"isinstance",
"(",
"obj",
",",
"(",
"int",
",",
"float",
",",
"complex",
")",... | Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean | [
"Test",
"if",
"the",
"argument",
"is",
"a",
"number",
"(",
"complex",
"float",
"or",
"integer",
")",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/member.py#L68-L81 | train |
pmacosta/pmisc | pmisc/member.py | isreal | def isreal(obj):
"""
Test if the argument is a real number (float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float))
) | python | def isreal(obj):
"""
Test if the argument is a real number (float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float))
) | [
"def",
"isreal",
"(",
"obj",
")",
":",
"return",
"(",
"(",
"obj",
"is",
"not",
"None",
")",
"and",
"(",
"not",
"isinstance",
"(",
"obj",
",",
"bool",
")",
")",
"and",
"isinstance",
"(",
"obj",
",",
"(",
"int",
",",
"float",
")",
")",
")"
] | Test if the argument is a real number (float or integer).
:param obj: Object
:type obj: any
:rtype: boolean | [
"Test",
"if",
"the",
"argument",
"is",
"a",
"real",
"number",
"(",
"float",
"or",
"integer",
")",
"."
] | dd2bb32e59eee872f1ef2db2d9921a396ab9f50b | https://github.com/pmacosta/pmisc/blob/dd2bb32e59eee872f1ef2db2d9921a396ab9f50b/pmisc/member.py#L84-L97 | train |
RobotStudio/bors | bors/app/builder.py | AppBuilder.create_api_context | def create_api_context(self, cls):
"""Create and return an API context"""
return self.api_context_schema().load({
"name": cls.name,
"cls": cls,
"inst": [],
"conf": self.conf.get_api_service(cls.name),
"calls": self.conf.get_api_calls(),
... | python | def create_api_context(self, cls):
"""Create and return an API context"""
return self.api_context_schema().load({
"name": cls.name,
"cls": cls,
"inst": [],
"conf": self.conf.get_api_service(cls.name),
"calls": self.conf.get_api_calls(),
... | [
"def",
"create_api_context",
"(",
"self",
",",
"cls",
")",
":",
"return",
"self",
".",
"api_context_schema",
"(",
")",
".",
"load",
"(",
"{",
"\"name\"",
":",
"cls",
".",
"name",
",",
"\"cls\"",
":",
"cls",
",",
"\"inst\"",
":",
"[",
"]",
",",
"\"con... | Create and return an API context | [
"Create",
"and",
"return",
"an",
"API",
"context"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/builder.py#L38-L49 | train |
RobotStudio/bors | bors/app/builder.py | AppBuilder.receive | def receive(self, data, api_context):
"""Pass an API result down the pipeline"""
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
... | python | def receive(self, data, api_context):
"""Pass an API result down the pipeline"""
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
... | [
"def",
"receive",
"(",
"self",
",",
"data",
",",
"api_context",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"f\"Putting data on the pipeline: {data}\"",
")",
"result",
"=",
"{",
"\"api_contexts\"",
":",
"self",
".",
"api_contexts",
",",
"\"api_context\"",
... | Pass an API result down the pipeline | [
"Pass",
"an",
"API",
"result",
"down",
"the",
"pipeline"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/builder.py#L56-L66 | train |
RobotStudio/bors | bors/app/builder.py | AppBuilder.shutdown | def shutdown(self, signum, frame): # pylint: disable=unused-argument
"""Shut it down"""
if not self.exit:
self.exit = True
self.log.debug(f"SIGTRAP!{signum};{frame}")
self.api.shutdown()
self.strat.shutdown() | python | def shutdown(self, signum, frame): # pylint: disable=unused-argument
"""Shut it down"""
if not self.exit:
self.exit = True
self.log.debug(f"SIGTRAP!{signum};{frame}")
self.api.shutdown()
self.strat.shutdown() | [
"def",
"shutdown",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"self",
".",
"exit",
":",
"self",
".",
"exit",
"=",
"True",
"self",
".",
"log",
".",
"debug",
"(",
"f\"SIGTRAP!{signum};{frame}\"",
")",
... | Shut it down | [
"Shut",
"it",
"down"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/app/builder.py#L68-L74 | train |
CogSciUOS/StudDP | studdp/model.py | BaseNode.course | def course(self):
"""
Course this node belongs to
"""
course = self.parent
while course.parent:
course = course.parent
return course | python | def course(self):
"""
Course this node belongs to
"""
course = self.parent
while course.parent:
course = course.parent
return course | [
"def",
"course",
"(",
"self",
")",
":",
"course",
"=",
"self",
".",
"parent",
"while",
"course",
".",
"parent",
":",
"course",
"=",
"course",
".",
"parent",
"return",
"course"
] | Course this node belongs to | [
"Course",
"this",
"node",
"belongs",
"to"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L45-L52 | train |
CogSciUOS/StudDP | studdp/model.py | BaseNode.path | def path(self):
"""
Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap
"""
if self.parent is None:
return self.title
return join(self.parent.path, self.title) | python | def path(self):
"""
Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap
"""
if self.parent is None:
return self.title
return join(self.parent.path, self.title) | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"return",
"self",
".",
"title",
"return",
"join",
"(",
"self",
".",
"parent",
".",
"path",
",",
"self",
".",
"title",
")"
] | Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap | [
"Path",
"of",
"this",
"node",
"on",
"Studip",
".",
"Looks",
"like",
"Coures",
"/",
"folder",
"/",
"folder",
"/",
"document",
".",
"Respects",
"the",
"renaming",
"policies",
"defined",
"in",
"the",
"namemap"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L55-L61 | train |
CogSciUOS/StudDP | studdp/model.py | BaseNode.title | def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used.
"""
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
retur... | python | def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used.
"""
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
retur... | [
"def",
"title",
"(",
"self",
")",
":",
"tmp",
"=",
"c",
".",
"namemap_lookup",
"(",
"self",
".",
"id",
")",
"if",
"c",
".",
"namemap_lookup",
"(",
"self",
".",
"id",
")",
"is",
"not",
"None",
"else",
"self",
".",
"_title",
"return",
"secure_filename"... | get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used. | [
"get",
"title",
"of",
"this",
"node",
".",
"If",
"an",
"entry",
"for",
"this",
"course",
"is",
"found",
"in",
"the",
"configuration",
"namemap",
"it",
"is",
"used",
"otherwise",
"the",
"default",
"value",
"from",
"stud",
".",
"ip",
"is",
"used",
"."
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L64-L70 | train |
CogSciUOS/StudDP | studdp/model.py | Folder.deep_documents | def deep_documents(self):
"""
list of all documents find in subtrees of this node
"""
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return... | python | def deep_documents(self):
"""
list of all documents find in subtrees of this node
"""
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return... | [
"def",
"deep_documents",
"(",
"self",
")",
":",
"tree",
"=",
"[",
"]",
"for",
"entry",
"in",
"self",
".",
"contents",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Document",
")",
":",
"tree",
".",
"append",
"(",
"entry",
")",
"else",
":",
"tree",
"... | list of all documents find in subtrees of this node | [
"list",
"of",
"all",
"documents",
"find",
"in",
"subtrees",
"of",
"this",
"node"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L90-L100 | train |
CogSciUOS/StudDP | studdp/model.py | Course.title | def title(self):
"""
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME
"""
name = c.namemap_lookup(self.id)
if name is None:
name = self._title + " " + client.get_semester_... | python | def title(self):
"""
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME
"""
name = c.namemap_lookup(self.id)
if name is None:
name = self._title + " " + client.get_semester_... | [
"def",
"title",
"(",
"self",
")",
":",
"name",
"=",
"c",
".",
"namemap_lookup",
"(",
"self",
".",
"id",
")",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"self",
".",
"_title",
"+",
"\" \"",
"+",
"client",
".",
"get_semester_title",
"(",
"self",
"... | The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME | [
"The",
"title",
"of",
"the",
"course",
".",
"If",
"no",
"entry",
"in",
"the",
"namemap",
"of",
"the",
"configuration",
"is",
"found",
"a",
"new",
"entry",
"is",
"created",
"with",
"name",
"=",
"$STUD",
".",
"IP_NAME",
"+",
"$SEMESTER_NAME"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L114-L122 | train |
CogSciUOS/StudDP | studdp/model.py | _APIClient._get | def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
"""
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) | python | def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
"""
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) | [
"def",
"_get",
"(",
"self",
",",
"route",
",",
"stream",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"Running GET request against %s\"",
"%",
"route",
")",
"return",
"r",
".",
"get",
"(",
"self",
".",
"_url",
"(",
"route",
")",
",",
"auth",
"... | run a get request against an url. Returns the response which can optionally be streamed | [
"run",
"a",
"get",
"request",
"against",
"an",
"url",
".",
"Returns",
"the",
"response",
"which",
"can",
"optionally",
"be",
"streamed"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L168-L173 | train |
CogSciUOS/StudDP | studdp/model.py | _APIClient.get_contents | def get_contents(self, folder: Folder):
"""
List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder.
"""
log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id))
if isinstance(folder, Course):
response = j... | python | def get_contents(self, folder: Folder):
"""
List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder.
"""
log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id))
if isinstance(folder, Course):
response = j... | [
"def",
"get_contents",
"(",
"self",
",",
"folder",
":",
"Folder",
")",
":",
"log",
".",
"debug",
"(",
"\"Listing Contents of %s/%s\"",
"%",
"(",
"folder",
".",
"course",
".",
"id",
",",
"folder",
".",
"id",
")",
")",
"if",
"isinstance",
"(",
"folder",
... | List all contents of a folder. Returns a list of all Documents and Folders (in this order) in the folder. | [
"List",
"all",
"contents",
"of",
"a",
"folder",
".",
"Returns",
"a",
"list",
"of",
"all",
"Documents",
"and",
"Folders",
"(",
"in",
"this",
"order",
")",
"in",
"the",
"folder",
"."
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L175-L190 | train |
CogSciUOS/StudDP | studdp/model.py | _APIClient.download_document | def download_document(self, document: Document, overwrite=True, path=None):
"""
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on... | python | def download_document(self, document: Document, overwrite=True, path=None):
"""
Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on... | [
"def",
"download_document",
"(",
"self",
",",
"document",
":",
"Document",
",",
"overwrite",
"=",
"True",
",",
"path",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expan... | Download a document to the given path. if no path is provided the path is constructed frome the base_url + stud.ip path + filename.
If overwrite is set the local version will be overwritten if the file was changed on studip since the last check | [
"Download",
"a",
"document",
"to",
"the",
"given",
"path",
".",
"if",
"no",
"path",
"is",
"provided",
"the",
"path",
"is",
"constructed",
"frome",
"the",
"base_url",
"+",
"stud",
".",
"ip",
"path",
"+",
"filename",
".",
"If",
"overwrite",
"is",
"set",
... | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L196-L208 | train |
CogSciUOS/StudDP | studdp/model.py | _APIClient.get_semester_title | def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
"""
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) | python | def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
"""
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) | [
"def",
"get_semester_title",
"(",
"self",
",",
"node",
":",
"BaseNode",
")",
":",
"log",
".",
"debug",
"(",
"\"Getting Semester Title for %s\"",
"%",
"node",
".",
"course",
".",
"id",
")",
"return",
"self",
".",
"_get_semester_from_id",
"(",
"node",
".",
"co... | get the semester of a node | [
"get",
"the",
"semester",
"of",
"a",
"node"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L210-L215 | train |
CogSciUOS/StudDP | studdp/model.py | _APIClient.get_courses | def get_courses(self):
"""
use the base_url and auth data from the configuration to list all courses the user is subscribed to
"""
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for co... | python | def get_courses(self):
"""
use the base_url and auth data from the configuration to list all courses the user is subscribed to
"""
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for co... | [
"def",
"get_courses",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"Listing Courses...\"",
")",
"courses",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"_get",
"(",
"'/api/courses'",
")",
".",
"text",
")",
"[",
"\"courses\"",
"]",
"courses",
"=",
... | use the base_url and auth data from the configuration to list all courses the user is subscribed to | [
"use",
"the",
"base_url",
"and",
"auth",
"data",
"from",
"the",
"configuration",
"to",
"list",
"all",
"courses",
"the",
"user",
"is",
"subscribed",
"to"
] | e953aea51766438f2901c9e87f5b7b9e5bb892f5 | https://github.com/CogSciUOS/StudDP/blob/e953aea51766438f2901c9e87f5b7b9e5bb892f5/studdp/model.py#L221-L229 | train |
limix/optimix | optimix/_function.py | FuncOpt._minimize_scalar | def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
"""
... | python | def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
"""
... | [
"def",
"_minimize_scalar",
"(",
"self",
",",
"desc",
"=",
"\"Progress\"",
",",
"rtol",
"=",
"1.4902e-08",
",",
"atol",
"=",
"1.4902e-08",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"tqdm",
"import",
"tqdm",
"from",
"numpy",
"import",
"asarray",
"from",... | Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise. | [
"Minimize",
"a",
"scalar",
"function",
"using",
"Brent",
"s",
"method",
"."
] | d7b1356df259c9f6ee0d658258fb47d0074fc416 | https://github.com/limix/optimix/blob/d7b1356df259c9f6ee0d658258fb47d0074fc416/optimix/_function.py#L16-L47 | train |
BlackEarth/bl | bl/string.py | String.digest | def digest(self, alg='sha256', b64=True, strip=True):
"""return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = wheth... | python | def digest(self, alg='sha256', b64=True, strip=True):
"""return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = wheth... | [
"def",
"digest",
"(",
"self",
",",
"alg",
"=",
"'sha256'",
",",
"b64",
"=",
"True",
",",
"strip",
"=",
"True",
")",
":",
"import",
"base64",
",",
"hashlib",
"h",
"=",
"hashlib",
".",
"new",
"(",
"alg",
")",
"h",
".",
"update",
"(",
"str",
"(",
... | return a url-safe hash of the string, optionally (and by default) base64-encoded
alg='sha256' = the hash algorithm, must be in hashlib
b64=True = whether to base64-encode the output
strip=True = whether to strip trailing '=' from the base64 output
Using the... | [
"return",
"a",
"url",
"-",
"safe",
"hash",
"of",
"the",
"string",
"optionally",
"(",
"and",
"by",
"default",
")",
"base64",
"-",
"encoded",
"alg",
"=",
"sha256",
"=",
"the",
"hash",
"algorithm",
"must",
"be",
"in",
"hashlib",
"b64",
"=",
"True",
"=",
... | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L31-L54 | train |
BlackEarth/bl | bl/string.py | String.camelify | def camelify(self):
"""turn a string to CamelCase, omitting non-word characters"""
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) | python | def camelify(self):
"""turn a string to CamelCase, omitting non-word characters"""
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) | [
"def",
"camelify",
"(",
"self",
")",
":",
"outstring",
"=",
"self",
".",
"titleify",
"(",
"allwords",
"=",
"True",
")",
"outstring",
"=",
"re",
".",
"sub",
"(",
"r\"&[^;]+;\"",
",",
"\" \"",
",",
"outstring",
")",
"outstring",
"=",
"re",
".",
"sub",
... | turn a string to CamelCase, omitting non-word characters | [
"turn",
"a",
"string",
"to",
"CamelCase",
"omitting",
"non",
"-",
"word",
"characters"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L61-L66 | train |
BlackEarth/bl | bl/string.py | String.titleify | def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it"""
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
... | python | def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it"""
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
... | [
"def",
"titleify",
"(",
"self",
",",
"lang",
"=",
"'en'",
",",
"allwords",
"=",
"False",
",",
"lastword",
"=",
"True",
")",
":",
"if",
"lang",
"in",
"LOWERCASE_WORDS",
":",
"lc_words",
"=",
"LOWERCASE_WORDS",
"[",
"lang",
"]",
"else",
":",
"lc_words",
... | takes a string and makes a title from it | [
"takes",
"a",
"string",
"and",
"makes",
"a",
"title",
"from",
"it"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L68-L91 | train |
BlackEarth/bl | bl/string.py | String.identifier | def identifier(self, camelsplit=False, ascii=True):
"""return a python identifier from the string (underscore separators)"""
return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_') | python | def identifier(self, camelsplit=False, ascii=True):
"""return a python identifier from the string (underscore separators)"""
return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_') | [
"def",
"identifier",
"(",
"self",
",",
"camelsplit",
"=",
"False",
",",
"ascii",
"=",
"True",
")",
":",
"return",
"self",
".",
"nameify",
"(",
"camelsplit",
"=",
"camelsplit",
",",
"ascii",
"=",
"ascii",
",",
"sep",
"=",
"'_'",
")"
] | return a python identifier from the string (underscore separators) | [
"return",
"a",
"python",
"identifier",
"from",
"the",
"string",
"(",
"underscore",
"separators",
")"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L93-L95 | train |
BlackEarth/bl | bl/string.py | String.nameify | def nameify(self, camelsplit=False, ascii=True, sep='-'):
"""return an XML name (hyphen-separated by default, initial underscore if non-letter)"""
s = String(str(self)) # immutable
if camelsplit == True:
s = s.camelsplit()
s = s.hyphenify(ascii=ascii).replace('-', sep)
... | python | def nameify(self, camelsplit=False, ascii=True, sep='-'):
"""return an XML name (hyphen-separated by default, initial underscore if non-letter)"""
s = String(str(self)) # immutable
if camelsplit == True:
s = s.camelsplit()
s = s.hyphenify(ascii=ascii).replace('-', sep)
... | [
"def",
"nameify",
"(",
"self",
",",
"camelsplit",
"=",
"False",
",",
"ascii",
"=",
"True",
",",
"sep",
"=",
"'-'",
")",
":",
"s",
"=",
"String",
"(",
"str",
"(",
"self",
")",
")",
"# immutable\r",
"if",
"camelsplit",
"==",
"True",
":",
"s",
"=",
... | return an XML name (hyphen-separated by default, initial underscore if non-letter) | [
"return",
"an",
"XML",
"name",
"(",
"hyphen",
"-",
"separated",
"by",
"default",
"initial",
"underscore",
"if",
"non",
"-",
"letter",
")"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L101-L109 | train |
BlackEarth/bl | bl/string.py | String.hyphenify | def hyphenify(self, ascii=False):
"""Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters.
"""
s = str(self)
s = re.sub("""['"\u2018\u2019\u201c\u20... | python | def hyphenify(self, ascii=False):
"""Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters.
"""
s = str(self)
s = re.sub("""['"\u2018\u2019\u201c\u20... | [
"def",
"hyphenify",
"(",
"self",
",",
"ascii",
"=",
"False",
")",
":",
"s",
"=",
"str",
"(",
"self",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"\"\"\"['\"\\u2018\\u2019\\u201c\\u201d]\"\"\"",
",",
"''",
",",
"s",
")",
"# quotes\r",
"s",
"=",
"re",
".",
"... | Turn non-word characters (incl. underscore) into single hyphens.
If ascii=True, return ASCII-only.
If also lossless=True, use the UTF-8 codes for the non-ASCII characters. | [
"Turn",
"non",
"-",
"word",
"characters",
"(",
"incl",
".",
"underscore",
")",
"into",
"single",
"hyphens",
".",
"If",
"ascii",
"=",
"True",
"return",
"ASCII",
"-",
"only",
".",
"If",
"also",
"lossless",
"=",
"True",
"use",
"the",
"UTF",
"-",
"8",
"c... | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L111-L124 | train |
BlackEarth/bl | bl/string.py | String.camelsplit | def camelsplit(self):
"""Turn a CamelCase string into a string with spaces"""
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].i... | python | def camelsplit(self):
"""Turn a CamelCase string into a string with spaces"""
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].i... | [
"def",
"camelsplit",
"(",
"self",
")",
":",
"s",
"=",
"str",
"(",
"self",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"i",
"!=",
"0",
"and",
"(",
"(",
"s",
"[",
"i",... | Turn a CamelCase string into a string with spaces | [
"Turn",
"a",
"CamelCase",
"string",
"into",
"a",
"string",
"with",
"spaces"
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/string.py#L126-L135 | train |
openstax/pyramid_sawing | pyramid_sawing/main.py | includeme | def includeme(config):
"""Pyramid pluggable and discoverable function."""
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
... | python | def includeme(config):
"""Pyramid pluggable and discoverable function."""
global_settings = config.registry.settings
settings = local_settings(global_settings, PREFIX)
try:
file = settings['file']
except KeyError:
raise KeyError("Must supply '{}.file' configuration value "
... | [
"def",
"includeme",
"(",
"config",
")",
":",
"global_settings",
"=",
"config",
".",
"registry",
".",
"settings",
"settings",
"=",
"local_settings",
"(",
"global_settings",
",",
"PREFIX",
")",
"try",
":",
"file",
"=",
"settings",
"[",
"'file'",
"]",
"except",... | Pyramid pluggable and discoverable function. | [
"Pyramid",
"pluggable",
"and",
"discoverable",
"function",
"."
] | d2ac7faf30c1517ed4621b8e62b7848e926078b9 | https://github.com/openstax/pyramid_sawing/blob/d2ac7faf30c1517ed4621b8e62b7848e926078b9/pyramid_sawing/main.py#L44-L63 | train |
RobotStudio/bors | bors/api/adapter/api.py | ApiAdapter.run | def run(self):
"""Executed on startup of application"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
for call, calldata in self.context.get("calls", {}).items():
def loop():
"""Loop on event... | python | def run(self):
"""Executed on startup of application"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
for call, calldata in self.context.get("calls", {}).items():
def loop():
"""Loop on event... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"api",
"=",
"self",
".",
"context",
".",
"get",
"(",
"\"cls\"",
")",
"(",
"self",
".",
"context",
")",
"self",
".",
"context",
"[",
"\"inst\"",
"]",
".",
"append",
"(",
"self",
")",
"# Adapters used... | Executed on startup of application | [
"Executed",
"on",
"startup",
"of",
"application"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L20-L32 | train |
RobotStudio/bors | bors/api/adapter/api.py | ApiAdapter.call | def call(self, callname, arguments=None):
"""Executed on each scheduled iteration"""
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
excep... | python | def call(self, callname, arguments=None):
"""Executed on each scheduled iteration"""
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
excep... | [
"def",
"call",
"(",
"self",
",",
"callname",
",",
"arguments",
"=",
"None",
")",
":",
"# See if a method override exists",
"action",
"=",
"getattr",
"(",
"self",
".",
"api",
",",
"callname",
",",
"None",
")",
"if",
"action",
"is",
"None",
":",
"try",
":"... | Executed on each scheduled iteration | [
"Executed",
"on",
"each",
"scheduled",
"iteration"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L34-L53 | train |
RobotStudio/bors | bors/api/adapter/api.py | ApiAdapter._generate_request | def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API"""
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") | python | def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API"""
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") | [
"def",
"_generate_request",
"(",
"self",
",",
"callname",
",",
"request",
")",
":",
"# Retrieve path from API class",
"schema",
"=",
"self",
".",
"api",
".",
"request_schema",
"(",
")",
"schema",
".",
"context",
"[",
"'callname'",
"]",
"=",
"callname",
"return... | Generate a request object for delivery to the API | [
"Generate",
"a",
"request",
"object",
"for",
"delivery",
"to",
"the",
"API"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L55-L60 | train |
RobotStudio/bors | bors/api/adapter/api.py | ApiAdapter._generate_result | def _generate_result(self, callname, result):
"""Generate a results object for delivery to the context object"""
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) | python | def _generate_result(self, callname, result):
"""Generate a results object for delivery to the context object"""
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) | [
"def",
"_generate_result",
"(",
"self",
",",
"callname",
",",
"result",
")",
":",
"# Retrieve path from API class",
"schema",
"=",
"self",
".",
"api",
".",
"result_schema",
"(",
")",
"schema",
".",
"context",
"[",
"'callname'",
"]",
"=",
"callname",
"self",
... | Generate a results object for delivery to the context object | [
"Generate",
"a",
"results",
"object",
"for",
"delivery",
"to",
"the",
"context",
"object"
] | 38bf338fc6905d90819faa56bd832140116720f0 | https://github.com/RobotStudio/bors/blob/38bf338fc6905d90819faa56bd832140116720f0/bors/api/adapter/api.py#L62-L67 | train |
BlackEarth/bl | bl/csv.py | excel_key | def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | python | def excel_key(index):
"""create a key for index by converting index into a base-26 number, using A-Z as the characters."""
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | [
"def",
"excel_key",
"(",
"index",
")",
":",
"X",
"=",
"lambda",
"n",
":",
"~",
"n",
"and",
"X",
"(",
"(",
"n",
"//",
"26",
")",
"-",
"1",
")",
"+",
"chr",
"(",
"65",
"+",
"(",
"n",
"%",
"26",
")",
")",
"or",
"''",
"return",
"X",
"(",
"i... | create a key for index by converting index into a base-26 number, using A-Z as the characters. | [
"create",
"a",
"key",
"for",
"index",
"by",
"converting",
"index",
"into",
"a",
"base",
"-",
"26",
"number",
"using",
"A",
"-",
"Z",
"as",
"the",
"characters",
"."
] | edf6f37dac718987260b90ad0e7f7fe084a7c1a3 | https://github.com/BlackEarth/bl/blob/edf6f37dac718987260b90ad0e7f7fe084a7c1a3/bl/csv.py#L29-L32 | train |
willkg/socorro-siggen | siggen/utils.py | convert_to_crash_data | def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... | python | def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... | [
"def",
"convert_to_crash_data",
"(",
"raw_crash",
",",
"processed_crash",
")",
":",
"# We want to generate fresh signatures, so we remove the \"normalized\" field",
"# from stack frames from the processed crash because this is essentially",
"# cached data from previous processing",
"for",
"t... | Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed crash data from Socorro
:returns: crash data structure that conf... | [
"Takes",
"a",
"raw",
"crash",
"and",
"a",
"processed",
"crash",
"(",
"these",
"are",
"Socorro",
"-",
"centric",
"data",
"structures",
")",
"and",
"converts",
"them",
"to",
"a",
"crash",
"data",
"structure",
"used",
"by",
"signature",
"generation",
"."
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L16-L84 | train |
willkg/socorro-siggen | siggen/utils.py | drop_bad_characters | def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
te... | python | def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
te... | [
"def",
"drop_bad_characters",
"(",
"text",
")",
":",
"# Strip all non-ascii and non-printable characters",
"text",
"=",
"''",
".",
"join",
"(",
"[",
"c",
"for",
"c",
"in",
"text",
"if",
"c",
"in",
"ALLOWED_CHARS",
"]",
")",
"return",
"text"
] | Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped | [
"Takes",
"a",
"text",
"and",
"drops",
"all",
"non",
"-",
"printable",
"and",
"non",
"-",
"ascii",
"characters",
"and",
"also",
"any",
"whitespace",
"characters",
"that",
"aren",
"t",
"space",
"."
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L91-L102 | train |
willkg/socorro-siggen | siggen/utils.py | parse_source_file | def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... | python | def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... | [
"def",
"parse_source_file",
"(",
"source_file",
")",
":",
"if",
"not",
"source_file",
":",
"return",
"None",
"vcsinfo",
"=",
"source_file",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"vcsinfo",
")",
"==",
"4",
":",
"# These are repositories or cloud file... | Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the filename or ``None`` if it couldn't determine ... | [
"Parses",
"a",
"source",
"file",
"thing",
"and",
"returns",
"the",
"file",
"name"
] | db7e3233e665a458a961c48da22e93a69b1d08d6 | https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L105-L138 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.