project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
sek788432/Waymo-2D-Object-Detection | learning_schedules.py | exponential_decay_with_warmup | exponential_decay_with_warmup | Exponential decay schedule with warm up period. | [
"Exponential",
"decay",
"schedule",
"with",
"warm",
"up",
"period."
] | def exponential_decay_with_warmup(global_step, learning_rate_base, learning_rate_decay_steps, learning_rate_decay_factor, warmup_learning_rate=0.0, warmup_steps=0, min_learning_rate=0.0, staircase=True):
def eager_decay_rate():
post_warmup_learning_rate = tf.train.exponential_decay(learning_rate_base, glob... | ['def', 'exponential_decay_with_warmup(global_step,', 'learning_rate_base,', 'learning_rate_decay_steps,', 'learning_rate_decay_factor,', 'warmup_learning_rate=0.0,', 'warmup_steps=0,', 'min_learning_rate=0.0,', 'staircase=True):', 'def', 'eager_decay_rate():', 'post_warmup_learning_rate', '=', 'tf.train.exponential_de... | 975,435 |
sek788432/Waymo-2D-Object-Detection | target_assigner_utils.py | image_shape_to_grids | image_shape_to_grids | Computes xy-grids given the shape of the image. | [
"Computes",
"xy-grids",
"given",
"the",
"shape",
"of",
"the",
"image."
] | def image_shape_to_grids(height, width):
out_height = tf.cast(height, tf.float32)
out_width = tf.cast(width, tf.float32)
x_range = tf.range(out_width, dtype=tf.float32)
y_range = tf.range(out_height, dtype=tf.float32)
(x_grid, y_grid) = tf.meshgrid(x_range, y_range, indexing='xy')
return (y_grid... | ['def', 'image_shape_to_grids(height,', 'width):', 'out_height', '=', 'tf.cast(height,', 'tf.float32)', 'out_width', '=', 'tf.cast(width,', 'tf.float32)', 'x_range', '=', 'tf.range(out_width,', 'dtype=tf.float32)', 'y_range', '=', 'tf.range(out_height,', 'dtype=tf.float32)', '(x_grid,', 'y_grid)', '=', 'tf.meshgrid(x_r... | 975,567 |
sek788432/Waymo-2D-Object-Detection | sgnn.py | preprocess | preprocess | Normalize the text, and return tokens. | [
"Normalize",
"the",
"text,",
"and",
"return",
"tokens."
] | def preprocess(text):
assert len(text.get_shape().as_list()) == 2
assert text.get_shape().as_list()[-1] == 1
text = tf.reshape(text, [-1])
text = tf_text.case_fold_utf8(text)
tokenizer = tflite_text_api.WhitespaceTokenizer()
return tokenizer.tokenize(text) | ['def', 'preprocess(text):', 'assert', 'len(text.get_shape().as_list())', '==', '2', 'assert', 'text.get_shape().as_list()[-1]', '==', '1', 'text', '=', 'tf.reshape(text,', '[-1])', 'text', '=', 'tf_text.case_fold_utf8(text)', 'tokenizer', '=', 'tflite_text_api.WhitespaceTokenizer()', 'return', 'tokenizer.tokenize(text... | 975,694 |
sek788432/Waymo-2D-Object-Detection | tflite_utils.py | set_output_quantized_for_custom_ops | set_output_quantized_for_custom_ops | Set output types/quantized flag for custom/unsupported ops. | [
"Set",
"output",
"types/quantized",
"flag",
"for",
"custom/unsupported",
"ops."
] | def set_output_quantized_for_custom_ops(graph_def):
quantized_custom_ops = {'SequenceStringProjection': [tf.float32.as_datatype_enum], 'SequenceStringProjectionV2': [tf.float32.as_datatype_enum], 'PoolingOp': [tf.float32.as_datatype_enum], 'ExpectedValueOp': [tf.float32.as_datatype_enum], 'LayerNorm': [tf.float32.a... | ['def', 'set_output_quantized_for_custom_ops(graph_def):', 'quantized_custom_ops', '=', "{'SequenceStringProjection':", '[tf.float32.as_datatype_enum],', "'SequenceStringProjectionV2':", '[tf.float32.as_datatype_enum],', "'PoolingOp':", '[tf.float32.as_datatype_enum],', "'ExpectedValueOp':", '[tf.float32.as_datatype_en... | 975,704 |
sek788432/Waymo-2D-Object-Detection | dataset_loader.py | KittiRaw.collect_train_frames | collect_train_frames | Creates a list of training frames. | [
"Creates",
"a",
"list",
"of",
"training",
"frames."
] | def collect_train_frames(self):
all_frames = []
for date in self.date_list:
date_dir = os.path.join(self.dataset_dir, date)
drive_set = os.listdir(date_dir)
for dr in drive_set:
drive_dir = os.path.join(date_dir, dr)
if os.path.isdir(drive_dir):
if... | ['def', 'collect_train_frames(self):', 'all_frames', '=', '[]', 'for', 'date', 'in', 'self.date_list:', 'date_dir', '=', 'os.path.join(self.dataset_dir,', 'date)', 'drive_set', '=', 'os.listdir(date_dir)', 'for', 'dr', 'in', 'drive_set:', 'drive_dir', '=', 'os.path.join(date_dir,', 'dr)', 'if', 'os.path.isdir(drive_dir... | 975,910 |
worldbank/wb-nlp-tools | cleaner.py | BaseCleaner.get_tokens_and_phrases | get_tokens_and_phrases | This method parses and extracts phrases from texts based on POS which uses SpaCy. | [
"This",
"method",
"parses",
"and",
"extracts",
"phrases",
"from",
"texts",
"based",
"on",
"POS",
"which",
"uses",
"SpaCy."
] | def get_tokens_and_phrases(self, text: str, return_phrase_count: bool=False) -> dict:
doc = BaseCleaner.text_to_doc(text)
doc = self._apply_extractors(doc)
tokens = []
phrases = phrase.get_spacy_phrases(doc, min_token_length=self.min_token_length, token_func=self._is_valid_token, token_container=tokens)... | ['def', 'get_tokens_and_phrases(self,', 'text:', 'str,', 'return_phrase_count:', 'bool=False)', '->', 'dict:', 'doc', '=', 'BaseCleaner.text_to_doc(text)', 'doc', '=', 'self._apply_extractors(doc)', 'tokens', '=', '[]', 'phrases', '=', 'phrase.get_spacy_phrases(doc,', 'min_token_length=self.min_token_length,', 'token_f... | 975,933 |
worldbank/wb-nlp-tools | respelling.py | cached_infer_correct_word | cached_infer_correct_word | This method computes the inference score for the input word. | [
"This",
"method",
"computes",
"the",
"inference",
"score",
"for",
"the",
"input",
"word."
] | def cached_infer_correct_word(word: str, sim_thresh: float=0.0, print_log: bool=False, min_len: int=3, use_suggest_score: bool=True, **kwargs) -> dict:
correct_word = None
score = -1
payload = dict(word=word, correct_word=correct_word, score=score, sim_thresh=sim_thresh, print_log=print_log, min_len=min_len... | ['def', 'cached_infer_correct_word(word:', 'str,', 'sim_thresh:', 'float=0.0,', 'print_log:', 'bool=False,', 'min_len:', 'int=3,', 'use_suggest_score:', 'bool=True,', '**kwargs)', '->', 'dict:', 'correct_word', '=', 'None', 'score', '=', '-1', 'payload', '=', 'dict(word=word,', 'correct_word=correct_word,', 'score=scor... | 975,938 |
worldbank/wb-nlp-tools | respelling.py | Respeller.infer_correct_words | infer_correct_words | Applies the inference of correct words to a list of input words. | [
"Applies",
"the",
"inference",
"of",
"correct",
"words",
"to",
"a",
"list",
"of",
"input",
"words."
] | def infer_correct_words(self, words: list, return_tokens_as_list: bool, infer_correct_word_params: dict) -> [set, dict]:
respelled_set = {}
unfixed_words = set([])
for error_words in words:
res = self.infer_correct_word(error_words, **infer_correct_word_params)
word = res['word']
cor... | ['def', 'infer_correct_words(self,', 'words:', 'list,', 'return_tokens_as_list:', 'bool,', 'infer_correct_word_params:', 'dict)', '->', '[set,', 'dict]:', 'respelled_set', '=', '{}', 'unfixed_words', '=', 'set([])', 'for', 'error_words', 'in', 'words:', 'res', '=', 'self.infer_correct_word(error_words,', '**infer_corre... | 975,942 |
worldbank/wb-nlp-tools | acronyms.py | extract_acronyms | extract_acronyms | This function extracts candidate acronyms that satisfy a specific set of patterns. | [
"This",
"function",
"extracts",
"candidate",
"acronyms",
"that",
"satisfy",
"a",
"specific",
"set",
"of",
"patterns."
] | def extract_acronyms(txt):
acronyms = [i.strip('(').strip(')') for i in acronyms_pattern.findall(txt)]
keyword = '|'.join([f'\\({k}\\)' for k in acronyms])
candidates_acronym_pattern = "((?:[a-zA-ZÃ\x83Â\x80-Ã\x83Â\x96Ã\x83Â\x98-Ã\x83¶Ã\x83¸-Ã\x83¿Ã\x90°-Ã\x92³Ã\x90Â\x90-Ã\x92²'-]+ ){0,5})(" + keyword... | ['def', 'extract_acronyms(txt):', 'acronyms', '=', "[i.strip('(').strip(')')", 'for', 'i', 'in', 'acronyms_pattern.findall(txt)]', 'keyword', '=', "'|'.join([f'\\\\({k}\\\\)'", 'for', 'k', 'in', 'acronyms])', 'candidates_acronym_pattern', '=', '"((?:[a-zA-ZÃ\\x83Â\\x80-Ã\\x83Â\\x96Ã\\x83Â\\x98-Ã\\x83¶Ã\\x83¸-Ã\\x83¿... | 975,947 |
worldbank/wb-nlp-tools | cache_utils.py | get_redis_params | get_redis_params | Extracts redis params from env but fallsback to container host if not present. | [
"Extracts",
"redis",
"params",
"from",
"env",
"but",
"fallsback",
"to",
"container",
"host",
"if",
"not",
"present."
] | def get_redis_params():
redis_host = os.environ.get('WB_CLEANING_REDIS_HOSTNAME', 'redis')
redis_port = os.environ.get('WB_CLEANING_REDIS_PORT', '6379')
redis_db = os.environ.get('WB_CLEANING_REDIS_DB', '0')
redis_url = f'redis://{redis_host}:{redis_port}/{redis_db}'
return dict(redis_host=redis_hos... | ['def', 'get_redis_params():', 'redis_host', '=', "os.environ.get('WB_CLEANING_REDIS_HOSTNAME',", "'redis')", 'redis_port', '=', "os.environ.get('WB_CLEANING_REDIS_PORT',", "'6379')", 'redis_db', '=', "os.environ.get('WB_CLEANING_REDIS_DB',", "'0')", 'redis_url', '=', "f'redis://{redis_host}:{redis_port}/{redis_db}'", ... | 975,953 |
worldbank/wb-nlp-tools | cache_utils.py | store_to_bucket | store_to_bucket | Wrapper function for hset. | [
"Wrapper",
"function",
"for",
"hset."
] | def store_to_bucket(bucket_id, key, value):
return redis_cache.hset(bucket_id, key, value) | ['def', 'store_to_bucket(bucket_id,', 'key,', 'value):', 'return', 'redis_cache.hset(bucket_id,', 'key,', 'value)'] | 975,956 |
worldbank/wb-nlp-tools | corpus.py | generate_files | generate_files | A generator that loads text files given a directory. | [
"A",
"generator",
"that",
"loads",
"text",
"files",
"given",
"a",
"directory."
] | def generate_files(path: Path, split: bool=True, min_tokens: int=50, cached: bool=True):
return filter(lambda x: len(x[0]) >= min_tokens, map(lambda x: load_file(x, split=split) if not cached else cached_load_file(x, split=split), path.glob('*.txt'))) | ['def', 'generate_files(path:', 'Path,', 'split:', 'bool=True,', 'min_tokens:', 'int=50,', 'cached:', 'bool=True):', 'return', 'filter(lambda', 'x:', 'len(x[0])', '>=', 'min_tokens,', 'map(lambda', 'x:', 'load_file(x,', 'split=split)', 'if', 'not', 'cached', 'else', 'cached_load_file(x,', 'split=split),', "path.glob('*... | 975,960 |
worldbank/wb-nlp-tools | document.py | PDFDoc2Txt.parse | parse | Parse a PDF document to text from different source types. | [
"Parse",
"a",
"PDF",
"document",
"to",
"text",
"from",
"different",
"source",
"types."
] | def parse(self, source: Union[bytes, str], source_type: str='buffer') -> str:
if source_type == 'url':
buf = requests.get(source)
pdf_text = self._parse(parser.from_buffer, buf.content)
elif source_type == 'file':
pdf_text = self._parse(parser.from_file, source)
elif source_type == '... | ['def', 'parse(self,', 'source:', 'Union[bytes,', 'str],', 'source_type:', "str='buffer')", '->', 'str:', 'if', 'source_type', '==', "'url':", 'buf', '=', 'requests.get(source)', 'pdf_text', '=', 'self._parse(parser.from_buffer,', 'buf.content)', 'elif', 'source_type', '==', "'file':", 'pdf_text', '=', 'self._parse(par... | 975,961 |
worldbank/wb-nlp-tools | metadata.py | migrate_nlp_schema | migrate_nlp_schema | This method updates the data under the previous schema into the pydantic MetadataModel schema. | [
"This",
"method",
"updates",
"the",
"data",
"under",
"the",
"previous",
"schema",
"into",
"the",
"pydantic",
"MetadataModel",
"schema."
] | def migrate_nlp_schema(body):
body = dict(body)
try:
int(body['_id'], 16)
hex_id = body['_id'][:15]
except ValueError:
hex_id = md5(body['_id'].encode('utf-8')).hexdigest()[:15]
body['id'] = pop_get(body, '_id')
body['_id'] = body['id']
body['hex_id'] = hex_id
body['i... | ['def', 'migrate_nlp_schema(body):', 'body', '=', 'dict(body)', 'try:', "int(body['_id'],", '16)', 'hex_id', '=', "body['_id'][:15]", 'except', 'ValueError:', 'hex_id', '=', "md5(body['_id'].encode('utf-8')).hexdigest()[:15]", "body['id']", '=', 'pop_get(body,', "'_id')", "body['_id']", '=', "body['id']", "body['hex_id... | 975,965 |
worldbank/wb-nlp-tools | scripts.py | load_config | load_config | Function to load a yaml config file and returns a dictionary version of the config. | [
"Function",
"to",
"load",
"a",
"yaml",
"config",
"file",
"and",
"returns",
"a",
"dictionary",
"version",
"of",
"the",
"config."
] | def load_config(config_path: Path, config_root: str, logger=None) -> dict:
if logger is not None:
logger.info(f'Load config file {config_path}...')
with open(config_path) as cfg_file:
config = yaml.safe_load(cfg_file)
config = config[config_root]
if logger is not None:
logger... | ['def', 'load_config(config_path:', 'Path,', 'config_root:', 'str,', 'logger=None)', '->', 'dict:', 'if', 'logger', 'is', 'not', 'None:', "logger.info(f'Load", 'config', 'file', "{config_path}...')", 'with', 'open(config_path)', 'as', 'cfg_file:', 'config', '=', 'yaml.safe_load(cfg_file)', 'config', '=', 'config[config... | 975,969 |
worldbank/wb-nlp-tools | scripts.py | create_get_directory | create_get_directory | A helper function that automatically creates a directory if it doesn't exist. | [
"A",
"helper",
"function",
"that",
"automatically",
"creates",
"a",
"directory",
"if",
"it",
"doesn't",
"exist."
] | def create_get_directory(parent: Path, child: str) -> Path:
path = parent / child
if not path.exists():
path.mkdir(parents=True)
return path | ['def', 'create_get_directory(parent:', 'Path,', 'child:', 'str)', '->', 'Path:', 'path', '=', 'parent', '/', 'child', 'if', 'not', 'path.exists():', 'path.mkdir(parents=True)', 'return', 'path'] | 975,971 |
worldbank/wb-nlp-tools | scripts.py | checkpoint_log | checkpoint_log | Given a contexttimer instance, this logs a message with elapsed time since the timer was created. | [
"Given",
"a",
"contexttimer",
"instance,",
"this",
"logs",
"a",
"message",
"with",
"elapsed",
"time",
"since",
"the",
"timer",
"was",
"created."
] | def checkpoint_log(logger, timer=None, message=''):
elapsed_time = timer.elapsed / 60 if timer else None
if logger:
logger.info('Time elapsed now in minutes: %s %s', elapsed_time, message)
else:
print(f'Time elapsed now in minutes: {elapsed_time} {message}') | ['def', 'checkpoint_log(logger,', 'timer=None,', "message=''):", 'elapsed_time', '=', 'timer.elapsed', '/', '60', 'if', 'timer', 'else', 'None', 'if', 'logger:', "logger.info('Time", 'elapsed', 'now', 'in', 'minutes:', '%s', "%s',", 'elapsed_time,', 'message)', 'else:', "print(f'Time", 'elapsed', 'now', 'in', 'minutes:... | 975,973 |
devashish-patel/webcam-motion-detector | pathlib2.py | Path.mkdir | mkdir | Create a new directory at this given path. | [
"Create",
"a",
"new",
"directory",
"at",
"this",
"given",
"path."
] | def mkdir(self, mode=511, parents=False, exist_ok=False):
if self._closed:
self._raise_closed()
def _try_func():
self._accessor.mkdir(self, mode)
def _exc_func(exc):
if not parents or self.parent == self:
raise exc
self.parent.mkdir(parents=True, exist_ok=True)
... | ['def', 'mkdir(self,', 'mode=511,', 'parents=False,', 'exist_ok=False):', 'if', 'self._closed:', 'self._raise_closed()', 'def', '_try_func():', 'self._accessor.mkdir(self,', 'mode)', 'def', '_exc_func(exc):', 'if', 'not', 'parents', 'or', 'self.parent', '==', 'self:', 'raise', 'exc', 'self.parent.mkdir(parents=True,', ... | 976,712 |
devashish-patel/webcam-motion-detector | pefile.py | UnicodeStringWrapperPostProcessor.get_rva | get_rva | Get the RVA of the string. | [
"Get",
"the",
"RVA",
"of",
"the",
"string."
] | def get_rva(self):
return self.rva_ptr | ['def', 'get_rva(self):', 'return', 'self.rva_ptr'] | 976,732 |
devashish-patel/webcam-motion-detector | pefile.py | UnicodeStringWrapperPostProcessor.invalidate | invalidate | Make this instance None, to express it's no known string type. | [
"Make",
"this",
"instance",
"None,",
"to",
"express",
"it's",
"no",
"known",
"string",
"type."
] | def invalidate(self):
self = None | ['def', 'invalidate(self):', 'self', '=', 'None'] | 976,733 |
devashish-patel/webcam-motion-detector | pefile.py | Dump.add_header | add_header | Adds a header element. | [
"Adds",
"a",
"header",
"element."
] | def add_header(self, txt):
self.add_line('{0}{1}{0}\n'.format('-' * 10, txt)) | ['def', 'add_header(self,', 'txt):', "self.add_line('{0}{1}{0}\\n'.format('-'", '*', '10,', 'txt))'] | 976,738 |
devashish-patel/webcam-motion-detector | pefile.py | Dump.get_text | get_text | Get the text in its current state. | [
"Get",
"the",
"text",
"in",
"its",
"current",
"state."
] | def get_text(self):
return u''.join((u'{0}'.format(b) for b in self.text)) | ['def', 'get_text(self):', 'return', "u''.join((u'{0}'.format(b)", 'for', 'b', 'in', 'self.text))'] | 976,739 |
devashish-patel/webcam-motion-detector | pefile.py | Structure.get_field_absolute_offset | get_field_absolute_offset | Return the offset within the field for the requested field in the structure. | [
"Return",
"the",
"offset",
"within",
"the",
"field",
"for",
"the",
"requested",
"field",
"in",
"the",
"structure."
] | def get_field_absolute_offset(self, field_name):
return self.__file_offset__ + self.__field_offsets__[field_name] | ['def', 'get_field_absolute_offset(self,', 'field_name):', 'return', 'self.__file_offset__', '+', 'self.__field_offsets__[field_name]'] | 976,740 |
devashish-patel/webcam-motion-detector | pefile.py | Structure.get_field_relative_offset | get_field_relative_offset | Return the offset within the structure for the requested field. | [
"Return",
"the",
"offset",
"within",
"the",
"structure",
"for",
"the",
"requested",
"field."
] | def get_field_relative_offset(self, field_name):
return self.__field_offsets__[field_name] | ['def', 'get_field_relative_offset(self,', 'field_name):', 'return', 'self.__field_offsets__[field_name]'] | 976,741 |
devashish-patel/webcam-motion-detector | pefile.py | Structure.sizeof | sizeof | Return size of the structure. | [
"Return",
"size",
"of",
"the",
"structure."
] | def sizeof(self):
return self.__format_length__ | ['def', 'sizeof(self):', 'return', 'self.__format_length__'] | 976,743 |
devashish-patel/webcam-motion-detector | pefile.py | Structure.dump | dump | Returns a string representation of the structure. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"structure."
] | def dump(self, indentation=0):
dump = []
dump.append('[{0}]'.format(self.name))
printable_bytes = [ord(i) for i in string.printable if i not in string.whitespace]
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, (int, long)):
... | ['def', 'dump(self,', 'indentation=0):', 'dump', '=', '[]', "dump.append('[{0}]'.format(self.name))", 'printable_bytes', '=', '[ord(i)', 'for', 'i', 'in', 'string.printable', 'if', 'i', 'not', 'in', 'string.whitespace]', 'for', 'keys', 'in', 'self.__keys__:', 'for', 'key', 'in', 'keys:', 'val', '=', 'getattr(self,', 'k... | 976,744 |
devashish-patel/webcam-motion-detector | pefile.py | Structure.dump_dict | dump_dict | Returns a dictionary representation of the structure. | [
"Returns",
"a",
"dictionary",
"representation",
"of",
"the",
"structure."
] | def dump_dict(self):
dump_dict = dict()
dump_dict['Structure'] = self.name
for keys in self.__keys__:
for key in keys:
val = getattr(self, key)
if isinstance(val, (int, long)):
if key == 'TimeDateStamp' or key == 'dwTimeStamp':
try:
... | ['def', 'dump_dict(self):', 'dump_dict', '=', 'dict()', "dump_dict['Structure']", '=', 'self.name', 'for', 'keys', 'in', 'self.__keys__:', 'for', 'key', 'in', 'keys:', 'val', '=', 'getattr(self,', 'key)', 'if', 'isinstance(val,', '(int,', 'long)):', 'if', 'key', '==', "'TimeDateStamp'", 'or', 'key', '==', "'dwTimeStamp... | 976,745 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.contains_offset | contains_offset | Check whether the section contains the file offset provided. | [
"Check",
"whether",
"the",
"section",
"contains",
"the",
"file",
"offset",
"provided."
] | def contains_offset(self, offset):
if self.PointerToRawData is None:
return False
return self.pe.adjust_FileAlignment(self.PointerToRawData, self.pe.OPTIONAL_HEADER.FileAlignment) <= offset < self.pe.adjust_FileAlignment(self.PointerToRawData, self.pe.OPTIONAL_HEADER.FileAlignment) + self.SizeOfRawData | ['def', 'contains_offset(self,', 'offset):', 'if', 'self.PointerToRawData', 'is', 'None:', 'return', 'False', 'return', 'self.pe.adjust_FileAlignment(self.PointerToRawData,', 'self.pe.OPTIONAL_HEADER.FileAlignment)', '<=', 'offset', '<', 'self.pe.adjust_FileAlignment(self.PointerToRawData,', 'self.pe.OPTIONAL_HEADER.Fi... | 976,747 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.contains_rva | contains_rva | Check whether the section contains the address provided. | [
"Check",
"whether",
"the",
"section",
"contains",
"the",
"address",
"provided."
] | def contains_rva(self, rva):
if len(self.pe.__data__) - self.pe.adjust_FileAlignment(self.PointerToRawData, self.pe.OPTIONAL_HEADER.FileAlignment) < self.SizeOfRawData:
size = self.Misc_VirtualSize
else:
size = max(self.SizeOfRawData, self.Misc_VirtualSize)
VirtualAddress_adj = self.pe.adjus... | ['def', 'contains_rva(self,', 'rva):', 'if', 'len(self.pe.__data__)', '-', 'self.pe.adjust_FileAlignment(self.PointerToRawData,', 'self.pe.OPTIONAL_HEADER.FileAlignment)', '<', 'self.SizeOfRawData:', 'size', '=', 'self.Misc_VirtualSize', 'else:', 'size', '=', 'max(self.SizeOfRawData,', 'self.Misc_VirtualSize)', 'Virtua... | 976,748 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.get_entropy | get_entropy | Calculate and return the entropy for the section. | [
"Calculate",
"and",
"return",
"the",
"entropy",
"for",
"the",
"section."
] | def get_entropy(self):
return self.entropy_H(self.get_data()) | ['def', 'get_entropy(self):', 'return', 'self.entropy_H(self.get_data())'] | 976,749 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.get_hash_sha256 | get_hash_sha256 | Get the SHA-256 hex-digest of the section's data. | [
"Get",
"the",
"SHA-256",
"hex-digest",
"of",
"the",
"section's",
"data."
] | def get_hash_sha256(self):
if sha256 is not None:
return sha256(self.get_data()).hexdigest() | ['def', 'get_hash_sha256(self):', 'if', 'sha256', 'is', 'not', 'None:', 'return', 'sha256(self.get_data()).hexdigest()'] | 976,751 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.get_hash_sha512 | get_hash_sha512 | Get the SHA-512 hex-digest of the section's data. | [
"Get",
"the",
"SHA-512",
"hex-digest",
"of",
"the",
"section's",
"data."
] | def get_hash_sha512(self):
if sha512 is not None:
return sha512(self.get_data()).hexdigest() | ['def', 'get_hash_sha512(self):', 'if', 'sha512', 'is', 'not', 'None:', 'return', 'sha512(self.get_data()).hexdigest()'] | 976,752 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.get_hash_md5 | get_hash_md5 | Get the MD5 hex-digest of the section's data. | [
"Get",
"the",
"MD5",
"hex-digest",
"of",
"the",
"section's",
"data."
] | def get_hash_md5(self):
if md5 is not None:
return md5(self.get_data()).hexdigest() | ['def', 'get_hash_md5(self):', 'if', 'md5', 'is', 'not', 'None:', 'return', 'md5(self.get_data()).hexdigest()'] | 976,753 |
devashish-patel/webcam-motion-detector | pefile.py | SectionStructure.entropy_H | entropy_H | Calculate the entropy of a chunk of data. | [
"Calculate",
"the",
"entropy",
"of",
"a",
"chunk",
"of",
"data."
] | def entropy_H(self, data):
if len(data) == 0:
return 0.0
occurences = Counter(bytearray(data))
entropy = 0
for x in occurences.values():
p_x = float(x) / len(data)
entropy -= p_x * math.log(p_x, 2)
return entropy | ['def', 'entropy_H(self,', 'data):', 'if', 'len(data)', '==', '0:', 'return', '0.0', 'occurences', '=', 'Counter(bytearray(data))', 'entropy', '=', '0', 'for', 'x', 'in', 'occurences.values():', 'p_x', '=', 'float(x)', '/', 'len(data)', 'entropy', '-=', 'p_x', '*', 'math.log(p_x,', '2)', 'return', 'entropy'] | 976,754 |
devashish-patel/webcam-motion-detector | pefile.py | PE.parse_resource_data_entry | parse_resource_data_entry | Parse a data entry from the resources directory. | [
"Parse",
"a",
"data",
"entry",
"from",
"the",
"resources",
"directory."
] | def parse_resource_data_entry(self, rva):
try:
data = self.get_data(rva, Structure(self.__IMAGE_RESOURCE_DATA_ENTRY_format__).sizeof())
except PEFormatError as excp:
self.__warnings.append('Error parsing a resource directory data entry, the RVA is invalid: 0x%x' % rva)
return None
da... | ['def', 'parse_resource_data_entry(self,', 'rva):', 'try:', 'data', '=', 'self.get_data(rva,', 'Structure(self.__IMAGE_RESOURCE_DATA_ENTRY_format__).sizeof())', 'except', 'PEFormatError', 'as', 'excp:', "self.__warnings.append('Error", 'parsing', 'a', 'resource', 'directory', 'data', 'entry,', 'the', 'RVA', 'is', 'inva... | 976,762 |
devashish-patel/webcam-motion-detector | pefile.py | PE.parse_resource_entry | parse_resource_entry | Parse a directory entry from the resources directory. | [
"Parse",
"a",
"directory",
"entry",
"from",
"the",
"resources",
"directory."
] | def parse_resource_entry(self, rva):
try:
data = self.get_data(rva, Structure(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__).sizeof())
except PEFormatError as excp:
return None
resource = self.__unpack_data__(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__, data, file_offset=self.get_offset_... | ['def', 'parse_resource_entry(self,', 'rva):', 'try:', 'data', '=', 'self.get_data(rva,', 'Structure(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__).sizeof())', 'except', 'PEFormatError', 'as', 'excp:', 'return', 'None', 'resource', '=', 'self.__unpack_data__(self.__IMAGE_RESOURCE_DIRECTORY_ENTRY_format__,', 'data,', '... | 976,763 |
devashish-patel/webcam-motion-detector | pefile.py | PE.parse_delay_import_directory | parse_delay_import_directory | Walk and parse the delay import directory. | [
"Walk",
"and",
"parse",
"the",
"delay",
"import",
"directory."
] | def parse_delay_import_directory(self, rva, size):
import_descs = []
error_count = 0
while True:
try:
data = self.get_data(rva, Structure(self.__IMAGE_DELAY_IMPORT_DESCRIPTOR_format__).sizeof())
except PEFormatError as e:
self.__warnings.append('Error parsing the Dela... | ['def', 'parse_delay_import_directory(self,', 'rva,', 'size):', 'import_descs', '=', '[]', 'error_count', '=', '0', 'while', 'True:', 'try:', 'data', '=', 'self.get_data(rva,', 'Structure(self.__IMAGE_DELAY_IMPORT_DESCRIPTOR_format__).sizeof())', 'except', 'PEFormatError', 'as', 'e:', "self.__warnings.append('Error", '... | 976,765 |
devashish-patel/webcam-motion-detector | pefile.py | PE.parse_import_directory | parse_import_directory | Walk and parse the import directory. | [
"Walk",
"and",
"parse",
"the",
"import",
"directory."
] | def parse_import_directory(self, rva, size, dllnames_only=False):
import_descs = []
error_count = 0
while True:
try:
data = self.get_data(rva, Structure(self.__IMAGE_IMPORT_DESCRIPTOR_format__).sizeof())
except PEFormatError as e:
self.__warnings.append('Error parsing... | ['def', 'parse_import_directory(self,', 'rva,', 'size,', 'dllnames_only=False):', 'import_descs', '=', '[]', 'error_count', '=', '0', 'while', 'True:', 'try:', 'data', '=', 'self.get_data(rva,', 'Structure(self.__IMAGE_IMPORT_DESCRIPTOR_format__).sizeof())', 'except', 'PEFormatError', 'as', 'e:', "self.__warnings.appen... | 976,766 |
devashish-patel/webcam-motion-detector | pefile.py | PE.get_string_at_rva | get_string_at_rva | Get an ASCII string located at the given address. | [
"Get",
"an",
"ASCII",
"string",
"located",
"at",
"the",
"given",
"address."
] | def get_string_at_rva(self, rva, max_length=MAX_STRING_LENGTH):
if rva is None:
return None
s = self.get_section_by_rva(rva)
if not s:
return self.get_string_from_data(0, self.__data__[rva:rva + max_length])
return self.get_string_from_data(0, s.get_data(rva, length=max_length)) | ['def', 'get_string_at_rva(self,', 'rva,', 'max_length=MAX_STRING_LENGTH):', 'if', 'rva', 'is', 'None:', 'return', 'None', 's', '=', 'self.get_section_by_rva(rva)', 'if', 'not', 's:', 'return', 'self.get_string_from_data(0,', 'self.__data__[rva:rva', '+', 'max_length])', 'return', 'self.get_string_from_data(0,', 's.get... | 976,773 |
devashish-patel/webcam-motion-detector | pefile.py | PE.get_string_from_data | get_string_from_data | Get an ASCII string from data. | [
"Get",
"an",
"ASCII",
"string",
"from",
"data."
] | def get_string_from_data(self, offset, data):
s = self.get_bytes_from_data(offset, data)
end = s.find(b'\x00')
if end >= 0:
s = s[:end]
return s | ['def', 'get_string_from_data(self,', 'offset,', 'data):', 's', '=', 'self.get_bytes_from_data(offset,', 'data)', 'end', '=', "s.find(b'\\x00')", 'if', 'end', '>=', '0:', 's', '=', 's[:end]', 'return', 's'] | 976,774 |
devashish-patel/webcam-motion-detector | pefile.py | PE.get_section_by_offset | get_section_by_offset | Get the section containing the given file offset. | [
"Get",
"the",
"section",
"containing",
"the",
"given",
"file",
"offset."
] | def get_section_by_offset(self, offset):
sections = [s for s in self.sections if s.contains_offset(offset)]
if sections:
return sections[0]
return None | ['def', 'get_section_by_offset(self,', 'offset):', 'sections', '=', '[s', 'for', 's', 'in', 'self.sections', 'if', 's.contains_offset(offset)]', 'if', 'sections:', 'return', 'sections[0]', 'return', 'None'] | 976,776 |
devashish-patel/webcam-motion-detector | pefile.py | PE.print_info | print_info | Print all the PE header information in a human readable from. | [
"Print",
"all",
"the",
"PE",
"header",
"information",
"in",
"a",
"human",
"readable",
"from."
] | def print_info(self, encoding='utf-8'):
print(self.dump_info(encoding=encoding)) | ['def', 'print_info(self,', "encoding='utf-8'):", 'print(self.dump_info(encoding=encoding))'] | 976,779 |
devashish-patel/webcam-motion-detector | pefile.py | PE.dump_info | dump_info | Dump all the PE header information into human readable string. | [
"Dump",
"all",
"the",
"PE",
"header",
"information",
"into",
"human",
"readable",
"string."
] | def dump_info(self, dump=None, encoding='ascii'):
if dump is None:
dump = Dump()
warnings = self.get_warnings()
if warnings:
dump.add_header('Parsing Warnings')
for warning in warnings:
dump.add_line(warning)
dump.add_newline()
dump.add_header('DOS_HEADER'... | ['def', 'dump_info(self,', 'dump=None,', "encoding='ascii'):", 'if', 'dump', 'is', 'None:', 'dump', '=', 'Dump()', 'warnings', '=', 'self.get_warnings()', 'if', 'warnings:', "dump.add_header('Parsing", "Warnings')", 'for', 'warning', 'in', 'warnings:', 'dump.add_line(warning)', 'dump.add_newline()', "dump.add_header('D... | 976,780 |
devashish-patel/webcam-motion-detector | pefile.py | PE.dump_dict | dump_dict | Dump all the PE header information into a dictionary. | [
"Dump",
"all",
"the",
"PE",
"header",
"information",
"into",
"a",
"dictionary."
] | def dump_dict(self, dump=None):
dump_dict = dict()
warnings = self.get_warnings()
if warnings:
dump_dict['Parsing Warnings'] = warnings
dump_dict['DOS_HEADER'] = self.DOS_HEADER.dump_dict()
dump_dict['NT_HEADERS'] = self.NT_HEADERS.dump_dict()
dump_dict['FILE_HEADER'] = self.FILE_HEADER.... | ['def', 'dump_dict(self,', 'dump=None):', 'dump_dict', '=', 'dict()', 'warnings', '=', 'self.get_warnings()', 'if', 'warnings:', "dump_dict['Parsing", "Warnings']", '=', 'warnings', "dump_dict['DOS_HEADER']", '=', 'self.DOS_HEADER.dump_dict()', "dump_dict['NT_HEADERS']", '=', 'self.NT_HEADERS.dump_dict()', "dump_dict['... | 976,781 |
devashish-patel/webcam-motion-detector | pefile.py | PE.set_dword_at_offset | set_dword_at_offset | Set the double word value at the given file offset. | [
"Set",
"the",
"double",
"word",
"value",
"at",
"the",
"given",
"file",
"offset."
] | def set_dword_at_offset(self, offset, dword):
return self.set_bytes_at_offset(offset, self.get_data_from_dword(dword)) | ['def', 'set_dword_at_offset(self,', 'offset,', 'dword):', 'return', 'self.set_bytes_at_offset(offset,', 'self.get_data_from_dword(dword))'] | 976,788 |
devashish-patel/webcam-motion-detector | pefile.py | PE.set_word_at_rva | set_word_at_rva | Set the word value at the file offset corresponding to the given RVA. | [
"Set",
"the",
"word",
"value",
"at",
"the",
"file",
"offset",
"corresponding",
"to",
"the",
"given",
"RVA."
] | def set_word_at_rva(self, rva, word):
return self.set_bytes_at_rva(rva, self.get_data_from_word(word)) | ['def', 'set_word_at_rva(self,', 'rva,', 'word):', 'return', 'self.set_bytes_at_rva(rva,', 'self.get_data_from_word(word))'] | 976,793 |
devashish-patel/webcam-motion-detector | pefile.py | PE.set_qword_at_rva | set_qword_at_rva | Set the quad-word value at the file offset corresponding to the given RVA. | [
"Set",
"the",
"quad-word",
"value",
"at",
"the",
"file",
"offset",
"corresponding",
"to",
"the",
"given",
"RVA."
] | def set_qword_at_rva(self, rva, qword):
return self.set_bytes_at_rva(rva, self.get_data_from_qword(qword)) | ['def', 'set_qword_at_rva(self,', 'rva,', 'qword):', 'return', 'self.set_bytes_at_rva(rva,', 'self.get_data_from_qword(qword))'] | 976,799 |
devashish-patel/webcam-motion-detector | pefile.py | PE.set_qword_at_offset | set_qword_at_offset | Set the quad-word value at the given file offset. | [
"Set",
"the",
"quad-word",
"value",
"at",
"the",
"given",
"file",
"offset."
] | def set_qword_at_offset(self, offset, qword):
return self.set_bytes_at_offset(offset, self.get_data_from_qword(qword)) | ['def', 'set_qword_at_offset(self,', 'offset,', 'qword):', 'return', 'self.set_bytes_at_offset(offset,', 'self.get_data_from_qword(qword))'] | 976,800 |
devashish-patel/webcam-motion-detector | pefile.py | PE.merge_modified_section_data | merge_modified_section_data | Update the PE image content with any individual section data that has been modified. | [
"Update",
"the",
"PE",
"image",
"content",
"with",
"any",
"individual",
"section",
"data",
"that",
"has",
"been",
"modified."
] | def merge_modified_section_data(self):
for section in self.sections:
section_data_start = self.adjust_FileAlignment(section.PointerToRawData, self.OPTIONAL_HEADER.FileAlignment)
section_data_end = section_data_start + section.SizeOfRawData
if section_data_start < len(self.__data__) and secti... | ['def', 'merge_modified_section_data(self):', 'for', 'section', 'in', 'self.sections:', 'section_data_start', '=', 'self.adjust_FileAlignment(section.PointerToRawData,', 'self.OPTIONAL_HEADER.FileAlignment)', 'section_data_end', '=', 'section_data_start', '+', 'section.SizeOfRawData', 'if', 'section_data_start', '<', '... | 976,803 |
devashish-patel/webcam-motion-detector | pefile.py | PE.trim | trim | Return the just data defined by the PE headers, removing any overlayed data. | [
"Return",
"the",
"just",
"data",
"defined",
"by",
"the",
"PE",
"headers,",
"removing",
"any",
"overlayed",
"data."
] | def trim(self):
overlay_data_offset = self.get_overlay_data_start_offset()
if overlay_data_offset is not None:
return self.__data__[:overlay_data_offset]
return self.__data__[:] | ['def', 'trim(self):', 'overlay_data_offset', '=', 'self.get_overlay_data_start_offset()', 'if', 'overlay_data_offset', 'is', 'not', 'None:', 'return', 'self.__data__[:overlay_data_offset]', 'return', 'self.__data__[:]'] | 976,810 |
devashish-patel/webcam-motion-detector | peutils.py | SignatureDatabase.match_all | match_all | Matches and returns all the likely matches. | [
"Matches",
"and",
"returns",
"all",
"the",
"likely",
"matches."
] | def match_all(self, pe, ep_only=True, section_start_only=False):
matches = self.__match(pe, ep_only, section_start_only)
if matches:
if ep_only == False:
return matches
return matches[1]
return None | ['def', 'match_all(self,', 'pe,', 'ep_only=True,', 'section_start_only=False):', 'matches', '=', 'self.__match(pe,', 'ep_only,', 'section_start_only)', 'if', 'matches:', 'if', 'ep_only', '==', 'False:', 'return', 'matches', 'return', 'matches[1]', 'return', 'None'] | 976,816 |
devashish-patel/webcam-motion-detector | scandir.py | filetime_to_time | filetime_to_time | Convert Win32 FILETIME to time since Unix epoch in seconds. | [
"Convert",
"Win32",
"FILETIME",
"to",
"time",
"since",
"Unix",
"epoch",
"in",
"seconds."
] | def filetime_to_time(filetime):
total = filetime.dwHighDateTime << 32 | filetime.dwLowDateTime
return total / 10000000 - SECONDS_BETWEEN_EPOCHS | ['def', 'filetime_to_time(filetime):', 'total', '=', 'filetime.dwHighDateTime', '<<', '32', '|', 'filetime.dwLowDateTime', 'return', 'total', '/', '10000000', '-', 'SECONDS_BETWEEN_EPOCHS'] | 976,883 |
devashish-patel/webcam-motion-detector | scandir.py | find_data_to_stat | find_data_to_stat | Convert Win32 FIND_DATA struct to stat_result. | [
"Convert",
"Win32",
"FIND_DATA",
"struct",
"to",
"stat_result."
] | def find_data_to_stat(data):
attributes = data.dwFileAttributes
st_mode = 0
if attributes & FILE_ATTRIBUTE_DIRECTORY:
st_mode |= S_IFDIR | 73
else:
st_mode |= S_IFREG
if attributes & FILE_ATTRIBUTE_READONLY:
st_mode |= 292
else:
st_mode |= 438
if attributes & ... | ['def', 'find_data_to_stat(data):', 'attributes', '=', 'data.dwFileAttributes', 'st_mode', '=', '0', 'if', 'attributes', '&', 'FILE_ATTRIBUTE_DIRECTORY:', 'st_mode', '|=', 'S_IFDIR', '|', '73', 'else:', 'st_mode', '|=', 'S_IFREG', 'if', 'attributes', '&', 'FILE_ATTRIBUTE_READONLY:', 'st_mode', '|=', '292', 'else:', 'st... | 976,884 |
devashish-patel/webcam-motion-detector | Dot.py | Dot.node_style | node_style | Modifies a node style to the dot representation. | [
"Modifies",
"a",
"node",
"style",
"to",
"the",
"dot",
"representation."
] | def node_style(self, node, **kwargs):
if node not in self.edges:
self.edges[node] = {}
self.nodes[node] = kwargs | ['def', 'node_style(self,', 'node,', '**kwargs):', 'if', 'node', 'not', 'in', 'self.edges:', 'self.edges[node]', '=', '{}', 'self.nodes[node]', '=', 'kwargs'] | 976,907 |
devashish-patel/webcam-motion-detector | Dot.py | Dot.edge_style | edge_style | Modifies an edge style to the dot representation. | [
"Modifies",
"an",
"edge",
"style",
"to",
"the",
"dot",
"representation."
] | def edge_style(self, head, tail, **kwargs):
if tail not in self.nodes:
raise GraphError('invalid node %s' % (tail,))
try:
if tail not in self.edges[head]:
self.edges[head][tail] = {}
self.edges[head][tail] = kwargs
except KeyError:
raise GraphError('invalid edge ... | ['def', 'edge_style(self,', 'head,', 'tail,', '**kwargs):', 'if', 'tail', 'not', 'in', 'self.nodes:', 'raise', "GraphError('invalid", 'node', "%s'", '%', '(tail,))', 'try:', 'if', 'tail', 'not', 'in', 'self.edges[head]:', 'self.edges[head][tail]', '=', '{}', 'self.edges[head][tail]', '=', 'kwargs', 'except', 'KeyError:... | 976,909 |
devashish-patel/webcam-motion-detector | Graph.py | Graph.restore_node | restore_node | Restores a previously hidden node back into the graph and restores all of its incoming and outgoing edges. | [
"Restores",
"a",
"previously",
"hidden",
"node",
"back",
"into",
"the",
"graph",
"and",
"restores",
"all",
"of",
"its",
"incoming",
"and",
"outgoing",
"edges."
] | def restore_node(self, node):
try:
(self.nodes[node], all_edges) = self.hidden_nodes[node]
for edge in all_edges:
self.restore_edge(edge)
del self.hidden_nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node) | ['def', 'restore_node(self,', 'node):', 'try:', '(self.nodes[node],', 'all_edges)', '=', 'self.hidden_nodes[node]', 'for', 'edge', 'in', 'all_edges:', 'self.restore_edge(edge)', 'del', 'self.hidden_nodes[node]', 'except', 'KeyError:', 'raise', "GraphError('Invalid", 'node', "%s'", '%', 'node)'] | 976,916 |
devashish-patel/webcam-motion-detector | Graph.py | Graph.restore_edge | restore_edge | Restores a previously hidden edge back into the graph. | [
"Restores",
"a",
"previously",
"hidden",
"edge",
"back",
"into",
"the",
"graph."
] | def restore_edge(self, edge):
try:
(head_id, tail_id, data) = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = (head_id, tail_id, data)
del self.hidden_edges[edge]
except KeyError:
raise GraphError(... | ['def', 'restore_edge(self,', 'edge):', 'try:', '(head_id,', 'tail_id,', 'data)', '=', 'self.hidden_edges[edge]', 'self.nodes[tail_id][0].append(edge)', 'self.nodes[head_id][1].append(edge)', 'self.edges[edge]', '=', '(head_id,', 'tail_id,', 'data)', 'del', 'self.hidden_edges[edge]', 'except', 'KeyError:', 'raise', "Gr... | 976,917 |
devashish-patel/webcam-motion-detector | Graph.py | Graph.node_list | node_list | Return a list of the node ids for all visible nodes in the graph. | [
"Return",
"a",
"list",
"of",
"the",
"node",
"ids",
"for",
"all",
"visible",
"nodes",
"in",
"the",
"graph."
] | def node_list(self):
return list(self.nodes.keys()) | ['def', 'node_list(self):', 'return', 'list(self.nodes.keys())'] | 976,924 |
devashish-patel/webcam-motion-detector | Graph.py | Graph.forw_bfs_subgraph | forw_bfs_subgraph | Creates and returns a subgraph consisting of the breadth first reachable nodes based on their outgoing edges. | [
"Creates",
"and",
"returns",
"a",
"subgraph",
"consisting",
"of",
"the",
"breadth",
"first",
"reachable",
"nodes",
"based",
"on",
"their",
"outgoing",
"edges."
] | def forw_bfs_subgraph(self, start_id):
return self._bfs_subgraph(start_id, forward=True) | ['def', 'forw_bfs_subgraph(self,', 'start_id):', 'return', 'self._bfs_subgraph(start_id,', 'forward=True)'] | 976,948 |
devashish-patel/webcam-motion-detector | Graph.py | Graph.back_bfs_subgraph | back_bfs_subgraph | Creates and returns a subgraph consisting of the breadth first reachable nodes based on the incoming edges. | [
"Creates",
"and",
"returns",
"a",
"subgraph",
"consisting",
"of",
"the",
"breadth",
"first",
"reachable",
"nodes",
"based",
"on",
"the",
"incoming",
"edges."
] | def back_bfs_subgraph(self, start_id):
return self._bfs_subgraph(start_id, forward=False) | ['def', 'back_bfs_subgraph(self,', 'start_id):', 'return', 'self._bfs_subgraph(start_id,', 'forward=False)'] | 976,949 |
devashish-patel/webcam-motion-detector | GraphAlgo.py | _priorityDictionary.setdefault | setdefault | Reimplement setdefault to pass through our customized __setitem__. | [
"Reimplement",
"setdefault",
"to",
"pass",
"through",
"our",
"customized",
"__setitem__."
] | def setdefault(self, key, val):
if key not in self:
self[key] = val
return self[key] | ['def', 'setdefault(self,', 'key,', 'val):', 'if', 'key', 'not', 'in', 'self:', 'self[key]', '=', 'val', 'return', 'self[key]'] | 976,961 |
devashish-patel/webcam-motion-detector | model.py | get_class | get_class | Look up a Bokeh model class, given its view model name. | [
"Look",
"up",
"a",
"Bokeh",
"model",
"class,",
"given",
"its",
"view",
"model",
"name."
] | def get_class(view_model_name):
from . import models
models
from .plotting import Figure
Figure
d = MetaModel.model_class_reverse_map
if view_model_name in d:
return d[view_model_name]
else:
raise KeyError("View model name '%s' not found" % view_model_name) | ['def', 'get_class(view_model_name):', 'from', '.', 'import', 'models', 'models', 'from', '.plotting', 'import', 'Figure', 'Figure', 'd', '=', 'MetaModel.model_class_reverse_map', 'if', 'view_model_name', 'in', 'd:', 'return', 'd[view_model_name]', 'else:', 'raise', 'KeyError("View', 'model', 'name', "'%s'", 'not', 'fo... | 977,051 |
devashish-patel/webcam-motion-detector | model.py | Model.on_change | on_change | Add a callback on this object to trigger when ``attr`` changes. | [
"Add",
"a",
"callback",
"on",
"this",
"object",
"to",
"trigger",
"when",
"``attr``",
"changes."
] | def on_change(self, attr, *callbacks):
if attr not in self.properties():
raise ValueError('attempted to add a callback on nonexistent %s.%s property' % (self.__class__.__name__, attr))
super(Model, self).on_change(attr, *callbacks) | ['def', 'on_change(self,', 'attr,', '*callbacks):', 'if', 'attr', 'not', 'in', 'self.properties():', 'raise', "ValueError('attempted", 'to', 'add', 'a', 'callback', 'on', 'nonexistent', '%s.%s', "property'", '%', '(self.__class__.__name__,', 'attr))', 'super(Model,', 'self).on_change(attr,', '*callbacks)'] | 977,055 |
devashish-patel/webcam-motion-detector | model.py | Model.references | references | Returns all ``Models`` that this object has references to. | [
"Returns",
"all",
"``Models``",
"that",
"this",
"object",
"has",
"references",
"to."
] | def references(self):
return set(collect_models(self)) | ['def', 'references(self):', 'return', 'set(collect_models(self))'] | 977,056 |
devashish-patel/webcam-motion-detector | model.py | Model.select | select | Query this object and all of its references for objects that match the given selector. | [
"Query",
"this",
"object",
"and",
"all",
"of",
"its",
"references",
"for",
"objects",
"that",
"match",
"the",
"given",
"selector."
] | def select(self, selector):
return find(self.references(), selector) | ['def', 'select(self,', 'selector):', 'return', 'find(self.references(),', 'selector)'] | 977,057 |
devashish-patel/webcam-motion-detector | settings.py | Settings.browser | browser | Set the default browser that Bokeh should use to show documents with. | [
"Set",
"the",
"default",
"browser",
"that",
"Bokeh",
"should",
"use",
"to",
"show",
"documents",
"with."
] | def browser(self, default=None):
return self._get_str('BROWSER', default, 'none') | ['def', 'browser(self,', 'default=None):', 'return', "self._get_str('BROWSER',", 'default,', "'none')"] | 977,069 |
devashish-patel/webcam-motion-detector | settings.py | Settings.docs_cdn | docs_cdn | Set the version of BokehJS should use for CDN resources when building the docs. | [
"Set",
"the",
"version",
"of",
"BokehJS",
"should",
"use",
"for",
"CDN",
"resources",
"when",
"building",
"the",
"docs."
] | def docs_cdn(self, default=None):
return self._get_str('DOCS_CDN', default) | ['def', 'docs_cdn(self,', 'default=None):', 'return', "self._get_str('DOCS_CDN',", 'default)'] | 977,073 |
devashish-patel/webcam-motion-detector | settings.py | Settings.docs_version | docs_version | Set the version to use for building the docs. | [
"Set",
"the",
"version",
"to",
"use",
"for",
"building",
"the",
"docs."
] | def docs_version(self, default=None):
return self._get_str('DOCS_VERSION', default) | ['def', 'docs_version(self,', 'default=None):', 'return', "self._get_str('DOCS_VERSION',", 'default)'] | 977,074 |
devashish-patel/webcam-motion-detector | settings.py | Settings.minified | minified | Set whether Bokeh should use minified BokehJS resources. | [
"Set",
"whether",
"Bokeh",
"should",
"use",
"minified",
"BokehJS",
"resources."
] | def minified(self, default=None):
return self._get_bool('MINIFIED', default, False) | ['def', 'minified(self,', 'default=None):', 'return', "self._get_bool('MINIFIED',", 'default,', 'False)'] | 977,076 |
devashish-patel/webcam-motion-detector | settings.py | Settings.pretty | pretty | Set whether JSON strings should be pretty-printed. | [
"Set",
"whether",
"JSON",
"strings",
"should",
"be",
"pretty-printed."
] | def pretty(self, default=None):
return self._get_bool('PRETTY', default, True) | ['def', 'pretty(self,', 'default=None):', 'return', "self._get_bool('PRETTY',", 'default,', 'True)'] | 977,079 |
devashish-patel/webcam-motion-detector | settings.py | Settings.secret_key_bytes | secret_key_bytes | Return the secret_key, converted to bytes and cached. | [
"Return",
"the",
"secret_key,",
"converted",
"to",
"bytes",
"and",
"cached."
] | def secret_key_bytes(self):
if not hasattr(self, '_secret_key_bytes'):
key = self.secret_key()
if key is None:
self._secret_key_bytes = None
else:
self._secret_key_bytes = codecs.encode(key, 'utf-8')
return self._secret_key_bytes | ['def', 'secret_key_bytes(self):', 'if', 'not', 'hasattr(self,', "'_secret_key_bytes'):", 'key', '=', 'self.secret_key()', 'if', 'key', 'is', 'None:', 'self._secret_key_bytes', '=', 'None', 'else:', 'self._secret_key_bytes', '=', 'codecs.encode(key,', "'utf-8')", 'return', 'self._secret_key_bytes'] | 977,083 |
devashish-patel/webcam-motion-detector | settings.py | Settings.perform_document_validation | perform_document_validation | Set whether Bokeh should perform validation checks on documents. | [
"Set",
"whether",
"Bokeh",
"should",
"perform",
"validation",
"checks",
"on",
"documents."
] | def perform_document_validation(self, default=True):
return self._get_bool('VALIDATE_DOC', default) | ['def', 'perform_document_validation(self,', 'default=True):', 'return', "self._get_bool('VALIDATE_DOC',", 'default)'] | 977,085 |
devashish-patel/webcam-motion-detector | settings.py | Settings.bokehjssrcdir | bokehjssrcdir | The absolute path of the BokehJS source code in the installed Bokeh source tree. | [
"The",
"absolute",
"path",
"of",
"the",
"BokehJS",
"source",
"code",
"in",
"the",
"installed",
"Bokeh",
"source",
"tree."
] | def bokehjssrcdir(self):
if self._is_dev or self.debugjs:
bokehjssrcdir = abspath(join(ROOT_DIR, '..', 'bokehjs', 'src'))
if isdir(bokehjssrcdir):
return bokehjssrcdir
return None | ['def', 'bokehjssrcdir(self):', 'if', 'self._is_dev', 'or', 'self.debugjs:', 'bokehjssrcdir', '=', 'abspath(join(ROOT_DIR,', "'..',", "'bokehjs',", "'src'))", 'if', 'isdir(bokehjssrcdir):', 'return', 'bokehjssrcdir', 'return', 'None'] | 977,086 |
devashish-patel/webcam-motion-detector | transform.py | dodge | dodge | Create a ``DataSpec`` dict to apply a client-side ``Jitter`` transformation to a ``ColumnDataSource`` column. | [
"Create",
"a",
"``DataSpec``",
"dict",
"to",
"apply",
"a",
"client-side",
"``Jitter``",
"transformation",
"to",
"a",
"``ColumnDataSource``",
"column."
] | def dodge(field_name, value, range=None):
return field(field_name, Dodge(value=value, range=range)) | ['def', 'dodge(field_name,', 'value,', 'range=None):', 'return', 'field(field_name,', 'Dodge(value=value,', 'range=range))'] | 977,089 |
devashish-patel/webcam-motion-detector | transform.py | factor_cmap | factor_cmap | Create a ``DataSpec`` dict to apply a client-side ``CategoricalColorMapper`` transformation to a ``ColumnDataSource`` column. | [
"Create",
"a",
"``DataSpec``",
"dict",
"to",
"apply",
"a",
"client-side",
"``CategoricalColorMapper``",
"transformation",
"to",
"a",
"``ColumnDataSource``",
"column."
] | def factor_cmap(field_name, palette, factors, start=0, end=None, nan_color='gray'):
return field(field_name, CategoricalColorMapper(palette=palette, factors=factors, start=start, end=end, nan_color=nan_color)) | ['def', 'factor_cmap(field_name,', 'palette,', 'factors,', 'start=0,', 'end=None,', "nan_color='gray'):", 'return', 'field(field_name,', 'CategoricalColorMapper(palette=palette,', 'factors=factors,', 'start=start,', 'end=end,', 'nan_color=nan_color))'] | 977,090 |
devashish-patel/webcam-motion-detector | transform.py | log_cmap | log_cmap | Create a ``DataSpec`` dict to apply a client-side ``LogColorMapper`` transformation to a ``ColumnDataSource`` column. | [
"Create",
"a",
"``DataSpec``",
"dict",
"to",
"apply",
"a",
"client-side",
"``LogColorMapper``",
"transformation",
"to",
"a",
"``ColumnDataSource``",
"column."
] | def log_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color='gray'):
return field(field_name, LogColorMapper(palette=palette, low=low, high=high, nan_color=nan_color, low_color=low_color, high_color=high_color)) | ['def', 'log_cmap(field_name,', 'palette,', 'low,', 'high,', 'low_color=None,', 'high_color=None,', "nan_color='gray'):", 'return', 'field(field_name,', 'LogColorMapper(palette=palette,', 'low=low,', 'high=high,', 'nan_color=nan_color,', 'low_color=low_color,', 'high_color=high_color))'] | 977,093 |
devashish-patel/webcam-motion-detector | transform.py | transform | transform | Create a ``DataSpec`` dict to apply an arbitrary client-side ``Transform`` to a ``ColumnDataSource`` column. | [
"Create",
"a",
"``DataSpec``",
"dict",
"to",
"apply",
"an",
"arbitrary",
"client-side",
"``Transform``",
"to",
"a",
"``ColumnDataSource``",
"column."
] | def transform(field_name, transform):
return field(field_name, transform) | ['def', 'transform(field_name,', 'transform):', 'return', 'field(field_name,', 'transform)'] | 977,095 |
devashish-patel/webcam-motion-detector | application.py | Application.handlers | handlers | The ordered list of handlers this Application is configured with. | [
"The",
"ordered",
"list",
"of",
"handlers",
"this",
"Application",
"is",
"configured",
"with."
] | def handlers(self):
return tuple(self._handlers) | ['def', 'handlers(self):', 'return', 'tuple(self._handlers)'] | 977,096 |
devashish-patel/webcam-motion-detector | application.py | Application.static_path | static_path | Path to any (optional) static resources specified by handlers. | [
"Path",
"to",
"any",
"(optional)",
"static",
"resources",
"specified",
"by",
"handlers."
] | def static_path(self):
return self._static_path | ['def', 'static_path(self):', 'return', 'self._static_path'] | 977,098 |
devashish-patel/webcam-motion-detector | application.py | Application.create_document | create_document | Creates and initializes a document using the Application's handlers. | [
"Creates",
"and",
"initializes",
"a",
"document",
"using",
"the",
"Application's",
"handlers."
] | def create_document(self):
doc = Document()
self.initialize_document(doc)
return doc | ['def', 'create_document(self):', 'doc', '=', 'Document()', 'self.initialize_document(doc)', 'return', 'doc'] | 977,100 |
devashish-patel/webcam-motion-detector | application.py | SessionContext.id | id | The unique ID for the session associated with this context. | [
"The",
"unique",
"ID",
"for",
"the",
"session",
"associated",
"with",
"this",
"context."
] | def id(self):
return self._id | ['def', 'id(self):', 'return', 'self._id'] | 977,114 |
devashish-patel/webcam-motion-detector | code.py | CodeHandler.error | error | If the handler fails, may contain a related error message. | [
"If",
"the",
"handler",
"fails,",
"may",
"contain",
"a",
"related",
"error",
"message."
] | def error(self):
return self._runner.error | ['def', 'error(self):', 'return', 'self._runner.error'] | 977,117 |
devashish-patel/webcam-motion-detector | code.py | CodeHandler.url_path | url_path | The last path component for the basename of the configured filename. | [
"The",
"last",
"path",
"component",
"for",
"the",
"basename",
"of",
"the",
"configured",
"filename."
] | def url_path(self):
if self.failed:
return None
else:
return '/' + os.path.splitext(os.path.basename(self._runner.path))[0] | ['def', 'url_path(self):', 'if', 'self.failed:', 'return', 'None', 'else:', 'return', "'/'", '+', 'os.path.splitext(os.path.basename(self._runner.path))[0]'] | 977,121 |
devashish-patel/webcam-motion-detector | code_runner.py | CodeRunner.error_detail | error_detail | If code execution fails, may contain a traceback or other details. | [
"If",
"code",
"execution",
"fails,",
"may",
"contain",
"a",
"traceback",
"or",
"other",
"details."
] | def error_detail(self):
return self._error_detail | ['def', 'error_detail(self):', 'return', 'self._error_detail'] | 977,123 |
devashish-patel/webcam-motion-detector | code_runner.py | CodeRunner.path | path | The path that new modules will be configured with. | [
"The",
"path",
"that",
"new",
"modules",
"will",
"be",
"configured",
"with."
] | def path(self):
return self._path | ['def', 'path(self):', 'return', 'self._path'] | 977,125 |
devashish-patel/webcam-motion-detector | server_lifecycle.py | ServerLifecycleHandler.on_server_loaded | on_server_loaded | Execute `on_server_unloaded`` from the configured module (if it is defined) when the server is first started. | [
"Execute",
"`on_server_unloaded``",
"from",
"the",
"configured",
"module",
"(if",
"it",
"is",
"defined)",
"when",
"the",
"server",
"is",
"first",
"started."
] | def on_server_loaded(self, server_context):
return self._on_server_loaded(server_context) | ['def', 'on_server_loaded(self,', 'server_context):', 'return', 'self._on_server_loaded(server_context)'] | 977,155 |
devashish-patel/webcam-motion-detector | server_lifecycle.py | ServerLifecycleHandler.on_session_created | on_session_created | Execute ``on_session_created`` from the configured module (if it is defined) when a new session is created. | [
"Execute",
"``on_session_created``",
"from",
"the",
"configured",
"module",
"(if",
"it",
"is",
"defined)",
"when",
"a",
"new",
"session",
"is",
"created."
] | def on_session_created(self, session_context):
return self._on_session_created(session_context) | ['def', 'on_session_created(self,', 'session_context):', 'return', 'self._on_session_created(session_context)'] | 977,157 |
devashish-patel/webcam-motion-detector | server_lifecycle.py | ServerLifecycleHandler.on_session_destroyed | on_session_destroyed | Execute ``on_session_destroyed`` from the configured module (if it is defined) when a new session is destroyed. | [
"Execute",
"``on_session_destroyed``",
"from",
"the",
"configured",
"module",
"(if",
"it",
"is",
"defined)",
"when",
"a",
"new",
"session",
"is",
"destroyed."
] | def on_session_destroyed(self, session_context):
return self._on_session_destroyed(session_context) | ['def', 'on_session_destroyed(self,', 'session_context):', 'return', 'self._on_session_destroyed(session_context)'] | 977,158 |
devashish-patel/webcam-motion-detector | connection.py | ClientConnection.connected | connected | Whether we've connected the Websocket and have exchanged initial handshake messages. | [
"Whether",
"we've",
"connected",
"the",
"Websocket",
"and",
"have",
"exchanged",
"initial",
"handshake",
"messages."
] | def connected(self):
return isinstance(self._state, CONNECTED_AFTER_ACK) | ['def', 'connected(self):', 'return', 'isinstance(self._state,', 'CONNECTED_AFTER_ACK)'] | 977,160 |
devashish-patel/webcam-motion-detector | connection.py | ClientConnection.url | url | The URL of the websocket this Connection is to. | [
"The",
"URL",
"of",
"the",
"websocket",
"this",
"Connection",
"is",
"to."
] | def url(self):
return self._url | ['def', 'url(self):', 'return', 'self._url'] | 977,162 |
devashish-patel/webcam-motion-detector | connection.py | ClientConnection.close | close | Close the Websocket connection. | [
"Close",
"the",
"Websocket",
"connection."
] | def close(self, why='closed'):
if self._socket is not None:
self._socket.close(1000, why) | ['def', 'close(self,', "why='closed'):", 'if', 'self._socket', 'is', 'not', 'None:', 'self._socket.close(1000,', 'why)'] | 977,163 |
devashish-patel/webcam-motion-detector | connection.py | ClientConnection.push_doc | push_doc | Push a document to the server, overwriting any existing server-side doc. | [
"Push",
"a",
"document",
"to",
"the",
"server,",
"overwriting",
"any",
"existing",
"server-side",
"doc."
] | def push_doc(self, document):
msg = self._protocol.create('PUSH-DOC', document)
reply = self._send_message_wait_for_reply(msg)
if reply is None:
raise RuntimeError('Connection to server was lost')
elif reply.header['msgtype'] == 'ERROR':
raise RuntimeError('Failed to push document: ' + r... | ['def', 'push_doc(self,', 'document):', 'msg', '=', "self._protocol.create('PUSH-DOC',", 'document)', 'reply', '=', 'self._send_message_wait_for_reply(msg)', 'if', 'reply', 'is', 'None:', 'raise', "RuntimeError('Connection", 'to', 'server', 'was', "lost')", 'elif', "reply.header['msgtype']", '==', "'ERROR':", 'raise', ... | 977,167 |
devashish-patel/webcam-motion-detector | session.py | ClientSession.connected | connected | Whether this session is currently connected. | [
"Whether",
"this",
"session",
"is",
"currently",
"connected."
] | def connected(self):
return self._connection.connected | ['def', 'connected(self):', 'return', 'self._connection.connected'] | 977,170 |
devashish-patel/webcam-motion-detector | session.py | ClientSession.id | id | A unique ID for this session. | [
"A",
"unique",
"ID",
"for",
"this",
"session."
] | def id(self):
return self._id | ['def', 'id(self):', 'return', 'self._id'] | 977,172 |
devashish-patel/webcam-motion-detector | session.py | ClientSession.close | close | Close the connection to the server. | [
"Close",
"the",
"connection",
"to",
"the",
"server."
] | def close(self, why='closed'):
self._connection.close(why) | ['def', 'close(self,', "why='closed'):", 'self._connection.close(why)'] | 977,174 |
devashish-patel/webcam-motion-detector | session.py | ClientSession.show | show | Open a browser displaying this session. | [
"Open",
"a",
"browser",
"displaying",
"this",
"session."
] | def show(self, obj=None, browser=None, new='tab'):
if obj and obj not in self.document.roots:
self.document.add_root(obj)
show_session(session=self, browser=browser, new=new) | ['def', 'show(self,', 'obj=None,', 'browser=None,', "new='tab'):", 'if', 'obj', 'and', 'obj', 'not', 'in', 'self.document.roots:', 'self.document.add_root(obj)', 'show_session(session=self,', 'browser=browser,', 'new=new)'] | 977,180 |
devashish-patel/webcam-motion-detector | states.py | WAITING_FOR_REPLY.reqid | reqid | The request ID of the originating message. | [
"The",
"request",
"ID",
"of",
"the",
"originating",
"message."
] | def reqid(self):
return self._reqid | ['def', 'reqid(self):', 'return', 'self._reqid'] | 977,182 |
devashish-patel/webcam-motion-detector | color.py | Color.clamp | clamp | Clamp numeric values to be non-negative, an optionally, less than a given maximum. | [
"Clamp",
"numeric",
"values",
"to",
"be",
"non-negative,",
"an",
"optionally,",
"less",
"than",
"a",
"given",
"maximum."
] | def clamp(value, maximum=None):
value = max(value, 0)
if maximum is not None:
return min(value, maximum)
else:
return value | ['def', 'clamp(value,', 'maximum=None):', 'value', '=', 'max(value,', '0)', 'if', 'maximum', 'is', 'not', 'None:', 'return', 'min(value,', 'maximum)', 'else:', 'return', 'value'] | 977,187 |
devashish-patel/webcam-motion-detector | color.py | Color.lighten | lighten | Lighten (increase the luminance) of this color. | [
"Lighten",
"(increase",
"the",
"luminance)",
"of",
"this",
"color."
] | def lighten(self, amount):
hsl = self.to_hsl()
hsl.l = self.clamp(hsl.l + amount, 1)
return self.from_hsl(hsl) | ['def', 'lighten(self,', 'amount):', 'hsl', '=', 'self.to_hsl()', 'hsl.l', '=', 'self.clamp(hsl.l', '+', 'amount,', '1)', 'return', 'self.from_hsl(hsl)'] | 977,192 |
devashish-patel/webcam-motion-detector | hsl.py | HSL.from_hsl | from_hsl | Copy an HSL color from another HSL color value. | [
"Copy",
"an",
"HSL",
"color",
"from",
"another",
"HSL",
"color",
"value."
] | def from_hsl(cls, value):
return value.copy() | ['def', 'from_hsl(cls,', 'value):', 'return', 'value.copy()'] | 977,197 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.