query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
set the event to triggered | def set ( self ) : self . _is_set = True scheduler . state . awoken_from_events . update ( self . _waiters ) del self . _waiters [ : ] | 6,800 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L35-L44 | [
"def",
"update_data",
"(",
"self",
")",
":",
"url",
"=",
"(",
"'https://www.openhumans.org/api/direct-sharing/project/'",
"'members/?access_token={}'",
".",
"format",
"(",
"self",
".",
"master_access_token",
")",
")",
"results",
"=",
"get_all_results",
"(",
"url",
")",
"self",
".",
"project_data",
"=",
"dict",
"(",
")",
"for",
"result",
"in",
"results",
":",
"self",
".",
"project_data",
"[",
"result",
"[",
"'project_member_id'",
"]",
"]",
"=",
"result",
"if",
"len",
"(",
"result",
"[",
"'data'",
"]",
")",
"<",
"result",
"[",
"'file_count'",
"]",
":",
"member_data",
"=",
"get_page",
"(",
"result",
"[",
"'exchange_member'",
"]",
")",
"final_data",
"=",
"member_data",
"[",
"'data'",
"]",
"while",
"member_data",
"[",
"'next'",
"]",
":",
"member_data",
"=",
"get_page",
"(",
"member_data",
"[",
"'next'",
"]",
")",
"final_data",
"=",
"final_data",
"+",
"member_data",
"[",
"'data'",
"]",
"self",
".",
"project_data",
"[",
"result",
"[",
"'project_member_id'",
"]",
"]",
"[",
"'data'",
"]",
"=",
"final_data",
"return",
"self",
".",
"project_data"
] |
pause the current coroutine until this event is set | def wait ( self , timeout = None ) : if self . _is_set : return False current = compat . getcurrent ( ) # the waiting greenlet waketime = None if timeout is None else time . time ( ) + timeout if timeout is not None : scheduler . schedule_at ( waketime , current ) self . _waiters . append ( current ) scheduler . state . mainloop . switch ( ) if timeout is not None : if not scheduler . _remove_timer ( waketime , current ) : scheduler . state . awoken_from_events . discard ( current ) if current in self . _waiters : self . _waiters . remove ( current ) return True return False | 6,801 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L54-L89 | [
"def",
"validate_cookies",
"(",
"session",
",",
"class_name",
")",
":",
"if",
"not",
"do_we_have_enough_cookies",
"(",
"session",
".",
"cookies",
",",
"class_name",
")",
":",
"return",
"False",
"url",
"=",
"CLASS_URL",
".",
"format",
"(",
"class_name",
"=",
"class_name",
")",
"+",
"'/class'",
"r",
"=",
"session",
".",
"head",
"(",
"url",
",",
"allow_redirects",
"=",
"False",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"else",
":",
"logging",
".",
"debug",
"(",
"'Stale session.'",
")",
"try",
":",
"session",
".",
"cookies",
".",
"clear",
"(",
"'.coursera.org'",
")",
"except",
"KeyError",
":",
"pass",
"return",
"False"
] |
acquire ownership of the lock | def acquire ( self , blocking = True ) : current = compat . getcurrent ( ) if self . _owner is current : self . _count += 1 return True if self . _locked and not blocking : return False if self . _locked : self . _waiters . append ( compat . getcurrent ( ) ) scheduler . state . mainloop . switch ( ) else : self . _locked = True self . _owner = current self . _count = 1 return True | 6,802 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L186-L221 | [
"def",
"deserialize",
"(",
"obj",
")",
":",
"# Be careful of shallow copy here",
"target",
"=",
"dict",
"(",
"obj",
")",
"class_name",
"=",
"None",
"if",
"'__class__'",
"in",
"target",
":",
"class_name",
"=",
"target",
".",
"pop",
"(",
"'__class__'",
")",
"if",
"'__module__'",
"in",
"obj",
":",
"obj",
".",
"pop",
"(",
"'__module__'",
")",
"# Use getattr(module, class_name) for custom types if needed",
"if",
"class_name",
"==",
"'datetime'",
":",
"return",
"datetime",
".",
"datetime",
"(",
"tzinfo",
"=",
"utc",
",",
"*",
"*",
"target",
")",
"if",
"class_name",
"==",
"'StreamingBody'",
":",
"return",
"StringIO",
"(",
"target",
"[",
"'body'",
"]",
")",
"# Return unrecognized structures as-is",
"return",
"obj"
] |
release one ownership of the lock | def release ( self ) : if not self . _locked or self . _owner is not compat . getcurrent ( ) : raise RuntimeError ( "cannot release un-acquired lock" ) self . _count -= 1 if self . _count == 0 : self . _owner = None if self . _waiters : waiter = self . _waiters . popleft ( ) self . _locked = True self . _owner = waiter scheduler . state . awoken_from_events . add ( waiter ) else : self . _locked = False self . _owner = None | 6,803 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L223-L245 | [
"def",
"export_csv",
"(",
"self",
",",
"table",
",",
"output",
"=",
"None",
",",
"columns",
"=",
"\"*\"",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"pandas",
".",
"io",
".",
"sql",
"as",
"panda",
"# Determine if we're writing to a file or returning a string.",
"isfile",
"=",
"output",
"is",
"not",
"None",
"output",
"=",
"output",
"or",
"StringIO",
"(",
")",
"if",
"table",
"not",
"in",
"self",
".",
"tables",
":",
"raise",
"SchemaError",
"(",
"\"Cannot find table '{table}'\"",
".",
"format",
"(",
"table",
"=",
"table",
")",
")",
"# Don't print row indexes by default.",
"if",
"\"index\"",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"\"index\"",
"]",
"=",
"False",
"table",
"=",
"panda",
".",
"read_sql",
"(",
"\"SELECT {columns} FROM {table}\"",
".",
"format",
"(",
"columns",
"=",
"columns",
",",
"table",
"=",
"table",
")",
",",
"self",
".",
"connection",
")",
"table",
".",
"to_csv",
"(",
"output",
",",
"*",
"*",
"kwargs",
")",
"return",
"None",
"if",
"isfile",
"else",
"output",
".",
"getvalue",
"(",
")"
] |
wait to be woken up by the condition | def wait ( self , timeout = None ) : if not self . _is_owned ( ) : raise RuntimeError ( "cannot wait on un-acquired lock" ) current = compat . getcurrent ( ) waketime = None if timeout is None else time . time ( ) + timeout if timeout is not None : scheduler . schedule_at ( waketime , current ) self . _waiters . append ( ( current , waketime ) ) self . _lock . release ( ) scheduler . state . mainloop . switch ( ) self . _lock . acquire ( ) if timeout is not None : timedout = not scheduler . _remove_timer ( waketime , current ) if timedout : self . _waiters . remove ( ( current , waketime ) ) return timedout return False | 6,804 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L274-L306 | [
"def",
"_ar_data",
"(",
"self",
",",
"ar",
")",
":",
"if",
"not",
"ar",
":",
"return",
"{",
"}",
"if",
"ar",
".",
"portal_type",
"==",
"\"AnalysisRequest\"",
":",
"return",
"{",
"'obj'",
":",
"ar",
",",
"'id'",
":",
"ar",
".",
"getId",
"(",
")",
",",
"'date_received'",
":",
"self",
".",
"ulocalized_time",
"(",
"ar",
".",
"getDateReceived",
"(",
")",
",",
"long_format",
"=",
"0",
")",
",",
"'date_sampled'",
":",
"self",
".",
"ulocalized_time",
"(",
"ar",
".",
"getDateSampled",
"(",
")",
",",
"long_format",
"=",
"True",
")",
",",
"'url'",
":",
"ar",
".",
"absolute_url",
"(",
")",
",",
"}",
"elif",
"ar",
".",
"portal_type",
"==",
"\"ReferenceSample\"",
":",
"return",
"{",
"'obj'",
":",
"ar",
",",
"'id'",
":",
"ar",
".",
"id",
",",
"'date_received'",
":",
"self",
".",
"ulocalized_time",
"(",
"ar",
".",
"getDateReceived",
"(",
")",
",",
"long_format",
"=",
"0",
")",
",",
"'date_sampled'",
":",
"self",
".",
"ulocalized_time",
"(",
"ar",
".",
"getDateSampled",
"(",
")",
",",
"long_format",
"=",
"True",
")",
",",
"'url'",
":",
"ar",
".",
"absolute_url",
"(",
")",
",",
"}",
"else",
":",
"return",
"{",
"'obj'",
":",
"ar",
",",
"'id'",
":",
"ar",
".",
"id",
",",
"'date_received'",
":",
"\"\"",
",",
"'date_sampled'",
":",
"\"\"",
",",
"'url'",
":",
"ar",
".",
"absolute_url",
"(",
")",
",",
"}"
] |
wake one or more waiting greenlets | def notify ( self , num = 1 ) : if not self . _is_owned ( ) : raise RuntimeError ( "cannot wait on un-acquired lock" ) for i in xrange ( min ( num , len ( self . _waiters ) ) ) : scheduler . state . awoken_from_events . add ( self . _waiters . popleft ( ) [ 0 ] ) | 6,805 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L308-L321 | [
"def",
"deserialize",
"(",
"obj",
")",
":",
"# Be careful of shallow copy here",
"target",
"=",
"dict",
"(",
"obj",
")",
"class_name",
"=",
"None",
"if",
"'__class__'",
"in",
"target",
":",
"class_name",
"=",
"target",
".",
"pop",
"(",
"'__class__'",
")",
"if",
"'__module__'",
"in",
"obj",
":",
"obj",
".",
"pop",
"(",
"'__module__'",
")",
"# Use getattr(module, class_name) for custom types if needed",
"if",
"class_name",
"==",
"'datetime'",
":",
"return",
"datetime",
".",
"datetime",
"(",
"tzinfo",
"=",
"utc",
",",
"*",
"*",
"target",
")",
"if",
"class_name",
"==",
"'StreamingBody'",
":",
"return",
"StringIO",
"(",
"target",
"[",
"'body'",
"]",
")",
"# Return unrecognized structures as-is",
"return",
"obj"
] |
wake all waiting greenlets | def notify_all ( self ) : if not self . _is_owned ( ) : raise RuntimeError ( "cannot wait on un-acquired lock" ) scheduler . state . awoken_from_events . update ( x [ 0 ] for x in self . _waiters ) self . _waiters . clear ( ) | 6,806 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L323-L333 | [
"def",
"loadYAML",
"(",
"filename",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"config",
"=",
"None",
"try",
":",
"if",
"filename",
":",
"data",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"config",
"=",
"yaml",
".",
"load",
"(",
"data",
")",
"if",
"type",
"(",
"data",
")",
"is",
"file",
":",
"data",
".",
"close",
"(",
")",
"except",
"IOError",
",",
"e",
":",
"msg",
"=",
"'Could not read AIT configuration file \"%s\": %s'",
"log",
".",
"error",
"(",
"msg",
",",
"filename",
",",
"str",
"(",
"e",
")",
")",
"return",
"config"
] |
decrement the counter waiting if it is already at 0 | def acquire ( self , blocking = True ) : if self . _value : self . _value -= 1 return True if not blocking : return False self . _waiters . append ( compat . getcurrent ( ) ) scheduler . state . mainloop . switch ( ) return True | 6,807 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L351-L376 | [
"def",
"set_options_from_file",
"(",
"self",
",",
"filename",
",",
"file_format",
"=",
"'yaml'",
")",
":",
"if",
"file_format",
".",
"lower",
"(",
")",
"==",
"'yaml'",
":",
"return",
"self",
".",
"set_options_from_YAML",
"(",
"filename",
")",
"elif",
"file_format",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"return",
"self",
".",
"set_options_from_JSON",
"(",
"filename",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown format {}'",
".",
"format",
"(",
"file_format",
")",
")"
] |
increment the counter waking up a waiter if there was any | def release ( self ) : if self . _waiters : scheduler . state . awoken_from_events . add ( self . _waiters . popleft ( ) ) else : self . _value += 1 | 6,808 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L378-L383 | [
"def",
"_ProcessFileEntryDataStream",
"(",
"self",
",",
"mediator",
",",
"file_entry",
",",
"data_stream",
")",
":",
"display_name",
"=",
"mediator",
".",
"GetDisplayName",
"(",
")",
"data_stream_name",
"=",
"getattr",
"(",
"data_stream",
",",
"'name'",
",",
"''",
")",
"or",
"''",
"logger",
".",
"debug",
"(",
"(",
"'[ProcessFileEntryDataStream] processing data stream: \"{0:s}\" of '",
"'file entry: {1:s}'",
")",
".",
"format",
"(",
"data_stream_name",
",",
"display_name",
")",
")",
"mediator",
".",
"ClearEventAttributes",
"(",
")",
"if",
"data_stream",
"and",
"self",
".",
"_analyzers",
":",
"# Since AnalyzeDataStream generates event attributes it needs to be",
"# called before producing events.",
"self",
".",
"_AnalyzeDataStream",
"(",
"mediator",
",",
"file_entry",
",",
"data_stream",
".",
"name",
")",
"self",
".",
"_ExtractMetadataFromFileEntry",
"(",
"mediator",
",",
"file_entry",
",",
"data_stream",
")",
"# Not every file entry has a data stream. In such cases we want to",
"# extract the metadata only.",
"if",
"not",
"data_stream",
":",
"return",
"# Determine if the content of the file entry should not be extracted.",
"skip_content_extraction",
"=",
"self",
".",
"_CanSkipContentExtraction",
"(",
"file_entry",
")",
"if",
"skip_content_extraction",
":",
"display_name",
"=",
"mediator",
".",
"GetDisplayName",
"(",
")",
"logger",
".",
"debug",
"(",
"'Skipping content extraction of: {0:s}'",
".",
"format",
"(",
"display_name",
")",
")",
"self",
".",
"processing_status",
"=",
"definitions",
".",
"STATUS_INDICATOR_IDLE",
"return",
"path_spec",
"=",
"copy",
".",
"deepcopy",
"(",
"file_entry",
".",
"path_spec",
")",
"if",
"data_stream",
"and",
"not",
"data_stream",
".",
"IsDefault",
"(",
")",
":",
"path_spec",
".",
"data_stream",
"=",
"data_stream",
".",
"name",
"archive_types",
"=",
"[",
"]",
"compressed_stream_types",
"=",
"[",
"]",
"if",
"self",
".",
"_process_compressed_streams",
":",
"compressed_stream_types",
"=",
"self",
".",
"_GetCompressedStreamTypes",
"(",
"mediator",
",",
"path_spec",
")",
"if",
"not",
"compressed_stream_types",
":",
"archive_types",
"=",
"self",
".",
"_GetArchiveTypes",
"(",
"mediator",
",",
"path_spec",
")",
"if",
"archive_types",
":",
"if",
"self",
".",
"_process_archives",
":",
"self",
".",
"_ProcessArchiveTypes",
"(",
"mediator",
",",
"path_spec",
",",
"archive_types",
")",
"if",
"dfvfs_definitions",
".",
"TYPE_INDICATOR_ZIP",
"in",
"archive_types",
":",
"# ZIP files are the base of certain file formats like docx.",
"self",
".",
"_ExtractContentFromDataStream",
"(",
"mediator",
",",
"file_entry",
",",
"data_stream",
".",
"name",
")",
"elif",
"compressed_stream_types",
":",
"self",
".",
"_ProcessCompressedStreamTypes",
"(",
"mediator",
",",
"path_spec",
",",
"compressed_stream_types",
")",
"else",
":",
"self",
".",
"_ExtractContentFromDataStream",
"(",
"mediator",
",",
"file_entry",
",",
"data_stream",
".",
"name",
")"
] |
schedule to start the greenlet that runs this thread s function | def start ( self ) : if self . _started : raise RuntimeError ( "thread already started" ) def run ( ) : try : self . run ( * self . _args , * * self . _kwargs ) except SystemExit : # only shut down the thread, not the whole process pass finally : self . _deactivate ( ) self . _glet = scheduler . greenlet ( run ) self . _ident = id ( self . _glet ) scheduler . schedule ( self . _glet ) self . _activate ( ) | 6,809 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L512-L532 | [
"def",
"add_other_location",
"(",
"self",
",",
"location",
",",
"exact",
"=",
"True",
",",
"alterror",
"=",
"None",
",",
"locations",
"=",
"None",
")",
":",
"# type: (str, bool, Optional[str], Optional[List[str]]) -> bool",
"hdx_code",
",",
"match",
"=",
"Locations",
".",
"get_HDX_code_from_location_partial",
"(",
"location",
",",
"locations",
"=",
"locations",
",",
"configuration",
"=",
"self",
".",
"configuration",
")",
"if",
"hdx_code",
"is",
"None",
"or",
"(",
"exact",
"is",
"True",
"and",
"match",
"is",
"False",
")",
":",
"if",
"alterror",
"is",
"None",
":",
"raise",
"HDXError",
"(",
"'Location: %s - cannot find in HDX!'",
"%",
"location",
")",
"else",
":",
"raise",
"HDXError",
"(",
"alterror",
")",
"groups",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'groups'",
",",
"None",
")",
"hdx_code",
"=",
"hdx_code",
".",
"lower",
"(",
")",
"if",
"groups",
":",
"if",
"hdx_code",
"in",
"[",
"x",
"[",
"'name'",
"]",
"for",
"x",
"in",
"groups",
"]",
":",
"return",
"False",
"else",
":",
"groups",
"=",
"list",
"(",
")",
"groups",
".",
"append",
"(",
"{",
"'name'",
":",
"hdx_code",
"}",
")",
"self",
".",
"data",
"[",
"'groups'",
"]",
"=",
"groups",
"return",
"True"
] |
block until this thread terminates | def join ( self , timeout = None ) : if not self . _started : raise RuntimeError ( "cannot join thread before it is started" ) if compat . getcurrent ( ) is self . _glet : raise RuntimeError ( "cannot join current thread" ) self . _finished . wait ( timeout ) | 6,810 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L542-L563 | [
"def",
"cache_jobs",
"(",
"opts",
",",
"jid",
",",
"ret",
")",
":",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"opts",
"=",
"opts",
")",
"fn_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"opts",
"[",
"'cachedir'",
"]",
",",
"'minion_jobs'",
",",
"jid",
",",
"'return.p'",
")",
"jdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"fn_",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"jdir",
")",
":",
"os",
".",
"makedirs",
"(",
"jdir",
")",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"fn_",
",",
"'w+b'",
")",
"as",
"fp_",
":",
"fp_",
".",
"write",
"(",
"serial",
".",
"dumps",
"(",
"ret",
")",
")"
] |
attempt to prevent the timer from ever running its function | def cancel ( self ) : done = self . finished . is_set ( ) self . finished . set ( ) return not done | 6,811 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L655-L664 | [
"def",
"tag_pos_volume",
"(",
"line",
")",
":",
"def",
"tagger",
"(",
"match",
")",
":",
"groups",
"=",
"match",
".",
"groupdict",
"(",
")",
"try",
":",
"year",
"=",
"match",
".",
"group",
"(",
"'year'",
")",
"except",
"IndexError",
":",
"# Extract year from volume name",
"# which should always include the year",
"g",
"=",
"re",
".",
"search",
"(",
"re_pos_year_num",
",",
"match",
".",
"group",
"(",
"'volume_num'",
")",
",",
"re",
".",
"UNICODE",
")",
"year",
"=",
"g",
".",
"group",
"(",
"0",
")",
"if",
"year",
":",
"groups",
"[",
"'year'",
"]",
"=",
"' <cds.YR>(%s)</cds.YR>'",
"%",
"year",
".",
"strip",
"(",
")",
".",
"strip",
"(",
"'()'",
")",
"else",
":",
"groups",
"[",
"'year'",
"]",
"=",
"''",
"return",
"'<cds.JOURNAL>PoS</cds.JOURNAL>'",
"' <cds.VOL>%(volume_name)s%(volume_num)s</cds.VOL>'",
"'%(year)s'",
"' <cds.PG>%(page)s</cds.PG>'",
"%",
"groups",
"for",
"p",
"in",
"re_pos",
":",
"line",
"=",
"p",
".",
"sub",
"(",
"tagger",
",",
"line",
")",
"return",
"line"
] |
a classmethod decorator to immediately turn a function into a timer | def wrap ( cls , secs , args = ( ) , kwargs = None ) : def decorator ( func ) : return cls ( secs , func , args , kwargs ) return decorator | 6,812 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L673-L700 | [
"def",
"batch_star",
"(",
"self",
",",
"path",
")",
":",
"if",
"lib",
".",
"EnvBatchStar",
"(",
"self",
".",
"_env",
",",
"path",
".",
"encode",
"(",
")",
")",
"!=",
"1",
":",
"raise",
"CLIPSError",
"(",
"self",
".",
"_env",
")"
] |
get an item out of the queue | def get ( self , block = True , timeout = None ) : if not self . _data : if not block : raise Empty ( ) current = compat . getcurrent ( ) waketime = None if timeout is None else time . time ( ) + timeout if timeout is not None : scheduler . schedule_at ( waketime , current ) self . _waiters . append ( ( current , waketime ) ) scheduler . state . mainloop . switch ( ) if timeout is not None : if not scheduler . _remove_timer ( waketime , current ) : self . _waiters . remove ( ( current , waketime ) ) raise Empty ( ) if self . full ( ) and self . _waiters : scheduler . schedule ( self . _waiters . popleft ( ) [ 0 ] ) return self . _get ( ) | 6,813 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L743-L789 | [
"def",
"from_string",
"(",
"contents",
")",
":",
"if",
"contents",
"[",
"-",
"1",
"]",
"!=",
"\"\\n\"",
":",
"contents",
"+=",
"\"\\n\"",
"white_space",
"=",
"r\"[ \\t\\r\\f\\v]\"",
"natoms_line",
"=",
"white_space",
"+",
"r\"*\\d+\"",
"+",
"white_space",
"+",
"r\"*\\n\"",
"comment_line",
"=",
"r\"[^\\n]*\\n\"",
"coord_lines",
"=",
"r\"(\\s*\\w+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s*\\n)+\"",
"frame_pattern_text",
"=",
"natoms_line",
"+",
"comment_line",
"+",
"coord_lines",
"pat",
"=",
"re",
".",
"compile",
"(",
"frame_pattern_text",
",",
"re",
".",
"MULTILINE",
")",
"mols",
"=",
"[",
"]",
"for",
"xyz_match",
"in",
"pat",
".",
"finditer",
"(",
"contents",
")",
":",
"xyz_text",
"=",
"xyz_match",
".",
"group",
"(",
"0",
")",
"mols",
".",
"append",
"(",
"XYZ",
".",
"_from_frame_string",
"(",
"xyz_text",
")",
")",
"return",
"XYZ",
"(",
"mols",
")"
] |
put an item into the queue | def put ( self , item , block = True , timeout = None ) : if self . full ( ) : if not block : raise Full ( ) current = compat . getcurrent ( ) waketime = None if timeout is None else time . time ( ) + timeout if timeout is not None : scheduler . schedule_at ( waketime , current ) self . _waiters . append ( ( current , waketime ) ) scheduler . state . mainloop . switch ( ) if timeout is not None : if not scheduler . _remove_timer ( waketime , current ) : self . _waiters . remove ( ( current , waketime ) ) raise Full ( ) if self . _waiters and not self . full ( ) : scheduler . schedule ( self . _waiters . popleft ( ) [ 0 ] ) if not self . _open_tasks : self . _jobs_done . clear ( ) self . _open_tasks += 1 self . _put ( item ) | 6,814 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L803-L852 | [
"def",
"from_string",
"(",
"contents",
")",
":",
"if",
"contents",
"[",
"-",
"1",
"]",
"!=",
"\"\\n\"",
":",
"contents",
"+=",
"\"\\n\"",
"white_space",
"=",
"r\"[ \\t\\r\\f\\v]\"",
"natoms_line",
"=",
"white_space",
"+",
"r\"*\\d+\"",
"+",
"white_space",
"+",
"r\"*\\n\"",
"comment_line",
"=",
"r\"[^\\n]*\\n\"",
"coord_lines",
"=",
"r\"(\\s*\\w+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s+[0-9\\-\\+\\.eEdD]+\\s*\\n)+\"",
"frame_pattern_text",
"=",
"natoms_line",
"+",
"comment_line",
"+",
"coord_lines",
"pat",
"=",
"re",
".",
"compile",
"(",
"frame_pattern_text",
",",
"re",
".",
"MULTILINE",
")",
"mols",
"=",
"[",
"]",
"for",
"xyz_match",
"in",
"pat",
".",
"finditer",
"(",
"contents",
")",
":",
"xyz_text",
"=",
"xyz_match",
".",
"group",
"(",
"0",
")",
"mols",
".",
"append",
"(",
"XYZ",
".",
"_from_frame_string",
"(",
"xyz_text",
")",
")",
"return",
"XYZ",
"(",
"mols",
")"
] |
increment the counter and wake anyone waiting for the new value | def increment ( self ) : self . _count += 1 waiters = self . _waiters . pop ( self . _count , [ ] ) if waiters : scheduler . state . awoken_from_events . update ( waiters ) | 6,815 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L952-L957 | [
"def",
"parse_date",
"(",
"string_date",
")",
":",
"# git time",
"try",
":",
"if",
"string_date",
".",
"count",
"(",
"' '",
")",
"==",
"1",
"and",
"string_date",
".",
"rfind",
"(",
"':'",
")",
"==",
"-",
"1",
":",
"timestamp",
",",
"offset",
"=",
"string_date",
".",
"split",
"(",
")",
"timestamp",
"=",
"int",
"(",
"timestamp",
")",
"return",
"timestamp",
",",
"utctz_to_altz",
"(",
"verify_utctz",
"(",
"offset",
")",
")",
"else",
":",
"offset",
"=",
"\"+0000\"",
"# local time by default",
"if",
"string_date",
"[",
"-",
"5",
"]",
"in",
"'-+'",
":",
"offset",
"=",
"verify_utctz",
"(",
"string_date",
"[",
"-",
"5",
":",
"]",
")",
"string_date",
"=",
"string_date",
"[",
":",
"-",
"6",
"]",
"# skip space as well",
"# END split timezone info",
"offset",
"=",
"utctz_to_altz",
"(",
"offset",
")",
"# now figure out the date and time portion - split time",
"date_formats",
"=",
"[",
"]",
"splitter",
"=",
"-",
"1",
"if",
"','",
"in",
"string_date",
":",
"date_formats",
".",
"append",
"(",
"\"%a, %d %b %Y\"",
")",
"splitter",
"=",
"string_date",
".",
"rfind",
"(",
"' '",
")",
"else",
":",
"# iso plus additional",
"date_formats",
".",
"append",
"(",
"\"%Y-%m-%d\"",
")",
"date_formats",
".",
"append",
"(",
"\"%Y.%m.%d\"",
")",
"date_formats",
".",
"append",
"(",
"\"%m/%d/%Y\"",
")",
"date_formats",
".",
"append",
"(",
"\"%d.%m.%Y\"",
")",
"splitter",
"=",
"string_date",
".",
"rfind",
"(",
"'T'",
")",
"if",
"splitter",
"==",
"-",
"1",
":",
"splitter",
"=",
"string_date",
".",
"rfind",
"(",
"' '",
")",
"# END handle 'T' and ' '",
"# END handle rfc or iso",
"assert",
"splitter",
">",
"-",
"1",
"# split date and time",
"time_part",
"=",
"string_date",
"[",
"splitter",
"+",
"1",
":",
"]",
"# skip space",
"date_part",
"=",
"string_date",
"[",
":",
"splitter",
"]",
"# parse time",
"tstruct",
"=",
"time",
".",
"strptime",
"(",
"time_part",
",",
"\"%H:%M:%S\"",
")",
"for",
"fmt",
"in",
"date_formats",
":",
"try",
":",
"dtstruct",
"=",
"time",
".",
"strptime",
"(",
"date_part",
",",
"fmt",
")",
"utctime",
"=",
"calendar",
".",
"timegm",
"(",
"(",
"dtstruct",
".",
"tm_year",
",",
"dtstruct",
".",
"tm_mon",
",",
"dtstruct",
".",
"tm_mday",
",",
"tstruct",
".",
"tm_hour",
",",
"tstruct",
".",
"tm_min",
",",
"tstruct",
".",
"tm_sec",
",",
"dtstruct",
".",
"tm_wday",
",",
"dtstruct",
".",
"tm_yday",
",",
"tstruct",
".",
"tm_isdst",
")",
")",
"return",
"int",
"(",
"utctime",
")",
",",
"offset",
"except",
"ValueError",
":",
"continue",
"# END exception handling",
"# END for each fmt",
"# still here ? fail",
"raise",
"ValueError",
"(",
"\"no format matched\"",
")",
"# END handle format",
"except",
"Exception",
":",
"raise",
"ValueError",
"(",
"\"Unsupported date format: %s\"",
"%",
"string_date",
")"
] |
wait until the count has reached a particular number | def wait ( self , until = 0 ) : if self . _count != until : self . _waiters . setdefault ( until , [ ] ) . append ( compat . getcurrent ( ) ) scheduler . state . mainloop . switch ( ) | 6,816 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/util.py#L976-L987 | [
"def",
"_create_from_pandas_with_arrow",
"(",
"self",
",",
"pdf",
",",
"schema",
",",
"timezone",
")",
":",
"from",
"pyspark",
".",
"serializers",
"import",
"ArrowStreamPandasSerializer",
"from",
"pyspark",
".",
"sql",
".",
"types",
"import",
"from_arrow_type",
",",
"to_arrow_type",
",",
"TimestampType",
"from",
"pyspark",
".",
"sql",
".",
"utils",
"import",
"require_minimum_pandas_version",
",",
"require_minimum_pyarrow_version",
"require_minimum_pandas_version",
"(",
")",
"require_minimum_pyarrow_version",
"(",
")",
"from",
"pandas",
".",
"api",
".",
"types",
"import",
"is_datetime64_dtype",
",",
"is_datetime64tz_dtype",
"import",
"pyarrow",
"as",
"pa",
"# Create the Spark schema from list of names passed in with Arrow types",
"if",
"isinstance",
"(",
"schema",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"arrow_schema",
"=",
"pa",
".",
"Schema",
".",
"from_pandas",
"(",
"pdf",
",",
"preserve_index",
"=",
"False",
")",
"struct",
"=",
"StructType",
"(",
")",
"for",
"name",
",",
"field",
"in",
"zip",
"(",
"schema",
",",
"arrow_schema",
")",
":",
"struct",
".",
"add",
"(",
"name",
",",
"from_arrow_type",
"(",
"field",
".",
"type",
")",
",",
"nullable",
"=",
"field",
".",
"nullable",
")",
"schema",
"=",
"struct",
"# Determine arrow types to coerce data when creating batches",
"if",
"isinstance",
"(",
"schema",
",",
"StructType",
")",
":",
"arrow_types",
"=",
"[",
"to_arrow_type",
"(",
"f",
".",
"dataType",
")",
"for",
"f",
"in",
"schema",
".",
"fields",
"]",
"elif",
"isinstance",
"(",
"schema",
",",
"DataType",
")",
":",
"raise",
"ValueError",
"(",
"\"Single data type %s is not supported with Arrow\"",
"%",
"str",
"(",
"schema",
")",
")",
"else",
":",
"# Any timestamps must be coerced to be compatible with Spark",
"arrow_types",
"=",
"[",
"to_arrow_type",
"(",
"TimestampType",
"(",
")",
")",
"if",
"is_datetime64_dtype",
"(",
"t",
")",
"or",
"is_datetime64tz_dtype",
"(",
"t",
")",
"else",
"None",
"for",
"t",
"in",
"pdf",
".",
"dtypes",
"]",
"# Slice the DataFrame to be batched",
"step",
"=",
"-",
"(",
"-",
"len",
"(",
"pdf",
")",
"//",
"self",
".",
"sparkContext",
".",
"defaultParallelism",
")",
"# round int up",
"pdf_slices",
"=",
"(",
"pdf",
"[",
"start",
":",
"start",
"+",
"step",
"]",
"for",
"start",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"pdf",
")",
",",
"step",
")",
")",
"# Create list of Arrow (columns, type) for serializer dump_stream",
"arrow_data",
"=",
"[",
"[",
"(",
"c",
",",
"t",
")",
"for",
"(",
"_",
",",
"c",
")",
",",
"t",
"in",
"zip",
"(",
"pdf_slice",
".",
"iteritems",
"(",
")",
",",
"arrow_types",
")",
"]",
"for",
"pdf_slice",
"in",
"pdf_slices",
"]",
"jsqlContext",
"=",
"self",
".",
"_wrapped",
".",
"_jsqlContext",
"safecheck",
"=",
"self",
".",
"_wrapped",
".",
"_conf",
".",
"arrowSafeTypeConversion",
"(",
")",
"col_by_name",
"=",
"True",
"# col by name only applies to StructType columns, can't happen here",
"ser",
"=",
"ArrowStreamPandasSerializer",
"(",
"timezone",
",",
"safecheck",
",",
"col_by_name",
")",
"def",
"reader_func",
"(",
"temp_filename",
")",
":",
"return",
"self",
".",
"_jvm",
".",
"PythonSQLUtils",
".",
"readArrowStreamFromFile",
"(",
"jsqlContext",
",",
"temp_filename",
")",
"def",
"create_RDD_server",
"(",
")",
":",
"return",
"self",
".",
"_jvm",
".",
"ArrowRDDServer",
"(",
"jsqlContext",
")",
"# Create Spark DataFrame from Arrow stream file, using one batch per partition",
"jrdd",
"=",
"self",
".",
"_sc",
".",
"_serialize_to_jvm",
"(",
"arrow_data",
",",
"ser",
",",
"reader_func",
",",
"create_RDD_server",
")",
"jdf",
"=",
"self",
".",
"_jvm",
".",
"PythonSQLUtils",
".",
"toDataFrame",
"(",
"jrdd",
",",
"schema",
".",
"json",
"(",
")",
",",
"jsqlContext",
")",
"df",
"=",
"DataFrame",
"(",
"jdf",
",",
"self",
".",
"_wrapped",
")",
"df",
".",
"_schema",
"=",
"schema",
"return",
"df"
] |
callback function suitable for psycopg2 . set_wait_callback | def wait_callback ( connection ) : while 1 : state = connection . poll ( ) if state == extensions . POLL_OK : break elif state == extensions . POLL_READ : descriptor . wait_fds ( [ ( connection . fileno ( ) , 1 ) ] ) elif state == extensions . POLL_WRITE : descriptor . wait_fds ( [ ( connection . fileno ( ) , 2 ) ] ) else : raise psycopg2 . OperationalError ( "Bad poll result: %r" % state ) | 6,817 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/ext/psycopg2.py#L12-L32 | [
"def",
"CleanAff4Clients",
"(",
"self",
")",
":",
"inactive_client_ttl",
"=",
"config",
".",
"CONFIG",
"[",
"\"DataRetention.inactive_client_ttl\"",
"]",
"if",
"not",
"inactive_client_ttl",
":",
"self",
".",
"Log",
"(",
"\"TTL not set - nothing to do...\"",
")",
"return",
"exception_label",
"=",
"config",
".",
"CONFIG",
"[",
"\"DataRetention.inactive_client_ttl_exception_label\"",
"]",
"index",
"=",
"client_index",
".",
"CreateClientIndex",
"(",
"token",
"=",
"self",
".",
"token",
")",
"client_urns",
"=",
"index",
".",
"LookupClients",
"(",
"[",
"\".\"",
"]",
")",
"deadline",
"=",
"rdfvalue",
".",
"RDFDatetime",
".",
"Now",
"(",
")",
"-",
"inactive_client_ttl",
"deletion_count",
"=",
"0",
"for",
"client_group",
"in",
"collection",
".",
"Batch",
"(",
"client_urns",
",",
"1000",
")",
":",
"inactive_client_urns",
"=",
"[",
"]",
"for",
"client",
"in",
"aff4",
".",
"FACTORY",
".",
"MultiOpen",
"(",
"client_group",
",",
"mode",
"=",
"\"r\"",
",",
"aff4_type",
"=",
"aff4_grr",
".",
"VFSGRRClient",
",",
"token",
"=",
"self",
".",
"token",
")",
":",
"if",
"exception_label",
"in",
"client",
".",
"GetLabelsNames",
"(",
")",
":",
"continue",
"if",
"client",
".",
"Get",
"(",
"client",
".",
"Schema",
".",
"LAST",
")",
"<",
"deadline",
":",
"inactive_client_urns",
".",
"append",
"(",
"client",
".",
"urn",
")",
"aff4",
".",
"FACTORY",
".",
"MultiDelete",
"(",
"inactive_client_urns",
",",
"token",
"=",
"self",
".",
"token",
")",
"deletion_count",
"+=",
"len",
"(",
"inactive_client_urns",
")",
"self",
".",
"HeartBeat",
"(",
")",
"self",
".",
"Log",
"(",
"\"Deleted %d inactive clients.\"",
"%",
"deletion_count",
")"
] |
Returns the dependency path from the term to the root | def get_path_to_root ( self , termid ) : # Get the sentence for the term root = None sentence = self . sentence_for_termid . get ( termid ) if sentence is None : #try with the top node top_node = self . top_relation_for_term . get ( termid ) if top_node is not None : root = top_node [ 1 ] else : return None else : if sentence in self . root_for_sentence : root = self . root_for_sentence [ sentence ] else : ##There is no root for this sentence return None # In this point top_node should be properly set path = self . get_shortest_path ( termid , root ) return path | 6,818 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/dependency.py#L307-L333 | [
"def",
"delete_group",
"(",
"group_id",
",",
"purge_data",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"try",
":",
"group_i",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceGroup",
")",
".",
"filter",
"(",
"ResourceGroup",
".",
"id",
"==",
"group_id",
")",
".",
"one",
"(",
")",
"except",
"NoResultFound",
":",
"raise",
"ResourceNotFoundError",
"(",
"\"Group %s not found\"",
"%",
"(",
"group_id",
")",
")",
"group_items",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceGroupItem",
")",
".",
"filter",
"(",
"ResourceGroupItem",
".",
"group_id",
"==",
"group_id",
")",
".",
"all",
"(",
")",
"for",
"gi",
"in",
"group_items",
":",
"db",
".",
"DBSession",
".",
"delete",
"(",
"gi",
")",
"if",
"purge_data",
"==",
"'Y'",
":",
"_purge_datasets_unique_to_resource",
"(",
"'GROUP'",
",",
"group_id",
")",
"log",
".",
"info",
"(",
"\"Deleting group %s, id=%s\"",
",",
"group_i",
".",
"name",
",",
"group_id",
")",
"group_i",
".",
"network",
".",
"check_write_permission",
"(",
"user_id",
")",
"db",
".",
"DBSession",
".",
"delete",
"(",
"group_i",
")",
"db",
".",
"DBSession",
".",
"flush",
"(",
")"
] |
Returns the complete list of dependents and embedded dependents of a certain term . | def get_full_dependents ( self , term_id , relations , counter = 0 ) : counter += 1 deps = self . relations_for_term if term_id in deps and len ( deps . get ( term_id ) ) > 0 : for dep in deps . get ( term_id ) : if not dep [ 1 ] in relations : relations . append ( dep [ 1 ] ) if dep [ 1 ] in deps : deprelations = self . get_full_dependents ( dep [ 1 ] , relations , counter ) for deprel in deprelations : if not deprel in relations : relations . append ( deprel ) return relations | 6,819 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/dependency.py#L354-L370 | [
"def",
"_validate_checksum",
"(",
"self",
",",
"buffer",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"Validating the buffer\"",
")",
"if",
"len",
"(",
"buffer",
")",
"==",
"0",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"Buffer was empty\"",
")",
"if",
"self",
".",
"_conn",
".",
"isOpen",
"(",
")",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"'Closing connection'",
")",
"self",
".",
"_conn",
".",
"close",
"(",
")",
"return",
"False",
"p0",
"=",
"hex2int",
"(",
"buffer",
"[",
"0",
"]",
")",
"p1",
"=",
"hex2int",
"(",
"buffer",
"[",
"1",
"]",
")",
"checksum",
"=",
"sum",
"(",
"[",
"hex2int",
"(",
"c",
")",
"for",
"c",
"in",
"buffer",
"[",
":",
"35",
"]",
"]",
")",
"&",
"0xFF",
"p35",
"=",
"hex2int",
"(",
"buffer",
"[",
"35",
"]",
")",
"if",
"p0",
"!=",
"165",
"or",
"p1",
"!=",
"150",
"or",
"p35",
"!=",
"checksum",
":",
"self",
".",
"_log",
".",
"debug",
"(",
"\"Buffer checksum was not valid\"",
")",
"return",
"False",
"return",
"True"
] |
Given a string of module names it will return the include directories essential to their compilation as long as the module has the conventional get_include function . | def getDirsToInclude ( string ) : dirs = [ ] a = string . strip ( ) obj = a . split ( '-' ) if len ( obj ) == 1 and obj [ 0 ] : for module in obj : try : exec ( 'import {}' . format ( module ) ) except ImportError : raise FileNotFoundError ( "The module '{}' does not" "exist" . format ( module ) ) try : dirs . append ( '-I{}' . format ( eval ( module ) . get_include ( ) ) ) except AttributeError : print ( NOT_NEEDED_MESSAGE . format ( module ) ) return dirs | 6,820 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L42-L63 | [
"def",
"Subtract",
"(",
"self",
",",
"other",
")",
":",
"for",
"val",
",",
"freq",
"in",
"other",
".",
"Items",
"(",
")",
":",
"self",
".",
"Incr",
"(",
"val",
",",
"-",
"freq",
")"
] |
These will delete any configs found in either the current directory or the user s home directory | def purge_configs ( ) : user_config = path ( CONFIG_FILE_NAME , root = USER ) inplace_config = path ( CONFIG_FILE_NAME ) if os . path . isfile ( user_config ) : os . remove ( user_config ) if os . path . isfile ( inplace_config ) : os . remove ( inplace_config ) | 6,821 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L66-L78 | [
"def",
"minimum",
"(",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"output_shape",
"=",
"convert_to_shape",
"(",
"output_shape",
")",
"with",
"tf",
".",
"name_scope",
"(",
"name",
",",
"default_name",
"=",
"\"minimum\"",
")",
":",
"x1",
",",
"x2",
"=",
"binary_arguments_to_tensors",
"(",
"x1",
",",
"x2",
")",
"return",
"MinMaxOperation",
"(",
"tf",
".",
"minimum",
",",
"x1",
",",
"x2",
",",
"output_shape",
"=",
"_infer_binary_broadcast_shape",
"(",
"x1",
".",
"shape",
",",
"x2",
".",
"shape",
",",
"output_shape",
")",
")",
".",
"outputs",
"[",
"0",
"]"
] |
Returns the path to the config file if found in either the current working directory or the user s home directory . If a config file is not found the function will return None . | def find_config_file ( ) : local_config_name = path ( CONFIG_FILE_NAME ) if os . path . isfile ( local_config_name ) : return local_config_name else : user_config_name = path ( CONFIG_FILE_NAME , root = USER ) if os . path . isfile ( user_config_name ) : return user_config_name else : return None | 6,822 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L95-L109 | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
Makes the data necessary to construct a functional config file | def make_config_data ( * , guided ) : config_data = { } config_data [ INCLUDE_DIRS_KEY ] = _make_include_dirs ( guided = guided ) config_data [ RUNTIME_DIRS_KEY ] = _make_runtime_dirs ( guided = guided ) config_data [ RUNTIME_KEY ] = _make_runtime ( ) return config_data | 6,823 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L308-L317 | [
"def",
"delete_binding",
"(",
"self",
",",
"vhost",
",",
"exchange",
",",
"queue",
",",
"rt_key",
")",
":",
"vhost",
"=",
"quote",
"(",
"vhost",
",",
"''",
")",
"exchange",
"=",
"quote",
"(",
"exchange",
",",
"''",
")",
"queue",
"=",
"quote",
"(",
"queue",
",",
"''",
")",
"body",
"=",
"''",
"path",
"=",
"Client",
".",
"urls",
"[",
"'rt_bindings_between_exch_queue'",
"]",
"%",
"(",
"vhost",
",",
"exchange",
",",
"queue",
",",
"rt_key",
")",
"return",
"self",
".",
"_call",
"(",
"path",
",",
"'DELETE'",
",",
"headers",
"=",
"Client",
".",
"json_headers",
")"
] |
If a config file is found in the standard locations it will be loaded and the config data would be retuned . If not found then generate the data on the fly and return it | def generate_configurations ( * , guided = False , fresh_start = False , save = False ) : if fresh_start : purge_configs ( ) loaded_status , loaded_data = get_config ( ) if loaded_status != CONFIG_VALID : if save : make_config_file ( guided = guided ) status , config_data = get_config ( ) else : config_data = make_config_data ( guided = guided ) else : config_data = loaded_data return config_data | 6,824 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/configuration.py#L333-L353 | [
"def",
"set_user",
"(",
"self",
",",
"user",
")",
":",
"super",
"(",
"Segment",
",",
"self",
")",
".",
"_check_ended",
"(",
")",
"self",
".",
"user",
"=",
"user"
] |
Execute an HTTP request to get details on a queue and return it . | def info ( self ) : url = "queues/%s" % ( self . name , ) result = self . client . get ( url ) return result [ 'body' ] [ 'queue' ] | 6,825 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L33-L40 | [
"def",
"parse_wrap_facets",
"(",
"facets",
")",
":",
"valid_forms",
"=",
"[",
"'~ var1'",
",",
"'~ var1 + var2'",
"]",
"error_msg",
"=",
"(",
"\"Valid formula for 'facet_wrap' look like\"",
"\" {}\"",
".",
"format",
"(",
"valid_forms",
")",
")",
"if",
"isinstance",
"(",
"facets",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"facets",
"if",
"not",
"isinstance",
"(",
"facets",
",",
"str",
")",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"if",
"'~'",
"in",
"facets",
":",
"variables_pattern",
"=",
"r'(\\w+(?:\\s*\\+\\s*\\w+)*|\\.)'",
"pattern",
"=",
"r'\\s*~\\s*{0}\\s*'",
".",
"format",
"(",
"variables_pattern",
")",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"facets",
")",
"if",
"not",
"match",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"facets",
"=",
"[",
"var",
".",
"strip",
"(",
")",
"for",
"var",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"'+'",
")",
"]",
"elif",
"re",
".",
"match",
"(",
"r'\\w+'",
",",
"facets",
")",
":",
"# allow plain string as the variable name",
"facets",
"=",
"[",
"facets",
"]",
"else",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"return",
"facets"
] |
Executes an HTTP request to clear all contents of a queue . | def clear ( self ) : url = "queues/%s/messages" % self . name result = self . client . delete ( url = url , body = json . dumps ( { } ) , headers = { 'Content-Type' : 'application/json' } ) return result [ 'body' ] | 6,826 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L54-L61 | [
"async",
"def",
"_parse_lines",
"(",
"lines",
",",
"regex",
")",
":",
"results",
"=",
"[",
"]",
"if",
"inspect",
".",
"iscoroutinefunction",
"(",
"lines",
")",
":",
"lines",
"=",
"await",
"lines",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
":",
"match",
"=",
"regex",
".",
"search",
"(",
"line",
")",
"if",
"not",
"match",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Could not parse row: %s\"",
",",
"line",
")",
"continue",
"results",
".",
"append",
"(",
"match",
".",
"groupdict",
"(",
")",
")",
"return",
"results"
] |
Execute an HTTP request to delete a message from queue . | def delete ( self , message_id , reservation_id = None , subscriber_name = None ) : url = "queues/%s/messages/%s" % ( self . name , message_id ) qitems = { } if reservation_id is not None : qitems [ 'reservation_id' ] = reservation_id if subscriber_name is not None : qitems [ 'subscriber_name' ] = subscriber_name body = json . dumps ( qitems ) result = self . client . delete ( url = url , body = body , headers = { 'Content-Type' : 'application/json' } ) return result [ 'body' ] | 6,827 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L63-L82 | [
"def",
"wrap_conn",
"(",
"conn_func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cursor_func",
"=",
"getattr",
"(",
"conn",
",",
"CURSOR_WRAP_METHOD",
")",
"wrapped",
"=",
"wrap_cursor",
"(",
"cursor_func",
")",
"setattr",
"(",
"conn",
",",
"cursor_func",
".",
"__name__",
",",
"wrapped",
")",
"return",
"conn",
"except",
"Exception",
":",
"# pragma: NO COVER",
"logging",
".",
"warning",
"(",
"'Fail to wrap conn, mysql not traced.'",
")",
"return",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"call"
] |
Execute an HTTP request to delete messages from queue . | def delete_multiple ( self , ids = None , messages = None ) : url = "queues/%s/messages" % self . name items = None if ids is None and messages is None : raise Exception ( 'Please, specify at least one parameter.' ) if ids is not None : items = [ { 'id' : item } for item in ids ] if messages is not None : items = [ { 'id' : item [ 'id' ] , 'reservation_id' : item [ 'reservation_id' ] } for item in messages [ 'messages' ] ] data = json . dumps ( { 'ids' : items } ) result = self . client . delete ( url = url , body = data , headers = { 'Content-Type' : 'application/json' } ) return result [ 'body' ] | 6,828 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L84-L106 | [
"def",
"wrap_conn",
"(",
"conn_func",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"conn",
"=",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cursor_func",
"=",
"getattr",
"(",
"conn",
",",
"CURSOR_WRAP_METHOD",
")",
"wrapped",
"=",
"wrap_cursor",
"(",
"cursor_func",
")",
"setattr",
"(",
"conn",
",",
"cursor_func",
".",
"__name__",
",",
"wrapped",
")",
"return",
"conn",
"except",
"Exception",
":",
"# pragma: NO COVER",
"logging",
".",
"warning",
"(",
"'Fail to wrap conn, mysql not traced.'",
")",
"return",
"conn_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"call"
] |
Executes an HTTP request to create message on the queue . Creates queue if not existed . | def post ( self , * messages ) : url = "queues/%s/messages" % self . name msgs = [ { 'body' : msg } if isinstance ( msg , basestring ) else msg for msg in messages ] data = json . dumps ( { 'messages' : msgs } ) result = self . client . post ( url = url , body = data , headers = { 'Content-Type' : 'application/json' } ) return result [ 'body' ] | 6,829 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L108-L124 | [
"def",
"_active_mounts_darwin",
"(",
"ret",
")",
":",
"for",
"line",
"in",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"'mount'",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"comps",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"line",
")",
".",
"split",
"(",
")",
"parens",
"=",
"re",
".",
"findall",
"(",
"r'\\((.*?)\\)'",
",",
"line",
",",
"re",
".",
"DOTALL",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\", \"",
")",
"ret",
"[",
"comps",
"[",
"2",
"]",
"]",
"=",
"{",
"'device'",
":",
"comps",
"[",
"0",
"]",
",",
"'fstype'",
":",
"parens",
"[",
"0",
"]",
",",
"'opts'",
":",
"_resolve_user_group_names",
"(",
"parens",
"[",
"1",
":",
"]",
")",
"}",
"return",
"ret"
] |
Retrieves Messages from the queue and reserves it . | def reserve ( self , max = None , timeout = None , wait = None , delete = None ) : url = "queues/%s/reservations" % self . name qitems = { } if max is not None : qitems [ 'n' ] = max if timeout is not None : qitems [ 'timeout' ] = timeout if wait is not None : qitems [ 'wait' ] = wait if delete is not None : qitems [ 'delete' ] = delete body = json . dumps ( qitems ) response = self . client . post ( url , body = body , headers = { 'Content-Type' : 'application/json' } ) return response [ 'body' ] | 6,830 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L136-L160 | [
"def",
"parse_files",
"(",
"self",
")",
":",
"log_re",
"=",
"self",
".",
"log_format_regex",
"log_lines",
"=",
"[",
"]",
"for",
"log_file",
"in",
"self",
".",
"matching_files",
"(",
")",
":",
"with",
"open",
"(",
"log_file",
")",
"as",
"f",
":",
"matches",
"=",
"re",
".",
"finditer",
"(",
"log_re",
",",
"f",
".",
"read",
"(",
")",
")",
"for",
"match",
"in",
"matches",
":",
"log_lines",
".",
"append",
"(",
"match",
".",
"groupdict",
"(",
")",
")",
"return",
"log_lines"
] |
Touching a reserved message extends its timeout to the duration specified when the message was created . | def touch ( self , message_id , reservation_id , timeout = None ) : url = "queues/%s/messages/%s/touch" % ( self . name , message_id ) qitems = { 'reservation_id' : reservation_id } if timeout is not None : qitems [ 'timeout' ] = timeout body = json . dumps ( qitems ) response = self . client . post ( url , body = body , headers = { 'Content-Type' : 'application/json' } ) return response [ 'body' ] | 6,831 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L177-L194 | [
"def",
"isrchi",
"(",
"value",
",",
"ndim",
",",
"array",
")",
":",
"value",
"=",
"ctypes",
".",
"c_int",
"(",
"value",
")",
"ndim",
"=",
"ctypes",
".",
"c_int",
"(",
"ndim",
")",
"array",
"=",
"stypes",
".",
"toIntVector",
"(",
"array",
")",
"return",
"libspice",
".",
"isrchi_c",
"(",
"value",
",",
"ndim",
",",
"array",
")"
] |
Release locked message after specified time . If there is no message with such id on the queue . | def release ( self , message_id , reservation_id , delay = 0 ) : url = "queues/%s/messages/%s/release" % ( self . name , message_id ) body = { 'reservation_id' : reservation_id } if delay > 0 : body [ 'delay' ] = delay body = json . dumps ( body ) response = self . client . post ( url , body = body , headers = { 'Content-Type' : 'application/json' } ) return response [ 'body' ] | 6,832 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L196-L213 | [
"def",
"pan",
"(",
"self",
",",
"value",
")",
":",
"assert",
"len",
"(",
"value",
")",
"==",
"2",
"self",
".",
"_pan",
"[",
":",
"]",
"=",
"value",
"self",
".",
"_constrain_pan",
"(",
")",
"self",
".",
"update",
"(",
")"
] |
Execute an HTTP request to get a list of queues and return it . | def queues ( self , page = None , per_page = None , previous = None , prefix = None ) : options = { } if page is not None : raise Exception ( 'page param is deprecated!' ) if per_page is not None : options [ 'per_page' ] = per_page if previous is not None : options [ 'previous' ] = previous if prefix is not None : options [ 'prefix' ] = prefix query = urlencode ( options ) url = 'queues' if query != '' : url = "%s?%s" % ( url , query ) result = self . client . get ( url ) return [ queue [ 'name' ] for queue in result [ 'body' ] [ 'queues' ] ] | 6,833 | https://github.com/iron-io/iron_mq_python/blob/d6a293f0d54b4ca2dca1c335f9867cd2310f6fc7/iron_mq.py#L318-L341 | [
"def",
"injected",
"(",
"self",
",",
"filename",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
":",
"return",
"False",
"with",
"codecs",
".",
"open",
"(",
"full_path",
",",
"'r+'",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"fh",
":",
"contents",
"=",
"fh",
".",
"read",
"(",
")",
"return",
"self",
".",
"wrapper_match",
".",
"search",
"(",
"contents",
")",
"is",
"not",
"None"
] |
Returns the timex object for the supplied identifier | def get_timex ( self , timex_id ) : if timex_id in self . idx : return Ctime ( self . idx [ timex_id ] ) else : return None | 6,834 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/time_data.py#L346-L355 | [
"def",
"get_connection_details",
"(",
"session",
",",
"vcenter_resource_model",
",",
"resource_context",
")",
":",
"session",
"=",
"session",
"resource_context",
"=",
"resource_context",
"# get vCenter connection details from vCenter resource",
"user",
"=",
"vcenter_resource_model",
".",
"user",
"vcenter_url",
"=",
"resource_context",
".",
"address",
"password",
"=",
"session",
".",
"DecryptPassword",
"(",
"vcenter_resource_model",
".",
"password",
")",
".",
"Value",
"return",
"VCenterConnectionDetails",
"(",
"vcenter_url",
",",
"user",
",",
"password",
")"
] |
Adds a timex object to the layer . | def add_timex ( self , timex_obj ) : timex_id = timex_obj . get_id ( ) #check if id is not already present if not timex_id in self . idx : timex_node = timex_obj . get_node ( ) self . node . append ( timex_node ) self . idx [ timex_id ] = timex_node else : #FIXME: what we want is that the element receives a new identifier that #is not present in current element yet print ( 'Error: trying to add new element with existing identifier' ) | 6,835 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/time_data.py#L367-L383 | [
"def",
"parse_coach_ec_df",
"(",
"infile",
")",
":",
"ec_df",
"=",
"pd",
".",
"read_table",
"(",
"infile",
",",
"delim_whitespace",
"=",
"True",
",",
"names",
"=",
"[",
"'pdb_template'",
",",
"'tm_score'",
",",
"'rmsd'",
",",
"'seq_ident'",
",",
"'seq_coverage'",
",",
"'c_score'",
",",
"'ec_number'",
",",
"'binding_residues'",
"]",
")",
"ec_df",
"[",
"'pdb_template_id'",
"]",
"=",
"ec_df",
"[",
"'pdb_template'",
"]",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
"[",
":",
"4",
"]",
")",
"ec_df",
"[",
"'pdb_template_chain'",
"]",
"=",
"ec_df",
"[",
"'pdb_template'",
"]",
".",
"apply",
"(",
"lambda",
"x",
":",
"x",
"[",
"4",
"]",
")",
"ec_df",
"=",
"ec_df",
"[",
"[",
"'pdb_template_id'",
",",
"'pdb_template_chain'",
",",
"'tm_score'",
",",
"'rmsd'",
",",
"'seq_ident'",
",",
"'seq_coverage'",
",",
"'c_score'",
",",
"'ec_number'",
",",
"'binding_residues'",
"]",
"]",
"ec_df",
"[",
"'c_score'",
"]",
"=",
"pd",
".",
"to_numeric",
"(",
"ec_df",
".",
"c_score",
",",
"errors",
"=",
"'coerce'",
")",
"return",
"ec_df"
] |
Checks if the directory looks like a filetracker storage . Exits with error if it doesn t . | def ensure_storage_format ( root_dir ) : if not os . path . isdir ( os . path . join ( root_dir , 'blobs' ) ) : print ( '"blobs/" directory not found' ) sys . exit ( 1 ) if not os . path . isdir ( os . path . join ( root_dir , 'links' ) ) : print ( '"links/" directory not found' ) sys . exit ( 1 ) if not os . path . isdir ( os . path . join ( root_dir , 'db' ) ) : print ( '"db/" directory not found' ) sys . exit ( 1 ) | 6,836 | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/scripts/recover.py#L132-L147 | [
"def",
"_update_message_request",
"(",
"self",
",",
"message",
")",
":",
"for",
"each",
"in",
"self",
".",
"row_keys",
":",
"message",
".",
"rows",
".",
"row_keys",
".",
"append",
"(",
"_to_bytes",
"(",
"each",
")",
")",
"for",
"each",
"in",
"self",
".",
"row_ranges",
":",
"r_kwrags",
"=",
"each",
".",
"get_range_kwargs",
"(",
")",
"message",
".",
"rows",
".",
"row_ranges",
".",
"add",
"(",
"*",
"*",
"r_kwrags",
")"
] |
Returns the deepest phrase type for the term identifier and the list of subsumed by the same element | def get_deepest_phrase_for_termid ( self , termid ) : terminal_id = self . terminal_for_term . get ( termid ) label = None subsumed = [ ] if terminal_id is not None : first_path = self . paths_for_terminal [ terminal_id ] [ 0 ] first_phrase_id = first_path [ 1 ] label = self . label_for_nonter . get ( first_phrase_id ) subsumed = self . terms_subsumed_by_nonter . get ( first_phrase_id , [ ] ) return label , sorted ( list ( subsumed ) ) | 6,837 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L89-L105 | [
"def",
"create_experiment",
"(",
"args",
")",
":",
"config_file_name",
"=",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
",",
"8",
")",
")",
"nni_config",
"=",
"Config",
"(",
"config_file_name",
")",
"config_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"args",
".",
"config",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"config_path",
")",
":",
"print_error",
"(",
"'Please set correct config path!'",
")",
"exit",
"(",
"1",
")",
"experiment_config",
"=",
"get_yml_content",
"(",
"config_path",
")",
"validate_all_content",
"(",
"experiment_config",
",",
"config_path",
")",
"nni_config",
".",
"set_config",
"(",
"'experimentConfig'",
",",
"experiment_config",
")",
"launch_experiment",
"(",
"args",
",",
"experiment_config",
",",
"'new'",
",",
"config_file_name",
")",
"nni_config",
".",
"set_config",
"(",
"'restServerPort'",
",",
"args",
".",
"port",
")"
] |
Returns the deepest common subsumer among two terms | def get_least_common_subsumer ( self , from_tid , to_tid ) : termid_from = self . terminal_for_term . get ( from_tid ) termid_to = self . terminal_for_term . get ( to_tid ) path_from = self . paths_for_terminal [ termid_from ] [ 0 ] path_to = self . paths_for_terminal [ termid_to ] [ 0 ] common_nodes = set ( path_from ) & set ( path_to ) if len ( common_nodes ) == 0 : return None else : indexes = [ ] for common_node in common_nodes : index1 = path_from . index ( common_node ) index2 = path_to . index ( common_node ) indexes . append ( ( common_node , index1 + index2 ) ) indexes . sort ( key = itemgetter ( 1 ) ) shortest_common = indexes [ 0 ] [ 0 ] return shortest_common | 6,838 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L108-L134 | [
"def",
"show_available_noise_curves",
"(",
"return_curves",
"=",
"True",
",",
"print_curves",
"=",
"False",
")",
":",
"if",
"return_curves",
"is",
"False",
"and",
"print_curves",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"Both return curves and print_curves are False.\"",
"+",
"\" You will not see the options\"",
")",
"cfd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"curves",
"=",
"[",
"curve",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"for",
"curve",
"in",
"os",
".",
"listdir",
"(",
"cfd",
"+",
"'/noise_curves/'",
")",
"]",
"if",
"print_curves",
":",
"for",
"f",
"in",
"curves",
":",
"print",
"(",
"f",
")",
"if",
"return_curves",
":",
"return",
"curves",
"return"
] |
Returns the labels of the deepest node that subsumes all the terms in the list of terms id s provided | def get_deepest_subsumer ( self , list_terms ) : #To store with how many terms every nonterminal appears count_per_no_terminal = defaultdict ( int ) #To store the total deep of each noter for all the term ides (as we want the deepest) total_deep_per_no_terminal = defaultdict ( int ) for term_id in list_terms : terminal_id = self . terminal_for_term . get ( term_id ) path = self . paths_for_terminal [ terminal_id ] [ 0 ] print ( term_id , path ) for c , noter in enumerate ( path ) : count_per_no_terminal [ noter ] += 1 total_deep_per_no_terminal [ noter ] += c deepest_and_common = None deepest = 10000 for noterid , this_total in total_deep_per_no_terminal . items ( ) : if count_per_no_terminal . get ( noterid , - 1 ) == len ( list_terms ) : ##Only the nontarms that ocurr with all the term ids in the input if this_total < deepest : deepest = this_total deepest_and_common = noterid label = None if deepest_and_common is not None : label = self . label_for_nonter [ deepest_and_common ] return deepest_and_common , label | 6,839 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L218-L248 | [
"def",
"_connect",
"(",
"self",
",",
"config",
")",
":",
"if",
"'connection_timeout'",
"not",
"in",
"self",
".",
"_config",
":",
"self",
".",
"_config",
"[",
"'connection_timeout'",
"]",
"=",
"480",
"try",
":",
"self",
".",
"_cnx",
"=",
"connect",
"(",
"*",
"*",
"config",
")",
"self",
".",
"_cursor",
"=",
"self",
".",
"_cnx",
".",
"cursor",
"(",
")",
"self",
".",
"_printer",
"(",
"'\\tMySQL DB connection established with db'",
",",
"config",
"[",
"'database'",
"]",
")",
"except",
"Error",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"errorcode",
".",
"ER_ACCESS_DENIED_ERROR",
":",
"print",
"(",
"\"Something is wrong with your user name or password\"",
")",
"elif",
"err",
".",
"errno",
"==",
"errorcode",
".",
"ER_BAD_DB_ERROR",
":",
"print",
"(",
"\"Database does not exist\"",
")",
"raise",
"err"
] |
Returns the chunks for a certain type | def get_chunks ( self , chunk_type ) : for nonter , this_type in self . label_for_nonter . items ( ) : if this_type == chunk_type : subsumed = self . terms_subsumed_by_nonter . get ( nonter ) if subsumed is not None : yield sorted ( list ( subsumed ) ) | 6,840 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L270-L282 | [
"def",
"OnDeactivateCard",
"(",
"self",
",",
"card",
")",
":",
"SimpleSCardAppEventObserver",
".",
"OnActivateCard",
"(",
"self",
",",
"card",
")",
"self",
".",
"feedbacktext",
".",
"SetLabel",
"(",
"'Deactivated card: '",
"+",
"repr",
"(",
"card",
")",
")"
] |
Returns all the chunks in which the term is contained | def get_all_chunks_for_term ( self , termid ) : terminal_id = self . terminal_for_term . get ( termid ) paths = self . paths_for_terminal [ terminal_id ] for path in paths : for node in path : this_type = self . label_for_nonter [ node ] subsumed = self . terms_subsumed_by_nonter . get ( node ) if subsumed is not None : yield this_type , sorted ( list ( subsumed ) ) | 6,841 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/feature_extractor/constituency.py#L331-L346 | [
"def",
"display",
"(",
"url",
")",
":",
"import",
"os",
"oscmd",
"=",
"\"curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'\"",
"%",
"(",
"url",
")",
"logger",
".",
"debug",
"(",
"oscmd",
")",
"os",
".",
"system",
"(",
"oscmd",
"+",
"' | xpaset ds9 fits'",
")",
"return"
] |
Return the attribute of namespace corresponding to value . | def _lookup_enum_in_ns ( namespace , value ) : for attribute in dir ( namespace ) : if getattr ( namespace , attribute ) == value : return attribute | 6,842 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L88-L92 | [
"def",
"make_or_augment_meta",
"(",
"self",
",",
"role",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
")",
":",
"utils",
".",
"create_meta_main",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
",",
"self",
".",
"config",
",",
"role",
",",
"\"\"",
")",
"self",
".",
"report",
"[",
"\"state\"",
"]",
"[",
"\"ok_role\"",
"]",
"+=",
"1",
"self",
".",
"report",
"[",
"\"roles\"",
"]",
"[",
"role",
"]",
"[",
"\"state\"",
"]",
"=",
"\"ok\"",
"# swap values in place to use the config values",
"swaps",
"=",
"[",
"(",
"\"author\"",
",",
"self",
".",
"config",
"[",
"\"author_name\"",
"]",
")",
",",
"(",
"\"company\"",
",",
"self",
".",
"config",
"[",
"\"author_company\"",
"]",
")",
",",
"(",
"\"license\"",
",",
"self",
".",
"config",
"[",
"\"license_type\"",
"]",
")",
",",
"]",
"(",
"new_meta",
",",
"_",
")",
"=",
"utils",
".",
"swap_yaml_string",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
",",
"swaps",
")",
"# normalize the --- at the top of the file by removing it first",
"new_meta",
"=",
"new_meta",
".",
"replace",
"(",
"\"---\"",
",",
"\"\"",
")",
"new_meta",
"=",
"new_meta",
".",
"lstrip",
"(",
")",
"# augment missing main keys",
"augments",
"=",
"[",
"(",
"\"ansigenome_info\"",
",",
"\"{}\"",
")",
",",
"(",
"\"galaxy_info\"",
",",
"\"{}\"",
")",
",",
"(",
"\"dependencies\"",
",",
"\"[]\"",
")",
",",
"]",
"new_meta",
"=",
"self",
".",
"augment_main_keys",
"(",
"augments",
",",
"new_meta",
")",
"# re-attach the ---",
"new_meta",
"=",
"\"---\\n\\n\"",
"+",
"new_meta",
"travis_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"paths",
"[",
"\"role\"",
"]",
",",
"\".travis.yml\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"travis_path",
")",
":",
"new_meta",
"=",
"new_meta",
".",
"replace",
"(",
"\"travis: False\"",
",",
"\"travis: True\"",
")",
"utils",
".",
"string_to_file",
"(",
"self",
".",
"paths",
"[",
"\"meta\"",
"]",
",",
"new_meta",
")"
] |
Return true if this is a word - type token . | def _is_word_type ( token_type ) : return token_type in [ TokenType . Word , TokenType . QuotedLiteral , TokenType . UnquotedLiteral , TokenType . Number , TokenType . Deref ] | 6,843 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L174-L180 | [
"def",
"write_astrom_data",
"(",
"self",
",",
"astrom_data",
")",
":",
"self",
".",
"write_headers",
"(",
"astrom_data",
".",
"observations",
",",
"astrom_data",
".",
"sys_header",
")",
"self",
".",
"_write_source_data",
"(",
"astrom_data",
".",
"sources",
")"
] |
Return true if this kind of token can be inside a comment . | def _is_in_comment_type ( token_type ) : return token_type in [ TokenType . Comment , TokenType . Newline , TokenType . Whitespace , TokenType . RST , TokenType . BeginRSTComment , TokenType . BeginInlineRST , TokenType . EndInlineRST ] | 6,844 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L183-L191 | [
"def",
"_dynamic_mul",
"(",
"self",
",",
"dimensions",
",",
"other",
",",
"keys",
")",
":",
"# If either is a HoloMap compute Dimension values",
"if",
"not",
"isinstance",
"(",
"self",
",",
"DynamicMap",
")",
"or",
"not",
"isinstance",
"(",
"other",
",",
"DynamicMap",
")",
":",
"keys",
"=",
"sorted",
"(",
"(",
"d",
",",
"v",
")",
"for",
"k",
"in",
"keys",
"for",
"d",
",",
"v",
"in",
"k",
")",
"grouped",
"=",
"dict",
"(",
"[",
"(",
"g",
",",
"[",
"v",
"for",
"_",
",",
"v",
"in",
"group",
"]",
")",
"for",
"g",
",",
"group",
"in",
"groupby",
"(",
"keys",
",",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"]",
")",
"dimensions",
"=",
"[",
"d",
"(",
"values",
"=",
"grouped",
"[",
"d",
".",
"name",
"]",
")",
"for",
"d",
"in",
"dimensions",
"]",
"map_obj",
"=",
"None",
"# Combine streams",
"map_obj",
"=",
"self",
"if",
"isinstance",
"(",
"self",
",",
"DynamicMap",
")",
"else",
"other",
"if",
"isinstance",
"(",
"self",
",",
"DynamicMap",
")",
"and",
"isinstance",
"(",
"other",
",",
"DynamicMap",
")",
":",
"self_streams",
"=",
"util",
".",
"dimensioned_streams",
"(",
"self",
")",
"other_streams",
"=",
"util",
".",
"dimensioned_streams",
"(",
"other",
")",
"streams",
"=",
"list",
"(",
"util",
".",
"unique_iterator",
"(",
"self_streams",
"+",
"other_streams",
")",
")",
"else",
":",
"streams",
"=",
"map_obj",
".",
"streams",
"def",
"dynamic_mul",
"(",
"*",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"key_map",
"=",
"{",
"d",
".",
"name",
":",
"k",
"for",
"d",
",",
"k",
"in",
"zip",
"(",
"dimensions",
",",
"key",
")",
"}",
"layers",
"=",
"[",
"]",
"try",
":",
"self_el",
"=",
"self",
".",
"select",
"(",
"HoloMap",
",",
"*",
"*",
"key_map",
")",
"if",
"self",
".",
"kdims",
"else",
"self",
"[",
"(",
")",
"]",
"layers",
".",
"append",
"(",
"self_el",
")",
"except",
"KeyError",
":",
"pass",
"try",
":",
"other_el",
"=",
"other",
".",
"select",
"(",
"HoloMap",
",",
"*",
"*",
"key_map",
")",
"if",
"other",
".",
"kdims",
"else",
"other",
"[",
"(",
")",
"]",
"layers",
".",
"append",
"(",
"other_el",
")",
"except",
"KeyError",
":",
"pass",
"return",
"Overlay",
"(",
"layers",
")",
"callback",
"=",
"Callable",
"(",
"dynamic_mul",
",",
"inputs",
"=",
"[",
"self",
",",
"other",
"]",
")",
"callback",
".",
"_is_overlay",
"=",
"True",
"if",
"map_obj",
":",
"return",
"map_obj",
".",
"clone",
"(",
"callback",
"=",
"callback",
",",
"shared_data",
"=",
"False",
",",
"kdims",
"=",
"dimensions",
",",
"streams",
"=",
"streams",
")",
"else",
":",
"return",
"DynamicMap",
"(",
"callback",
"=",
"callback",
",",
"kdims",
"=",
"dimensions",
",",
"streams",
"=",
"streams",
")"
] |
Return Single or Double depending on what kind of string this is . | def _get_string_type_from_token ( token_type ) : return_value = None if token_type in [ TokenType . BeginSingleQuotedLiteral , TokenType . EndSingleQuotedLiteral ] : return_value = "Single" elif token_type in [ TokenType . BeginDoubleQuotedLiteral , TokenType . EndDoubleQuotedLiteral ] : return_value = "Double" assert return_value is not None return return_value | 6,845 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L212-L223 | [
"def",
"start_blocking",
"(",
"self",
")",
":",
"self",
".",
"_cav_started",
".",
"clear",
"(",
")",
"self",
".",
"start",
"(",
")",
"self",
".",
"_cav_started",
".",
"wait",
"(",
")"
] |
Utility function to make a handler for header - body node . | def _make_header_body_handler ( end_body_regex , node_factory , has_footer = True ) : def handler ( tokens , tokens_len , body_index , function_call ) : """Handler function.""" def _end_header_body_definition ( token_index , tokens ) : """Header body termination function.""" if end_body_regex . match ( tokens [ token_index ] . content ) : try : if tokens [ token_index + 1 ] . type == TokenType . LeftParen : return True except IndexError : raise RuntimeError ( "Syntax Error" ) return False token_index , body = _ast_worker ( tokens , tokens_len , body_index , _end_header_body_definition ) extra_kwargs = { } if has_footer : # Handle footer token_index , footer = _handle_function_call ( tokens , tokens_len , token_index ) extra_kwargs = { "footer" : footer } return ( token_index , node_factory ( header = function_call , body = body . statements , line = tokens [ body_index ] . line , col = tokens [ body_index ] . col , index = body_index , * * extra_kwargs ) ) return handler | 6,846 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L248-L289 | [
"def",
"get_object_metadata",
"(",
"obj",
",",
"*",
"*",
"kw",
")",
":",
"# inject metadata of volatile data",
"metadata",
"=",
"{",
"\"actor\"",
":",
"get_user_id",
"(",
")",
",",
"\"roles\"",
":",
"get_roles",
"(",
")",
",",
"\"action\"",
":",
"\"\"",
",",
"\"review_state\"",
":",
"api",
".",
"get_review_status",
"(",
"obj",
")",
",",
"\"active\"",
":",
"api",
".",
"is_active",
"(",
"obj",
")",
",",
"\"snapshot_created\"",
":",
"DateTime",
"(",
")",
".",
"ISO",
"(",
")",
",",
"\"modified\"",
":",
"api",
".",
"get_modification_date",
"(",
"obj",
")",
".",
"ISO",
"(",
")",
",",
"\"remote_address\"",
":",
"\"\"",
",",
"\"user_agent\"",
":",
"\"\"",
",",
"\"referer\"",
":",
"\"\"",
",",
"\"comments\"",
":",
"\"\"",
",",
"}",
"# Update request data",
"metadata",
".",
"update",
"(",
"get_request_data",
"(",
")",
")",
"# allow metadata overrides",
"metadata",
".",
"update",
"(",
"kw",
")",
"return",
"metadata"
] |
Special handler for if - blocks . | def _handle_if_block ( tokens , tokens_len , body_index , function_call ) : # First handle the if statement and body next_index , if_statement = _IF_BLOCK_IF_HANDLER ( tokens , tokens_len , body_index , function_call ) elseif_statements = [ ] else_statement = None footer = None # Keep going until we hit endif while True : # Back up a bit until we found out what terminated the if statement # body assert _RE_END_IF_BODY . match ( tokens [ next_index ] . content ) terminator = tokens [ next_index ] . content . lower ( ) if terminator == "endif" : next_index , footer = _handle_function_call ( tokens , tokens_len , next_index ) break next_index , header = _handle_function_call ( tokens , tokens_len , next_index ) if terminator == "elseif" : next_index , elseif_stmnt = _ELSEIF_BLOCK_HANDLER ( tokens , tokens_len , next_index + 1 , header ) elseif_statements . append ( elseif_stmnt ) elif terminator == "else" : next_index , else_statement = _ELSE_BLOCK_HANDLER ( tokens , tokens_len , next_index + 1 , header ) assert footer is not None return next_index , IfBlock ( if_statement = if_statement , elseif_statements = elseif_statements , else_statement = else_statement , footer = footer , line = if_statement . line , col = if_statement . col , index = body_index ) | 6,847 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L302-L355 | [
"def",
"external_metadata",
"(",
"self",
",",
"datasource_type",
"=",
"None",
",",
"datasource_id",
"=",
"None",
")",
":",
"if",
"datasource_type",
"==",
"'druid'",
":",
"datasource",
"=",
"ConnectorRegistry",
".",
"get_datasource",
"(",
"datasource_type",
",",
"datasource_id",
",",
"db",
".",
"session",
")",
"elif",
"datasource_type",
"==",
"'table'",
":",
"database",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"Database",
")",
".",
"filter_by",
"(",
"id",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'db_id'",
")",
")",
".",
"one",
"(",
")",
")",
"Table",
"=",
"ConnectorRegistry",
".",
"sources",
"[",
"'table'",
"]",
"datasource",
"=",
"Table",
"(",
"database",
"=",
"database",
",",
"table_name",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'table_name'",
")",
",",
"schema",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'schema'",
")",
"or",
"None",
",",
")",
"external_metadata",
"=",
"datasource",
".",
"external_metadata",
"(",
")",
"return",
"self",
".",
"json_response",
"(",
"external_metadata",
")"
] |
Handle function calls which could include a control statement . | def _handle_function_call ( tokens , tokens_len , index ) : def _end_function_call ( token_index , tokens ) : """Function call termination detector.""" return tokens [ token_index ] . type == TokenType . RightParen # First handle the "function call" next_index , call_body = _ast_worker ( tokens , tokens_len , index + 2 , _end_function_call ) function_call = FunctionCall ( name = tokens [ index ] . content , arguments = call_body . arguments , line = tokens [ index ] . line , col = tokens [ index ] . col , index = index ) # Next find a handler for the body and pass control to that try : handler = _FUNCTION_CALL_DISAMBIGUATE [ tokens [ index ] . content . lower ( ) ] except KeyError : handler = None if handler : return handler ( tokens , tokens_len , next_index , function_call ) else : return ( next_index , function_call ) | 6,848 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L368-L400 | [
"def",
"missing_revisions",
"(",
"self",
",",
"doc_id",
",",
"*",
"revisions",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"(",
"self",
".",
"database_url",
",",
"'_missing_revs'",
")",
")",
"data",
"=",
"{",
"doc_id",
":",
"list",
"(",
"revisions",
")",
"}",
"resp",
"=",
"self",
".",
"r_session",
".",
"post",
"(",
"url",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
",",
"cls",
"=",
"self",
".",
"client",
".",
"encoder",
")",
")",
"resp",
".",
"raise_for_status",
"(",
")",
"resp_json",
"=",
"response_to_json_dict",
"(",
"resp",
")",
"missing_revs",
"=",
"resp_json",
"[",
"'missing_revs'",
"]",
".",
"get",
"(",
"doc_id",
")",
"if",
"missing_revs",
"is",
"None",
":",
"missing_revs",
"=",
"[",
"]",
"return",
"missing_revs"
] |
The main collector for all AST functions . | def _ast_worker ( tokens , tokens_len , index , term ) : statements = [ ] arguments = [ ] while index < tokens_len : if term : if term ( index , tokens ) : break # Function call if tokens [ index ] . type == TokenType . Word and index + 1 < tokens_len and tokens [ index + 1 ] . type == TokenType . LeftParen : index , statement = _handle_function_call ( tokens , tokens_len , index ) statements . append ( statement ) # Argument elif _is_word_type ( tokens [ index ] . type ) : arguments . append ( Word ( type = _word_type ( tokens [ index ] . type ) , contents = tokens [ index ] . content , line = tokens [ index ] . line , col = tokens [ index ] . col , index = index ) ) index = index + 1 return ( index , GenericBody ( statements = statements , arguments = arguments ) ) | 6,849 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L403-L438 | [
"def",
"get_placement_solver",
"(",
"service_instance",
")",
":",
"stub",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_new_service_instance_stub",
"(",
"service_instance",
",",
"ns",
"=",
"'pbm/2.0'",
",",
"path",
"=",
"'/pbm/sdk'",
")",
"pbm_si",
"=",
"pbm",
".",
"ServiceInstance",
"(",
"'ServiceInstance'",
",",
"stub",
")",
"try",
":",
"profile_manager",
"=",
"pbm_si",
".",
"RetrieveContent",
"(",
")",
".",
"placementSolver",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"return",
"profile_manager"
] |
Scan a string for tokens and return immediate form tokens . | def _scan_for_tokens ( contents ) : # Regexes are in priority order. Changing the order may alter the # behavior of the lexer scanner = re . Scanner ( [ # Things inside quotes ( r"(?<![^\s\(])([\"\'])(?:(?=(\\?))\2.)*?\1(?![^\s\)])" , lambda s , t : ( TokenType . QuotedLiteral , t ) ) , # Numbers on their own ( r"(?<![^\s\(])-?[0-9]+(?![^\s\)\(])" , lambda s , t : ( TokenType . Number , t ) ) , # Left Paren ( r"\(" , lambda s , t : ( TokenType . LeftParen , t ) ) , # Right Paren ( r"\)" , lambda s , t : ( TokenType . RightParen , t ) ) , # Either a valid function name or variable name. ( r"(?<![^\s\(])[a-zA-z_][a-zA-Z0-9_]*(?![^\s\)\(])" , lambda s , t : ( TokenType . Word , t ) ) , # Variable dereference. ( r"(?<![^\s\(])\${[a-zA-z_][a-zA-Z0-9_]*}(?![^\s\)])" , lambda s , t : ( TokenType . Deref , t ) ) , # Newline ( r"\n" , lambda s , t : ( TokenType . Newline , t ) ) , # Whitespace ( r"\s+" , lambda s , t : ( TokenType . Whitespace , t ) ) , # The beginning of a double-quoted string, terminating at end of line ( r"(?<![^\s\(\\])[\"]([^\"]|\\[\"])*$" , lambda s , t : ( TokenType . BeginDoubleQuotedLiteral , t ) ) , # The end of a double-quoted string ( r"[^\s]*(?<!\\)[\"](?![^\s\)])" , lambda s , t : ( TokenType . EndDoubleQuotedLiteral , t ) ) , # The beginning of a single-quoted string, terminating at end of line ( r"(?<![^\s\(\\])[\']([^\']|\\[\'])*$" , lambda s , t : ( TokenType . BeginSingleQuotedLiteral , t ) ) , # The end of a single-quoted string ( r"[^\s]*(?<!\\)[\'](?![^\s\)])" , lambda s , t : ( TokenType . EndSingleQuotedLiteral , t ) ) , # Begin-RST Comment Block ( r"#.rst:$" , lambda s , t : ( TokenType . BeginRSTComment , t ) ) , # Begin Inline RST ( r"#\[=*\[.rst:$" , lambda s , t : ( TokenType . BeginInlineRST , t ) ) , # End Inline RST ( r"#\]=*\]$" , lambda s , t : ( TokenType . EndInlineRST , t ) ) , # Comment ( r"#" , lambda s , t : ( TokenType . Comment , t ) ) , # Catch-all for literals which are compound statements. ( r"([^\s\(\)]+|[^\s\(]*[^\)]|[^\(][^\s\)]*)" , lambda s , t : ( TokenType . UnquotedLiteral , t ) ) ] ) tokens_return = [ ] lines = contents . splitlines ( True ) lineno = 0 for line in lines : lineno += 1 col = 1 tokens , remaining = scanner . scan ( line ) if remaining != "" : msg = "Unknown tokens found on line {0}: {1}" . format ( lineno , remaining ) raise RuntimeError ( msg ) for token_type , token_contents in tokens : tokens_return . append ( Token ( type = token_type , content = token_contents , line = lineno , col = col ) ) col += len ( token_contents ) return tokens_return | 6,850 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L441-L513 | [
"def",
"cart_db",
"(",
")",
":",
"config",
"=",
"_config_file",
"(",
")",
"_config_test",
"(",
"config",
")",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"Establishing cart connection:\"",
")",
"cart_con",
"=",
"MongoClient",
"(",
"dict",
"(",
"config",
".",
"items",
"(",
"config",
".",
"sections",
"(",
")",
"[",
"0",
"]",
")",
")",
"[",
"'cart_host'",
"]",
")",
"cart_db",
"=",
"cart_con",
".",
"carts",
"return",
"cart_db"
] |
For a range indicated from start to end replace with replacement . | def _replace_token_range ( tokens , start , end , replacement ) : tokens = tokens [ : start ] + replacement + tokens [ end : ] return tokens | 6,851 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L516-L519 | [
"def",
"dSbus_dV",
"(",
"Y",
",",
"V",
")",
":",
"I",
"=",
"Y",
"*",
"V",
"diagV",
"=",
"spdiag",
"(",
"V",
")",
"diagIbus",
"=",
"spdiag",
"(",
"I",
")",
"diagVnorm",
"=",
"spdiag",
"(",
"div",
"(",
"V",
",",
"abs",
"(",
"V",
")",
")",
")",
"# Element-wise division.",
"dS_dVm",
"=",
"diagV",
"*",
"conj",
"(",
"Y",
"*",
"diagVnorm",
")",
"+",
"conj",
"(",
"diagIbus",
")",
"*",
"diagVnorm",
"dS_dVa",
"=",
"1j",
"*",
"diagV",
"*",
"conj",
"(",
"diagIbus",
"-",
"Y",
"*",
"diagV",
")",
"return",
"dS_dVm",
",",
"dS_dVa"
] |
Return true if the token at index is really a comment . | def _is_really_comment ( tokens , index ) : if tokens [ index ] . type == TokenType . Comment : return True # Really a comment in disguise! try : if tokens [ index ] . content . lstrip ( ) [ 0 ] == "#" : return True except IndexError : return False | 6,852 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L522-L532 | [
"def",
"get_hostname",
"(",
"cls",
",",
"container_name",
",",
"client_name",
"=",
"None",
")",
":",
"base_name",
"=",
"container_name",
"for",
"old",
",",
"new",
"in",
"cls",
".",
"hostname_replace",
":",
"base_name",
"=",
"base_name",
".",
"replace",
"(",
"old",
",",
"new",
")",
"if",
"not",
"client_name",
"or",
"client_name",
"==",
"cls",
".",
"default_client_name",
":",
"return",
"base_name",
"client_suffix",
"=",
"client_name",
"for",
"old",
",",
"new",
"in",
"cls",
".",
"hostname_replace",
":",
"client_suffix",
"=",
"client_suffix",
".",
"replace",
"(",
"old",
",",
"new",
")",
"return",
"'{0}-{1}'",
".",
"format",
"(",
"base_name",
",",
"client_suffix",
")"
] |
Return lines of tokens pasted together line by line . | def _paste_tokens_line_by_line ( tokens , token_type , begin , end ) : block_index = begin while block_index < end : rst_line = tokens [ block_index ] . line line_traversal_index = block_index pasted = "" try : while tokens [ line_traversal_index ] . line == rst_line : pasted += tokens [ line_traversal_index ] . content line_traversal_index += 1 except IndexError : assert line_traversal_index == end last_tokens_len = len ( tokens ) tokens = _replace_token_range ( tokens , block_index , line_traversal_index , [ Token ( type = token_type , content = pasted , line = tokens [ block_index ] . line , col = tokens [ block_index ] . col ) ] ) end -= last_tokens_len - len ( tokens ) block_index += 1 return ( block_index , len ( tokens ) , tokens ) | 6,853 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L585-L611 | [
"def",
"synchronizeLayout",
"(",
"primary",
",",
"secondary",
",",
"surface_size",
")",
":",
"primary",
".",
"configure_bound",
"(",
"surface_size",
")",
"secondary",
".",
"configure_bound",
"(",
"surface_size",
")",
"# Check for key size.",
"if",
"(",
"primary",
".",
"key_size",
"<",
"secondary",
".",
"key_size",
")",
":",
"logging",
".",
"warning",
"(",
"'Normalizing key size from secondary to primary'",
")",
"secondary",
".",
"key_size",
"=",
"primary",
".",
"key_size",
"elif",
"(",
"primary",
".",
"key_size",
">",
"secondary",
".",
"key_size",
")",
":",
"logging",
".",
"warning",
"(",
"'Normalizing key size from primary to secondary'",
")",
"primary",
".",
"key_size",
"=",
"secondary",
".",
"key_size",
"if",
"(",
"primary",
".",
"size",
"[",
"1",
"]",
">",
"secondary",
".",
"size",
"[",
"1",
"]",
")",
":",
"logging",
".",
"warning",
"(",
"'Normalizing layout size from secondary to primary'",
")",
"secondary",
".",
"set_size",
"(",
"primary",
".",
"size",
",",
"surface_size",
")",
"elif",
"(",
"primary",
".",
"size",
"[",
"1",
"]",
"<",
"secondary",
".",
"size",
"[",
"1",
"]",
")",
":",
"logging",
".",
"warning",
"(",
"'Normalizing layout size from primary to secondary'",
")",
"primary",
".",
"set_size",
"(",
"secondary",
".",
"size",
",",
"surface_size",
")"
] |
Given a current recorder and a token index try to find a recorder . | def _find_recorder ( recorder , tokens , index ) : if recorder is None : # See if we can start recording something for recorder_factory in _RECORDERS : recorder = recorder_factory . maybe_start_recording ( tokens , index ) if recorder is not None : return recorder return recorder | 6,854 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L814-L824 | [
"def",
"largest_graph",
"(",
"mol",
")",
":",
"mol",
".",
"require",
"(",
"\"Valence\"",
")",
"mol",
".",
"require",
"(",
"\"Topology\"",
")",
"m",
"=",
"clone",
"(",
"mol",
")",
"# Avoid modification of original object",
"if",
"m",
".",
"isolated",
":",
"for",
"k",
"in",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"m",
".",
"isolated",
")",
":",
"m",
".",
"remove_atom",
"(",
"k",
")",
"return",
"m"
] |
Paste multi - line strings comments RST etc together . | def _compress_tokens ( tokens ) : recorder = None def _edge_case_stray_end_quoted ( tokens , index ) : """Convert stray end_quoted_literals to unquoted_literals.""" # In this case, "tokenize" the matched token into what it would # have looked like had the last quote not been there. Put the # last quote on the end of the final token and call it an # unquoted_literal tokens [ index ] = Token ( type = TokenType . UnquotedLiteral , content = tokens [ index ] . content , line = tokens [ index ] . line , col = tokens [ index ] . col ) tokens_len = len ( tokens ) index = 0 with _EdgeCaseStrayParens ( ) as edge_case_stray_parens : edge_cases = [ ( _is_paren_type , edge_case_stray_parens ) , ( _is_end_quoted_type , _edge_case_stray_end_quoted ) , ] while index < tokens_len : recorder = _find_recorder ( recorder , tokens , index ) if recorder is not None : # Do recording result = recorder . consume_token ( tokens , index , tokens_len ) if result is not None : ( index , tokens_len , tokens ) = result recorder = None else : # Handle edge cases for matcher , handler in edge_cases : if matcher ( tokens [ index ] . type ) : handler ( tokens , index ) index += 1 return tokens | 6,855 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L827-L880 | [
"def",
"set_dimensional_calibrations",
"(",
"self",
",",
"dimensional_calibrations",
":",
"typing",
".",
"List",
"[",
"CalibrationModule",
".",
"Calibration",
"]",
")",
"->",
"None",
":",
"self",
".",
"__data_item",
".",
"set_dimensional_calibrations",
"(",
"dimensional_calibrations",
")"
] |
Parse a string called contents for CMake tokens . | def tokenize ( contents ) : tokens = _scan_for_tokens ( contents ) tokens = _compress_tokens ( tokens ) tokens = [ token for token in tokens if token . type != TokenType . Whitespace ] return tokens | 6,856 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L883-L888 | [
"def",
"_intersection",
"(",
"self",
",",
"keys",
",",
"rows",
")",
":",
"# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.",
"if",
"not",
"keys",
":",
"return",
"rows",
"ret",
"=",
"list",
"(",
")",
"for",
"row",
"in",
"rows",
":",
"start_date",
"=",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
"end_date",
"=",
"row",
"[",
"self",
".",
"_key_end_date",
"]",
"for",
"key_start_date",
",",
"key_end_date",
"in",
"keys",
":",
"start_date",
",",
"end_date",
"=",
"Type2JoinHelper",
".",
"_intersect",
"(",
"start_date",
",",
"end_date",
",",
"row",
"[",
"key_start_date",
"]",
",",
"row",
"[",
"key_end_date",
"]",
")",
"if",
"not",
"start_date",
":",
"break",
"if",
"key_start_date",
"not",
"in",
"[",
"self",
".",
"_key_start_date",
",",
"self",
".",
"_key_end_date",
"]",
":",
"del",
"row",
"[",
"key_start_date",
"]",
"if",
"key_end_date",
"not",
"in",
"[",
"self",
".",
"_key_start_date",
",",
"self",
".",
"_key_end_date",
"]",
":",
"del",
"row",
"[",
"key_end_date",
"]",
"if",
"start_date",
":",
"row",
"[",
"self",
".",
"_key_start_date",
"]",
"=",
"start_date",
"row",
"[",
"self",
".",
"_key_end_date",
"]",
"=",
"end_date",
"ret",
".",
"append",
"(",
"row",
")",
"return",
"ret"
] |
Parse a string called contents for an AST and return it . | def parse ( contents , tokens = None ) : # Shortcut for users who are interested in tokens if tokens is None : tokens = [ t for t in tokenize ( contents ) ] token_index , body = _ast_worker ( tokens , len ( tokens ) , 0 , None ) assert token_index == len ( tokens ) assert body . arguments == [ ] return ToplevelBody ( statements = body . statements ) | 6,857 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L891-L902 | [
"def",
"percent_initiated_conversations",
"(",
"records",
")",
":",
"interactions",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"r",
"in",
"records",
":",
"interactions",
"[",
"r",
".",
"correspondent_id",
"]",
".",
"append",
"(",
"r",
")",
"def",
"_percent_initiated",
"(",
"grouped",
")",
":",
"mapped",
"=",
"[",
"(",
"1",
"if",
"conv",
"[",
"0",
"]",
".",
"direction",
"==",
"'out'",
"else",
"0",
",",
"1",
")",
"for",
"conv",
"in",
"_conversations",
"(",
"grouped",
")",
"]",
"return",
"mapped",
"all_couples",
"=",
"[",
"sublist",
"for",
"i",
"in",
"interactions",
".",
"values",
"(",
")",
"for",
"sublist",
"in",
"_percent_initiated",
"(",
"i",
")",
"]",
"if",
"len",
"(",
"all_couples",
")",
"==",
"0",
":",
"init",
",",
"total",
"=",
"0",
",",
"0",
"else",
":",
"init",
",",
"total",
"=",
"list",
"(",
"map",
"(",
"sum",
",",
"list",
"(",
"zip",
"(",
"*",
"all_couples",
")",
")",
")",
")",
"return",
"init",
"/",
"total",
"if",
"total",
"!=",
"0",
"else",
"0"
] |
Return a new _CommentedLineRecorder when it is time to record . | def maybe_start_recording ( tokens , index ) : if _is_really_comment ( tokens , index ) : return _CommentedLineRecorder ( index , tokens [ index ] . line ) return None | 6,858 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L545-L550 | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"req",
",",
"schema",
",",
"error_status_code",
",",
"error_headers",
")",
":",
"status_code",
"=",
"error_status_code",
"or",
"self",
".",
"DEFAULT_VALIDATION_STATUS",
"raise",
"bottle",
".",
"HTTPError",
"(",
"status",
"=",
"status_code",
",",
"body",
"=",
"error",
".",
"messages",
",",
"headers",
"=",
"error_headers",
",",
"exception",
"=",
"error",
",",
")"
] |
Return a new _RSTCommentBlockRecorder when its time to record . | def maybe_start_recording ( tokens , index ) : if tokens [ index ] . type == TokenType . BeginRSTComment : return _RSTCommentBlockRecorder ( index , tokens [ index ] . line ) return None | 6,859 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L624-L629 | [
"def",
"cublasGetVersion",
"(",
"handle",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetVersion_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"version",
".",
"value"
] |
Return a new _InlineRSTRecorder when its time to record . | def maybe_start_recording ( tokens , index ) : if tokens [ index ] . type == TokenType . BeginInlineRST : return _InlineRSTRecorder ( index ) | 6,860 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L666-L669 | [
"def",
"cublasGetVersion",
"(",
"handle",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetVersion_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"version",
".",
"value"
] |
Return a new _MultilineStringRecorder when its time to record . | def maybe_start_recording ( tokens , index ) : if _is_begin_quoted_type ( tokens [ index ] . type ) : string_type = _get_string_type_from_token ( tokens [ index ] . type ) return _MultilineStringRecorder ( index , string_type ) return None | 6,861 | https://github.com/polysquare/cmake-ast/blob/431a32d595d76f1f8f993eb6ddcc79effbadff9d/cmakeast/ast.py#L696-L702 | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"download_request",
")",
":",
"if",
"hasattr",
"(",
"error",
",",
"\"errno\"",
")",
"and",
"error",
".",
"errno",
"==",
"errno",
".",
"EACCES",
":",
"self",
".",
"handle_certificate_problem",
"(",
"str",
"(",
"error",
")",
")",
"else",
":",
"self",
".",
"handle_general_download_error",
"(",
"str",
"(",
"error",
")",
",",
"download_request",
")"
] |
Create stratified k - folds from an indexed dataframe | def stratified_kfold ( df , n_folds ) : sessions = pd . DataFrame . from_records ( list ( df . index . unique ( ) ) ) . groupby ( 0 ) . apply ( lambda x : x [ 1 ] . unique ( ) ) sessions . apply ( lambda x : np . random . shuffle ( x ) ) folds = [ ] for i in range ( n_folds ) : idx = sessions . apply ( lambda x : pd . Series ( x [ i * ( len ( x ) / n_folds ) : ( i + 1 ) * ( len ( x ) / n_folds ) ] ) ) idx = pd . DataFrame ( idx . stack ( ) . reset_index ( level = 1 , drop = True ) ) . set_index ( 0 , append = True ) . index . values folds . append ( df . loc [ idx ] ) return folds | 6,862 | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/examples/keystroke.py#L15-L26 | [
"def",
"_check_error_response",
"(",
"response",
",",
"query",
")",
":",
"if",
"\"error\"",
"in",
"response",
":",
"http_error",
"=",
"[",
"\"HTTP request timed out.\"",
",",
"\"Pool queue is full\"",
"]",
"geo_error",
"=",
"[",
"\"Page coordinates unknown.\"",
",",
"\"One of the parameters gscoord, gspage, gsbbox is required\"",
",",
"\"Invalid coordinate provided\"",
",",
"]",
"err",
"=",
"response",
"[",
"\"error\"",
"]",
"[",
"\"info\"",
"]",
"if",
"err",
"in",
"http_error",
":",
"raise",
"HTTPTimeoutError",
"(",
"query",
")",
"elif",
"err",
"in",
"geo_error",
":",
"raise",
"MediaWikiGeoCoordError",
"(",
"err",
")",
"else",
":",
"raise",
"MediaWikiException",
"(",
"err",
")"
] |
Generates a 2 - state model with lognormal emissions and frequency smoothing | def keystroke_model ( ) : model = Pohmm ( n_hidden_states = 2 , init_spread = 2 , emissions = [ 'lognormal' , 'lognormal' ] , smoothing = 'freq' , init_method = 'obs' , thresh = 1 ) return model | 6,863 | https://github.com/vmonaco/pohmm/blob/c00f8a62d3005a171d424549a55d46c421859ae9/examples/keystroke.py#L123-L131 | [
"def",
"discover_config_path",
"(",
"self",
",",
"config_filename",
":",
"str",
")",
"->",
"str",
":",
"if",
"config_filename",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"config_filename",
")",
":",
"return",
"config_filename",
"for",
"place",
"in",
"_common_places",
":",
"config_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"place",
",",
"config_filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"return",
"config_path",
"return"
] |
start a server that runs python interpreters on connections made to it | def run_backdoor ( address , namespace = None ) : log . info ( "starting on %r" % ( address , ) ) serversock = io . Socket ( ) serversock . setsockopt ( socket . SOL_SOCKET , socket . SO_REUSEADDR , 1 ) serversock . bind ( address ) serversock . listen ( socket . SOMAXCONN ) while 1 : clientsock , address = serversock . accept ( ) log . info ( "connection received from %r" % ( address , ) ) scheduler . schedule ( backdoor_handler , args = ( clientsock , namespace ) ) | 6,864 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/backdoor.py#L40-L67 | [
"def",
"remove",
"(",
"self",
",",
"oid",
")",
":",
"hba",
"=",
"self",
".",
"lookup_by_oid",
"(",
"oid",
")",
"partition",
"=",
"self",
".",
"parent",
"devno",
"=",
"hba",
".",
"properties",
".",
"get",
"(",
"'device-number'",
",",
"None",
")",
"if",
"devno",
":",
"partition",
".",
"devno_free_if_allocated",
"(",
"devno",
")",
"wwpn",
"=",
"hba",
".",
"properties",
".",
"get",
"(",
"'wwpn'",
",",
"None",
")",
"if",
"wwpn",
":",
"partition",
".",
"wwpn_free_if_allocated",
"(",
"wwpn",
")",
"assert",
"'hba-uris'",
"in",
"partition",
".",
"properties",
"hba_uris",
"=",
"partition",
".",
"properties",
"[",
"'hba-uris'",
"]",
"hba_uris",
".",
"remove",
"(",
"hba",
".",
"uri",
")",
"super",
"(",
"FakedHbaManager",
",",
"self",
")",
".",
"remove",
"(",
"oid",
")"
] |
start an interactive python interpreter on an existing connection | def backdoor_handler ( clientsock , namespace = None ) : namespace = { } if namespace is None else namespace . copy ( ) console = code . InteractiveConsole ( namespace ) multiline_statement = [ ] stdout , stderr = StringIO ( ) , StringIO ( ) clientsock . sendall ( PREAMBLE + "\n" + PS1 ) for input_line in _produce_lines ( clientsock ) : input_line = input_line . rstrip ( ) if input_line : input_line = '\n' + input_line source = '\n' . join ( multiline_statement ) + input_line response = '' with _wrap_stdio ( stdout , stderr ) : result = console . runsource ( source ) response += stdout . getvalue ( ) err = stderr . getvalue ( ) if err : response += err if err or not result : multiline_statement = [ ] response += PS1 else : multiline_statement . append ( input_line ) response += PS2 clientsock . sendall ( response ) | 6,865 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/backdoor.py#L70-L112 | [
"def",
"removeBetweenPercentile",
"(",
"requestContext",
",",
"seriesList",
",",
"n",
")",
":",
"if",
"n",
"<",
"50",
":",
"n",
"=",
"100",
"-",
"n",
"transposed",
"=",
"list",
"(",
"zip_longest",
"(",
"*",
"seriesList",
")",
")",
"lowPercentiles",
"=",
"[",
"_getPercentile",
"(",
"col",
",",
"100",
"-",
"n",
")",
"for",
"col",
"in",
"transposed",
"]",
"highPercentiles",
"=",
"[",
"_getPercentile",
"(",
"col",
",",
"n",
")",
"for",
"col",
"in",
"transposed",
"]",
"return",
"[",
"l",
"for",
"l",
"in",
"seriesList",
"if",
"sum",
"(",
"[",
"not",
"lowPercentiles",
"[",
"index",
"]",
"<",
"val",
"<",
"highPercentiles",
"[",
"index",
"]",
"for",
"index",
",",
"val",
"in",
"enumerate",
"(",
"l",
")",
"]",
")",
">",
"0",
"]"
] |
Prepare the parameters passed to the templatetag | def prepare_params ( self ) : if self . options . resolve_fragment : self . fragment_name = self . node . fragment_name . resolve ( self . context ) else : self . fragment_name = str ( self . node . fragment_name ) # Remove quotes that surround the name for char in '\'\"' : if self . fragment_name . startswith ( char ) or self . fragment_name . endswith ( char ) : if self . fragment_name . startswith ( char ) and self . fragment_name . endswith ( char ) : self . fragment_name = self . fragment_name [ 1 : - 1 ] break else : raise ValueError ( 'Number of quotes around the fragment name is incoherent' ) self . expire_time = self . get_expire_time ( ) if self . options . versioning : self . version = force_bytes ( self . get_version ( ) ) self . vary_on = [ template . Variable ( var ) . resolve ( self . context ) for var in self . node . vary_on ] | 6,866 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L234-L256 | [
"def",
"from_rep",
"(",
"u",
")",
":",
"if",
"isinstance",
"(",
"u",
",",
"pyversion",
".",
"string_types",
")",
":",
"return",
"uuid",
".",
"UUID",
"(",
"u",
")",
"# hack to remove signs",
"a",
"=",
"ctypes",
".",
"c_ulong",
"(",
"u",
"[",
"0",
"]",
")",
"b",
"=",
"ctypes",
".",
"c_ulong",
"(",
"u",
"[",
"1",
"]",
")",
"combined",
"=",
"a",
".",
"value",
"<<",
"64",
"|",
"b",
".",
"value",
"return",
"uuid",
".",
"UUID",
"(",
"int",
"=",
"combined",
")"
] |
Return the expire time passed to the templatetag . Must be None or an integer . | def get_expire_time ( self ) : try : expire_time = self . node . expire_time . resolve ( self . context ) except template . VariableDoesNotExist : raise template . TemplateSyntaxError ( '"%s" tag got an unknown variable: %r' % ( self . node . nodename , self . node . expire_time . var ) ) try : if expire_time is not None : expire_time = str ( expire_time ) if not expire_time . isdigit ( ) : raise TypeError expire_time = int ( expire_time ) except ( ValueError , TypeError ) : raise template . TemplateSyntaxError ( '"%s" tag got a non-integer (or None) timeout value: %r' % ( self . node . nodename , expire_time ) ) return expire_time | 6,867 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L258-L281 | [
"def",
"get_canonical_headers",
"(",
"headers",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"[",
"]",
"elif",
"isinstance",
"(",
"headers",
",",
"dict",
")",
":",
"headers",
"=",
"list",
"(",
"headers",
".",
"items",
"(",
")",
")",
"if",
"not",
"headers",
":",
"return",
"[",
"]",
",",
"[",
"]",
"normalized",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"key",
",",
"val",
"in",
"headers",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"val",
"=",
"MULTIPLE_SPACES",
".",
"sub",
"(",
"\" \"",
",",
"val",
".",
"strip",
"(",
")",
")",
"normalized",
"[",
"key",
"]",
".",
"append",
"(",
"val",
")",
"ordered_headers",
"=",
"sorted",
"(",
"(",
"key",
",",
"\",\"",
".",
"join",
"(",
"val",
")",
")",
"for",
"key",
",",
"val",
"in",
"normalized",
".",
"items",
"(",
")",
")",
"canonical_headers",
"=",
"[",
"\"{}:{}\"",
".",
"format",
"(",
"*",
"item",
")",
"for",
"item",
"in",
"ordered_headers",
"]",
"return",
"canonical_headers",
",",
"ordered_headers"
] |
Return the stringified version passed to the templatetag . | def get_version ( self ) : if not self . node . version : return None try : version = smart_str ( '%s' % self . node . version . resolve ( self . context ) ) except template . VariableDoesNotExist : raise template . TemplateSyntaxError ( '"%s" tag got an unknown variable: %r' % ( self . node . nodename , self . node . version . var ) ) return '%s' % version | 6,868 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L283-L295 | [
"def",
"total_flux",
"(",
"flux",
",",
"A",
")",
":",
"X",
"=",
"set",
"(",
"np",
".",
"arange",
"(",
"flux",
".",
"shape",
"[",
"0",
"]",
")",
")",
"# total state space",
"A",
"=",
"set",
"(",
"A",
")",
"notA",
"=",
"X",
".",
"difference",
"(",
"A",
")",
"\"\"\"Extract rows corresponding to A\"\"\"",
"W",
"=",
"flux",
".",
"tocsr",
"(",
")",
"W",
"=",
"W",
"[",
"list",
"(",
"A",
")",
",",
":",
"]",
"\"\"\"Extract columns corresonding to X\\A\"\"\"",
"W",
"=",
"W",
".",
"tocsc",
"(",
")",
"W",
"=",
"W",
"[",
":",
",",
"list",
"(",
"notA",
")",
"]",
"F",
"=",
"W",
".",
"sum",
"(",
")",
"return",
"F"
] |
Take all the arguments passed after the fragment name and return a hashed version which will be used in the cache key | def hash_args ( self ) : return hashlib . md5 ( force_bytes ( ':' . join ( [ urlquote ( force_bytes ( var ) ) for var in self . vary_on ] ) ) ) . hexdigest ( ) | 6,869 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L297-L302 | [
"def",
"get_stats",
"(",
"self",
")",
":",
"canRequestBusStatistics",
"(",
"self",
".",
"_write_handle",
")",
"stats",
"=",
"structures",
".",
"BusStatistics",
"(",
")",
"canGetBusStatistics",
"(",
"self",
".",
"_write_handle",
",",
"ctypes",
".",
"pointer",
"(",
"stats",
")",
",",
"ctypes",
".",
"sizeof",
"(",
"stats",
")",
")",
"return",
"stats"
] |
Return the arguments to be passed to the base cache key returned by get_base_cache_key . | def get_cache_key_args ( self ) : cache_key_args = dict ( nodename = self . node . nodename , name = self . fragment_name , hash = self . hash_args ( ) , ) if self . options . include_pk : cache_key_args [ 'pk' ] = self . get_pk ( ) return cache_key_args | 6,870 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L326-L338 | [
"def",
"IOWR",
"(",
"cls",
",",
"op",
",",
"structure",
")",
":",
"return",
"cls",
".",
"_IOC",
"(",
"READ",
"|",
"WRITE",
",",
"op",
",",
"structure",
")"
] |
Set content into the cache | def cache_set ( self , to_cache ) : self . cache . set ( self . cache_key , to_cache , self . expire_time ) | 6,871 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L362-L366 | [
"def",
"log_sum_exp",
"(",
"self",
",",
"x",
",",
"axis",
")",
":",
"x_max",
"=",
"np",
".",
"max",
"(",
"x",
",",
"axis",
"=",
"axis",
")",
"if",
"axis",
"==",
"1",
":",
"return",
"x_max",
"+",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"exp",
"(",
"x",
"-",
"x_max",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
")",
",",
"axis",
"=",
"1",
")",
")",
"else",
":",
"return",
"x_max",
"+",
"np",
".",
"log",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"exp",
"(",
"x",
"-",
"x_max",
")",
",",
"axis",
"=",
"0",
")",
")"
] |
Render the template and save the generated content | def render_node ( self ) : self . content = self . node . nodelist . render ( self . context ) | 6,872 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L421-L425 | [
"def",
"_orthogonalize",
"(",
"X",
")",
":",
"if",
"X",
".",
"size",
"==",
"X",
".",
"shape",
"[",
"0",
"]",
":",
"return",
"X",
"from",
"scipy",
".",
"linalg",
"import",
"pinv",
",",
"norm",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
":",
"X",
"[",
":",
",",
"i",
"]",
"-=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"X",
"[",
":",
",",
"i",
"]",
",",
"X",
"[",
":",
",",
":",
"i",
"]",
")",
",",
"pinv",
"(",
"X",
"[",
":",
",",
":",
"i",
"]",
")",
")",
"# X[:, i] /= norm(X[:, i])",
"return",
"X"
] |
Render the template apply options on it and save it to the cache . | def create_content ( self ) : self . render_node ( ) if self . options . compress_spaces : self . content = self . RE_SPACELESS . sub ( ' ' , self . content ) if self . options . compress : to_cache = self . encode_content ( ) else : to_cache = self . content to_cache = self . join_content_version ( to_cache ) try : self . cache_set ( to_cache ) except Exception : if is_template_debug_activated ( ) : raise logger . exception ( 'Error when saving the cached template fragment' ) | 6,873 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L427-L448 | [
"def",
"woe",
"(",
"df",
",",
"feature_name",
",",
"target_name",
")",
":",
"def",
"group_woe",
"(",
"group",
")",
":",
"event",
"=",
"float",
"(",
"group",
".",
"sum",
"(",
")",
")",
"non_event",
"=",
"group",
".",
"shape",
"[",
"0",
"]",
"-",
"event",
"rel_event",
"=",
"event",
"/",
"event_total",
"rel_non_event",
"=",
"non_event",
"/",
"non_event_total",
"return",
"np",
".",
"log",
"(",
"rel_non_event",
"/",
"rel_event",
")",
"*",
"100",
"if",
"df",
"[",
"target_name",
"]",
".",
"nunique",
"(",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'Target column should be binary (1/0).'",
")",
"event_total",
"=",
"float",
"(",
"df",
"[",
"df",
"[",
"target_name",
"]",
"==",
"1.0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
"non_event_total",
"=",
"float",
"(",
"df",
".",
"shape",
"[",
"0",
"]",
"-",
"event_total",
")",
"woe_vals",
"=",
"df",
".",
"groupby",
"(",
"feature_name",
")",
"[",
"target_name",
"]",
".",
"transform",
"(",
"group_woe",
")",
"return",
"woe_vals"
] |
Return the templatetags module name for which the current class is used . It s used to render the nocache blocks by loading the correct module | def get_templatetag_module ( cls ) : if cls not in CacheTag . _templatetags_modules : # find the library including the main templatetag of the current class all_tags = cls . get_all_tags_and_filters_by_function ( ) [ 'tags' ] CacheTag . _templatetags_modules [ cls ] = all_tags [ CacheTag . _templatetags [ cls ] [ 'cache' ] ] [ 0 ] return CacheTag . _templatetags_modules [ cls ] | 6,874 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L562-L571 | [
"def",
"split",
"(",
"self",
",",
"verbose",
"=",
"None",
",",
"end_in_new_line",
"=",
"None",
")",
":",
"elapsed_time",
"=",
"self",
".",
"get_elapsed_time",
"(",
")",
"self",
".",
"split_elapsed_time",
".",
"append",
"(",
"elapsed_time",
")",
"self",
".",
"_cumulative_elapsed_time",
"+=",
"elapsed_time",
"self",
".",
"_elapsed_time",
"=",
"datetime",
".",
"timedelta",
"(",
")",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"self",
".",
"verbose_end",
"if",
"verbose",
":",
"if",
"end_in_new_line",
"is",
"None",
":",
"end_in_new_line",
"=",
"self",
".",
"end_in_new_line",
"if",
"end_in_new_line",
":",
"self",
".",
"log",
"(",
"\"{} done in {}\"",
".",
"format",
"(",
"self",
".",
"description",
",",
"elapsed_time",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"\" done in {}\"",
".",
"format",
"(",
"elapsed_time",
")",
")",
"self",
".",
"_start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")"
] |
Render the nocache blocks of the content and return the whole html | def render_nocache ( self ) : tmpl = template . Template ( '' . join ( [ # start by loading the cache library template . BLOCK_TAG_START , 'load %s' % self . get_templatetag_module ( ) , template . BLOCK_TAG_END , # and surround the cached template by "raw" tags self . RAW_TOKEN_START , self . content , self . RAW_TOKEN_END , ] ) ) return tmpl . render ( self . context ) | 6,875 | https://github.com/twidi/django-adv-cache-tag/blob/811f8db4dac73667c7d2fe0ea97a24969593eb8a/adv_cache_tag/tag.py#L573-L588 | [
"def",
"_init_rabit",
"(",
")",
":",
"if",
"_LIB",
"is",
"not",
"None",
":",
"_LIB",
".",
"RabitGetRank",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitGetWorldSize",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitIsDistributed",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"_LIB",
".",
"RabitVersionNumber",
".",
"restype",
"=",
"ctypes",
".",
"c_int"
] |
Deactivate user accounts based on Active Directory s userAccountControl flags . Requires userAccountControl to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES . | def user_active_directory_deactivate ( user , attributes , created , updated ) : try : user_account_control = int ( attributes [ 'userAccountControl' ] [ 0 ] ) if user_account_control & 2 : user . is_active = False except KeyError : pass | 6,876 | https://github.com/marchete/django-adldap-sync/blob/f6be226a4fb2a433d22e95043bd656ce902f8254/adldap_sync/callbacks.py#L1-L12 | [
"def",
"_get_videoname",
"(",
"cls",
",",
"videofile",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"videofile",
")",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"[",
"0",
"]",
"return",
"name"
] |
Get the contents of a string between two characters | def _get_contents_between ( string , opener , closer ) : opener_location = string . index ( opener ) closer_location = string . index ( closer ) content = string [ opener_location + 1 : closer_location ] return content | 6,877 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L29-L36 | [
"def",
"catalogFactory",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"fn",
"=",
"lambda",
"member",
":",
"inspect",
".",
"isclass",
"(",
"member",
")",
"and",
"member",
".",
"__module__",
"==",
"__name__",
"catalogs",
"=",
"odict",
"(",
"inspect",
".",
"getmembers",
"(",
"sys",
".",
"modules",
"[",
"__name__",
"]",
",",
"fn",
")",
")",
"if",
"name",
"not",
"in",
"list",
"(",
"catalogs",
".",
"keys",
"(",
")",
")",
":",
"msg",
"=",
"\"%s not found in catalogs:\\n %s\"",
"%",
"(",
"name",
",",
"list",
"(",
"kernels",
".",
"keys",
"(",
")",
")",
")",
"logger",
".",
"error",
"(",
"msg",
")",
"msg",
"=",
"\"Unrecognized catalog: %s\"",
"%",
"name",
"raise",
"Exception",
"(",
"msg",
")",
"return",
"catalogs",
"[",
"name",
"]",
"(",
"*",
"*",
"kwargs",
")"
] |
Make sure thre is no whitespace in the given string . Will raise a ValueError if whitespace is detected | def _check_whitespace ( string ) : if string . count ( ' ' ) + string . count ( '\t' ) + string . count ( '\n' ) > 0 : raise ValueError ( INSTRUCTION_HAS_WHITESPACE ) | 6,878 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L39-L45 | [
"def",
"prepare_blobs",
"(",
"self",
")",
":",
"self",
".",
"raw_header",
"=",
"self",
".",
"extract_header",
"(",
")",
"if",
"self",
".",
"cache_enabled",
":",
"self",
".",
"_cache_offsets",
"(",
")"
] |
Checks that the parameters given are not empty . Ones with prefix symbols can be denoted by including the prefix in symbols | def _check_parameters ( parameters , symbols ) : for param in parameters : if not param : raise ValueError ( EMPTY_PARAMETER ) elif ( param [ 0 ] in symbols ) and ( not param [ 1 : ] ) : print ( param ) raise ValueError ( EMPTY_KEYWORD_PARAMETER ) | 6,879 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L71-L81 | [
"def",
"get_game_logs",
"(",
"self",
")",
":",
"logs",
"=",
"self",
".",
"response",
".",
"json",
"(",
")",
"[",
"'resultSets'",
"]",
"[",
"0",
"]",
"[",
"'rowSet'",
"]",
"headers",
"=",
"self",
".",
"response",
".",
"json",
"(",
")",
"[",
"'resultSets'",
"]",
"[",
"0",
"]",
"[",
"'headers'",
"]",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"logs",
",",
"columns",
"=",
"headers",
")",
"df",
".",
"GAME_DATE",
"=",
"pd",
".",
"to_datetime",
"(",
"df",
".",
"GAME_DATE",
")",
"return",
"df"
] |
Checks the dependencies constructor . Looks to make sure that the dependencies are the first things defined | def _check_dependencies ( string ) : opener , closer = '(' , ')' _check_enclosing_characters ( string , opener , closer ) if opener in string : if string [ 0 ] != opener : raise ValueError ( DEPENDENCIES_NOT_FIRST ) ret = True else : ret = False return ret | 6,880 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L84-L97 | [
"def",
"store_tokens",
"(",
"self",
",",
"access_token",
",",
"id_token",
")",
":",
"session",
"=",
"self",
".",
"request",
".",
"session",
"if",
"self",
".",
"get_settings",
"(",
"'OIDC_STORE_ACCESS_TOKEN'",
",",
"False",
")",
":",
"session",
"[",
"'oidc_access_token'",
"]",
"=",
"access_token",
"if",
"self",
".",
"get_settings",
"(",
"'OIDC_STORE_ID_TOKEN'",
",",
"False",
")",
":",
"session",
"[",
"'oidc_id_token'",
"]",
"=",
"id_token"
] |
Checks the building options to make sure that they are defined last after the task name and the dependencies | def _check_building_options ( string ) : opener , closer = '{' , '}' _check_enclosing_characters ( string , opener , closer ) if opener in string : if string [ - 1 ] != closer : raise ValueError ( OPTIONS_NOT_LAST ) ret = True else : ret = False return ret | 6,881 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L100-L113 | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"private_file",
"=",
"self",
".",
"get_private_file",
"(",
")",
"if",
"not",
"self",
".",
"can_access_file",
"(",
"private_file",
")",
":",
"return",
"HttpResponseForbidden",
"(",
"'Private storage access denied'",
")",
"if",
"not",
"private_file",
".",
"exists",
"(",
")",
":",
"return",
"self",
".",
"serve_file_not_found",
"(",
"private_file",
")",
"else",
":",
"return",
"self",
".",
"serve_file",
"(",
"private_file",
")"
] |
This function actually parses the dependencies are sorts them into the buildable and given dependencies | def _parse_dependencies ( string ) : contents = _get_contents_between ( string , '(' , ')' ) unsorted_dependencies = contents . split ( ',' ) _check_parameters ( unsorted_dependencies , ( '?' , ) ) buildable_dependencies = [ ] given_dependencies = [ ] for dependency in unsorted_dependencies : if dependency [ 0 ] == '?' : given_dependencies . append ( dependency [ 1 : ] ) else : buildable_dependencies . append ( dependency ) string = string [ string . index ( ')' ) + 1 : ] return buildable_dependencies , given_dependencies , string | 6,882 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L135-L153 | [
"def",
"get_rng",
"(",
"obj",
"=",
"None",
")",
":",
"seed",
"=",
"(",
"id",
"(",
"obj",
")",
"+",
"os",
".",
"getpid",
"(",
")",
"+",
"int",
"(",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"\"%Y%m%d%H%M%S%f\"",
")",
")",
")",
"%",
"4294967295",
"if",
"_RNG_SEED",
"is",
"not",
"None",
":",
"seed",
"=",
"_RNG_SEED",
"return",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")"
] |
This function takes an entire instruction in the form of a string and will parse the entire string and return a dictionary of the fields gathered from the parsing | def parseString ( string ) : buildable_dependencies = [ ] given_dependencies = [ ] output_directory = None output_format = None building_directory = None output_name = None _check_whitespace ( string ) there_are_dependencies = _check_dependencies ( string ) if there_are_dependencies : buildable_dependencies , given_dependencies , string = _parse_dependencies ( string ) there_are_options = _check_building_options ( string ) if there_are_options : output_directory , output_format , building_directory , string = _parse_building_options ( string ) if string [ 0 ] == '>' : string = string [ 1 : ] if string [ - 1 ] == '>' : string = string [ : - 1 ] is_a_flow_operator = _check_flow_operator ( string ) if is_a_flow_operator : greater_than_location = string . index ( '>' ) output_name = string [ greater_than_location + 1 : ] string = string [ : greater_than_location ] ret = object ( ) ret . input_name = string ret . output_name = output_name ret . buildable_dependencies = buildable_dependencies ret . given_dependencies = given_dependencies ret . output_format = output_format ret . building_directory = building_directory ret . output_directory = output_directory return ret | 6,883 | https://github.com/nickpandolfi/Cyther/blob/9fb0bd77af594008aa6ee8af460aa8c953abf5bc/cyther/parser.py#L195-L241 | [
"def",
"_get_site_amplification_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"s_b",
",",
"s_c",
",",
"s_d",
"=",
"self",
".",
"_get_site_dummy_variables",
"(",
"vs30",
")",
"return",
"(",
"C",
"[",
"\"sB\"",
"]",
"*",
"s_b",
")",
"+",
"(",
"C",
"[",
"\"sC\"",
"]",
"*",
"s_c",
")",
"+",
"(",
"C",
"[",
"\"sD\"",
"]",
"*",
"s_d",
")"
] |
Return specified alias or if none the alias associated with the provided credentials . | def GetAlias ( session = None ) : if session is not None : return session [ 'alias' ] if not clc . ALIAS : clc . v2 . API . _Login ( ) return ( clc . ALIAS ) | 6,884 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L35-L45 | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"random_state",
"=",
"np",
".",
"random",
")",
":",
"X",
",",
"y",
"=",
"self",
".",
"_prepare_inputs",
"(",
"X",
",",
"y",
",",
"ensure_min_samples",
"=",
"2",
")",
"chunks",
"=",
"Constraints",
"(",
"y",
")",
".",
"chunks",
"(",
"num_chunks",
"=",
"self",
".",
"num_chunks",
",",
"chunk_size",
"=",
"self",
".",
"chunk_size",
",",
"random_state",
"=",
"random_state",
")",
"return",
"RCA",
".",
"fit",
"(",
"self",
",",
"X",
",",
"chunks",
")"
] |
Return specified location or if none the default location associated with the provided credentials and alias . | def GetLocation ( session = None ) : if session is not None : return session [ 'location' ] if not clc . LOCATION : clc . v2 . API . _Login ( ) return ( clc . LOCATION ) | 6,885 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L49-L59 | [
"def",
"loop",
"(",
"self",
")",
":",
"while",
"True",
":",
"sleep",
"(",
"1",
")",
"new_file_list",
"=",
"self",
".",
"walk",
"(",
"self",
".",
"file_path",
",",
"{",
"}",
")",
"if",
"new_file_list",
"!=",
"self",
".",
"file_list",
":",
"if",
"self",
".",
"debug",
":",
"self",
".",
"diff_list",
"(",
"new_file_list",
",",
"self",
".",
"file_list",
")",
"self",
".",
"run_tests",
"(",
")",
"self",
".",
"file_list",
"=",
"new_file_list"
] |
Returns the primary datacenter object associated with the account . | def PrimaryDatacenter ( self ) : return ( clc . v2 . Datacenter ( alias = self . alias , location = self . data [ 'primaryDataCenter' ] , session = self . session ) ) | 6,886 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/account.py#L94-L104 | [
"def",
"silence",
"(",
"self",
",",
"seq_set",
":",
"SequenceSet",
",",
"flag_set",
":",
"AbstractSet",
"[",
"Flag",
"]",
",",
"flag_op",
":",
"FlagOp",
")",
"->",
"None",
":",
"session_flags",
"=",
"self",
".",
"session_flags",
"permanent_flag_set",
"=",
"self",
".",
"permanent_flags",
"&",
"flag_set",
"session_flag_set",
"=",
"session_flags",
"&",
"flag_set",
"for",
"seq",
",",
"msg",
"in",
"self",
".",
"_messages",
".",
"get_all",
"(",
"seq_set",
")",
":",
"msg_flags",
"=",
"msg",
".",
"permanent_flags",
"msg_sflags",
"=",
"session_flags",
".",
"get",
"(",
"msg",
".",
"uid",
")",
"updated_flags",
"=",
"flag_op",
".",
"apply",
"(",
"msg_flags",
",",
"permanent_flag_set",
")",
"updated_sflags",
"=",
"flag_op",
".",
"apply",
"(",
"msg_sflags",
",",
"session_flag_set",
")",
"if",
"msg_flags",
"!=",
"updated_flags",
":",
"self",
".",
"_silenced_flags",
".",
"add",
"(",
"(",
"msg",
".",
"uid",
",",
"updated_flags",
")",
")",
"if",
"msg_sflags",
"!=",
"updated_sflags",
":",
"self",
".",
"_silenced_sflags",
".",
"add",
"(",
"(",
"msg",
".",
"uid",
",",
"updated_sflags",
")",
")"
] |
Saves the actual file in the store . | def add_file ( self , name , filename , compress_hint = True ) : return self . add_stream ( name , open ( filename , 'rb' ) ) | 6,887 | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L38-L47 | [
"def",
"podcasts_iter",
"(",
"self",
",",
"*",
",",
"device_id",
"=",
"None",
",",
"page_size",
"=",
"250",
")",
":",
"if",
"device_id",
"is",
"None",
":",
"device_id",
"=",
"self",
".",
"device_id",
"start_token",
"=",
"None",
"prev_items",
"=",
"None",
"while",
"True",
":",
"response",
"=",
"self",
".",
"_call",
"(",
"mc_calls",
".",
"PodcastSeries",
",",
"device_id",
",",
"max_results",
"=",
"page_size",
",",
"start_token",
"=",
"start_token",
")",
"items",
"=",
"response",
".",
"body",
".",
"get",
"(",
"'data'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'items'",
",",
"[",
"]",
")",
"# Google does some weird shit.",
"if",
"items",
"!=",
"prev_items",
":",
"subscribed_podcasts",
"=",
"[",
"item",
"for",
"item",
"in",
"items",
"if",
"item",
".",
"get",
"(",
"'userPreferences'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'subscribed'",
")",
"]",
"yield",
"subscribed_podcasts",
"prev_items",
"=",
"items",
"else",
":",
"break",
"start_token",
"=",
"response",
".",
"body",
".",
"get",
"(",
"'nextPageToken'",
")",
"if",
"start_token",
"is",
"None",
":",
"break"
] |
Saves the content of file named name to filename . | def get_file ( self , name , filename ) : stream , vname = self . get_stream ( name ) path , version = split_name ( vname ) dir_path = os . path . dirname ( filename ) if dir_path : mkdir ( dir_path ) with open ( filename , 'wb' ) as f : shutil . copyfileobj ( stream , f ) return vname | 6,888 | https://github.com/sio2project/filetracker/blob/359b474850622e3d0c25ee2596d7242c02f84efb/filetracker/client/data_store.py#L80-L98 | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_access",
"is",
"not",
"None",
":",
"_logger",
".",
"debug",
"(",
"\"Cleaning up\"",
")",
"pci_cleanup",
"(",
"self",
".",
"_access",
")",
"self",
".",
"_access",
"=",
"None"
] |
Removes the tlink for the given tlink identifier | def remove_this_tlink ( self , tlink_id ) : for tlink in self . get_tlinks ( ) : if tlink . get_id ( ) == tlink_id : self . node . remove ( tlink . get_node ( ) ) break | 6,889 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/temporal_data.py#L344-L353 | [
"def",
"lose",
"(",
")",
":",
"changed",
"=",
"False",
"with",
"open",
"(",
"settings",
".",
"HOSTS_FILE",
",",
"\"r\"",
")",
"as",
"hosts_file",
":",
"new_file",
"=",
"[",
"]",
"in_block",
"=",
"False",
"for",
"line",
"in",
"hosts_file",
":",
"if",
"in_block",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"settings",
".",
"END_TOKEN",
":",
"in_block",
"=",
"False",
"changed",
"=",
"True",
"elif",
"line",
".",
"strip",
"(",
")",
"==",
"settings",
".",
"START_TOKEN",
":",
"in_block",
"=",
"True",
"else",
":",
"new_file",
".",
"append",
"(",
"line",
")",
"if",
"changed",
":",
"with",
"open",
"(",
"settings",
".",
"HOSTS_FILE",
",",
"\"w\"",
")",
"as",
"hosts_file",
":",
"hosts_file",
".",
"write",
"(",
"\"\"",
".",
"join",
"(",
"new_file",
")",
")",
"reset_network",
"(",
"\"Concentration is now lost :(.\"",
")"
] |
Removes the predicate anchor for the given predicate anchor identifier | def remove_this_predicateAnchor ( self , predAnch_id ) : for predAnch in self . get_predicateAnchors ( ) : if predAnch . get_id ( ) == predAnch_id : self . node . remove ( predAnch . get_node ( ) ) break | 6,890 | https://github.com/cltl/KafNafParserPy/blob/9bc32e803c176404b255ba317479b8780ed5f569/KafNafParserPy/temporal_data.py#L363-L372 | [
"def",
"set_options",
"(",
"self",
",",
"options",
")",
":",
"# COMMAND LINE OPTIONS",
"self",
".",
"wipe",
"=",
"options",
".",
"get",
"(",
"\"wipe\"",
")",
"self",
".",
"test_run",
"=",
"options",
".",
"get",
"(",
"\"test_run\"",
")",
"self",
".",
"quiet",
"=",
"options",
".",
"get",
"(",
"\"test_run\"",
")",
"self",
".",
"container_name",
"=",
"options",
".",
"get",
"(",
"\"container\"",
")",
"self",
".",
"verbosity",
"=",
"int",
"(",
"options",
".",
"get",
"(",
"\"verbosity\"",
")",
")",
"self",
".",
"syncmedia",
"=",
"options",
".",
"get",
"(",
"\"syncmedia\"",
")",
"self",
".",
"syncstatic",
"=",
"options",
".",
"get",
"(",
"\"syncstatic\"",
")",
"if",
"self",
".",
"test_run",
":",
"self",
".",
"verbosity",
"=",
"2",
"cli_includes",
"=",
"options",
".",
"get",
"(",
"\"includes\"",
")",
"cli_excludes",
"=",
"options",
".",
"get",
"(",
"\"excludes\"",
")",
"# CUMULUS CONNECTION AND SETTINGS FROM SETTINGS.PY",
"if",
"self",
".",
"syncmedia",
"and",
"self",
".",
"syncstatic",
":",
"raise",
"CommandError",
"(",
"\"options --media and --static are mutually exclusive\"",
")",
"if",
"not",
"self",
".",
"container_name",
":",
"if",
"self",
".",
"syncmedia",
":",
"self",
".",
"container_name",
"=",
"CUMULUS",
"[",
"\"CONTAINER\"",
"]",
"elif",
"self",
".",
"syncstatic",
":",
"self",
".",
"container_name",
"=",
"CUMULUS",
"[",
"\"STATIC_CONTAINER\"",
"]",
"else",
":",
"raise",
"CommandError",
"(",
"\"must select one of the required options, either --media or --static\"",
")",
"settings_includes",
"=",
"CUMULUS",
"[",
"\"INCLUDE_LIST\"",
"]",
"settings_excludes",
"=",
"CUMULUS",
"[",
"\"EXCLUDE_LIST\"",
"]",
"# PATH SETTINGS",
"if",
"self",
".",
"syncmedia",
":",
"self",
".",
"file_root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"settings",
".",
"MEDIA_ROOT",
")",
"self",
".",
"file_url",
"=",
"settings",
".",
"MEDIA_URL",
"elif",
"self",
".",
"syncstatic",
":",
"self",
".",
"file_root",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"settings",
".",
"STATIC_ROOT",
")",
"self",
".",
"file_url",
"=",
"settings",
".",
"STATIC_URL",
"if",
"not",
"self",
".",
"file_root",
".",
"endswith",
"(",
"\"/\"",
")",
":",
"self",
".",
"file_root",
"=",
"self",
".",
"file_root",
"+",
"\"/\"",
"if",
"self",
".",
"file_url",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"self",
".",
"file_url",
"=",
"self",
".",
"file_url",
"[",
"1",
":",
"]",
"# SYNCSTATIC VARS",
"# combine includes and excludes from the cli and django settings file",
"self",
".",
"includes",
"=",
"list",
"(",
"set",
"(",
"cli_includes",
"+",
"settings_includes",
")",
")",
"self",
".",
"excludes",
"=",
"list",
"(",
"set",
"(",
"cli_excludes",
"+",
"settings_excludes",
")",
")",
"# transform glob patterns to regular expressions",
"self",
".",
"local_filenames",
"=",
"[",
"]",
"self",
".",
"create_count",
"=",
"0",
"self",
".",
"upload_count",
"=",
"0",
"self",
".",
"update_count",
"=",
"0",
"self",
".",
"skip_count",
"=",
"0",
"self",
".",
"delete_count",
"=",
"0"
] |
wait for the first of a number of file descriptors to have activity | def wait_fds ( fd_events , inmask = 1 , outmask = 2 , timeout = None ) : current = compat . getcurrent ( ) activated = { } poll_regs = { } callback_refs = { } def activate ( fd , event ) : if not activated and timeout != 0 : # this is the first invocation of `activated` for a blocking # `wait_fds` call, so re-schedule the blocked coroutine scheduler . schedule ( current ) # if there was a timeout then also have to pull # the coroutine from the timed_paused structure if timeout : scheduler . _remove_timer ( waketime , current ) # in any case, set the event information activated . setdefault ( fd , 0 ) activated [ fd ] |= event for fd , events in fd_events : readable = None writable = None if events & inmask : readable = functools . partial ( activate , fd , inmask ) if events & outmask : writable = functools . partial ( activate , fd , outmask ) callback_refs [ fd ] = ( readable , writable ) poll_regs [ fd ] = scheduler . _register_fd ( fd , readable , writable ) if timeout : # real timeout value, schedule ourself `timeout` seconds in the future waketime = time . time ( ) + timeout scheduler . pause_until ( waketime ) elif timeout == 0 : # timeout == 0, only pause for 1 loop iteration scheduler . pause ( ) else : # timeout is None, it's up to _hit_poller->activate to bring us back scheduler . state . mainloop . switch ( ) for fd , reg in poll_regs . iteritems ( ) : readable , writable = callback_refs [ fd ] scheduler . _unregister_fd ( fd , readable , writable , reg ) if scheduler . state . interrupted : raise IOError ( errno . EINTR , "interrupted system call" ) return activated . items ( ) | 6,891 | https://github.com/teepark/greenhouse/blob/8fd1be4f5443ba090346b5ec82fdbeb0a060d956/greenhouse/io/descriptor.py#L13-L87 | [
"def",
"get_role_policy",
"(",
"role_name",
",",
"policy_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
"keyid",
",",
"profile",
"=",
"profile",
")",
"try",
":",
"_policy",
"=",
"conn",
".",
"get_role_policy",
"(",
"role_name",
",",
"policy_name",
")",
"# I _hate_ you for not giving me an object boto.",
"_policy",
"=",
"_policy",
".",
"get_role_policy_response",
".",
"policy_document",
"# Policy is url encoded",
"_policy",
"=",
"_unquote",
"(",
"_policy",
")",
"_policy",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"loads",
"(",
"_policy",
",",
"object_pairs_hook",
"=",
"odict",
".",
"OrderedDict",
")",
"return",
"_policy",
"except",
"boto",
".",
"exception",
".",
"BotoServerError",
":",
"return",
"{",
"}"
] |
patches setuptools . find_packages issue | def hack_find_packages ( include_str ) : new_list = [ include_str ] for element in find_packages ( include_str ) : new_list . append ( include_str + '.' + element ) return new_list | 6,892 | https://github.com/EVEprosper/ProsperCommon/blob/bcada3b25420099e1f204db8d55eb268e7b4dc27/setup.py#L30-L43 | [
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")",
"# initialize timestamp",
"timestamp",
"=",
"None",
"# if value is None",
"if",
"value",
"is",
"None",
":",
"# nonify timer",
"timer",
"=",
"None",
"else",
":",
"# else, renew a timer",
"# get timestamp",
"timestamp",
"=",
"time",
"(",
")",
"+",
"value",
"# start a new timer",
"timer",
"=",
"Timer",
"(",
"value",
",",
"self",
".",
"__del__",
")",
"timer",
".",
"start",
"(",
")",
"# set/update attributes",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"timer",
")",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"timestamp",
")"
] |
Poll until all request objects have completed . | def WaitUntilComplete ( self , poll_freq = 2 , timeout = None ) : start_time = time . time ( ) while len ( self . requests ) : cur_requests = [ ] for request in self . requests : status = request . Status ( ) if status in ( 'notStarted' , 'executing' , 'resumed' , 'queued' , 'running' ) : cur_requests . append ( request ) elif status == 'succeeded' : self . success_requests . append ( request ) elif status in ( "failed" , "unknown" ) : self . error_requests . append ( request ) self . requests = cur_requests if self . requests > 0 and clc . v2 . time_utils . TimeoutExpired ( start_time , timeout ) : raise clc . RequestTimeoutException ( 'Timeout waiting for Requests: {0}' . format ( self . requests [ 0 ] . id ) , self . requests [ 0 ] . Status ( ) ) time . sleep ( poll_freq ) # alternately - sleep for the delta between start time and 2s # Is this the best approach? Non-zero indicates some error. Exception seems the wrong approach for # a partial failure return ( len ( self . error_requests ) ) | 6,893 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L119-L153 | [
"def",
"build",
"(",
"format",
"=",
"'qcow2'",
",",
"path",
"=",
"'/tmp/'",
")",
":",
"try",
":",
"_",
"(",
"\"collector\"",
")",
".",
"Inspector",
"(",
"cachedir",
"=",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"piddir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"__opts__",
"[",
"'pidfile'",
"]",
")",
",",
"pidfilename",
"=",
"''",
")",
".",
"reuse_snapshot",
"(",
")",
".",
"build",
"(",
"format",
"=",
"format",
",",
"path",
"=",
"path",
")",
"except",
"InspectorKiwiProcessorException",
"as",
"ex",
":",
"raise",
"CommandExecutionError",
"(",
"ex",
")",
"except",
"Exception",
"as",
"ex",
":",
"log",
".",
"error",
"(",
"_get_error_message",
"(",
"ex",
")",
")",
"raise",
"Exception",
"(",
"ex",
")"
] |
Poll until status is completed . | def WaitUntilComplete ( self , poll_freq = 2 , timeout = None ) : start_time = time . time ( ) while not self . time_completed : status = self . Status ( ) if status == 'executing' : if not self . time_executed : self . time_executed = time . time ( ) if clc . v2 . time_utils . TimeoutExpired ( start_time , timeout ) : raise clc . RequestTimeoutException ( 'Timeout waiting for Request: {0}' . format ( self . id ) , status ) elif status == 'succeeded' : self . time_completed = time . time ( ) elif status in ( "failed" , "resumed" or "unknown" ) : # TODO - need to ID best reaction for resumed status (e.g. manual intervention) self . time_completed = time . time ( ) raise ( clc . CLCException ( "%s %s execution %s" % ( self . context_key , self . context_val , status ) ) ) time . sleep ( poll_freq ) | 6,894 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L197-L222 | [
"def",
"get_pore_surface_parameters",
"(",
"surface_area",
")",
":",
"PoreSurfaceParameters",
"=",
"DataFactory",
"(",
"'phtools.surface'",
")",
"d",
"=",
"{",
"'accessible_surface_area'",
":",
"surface_area",
".",
"get_dict",
"(",
")",
"[",
"'ASA_A^2'",
"]",
",",
"'target_volume'",
":",
"40e3",
",",
"'sampling_method'",
":",
"'random'",
",",
"}",
"return",
"PoreSurfaceParameters",
"(",
"dict",
"=",
"d",
")"
] |
Return server associated with this request . | def Server ( self ) : if self . context_key == 'newserver' : server_id = clc . v2 . API . Call ( 'GET' , self . context_val , session = self . session ) [ 'id' ] return ( clc . v2 . Server ( id = server_id , alias = self . alias , session = self . session ) ) elif self . context_key == 'server' : return ( clc . v2 . Server ( id = self . context_val , alias = self . alias , session = self . session ) ) else : raise ( clc . CLCException ( "%s object not server" % self . context_key ) ) | 6,895 | https://github.com/CenturyLinkCloud/clc-python-sdk/blob/f4dba40c627cb08dd4b7d0d277e8d67578010b05/src/clc/APIv2/queue.py#L225-L243 | [
"async",
"def",
"setup_streamer",
"(",
"self",
")",
":",
"self",
".",
"streamer",
".",
"volume",
"=",
"self",
".",
"volume",
"/",
"100",
"self",
".",
"streamer",
".",
"start",
"(",
")",
"self",
".",
"pause_time",
"=",
"None",
"self",
".",
"vclient_starttime",
"=",
"self",
".",
"vclient",
".",
"loop",
".",
"time",
"(",
")",
"# Cache next song",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Caching next song\"",
")",
"dl_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"download_next_song_cache",
")",
"dl_thread",
".",
"start",
"(",
")"
] |
This method performs the login on TheTVDB given the api key user name and account identifier . | def login ( self ) : auth_data = dict ( ) auth_data [ 'apikey' ] = self . api_key auth_data [ 'username' ] = self . username auth_data [ 'userkey' ] = self . account_identifier auth_resp = requests_util . run_request ( 'post' , self . API_BASE_URL + '/login' , data = json . dumps ( auth_data ) , headers = self . __get_header ( ) ) if auth_resp . status_code == 200 : auth_resp_data = self . parse_raw_response ( auth_resp ) self . __token = auth_resp_data [ 'token' ] self . __auth_time = datetime . now ( ) self . is_authenticated = True else : raise AuthenticationFailedException ( 'Authentication failed!' ) | 6,896 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L79-L99 | [
"def",
"thread_partition_array",
"(",
"x",
")",
":",
"n_threads",
"=",
"get_threadpool_size",
"(",
")",
"if",
"len",
"(",
"x",
".",
"shape",
")",
">",
"1",
":",
"maxind",
"=",
"x",
".",
"shape",
"[",
"1",
"]",
"else",
":",
"maxind",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"bounds",
"=",
"np",
".",
"array",
"(",
"np",
".",
"linspace",
"(",
"0",
",",
"maxind",
",",
"n_threads",
"+",
"1",
")",
",",
"dtype",
"=",
"'int'",
")",
"cmin",
"=",
"bounds",
"[",
":",
"-",
"1",
"]",
"cmax",
"=",
"bounds",
"[",
"1",
":",
"]",
"return",
"cmin",
",",
"cmax"
] |
Searchs for a series in TheTVDB by either its name imdb_id or zap2it_id . | def search_series ( self , name = None , imdb_id = None , zap2it_id = None ) : arguments = locals ( ) optional_parameters = { 'name' : 'name' , 'imdb_id' : 'imdbId' , 'zap2it_id' : 'zap2itId' } query_string = utils . query_param_string_from_option_args ( optional_parameters , arguments ) raw_response = requests_util . run_request ( 'get' , '%s%s?%s' % ( self . API_BASE_URL , '/search/series' , query_string ) , headers = self . __get_header_with_auth ( ) ) return self . parse_raw_response ( raw_response ) | 6,897 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L102-L120 | [
"def",
"receive_data_chunk",
"(",
"self",
",",
"raw_data",
",",
"start",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"raw_data",
")",
"# CHANGED: This un-hangs us long enough to keep things rolling.",
"eventlet",
".",
"sleep",
"(",
"0",
")"
] |
Retrieves the information on the actors of a particular series given its TheTVDB id . | def get_series_actors ( self , series_id ) : raw_response = requests_util . run_request ( 'get' , self . API_BASE_URL + '/series/%d/actors' % series_id , headers = self . __get_header_with_auth ( ) ) return self . parse_raw_response ( raw_response ) | 6,898 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L137-L148 | [
"def",
"create_balanced_geojson",
"(",
"input_file",
",",
"classes",
",",
"output_file",
"=",
"'balanced.geojson'",
",",
"samples_per_class",
"=",
"None",
")",
":",
"if",
"not",
"output_file",
".",
"endswith",
"(",
"'.geojson'",
")",
":",
"output_file",
"+=",
"'.geojson'",
"with",
"open",
"(",
"input_file",
")",
"as",
"f",
":",
"data",
"=",
"geojson",
".",
"load",
"(",
"f",
")",
"# Sort classes in separate lists",
"sorted_classes",
"=",
"{",
"clss",
":",
"[",
"]",
"for",
"clss",
"in",
"classes",
"}",
"for",
"feat",
"in",
"data",
"[",
"'features'",
"]",
":",
"try",
":",
"sorted_classes",
"[",
"feat",
"[",
"'properties'",
"]",
"[",
"'class_name'",
"]",
"]",
".",
"append",
"(",
"feat",
")",
"except",
"(",
"KeyError",
")",
":",
"continue",
"# Determine sample size per class",
"if",
"not",
"samples_per_class",
":",
"smallest_class",
"=",
"min",
"(",
"sorted_classes",
",",
"key",
"=",
"lambda",
"clss",
":",
"len",
"(",
"sorted_classes",
"[",
"clss",
"]",
")",
")",
"samples_per_class",
"=",
"len",
"(",
"sorted_classes",
"[",
"smallest_class",
"]",
")",
"# Randomly select features from each class",
"try",
":",
"samps",
"=",
"[",
"random",
".",
"sample",
"(",
"feats",
",",
"samples_per_class",
")",
"for",
"feats",
"in",
"sorted_classes",
".",
"values",
"(",
")",
"]",
"final",
"=",
"[",
"feat",
"for",
"sample",
"in",
"samps",
"for",
"feat",
"in",
"sample",
"]",
"except",
"(",
"ValueError",
")",
":",
"raise",
"Exception",
"(",
"'Insufficient features in at least one class. Set '",
"'samples_per_class to None to use maximum amount of '",
"'features.'",
")",
"# Shuffle and save balanced data",
"np",
".",
"random",
".",
"shuffle",
"(",
"final",
")",
"data",
"[",
"'features'",
"]",
"=",
"final",
"with",
"open",
"(",
"output_file",
",",
"'wb'",
")",
"as",
"f",
":",
"geojson",
".",
"dump",
"(",
"data",
",",
"f",
")"
] |
Retrieves all episodes for a particular series given its TheTVDB id . It retrieves a maximum of 100 results per page . | def get_series_episodes ( self , series_id , page = 1 ) : raw_response = requests_util . run_request ( 'get' , self . API_BASE_URL + '/series/%d/episodes?page=%d' % ( series_id , page ) , headers = self . __get_header_with_auth ( ) ) return self . parse_raw_response ( raw_response ) | 6,899 | https://github.com/thilux/tvdb_client/blob/2d5106f260367c0abe1284683697874df6343f78/tvdb_client/clients/ApiV2Client.py#L151-L164 | [
"def",
"_renameClasses",
"(",
"classes",
",",
"prefix",
")",
":",
"renameMap",
"=",
"{",
"}",
"for",
"classID",
",",
"glyphList",
"in",
"classes",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"glyphList",
")",
"==",
"0",
":",
"groupName",
"=",
"\"%s_empty_lu.%d_st.%d_cl.%d\"",
"%",
"(",
"prefix",
",",
"classID",
"[",
"0",
"]",
",",
"classID",
"[",
"1",
"]",
",",
"classID",
"[",
"2",
"]",
")",
"elif",
"len",
"(",
"glyphList",
")",
"==",
"1",
":",
"groupName",
"=",
"list",
"(",
"glyphList",
")",
"[",
"0",
"]",
"else",
":",
"glyphList",
"=",
"list",
"(",
"sorted",
"(",
"glyphList",
")",
")",
"groupName",
"=",
"prefix",
"+",
"glyphList",
"[",
"0",
"]",
"renameMap",
"[",
"classID",
"]",
"=",
"groupName",
"return",
"renameMap"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.