query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
convert an image by adding text
|
def add_text_to_image ( fname , txt , opFilename ) : ft = ImageFont . load ( "T://user//dev//src//python//_AS_LIB//timR24.pil" ) #wh = ft.getsize(txt) print ( "Adding text " , txt , " to " , fname , " pixels wide to file " , opFilename ) im = Image . open ( fname ) draw = ImageDraw . Draw ( im ) draw . text ( ( 0 , 0 ) , txt , fill = ( 0 , 0 , 0 ) , font = ft ) del draw im . save ( opFilename )
| 2,300
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L304-L313
|
[
"def",
"list_configs",
"(",
")",
":",
"try",
":",
"configs",
"=",
"snapper",
".",
"ListConfigs",
"(",
")",
"return",
"dict",
"(",
"(",
"config",
"[",
"0",
"]",
",",
"config",
"[",
"2",
"]",
")",
"for",
"config",
"in",
"configs",
")",
"except",
"dbus",
".",
"DBusException",
"as",
"exc",
":",
"raise",
"CommandExecutionError",
"(",
"'Error encountered while listing configurations: {0}'",
".",
"format",
"(",
"_dbus_exception_to_reason",
"(",
"exc",
",",
"locals",
"(",
")",
")",
")",
")"
] |
convert an image by adding a cross hair
|
def add_crosshair_to_image ( fname , opFilename ) : im = Image . open ( fname ) draw = ImageDraw . Draw ( im ) draw . line ( ( 0 , 0 ) + im . size , fill = ( 255 , 255 , 255 ) ) draw . line ( ( 0 , im . size [ 1 ] , im . size [ 0 ] , 0 ) , fill = ( 255 , 255 , 255 ) ) del draw im . save ( opFilename )
| 2,301
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L315-L322
|
[
"def",
"status_to_string",
"(",
"dbus_status",
")",
":",
"status_tuple",
"=",
"(",
"dbus_status",
"&",
"0b000000001",
",",
"dbus_status",
"&",
"0b000000010",
",",
"dbus_status",
"&",
"0b000000100",
",",
"dbus_status",
"&",
"0b000001000",
",",
"dbus_status",
"&",
"0b000010000",
",",
"dbus_status",
"&",
"0b000100000",
",",
"dbus_status",
"&",
"0b001000000",
",",
"dbus_status",
"&",
"0b010000000",
",",
"dbus_status",
"&",
"0b100000000",
")",
"return",
"[",
"DBUS_STATUS_MAP",
"[",
"status",
"]",
"for",
"status",
"in",
"status_tuple",
"if",
"status",
"]"
] |
convert an image by applying a contour
|
def filter_contour ( imageFile , opFile ) : im = Image . open ( imageFile ) im1 = im . filter ( ImageFilter . CONTOUR ) im1 . save ( opFile )
| 2,302
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L324-L328
|
[
"def",
"same_types",
"(",
"self",
",",
"index1",
",",
"index2",
")",
":",
"try",
":",
"same",
"=",
"self",
".",
"table",
"[",
"index1",
"]",
".",
"type",
"==",
"self",
".",
"table",
"[",
"index2",
"]",
".",
"type",
"!=",
"SharedData",
".",
"TYPES",
".",
"NO_TYPE",
"except",
"Exception",
":",
"self",
".",
"error",
"(",
")",
"return",
"same"
] |
Grayscale and shrink the image in one step
|
def get_img_hash ( image , hash_size = 8 ) : image = image . resize ( ( hash_size + 1 , hash_size ) , Image . ANTIALIAS , ) pixels = list ( image . getdata ( ) ) #print('get_img_hash: pixels=', pixels) # Compare adjacent pixels. difference = [ ] for row in range ( hash_size ) : for col in range ( hash_size ) : pixel_left = image . getpixel ( ( col , row ) ) pixel_right = image . getpixel ( ( col + 1 , row ) ) difference . append ( pixel_left > pixel_right ) # Convert the binary array to a hexadecimal string. decimal_value = 0 hex_string = [ ] for index , value in enumerate ( difference ) : if value : decimal_value += 2 ** ( index % 8 ) if ( index % 8 ) == 7 : hex_string . append ( hex ( decimal_value ) [ 2 : ] . rjust ( 2 , '0' ) ) decimal_value = 0 return '' . join ( hex_string )
| 2,303
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L374-L400
|
[
"def",
"RunValidationOutputToConsole",
"(",
"feed",
",",
"options",
")",
":",
"accumulator",
"=",
"CountingConsoleProblemAccumulator",
"(",
"options",
".",
"error_types_ignore_list",
")",
"problems",
"=",
"transitfeed",
".",
"ProblemReporter",
"(",
"accumulator",
")",
"_",
",",
"exit_code",
"=",
"RunValidation",
"(",
"feed",
",",
"options",
",",
"problems",
")",
"return",
"exit_code"
] |
read an image from file - PIL doesnt close nicely
|
def load_image ( fname ) : with open ( fname , "rb" ) as f : i = Image . open ( fname ) #i.load() return i
| 2,304
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L402-L407
|
[
"def",
"group_experiments_greedy",
"(",
"tomo_expt",
":",
"TomographyExperiment",
")",
":",
"diag_sets",
"=",
"_max_tpb_overlap",
"(",
"tomo_expt",
")",
"grouped_expt_settings_list",
"=",
"list",
"(",
"diag_sets",
".",
"values",
"(",
")",
")",
"grouped_tomo_expt",
"=",
"TomographyExperiment",
"(",
"grouped_expt_settings_list",
",",
"program",
"=",
"tomo_expt",
".",
"program",
")",
"return",
"grouped_tomo_expt"
] |
output the image as text
|
def dump_img ( fname ) : img = Image . open ( fname ) width , _ = img . size txt = '' pixels = list ( img . getdata ( ) ) for col in range ( width ) : txt += str ( pixels [ col : col + width ] ) return txt
| 2,305
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_tools.py#L409-L417
|
[
"def",
"get_user_last_submissions",
"(",
"self",
",",
"limit",
"=",
"5",
",",
"request",
"=",
"None",
")",
":",
"if",
"request",
"is",
"None",
":",
"request",
"=",
"{",
"}",
"request",
".",
"update",
"(",
"{",
"\"username\"",
":",
"self",
".",
"_user_manager",
".",
"session_username",
"(",
")",
"}",
")",
"# Before, submissions were first sorted by submission date, then grouped",
"# and then resorted by submission date before limiting. Actually, grouping",
"# and pushing, keeping the max date, followed by result filtering is much more",
"# efficient",
"data",
"=",
"self",
".",
"_database",
".",
"submissions",
".",
"aggregate",
"(",
"[",
"{",
"\"$match\"",
":",
"request",
"}",
",",
"{",
"\"$group\"",
":",
"{",
"\"_id\"",
":",
"{",
"\"courseid\"",
":",
"\"$courseid\"",
",",
"\"taskid\"",
":",
"\"$taskid\"",
"}",
",",
"\"submitted_on\"",
":",
"{",
"\"$max\"",
":",
"\"$submitted_on\"",
"}",
",",
"\"submissions\"",
":",
"{",
"\"$push\"",
":",
"{",
"\"_id\"",
":",
"\"$_id\"",
",",
"\"result\"",
":",
"\"$result\"",
",",
"\"status\"",
":",
"\"$status\"",
",",
"\"courseid\"",
":",
"\"$courseid\"",
",",
"\"taskid\"",
":",
"\"$taskid\"",
",",
"\"submitted_on\"",
":",
"\"$submitted_on\"",
"}",
"}",
",",
"}",
"}",
",",
"{",
"\"$project\"",
":",
"{",
"\"submitted_on\"",
":",
"1",
",",
"\"submissions\"",
":",
"{",
"# This could be replaced by $filter if mongo v3.2 is set as dependency",
"\"$setDifference\"",
":",
"[",
"{",
"\"$map\"",
":",
"{",
"\"input\"",
":",
"\"$submissions\"",
",",
"\"as\"",
":",
"\"submission\"",
",",
"\"in\"",
":",
"{",
"\"$cond\"",
":",
"[",
"{",
"\"$eq\"",
":",
"[",
"\"$submitted_on\"",
",",
"\"$$submission.submitted_on\"",
"]",
"}",
",",
"\"$$submission\"",
",",
"False",
"]",
"}",
"}",
"}",
",",
"[",
"False",
"]",
"]",
"}",
"}",
"}",
",",
"{",
"\"$sort\"",
":",
"{",
"\"submitted_on\"",
":",
"pymongo",
".",
"DESCENDING",
"}",
"}",
",",
"{",
"\"$limit\"",
":",
"limit",
"}",
"]",
")",
"return",
"[",
"item",
"[",
"\"submissions\"",
"]",
"[",
"0",
"]",
"for",
"item",
"in",
"data",
"]"
] |
Normalizes intensities of a gene in two samples
|
def NormInt ( df , sampleA , sampleB ) : c1 = df [ sampleA ] c2 = df [ sampleB ] return np . log10 ( np . sqrt ( c1 * c2 ) )
| 2,306
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/plots.py#L341-L354
|
[
"def",
"_error_messages",
"(",
"self",
",",
"driver_id",
")",
":",
"assert",
"isinstance",
"(",
"driver_id",
",",
"ray",
".",
"DriverID",
")",
"message",
"=",
"self",
".",
"redis_client",
".",
"execute_command",
"(",
"\"RAY.TABLE_LOOKUP\"",
",",
"ray",
".",
"gcs_utils",
".",
"TablePrefix",
".",
"ERROR_INFO",
",",
"\"\"",
",",
"driver_id",
".",
"binary",
"(",
")",
")",
"# If there are no errors, return early.",
"if",
"message",
"is",
"None",
":",
"return",
"[",
"]",
"gcs_entries",
"=",
"ray",
".",
"gcs_utils",
".",
"GcsTableEntry",
".",
"GetRootAsGcsTableEntry",
"(",
"message",
",",
"0",
")",
"error_messages",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"gcs_entries",
".",
"EntriesLength",
"(",
")",
")",
":",
"error_data",
"=",
"ray",
".",
"gcs_utils",
".",
"ErrorTableData",
".",
"GetRootAsErrorTableData",
"(",
"gcs_entries",
".",
"Entries",
"(",
"i",
")",
",",
"0",
")",
"assert",
"driver_id",
".",
"binary",
"(",
")",
"==",
"error_data",
".",
"DriverId",
"(",
")",
"error_message",
"=",
"{",
"\"type\"",
":",
"decode",
"(",
"error_data",
".",
"Type",
"(",
")",
")",
",",
"\"message\"",
":",
"decode",
"(",
"error_data",
".",
"ErrorMessage",
"(",
")",
")",
",",
"\"timestamp\"",
":",
"error_data",
".",
"Timestamp",
"(",
")",
",",
"}",
"error_messages",
".",
"append",
"(",
"error_message",
")",
"return",
"error_messages"
] |
Testing given number to be a prime .
|
def is_prime ( number ) : if number < 2 : return False if number % 2 == 0 : return number == 2 limit = int ( math . sqrt ( number ) ) for divisor in range ( 3 , limit + 1 , 2 ) : if number % divisor == 0 : return False return True
| 2,307
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/examples/python/primes/demo/primes.py#L32-L49
|
[
"def",
"_ParseLogonApplications",
"(",
"self",
",",
"parser_mediator",
",",
"registry_key",
")",
":",
"for",
"application",
"in",
"self",
".",
"_LOGON_APPLICATIONS",
":",
"command_value",
"=",
"registry_key",
".",
"GetValueByName",
"(",
"application",
")",
"if",
"not",
"command_value",
":",
"continue",
"values_dict",
"=",
"{",
"'Application'",
":",
"application",
",",
"'Command'",
":",
"command_value",
".",
"GetDataAsObject",
"(",
")",
",",
"'Trigger'",
":",
"'Logon'",
"}",
"event_data",
"=",
"windows_events",
".",
"WindowsRegistryEventData",
"(",
")",
"event_data",
".",
"key_path",
"=",
"registry_key",
".",
"path",
"event_data",
".",
"offset",
"=",
"registry_key",
".",
"offset",
"event_data",
".",
"regvalue",
"=",
"values_dict",
"event_data",
".",
"source_append",
"=",
"': Winlogon'",
"event",
"=",
"time_events",
".",
"DateTimeValuesEvent",
"(",
"registry_key",
".",
"last_written_time",
",",
"definitions",
".",
"TIME_DESCRIPTION_WRITTEN",
")",
"parser_mediator",
".",
"ProduceEventWithEventData",
"(",
"event",
",",
"event_data",
")"
] |
Returns a dict of QMED methods using all available methods .
|
def qmed_all_methods ( self ) : result = { } for method in self . methods : try : result [ method ] = getattr ( self , '_qmed_from_' + method ) ( ) except : result [ method ] = None return result
| 2,308
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L169-L185
|
[
"def",
"_ExtractHuntIdFromPath",
"(",
"entry",
",",
"event",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r\".*hunt/([^/]+).*\"",
",",
"entry",
".",
"http_request_path",
")",
"if",
"match",
":",
"event",
".",
"urn",
"=",
"\"aff4:/hunts/{}\"",
".",
"format",
"(",
"match",
".",
"group",
"(",
"1",
")",
")"
] |
Return QMED estimate based on annual maximum flow records .
|
def _qmed_from_amax_records ( self ) : valid_flows = valid_flows_array ( self . catchment ) n = len ( valid_flows ) if n < 2 : raise InsufficientDataError ( "Insufficient annual maximum flow records available for catchment {}." . format ( self . catchment . id ) ) return np . median ( valid_flows )
| 2,309
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L187-L199
|
[
"def",
"unique_key",
"(",
"connection",
")",
":",
"while",
"1",
":",
"key",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
")",
"if",
"not",
"connection",
".",
"exists",
"(",
"key",
")",
":",
"break",
"return",
"key"
] |
Return a list of 12 sets . Each sets contains the years included in the POT record period .
|
def _pot_month_counts ( self , pot_dataset ) : periods = pot_dataset . continuous_periods ( ) result = [ set ( ) for x in range ( 12 ) ] for period in periods : year = period . start_date . year month = period . start_date . month while True : # Month by month, add the year result [ month - 1 ] . add ( year ) # If at end of period, break loop if year == period . end_date . year and month == period . end_date . month : break # Next month (and year if needed) month += 1 if month == 13 : month = 1 year += 1 return result
| 2,310
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L229-L252
|
[
"def",
"_CreateIndexIfNotExists",
"(",
"self",
",",
"index_name",
",",
"mappings",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"_client",
".",
"indices",
".",
"exists",
"(",
"index_name",
")",
":",
"self",
".",
"_client",
".",
"indices",
".",
"create",
"(",
"body",
"=",
"{",
"'mappings'",
":",
"mappings",
"}",
",",
"index",
"=",
"index_name",
")",
"except",
"elasticsearch",
".",
"exceptions",
".",
"ConnectionError",
"as",
"exception",
":",
"raise",
"RuntimeError",
"(",
"'Unable to create Elasticsearch index with error: {0!s}'",
".",
"format",
"(",
"exception",
")",
")"
] |
Return QMED estimate based on catchment area .
|
def _qmed_from_area ( self ) : try : return 1.172 * self . catchment . descriptors . dtm_area ** self . _area_exponent ( ) # Area in km² except ( TypeError , KeyError ) : raise InsufficientDataError ( "Catchment `descriptors` attribute must be set first." )
| 2,311
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L310-L322
|
[
"def",
"refreshGroupMembership",
"(",
"self",
",",
"groups",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"groups\"",
":",
"groups",
"}",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/groups/refreshMembership\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"url",
",",
"param_dict",
"=",
"params",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] |
Return QMED estimation based on FEH catchment descriptors 1999 methodology .
|
def _qmed_from_descriptors_1999 ( self , as_rural = False ) : try : qmed_rural = 1.172 * self . catchment . descriptors . dtm_area ** self . _area_exponent ( ) * ( self . catchment . descriptors . saar / 1000.0 ) ** 1.560 * self . catchment . descriptors . farl ** 2.642 * ( self . catchment . descriptors . sprhost / 100.0 ) ** 1.211 * 0.0198 ** self . _residual_soil ( ) if as_rural : return qmed_rural else : return qmed_rural * self . urban_adj_factor ( ) except ( TypeError , KeyError ) : raise InsufficientDataError ( "Catchment `descriptors` attribute must be set first." )
| 2,312
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L324-L346
|
[
"def",
"apply_flat",
"(",
"self",
",",
"config",
",",
"namespace_separator",
"=",
"'_'",
",",
"prefix",
"=",
"''",
")",
":",
"# type: (Dict[str, Any], str, str) -> None",
"self",
".",
"_init_flat_pointers",
"(",
")",
"for",
"key_stack",
",",
"(",
"container",
",",
"orig_key",
")",
"in",
"self",
".",
"_flat_pointers",
".",
"items",
"(",
")",
":",
"flat_key",
"=",
"'{prefix}{joined_key}'",
".",
"format",
"(",
"prefix",
"=",
"prefix",
",",
"joined_key",
"=",
"namespace_separator",
".",
"join",
"(",
"key_stack",
")",
")",
"if",
"flat_key",
"in",
"config",
":",
"container",
"[",
"orig_key",
"]",
"=",
"config",
"[",
"flat_key",
"]"
] |
Return QMED estimation based on FEH catchment descriptors 2008 methodology .
|
def _qmed_from_descriptors_2008 ( self , as_rural = False , donor_catchments = None ) : try : # Basis rural QMED from descriptors lnqmed_rural = 2.1170 + 0.8510 * log ( self . catchment . descriptors . dtm_area ) - 1.8734 * 1000 / self . catchment . descriptors . saar + 3.4451 * log ( self . catchment . descriptors . farl ) - 3.0800 * self . catchment . descriptors . bfihost ** 2.0 qmed_rural = exp ( lnqmed_rural ) # Log intermediate results self . results_log [ 'qmed_descr_rural' ] = qmed_rural if donor_catchments is None : # If no donor catchments are provided, find the nearest 25 donor_catchments = self . find_donor_catchments ( ) if donor_catchments : # If found multiply rural estimate with weighted adjustment factors from all donors weights = self . _vec_alpha ( donor_catchments ) errors = self . _vec_lnqmed_residuals ( donor_catchments ) correction = np . dot ( weights , errors ) lnqmed_rural += correction qmed_rural = exp ( lnqmed_rural ) # Log intermediate results self . results_log [ 'donors' ] = donor_catchments for i , donor in enumerate ( self . results_log [ 'donors' ] ) : donor . weight = weights [ i ] donor . factor = exp ( errors [ i ] ) self . results_log [ 'donor_adj_factor' ] = exp ( correction ) self . results_log [ 'qmed_adj_rural' ] = qmed_rural if as_rural : return qmed_rural else : # Apply urbanisation adjustment urban_adj_factor = self . urban_adj_factor ( ) # Log intermediate results self . results_log [ 'qmed_descr_urban' ] = self . results_log [ 'qmed_descr_rural' ] * urban_adj_factor return qmed_rural * urban_adj_factor except ( TypeError , KeyError ) : raise InsufficientDataError ( "Catchment `descriptors` attribute must be set first." )
| 2,313
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L359-L416
|
[
"def",
"put",
"(",
"self",
",",
"key",
",",
"val",
",",
"minutes",
")",
":",
"minutes",
"=",
"self",
".",
"_get_minutes",
"(",
"minutes",
")",
"if",
"minutes",
"is",
"not",
"None",
":",
"self",
".",
"_store",
".",
"put",
"(",
"key",
",",
"val",
",",
"minutes",
")"
] |
Return percentage runoff urban adjustment factor .
|
def _pruaf ( self ) : return 1 + 0.47 * self . catchment . descriptors . urbext ( self . year ) * self . catchment . descriptors . bfihost / ( 1 - self . catchment . descriptors . bfihost )
| 2,314
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L418-L425
|
[
"def",
"_get_session",
"(",
"server",
")",
":",
"if",
"server",
"in",
"_sessions",
":",
"return",
"_sessions",
"[",
"server",
"]",
"config",
"=",
"_get_spacewalk_configuration",
"(",
"server",
")",
"if",
"not",
"config",
":",
"raise",
"Exception",
"(",
"'No config for \\'{0}\\' found on master'",
".",
"format",
"(",
"server",
")",
")",
"session",
"=",
"_get_client_and_key",
"(",
"config",
"[",
"'api_url'",
"]",
",",
"config",
"[",
"'username'",
"]",
",",
"config",
"[",
"'password'",
"]",
")",
"atexit",
".",
"register",
"(",
"_disconnect_session",
",",
"session",
")",
"client",
"=",
"session",
"[",
"'client'",
"]",
"key",
"=",
"session",
"[",
"'key'",
"]",
"_sessions",
"[",
"server",
"]",
"=",
"(",
"client",
",",
"key",
")",
"return",
"client",
",",
"key"
] |
Generic distance - decaying correlation function
|
def _dist_corr ( dist , phi1 , phi2 , phi3 ) : return phi1 * exp ( - phi2 * dist ) + ( 1 - phi1 ) * exp ( - phi3 * dist )
| 2,315
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L443-L458
|
[
"def",
"block",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"path",
"=",
"'/users/%s/block'",
"%",
"self",
".",
"id",
"server_data",
"=",
"self",
".",
"manager",
".",
"gitlab",
".",
"http_post",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
"if",
"server_data",
"is",
"True",
":",
"self",
".",
"_attrs",
"[",
"'state'",
"]",
"=",
"'blocked'",
"return",
"server_data"
] |
Return vector b of model error covariances to estimate weights
|
def _vec_b ( self , donor_catchments ) : p = len ( donor_catchments ) b = 0.1175 * np . ones ( p ) for i in range ( p ) : b [ i ] *= self . _model_error_corr ( self . catchment , donor_catchments [ i ] ) return b
| 2,316
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L492-L507
|
[
"def",
"_clean_result",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"'\\s\\s+'",
",",
"' '",
",",
"text",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"'\\.\\.+'",
",",
"'.'",
",",
"text",
")",
"text",
"=",
"text",
".",
"replace",
"(",
"\"'\"",
",",
"\"\\\\'\"",
")",
"return",
"text"
] |
Return beta the GLO scale parameter divided by loc parameter estimated using simple regression model
|
def _beta ( catchment ) : lnbeta = - 1.1221 - 0.0816 * log ( catchment . descriptors . dtm_area ) - 0.4580 * log ( catchment . descriptors . saar / 1000 ) + 0.1065 * log ( catchment . descriptors . bfihost ) return exp ( lnbeta )
| 2,317
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L510-L525
|
[
"def",
"_repr_html_",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"jinja2",
"import",
"Template",
"from",
"markdown",
"import",
"markdown",
"as",
"convert_markdown",
"extensions",
"=",
"[",
"'markdown.extensions.extra'",
",",
"'markdown.extensions.admonition'",
"]",
"return",
"convert_markdown",
"(",
"self",
".",
"markdown",
",",
"extensions",
")"
] |
Return model error coveriance matrix Sigma eta
|
def _matrix_sigma_eta ( self , donor_catchments ) : p = len ( donor_catchments ) sigma = 0.1175 * np . ones ( ( p , p ) ) for i in range ( p ) : for j in range ( p ) : if i != j : sigma [ i , j ] *= self . _model_error_corr ( donor_catchments [ i ] , donor_catchments [ j ] ) return sigma
| 2,318
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L527-L544
|
[
"def",
"delete_nve_member",
"(",
"self",
",",
"nexus_host",
",",
"nve_int_num",
",",
"vni",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_VNI_UPDATE",
"%",
"(",
"nve_int_num",
",",
"vni",
")",
"self",
".",
"client",
".",
"rest_delete",
"(",
"path_snip",
",",
"nexus_host",
")",
"self",
".",
"capture_and_print_timeshot",
"(",
"starttime",
",",
"\"delete_nve\"",
",",
"switch",
"=",
"nexus_host",
")"
] |
Return sampling error coveriance matrix Sigma eta
|
def _matrix_sigma_eps ( self , donor_catchments ) : p = len ( donor_catchments ) sigma = np . empty ( ( p , p ) ) for i in range ( p ) : beta_i = self . _beta ( donor_catchments [ i ] ) n_i = donor_catchments [ i ] . amax_records_end ( ) - donor_catchments [ i ] . amax_records_start ( ) + 1 for j in range ( p ) : beta_j = self . _beta ( donor_catchments [ j ] ) n_j = donor_catchments [ j ] . amax_records_end ( ) - donor_catchments [ j ] . amax_records_start ( ) + 1 rho_ij = self . _lnqmed_corr ( donor_catchments [ i ] , donor_catchments [ j ] ) n_ij = min ( donor_catchments [ i ] . amax_records_end ( ) , donor_catchments [ j ] . amax_records_end ( ) ) - max ( donor_catchments [ i ] . amax_records_start ( ) , donor_catchments [ j ] . amax_records_start ( ) ) + 1 sigma [ i , j ] = 4 * beta_i * beta_j * n_ij / n_i / n_j * rho_ij return sigma
| 2,319
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L546-L569
|
[
"def",
"delete_nve_member",
"(",
"self",
",",
"nexus_host",
",",
"nve_int_num",
",",
"vni",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_VNI_UPDATE",
"%",
"(",
"nve_int_num",
",",
"vni",
")",
"self",
".",
"client",
".",
"rest_delete",
"(",
"path_snip",
",",
"nexus_host",
")",
"self",
".",
"capture_and_print_timeshot",
"(",
"starttime",
",",
"\"delete_nve\"",
",",
"switch",
"=",
"nexus_host",
")"
] |
Return vector alpha which is the weights for donor model errors
|
def _vec_alpha ( self , donor_catchments ) : return np . dot ( linalg . inv ( self . _matrix_omega ( donor_catchments ) ) , self . _vec_b ( donor_catchments ) )
| 2,320
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L574-L585
|
[
"def",
"_parse_status",
"(",
"self",
",",
"output",
")",
":",
"parsed",
"=",
"self",
".",
"_parse_machine_readable_output",
"(",
"output",
")",
"statuses",
"=",
"[",
"]",
"# group tuples by target name",
"# assuming tuples are sorted by target name, this should group all",
"# the tuples with info for each target.",
"for",
"target",
",",
"tuples",
"in",
"itertools",
".",
"groupby",
"(",
"parsed",
",",
"lambda",
"tup",
":",
"tup",
"[",
"1",
"]",
")",
":",
"# transform tuples into a dict mapping \"type\" to \"data\"",
"info",
"=",
"{",
"kind",
":",
"data",
"for",
"timestamp",
",",
"_",
",",
"kind",
",",
"data",
"in",
"tuples",
"}",
"status",
"=",
"Status",
"(",
"name",
"=",
"target",
",",
"state",
"=",
"info",
".",
"get",
"(",
"'state'",
")",
",",
"provider",
"=",
"info",
".",
"get",
"(",
"'provider-name'",
")",
")",
"statuses",
".",
"append",
"(",
"status",
")",
"return",
"statuses"
] |
Return a suitable donor catchment to improve a QMED estimate based on catchment descriptors alone .
|
def find_donor_catchments ( self , limit = 6 , dist_limit = 500 ) : if self . gauged_catchments : return self . gauged_catchments . nearest_qmed_catchments ( self . catchment , limit , dist_limit ) else : return [ ]
| 2,321
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L616-L632
|
[
"def",
"build_conversion_table",
"(",
"self",
",",
"dataframes",
")",
":",
"self",
".",
"data",
"=",
"pd",
".",
"DataFrame",
"(",
"dataframes",
")",
"tmp_pairs",
"=",
"[",
"s",
".",
"split",
"(",
"\"/\"",
")",
"for",
"s",
"in",
"self",
".",
"data",
".",
"columns",
"]",
"self",
".",
"data",
".",
"columns",
"=",
"pd",
".",
"MultiIndex",
".",
"from_tuples",
"(",
"tmp_pairs",
")"
] |
Calculate L - CV and L - SKEW from a single catchment or a pooled group of catchments .
|
def _var_and_skew ( self , catchments , as_rural = False ) : if not hasattr ( catchments , '__getitem__' ) : # In case of a single catchment l_cv , l_skew = self . _l_cv_and_skew ( self . catchment ) self . results_log [ 'donors' ] = [ ] else : # Prepare arrays for donor L-CVs and L-SKEWs and their weights n = len ( catchments ) l_cvs = np . empty ( n ) l_skews = np . empty ( n ) l_cv_weights = np . empty ( n ) l_skew_weights = np . empty ( n ) # Fill arrays for index , donor in enumerate ( catchments ) : l_cvs [ index ] , l_skews [ index ] = self . _l_cv_and_skew ( donor ) l_cv_weights [ index ] = self . _l_cv_weight ( donor ) l_skew_weights [ index ] = self . _l_skew_weight ( donor ) # Weighted averages of L-CV and l-SKEW l_cv_weights /= sum ( l_cv_weights ) # Weights sum to 1 # Special case if the first donor is the subject catchment itself, assumed if similarity distance == 0. if self . _similarity_distance ( self . catchment , catchments [ 0 ] ) == 0 : l_cv_weights *= self . _l_cv_weight_factor ( ) # Reduce weights of all donor catchments l_cv_weights [ 0 ] += 1 - sum ( l_cv_weights ) # But increase the weight of the subject catchment l_cv_rural = sum ( l_cv_weights * l_cvs ) l_skew_weights /= sum ( l_skew_weights ) # Weights sum to 1 l_skew_rural = sum ( l_skew_weights * l_skews ) self . results_log [ 'l_cv_rural' ] = l_cv_rural self . results_log [ 'l_skew_rural' ] = l_skew_rural if as_rural : l_cv = l_cv_rural l_skew = l_skew_rural else : # Method source: eqns. 10 and 11, Kjeldsen 2010 l_cv = l_cv_rural * 0.5547 ** self . catchment . descriptors . urbext ( self . year ) l_skew = ( l_skew_rural + 1 ) * 1.1545 ** self . catchment . descriptors . urbext ( self . year ) - 1 # Record intermediate results (donors) self . results_log [ 'donors' ] = catchments total_record_length = 0 for index , donor in enumerate ( self . results_log [ 'donors' ] ) : donor . l_cv = l_cvs [ index ] donor . l_cv_weight = l_cv_weights [ index ] donor . l_skew = l_skews [ index ] donor . l_skew_weight = l_skew_weights [ index ] total_record_length += donor . record_length self . results_log [ 'donors_record_length' ] = total_record_length # Record intermediate results self . results_log [ 'l_cv' ] = l_cv self . results_log [ 'l_skew' ] = l_skew return l_cv , l_skew
| 2,322
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L713-L770
|
[
"def",
"count_annotations",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"Namespace",
")",
".",
"filter",
"(",
"Namespace",
".",
"is_annotation",
")",
".",
"count",
"(",
")"
] |
Calculate L - CV and L - SKEW for a gauged catchment . Uses lmoments3 library .
|
def _l_cv_and_skew ( self , catchment ) : z = self . _dimensionless_flows ( catchment ) l1 , l2 , t3 = lm . lmom_ratios ( z , nmom = 3 ) return l2 / l1 , t3
| 2,323
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L772-L780
|
[
"def",
"acknowledged",
"(",
"self",
",",
"value",
")",
":",
"assert",
"(",
"isinstance",
"(",
"value",
",",
"bool",
")",
")",
"self",
".",
"_acknowledged",
"=",
"value",
"if",
"value",
":",
"self",
".",
"_timeouted",
"=",
"False",
"self",
".",
"_rejected",
"=",
"False",
"self",
".",
"_cancelled",
"=",
"False"
] |
Return L - CV weighting for a donor catchment .
|
def _l_cv_weight ( self , donor_catchment ) : try : dist = donor_catchment . similarity_dist except AttributeError : dist = self . _similarity_distance ( self . catchment , donor_catchment ) b = 0.0047 * sqrt ( dist ) + 0.0023 / 2 c = 0.02609 / ( donor_catchment . record_length - 1 ) return 1 / ( b + c )
| 2,324
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L782-L794
|
[
"def",
"flatten",
"(",
"self",
",",
"messages",
",",
"parent_key",
"=",
"''",
")",
":",
"items",
"=",
"[",
"]",
"sep",
"=",
"'.'",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"messages",
".",
"items",
"(",
")",
")",
":",
"new_key",
"=",
"\"{0}{1}{2}\"",
".",
"format",
"(",
"parent_key",
",",
"sep",
",",
"k",
")",
"if",
"parent_key",
"else",
"k",
"if",
"isinstance",
"(",
"v",
",",
"collections",
".",
"MutableMapping",
")",
":",
"items",
".",
"extend",
"(",
"list",
"(",
"self",
".",
"flatten",
"(",
"v",
",",
"new_key",
")",
".",
"items",
"(",
")",
")",
")",
"else",
":",
"items",
".",
"append",
"(",
"(",
"new_key",
",",
"v",
")",
")",
"return",
"dict",
"(",
"items",
")"
] |
Return multiplier for L - CV weightings in case of enhanced single site analysis .
|
def _l_cv_weight_factor ( self ) : b = 0.0047 * sqrt ( 0 ) + 0.0023 / 2 c = 0.02609 / ( self . catchment . record_length - 1 ) return c / ( b + c )
| 2,325
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L796-L804
|
[
"def",
"device_removed",
"(",
"self",
",",
"device",
")",
":",
"if",
"not",
"self",
".",
"_mounter",
".",
"is_handleable",
"(",
"device",
")",
":",
"return",
"device_file",
"=",
"device",
".",
"device_presentation",
"if",
"(",
"device",
".",
"is_drive",
"or",
"device",
".",
"is_toplevel",
")",
"and",
"device_file",
":",
"self",
".",
"_show_notification",
"(",
"'device_removed'",
",",
"_",
"(",
"'Device removed'",
")",
",",
"_",
"(",
"'device disappeared on {0.device_presentation}'",
",",
"device",
")",
",",
"device",
".",
"icon_name",
")"
] |
Return L - SKEW weighting for donor catchment .
|
def _l_skew_weight ( self , donor_catchment ) : try : dist = donor_catchment . similarity_dist except AttributeError : dist = self . _similarity_distance ( self . catchment , donor_catchment ) b = 0.0219 * ( 1 - exp ( - dist / 0.2360 ) ) c = 0.2743 / ( donor_catchment . record_length - 2 ) return 1 / ( b + c )
| 2,326
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L806-L818
|
[
"def",
"poll",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"-",
"1",
"message",
"=",
"super",
"(",
"AvroConsumer",
",",
"self",
")",
".",
"poll",
"(",
"timeout",
")",
"if",
"message",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"message",
".",
"error",
"(",
")",
":",
"try",
":",
"if",
"message",
".",
"value",
"(",
")",
"is",
"not",
"None",
":",
"decoded_value",
"=",
"self",
".",
"_serializer",
".",
"decode_message",
"(",
"message",
".",
"value",
"(",
")",
",",
"is_key",
"=",
"False",
")",
"message",
".",
"set_value",
"(",
"decoded_value",
")",
"if",
"message",
".",
"key",
"(",
")",
"is",
"not",
"None",
":",
"decoded_key",
"=",
"self",
".",
"_serializer",
".",
"decode_message",
"(",
"message",
".",
"key",
"(",
")",
",",
"is_key",
"=",
"True",
")",
"message",
".",
"set_key",
"(",
"decoded_key",
")",
"except",
"SerializerError",
"as",
"e",
":",
"raise",
"SerializerError",
"(",
"\"Message deserialization failed for message at {} [{}] offset {}: {}\"",
".",
"format",
"(",
"message",
".",
"topic",
"(",
")",
",",
"message",
".",
"partition",
"(",
")",
",",
"message",
".",
"offset",
"(",
")",
",",
"e",
")",
")",
"return",
"message"
] |
Return flood growth curve function based on amax_records from the subject catchment only .
|
def _growth_curve_single_site ( self , distr = 'glo' ) : if self . catchment . amax_records : self . donor_catchments = [ ] return GrowthCurve ( distr , * self . _var_and_skew ( self . catchment ) ) else : raise InsufficientDataError ( "Catchment's `amax_records` must be set for a single site analysis." )
| 2,327
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L820-L831
|
[
"def",
"find_steam_location",
"(",
")",
":",
"if",
"registry",
"is",
"None",
":",
"return",
"None",
"key",
"=",
"registry",
".",
"CreateKey",
"(",
"registry",
".",
"HKEY_CURRENT_USER",
",",
"\"Software\\Valve\\Steam\"",
")",
"return",
"registry",
".",
"QueryValueEx",
"(",
"key",
",",
"\"SteamPath\"",
")",
"[",
"0",
"]"
] |
Return flood growth curve function based on amax_records from a pooling group .
|
def _growth_curve_pooling_group ( self , distr = 'glo' , as_rural = False ) : if not self . donor_catchments : self . find_donor_catchments ( ) gc = GrowthCurve ( distr , * self . _var_and_skew ( self . donor_catchments ) ) # Record intermediate results self . results_log [ 'distr_name' ] = distr . upper ( ) self . results_log [ 'distr_params' ] = gc . params return gc
| 2,328
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L833-L849
|
[
"def",
"store",
"(",
"config",
",",
"archiver",
",",
"revision",
",",
"stats",
")",
":",
"root",
"=",
"pathlib",
".",
"Path",
"(",
"config",
".",
"cache_path",
")",
"/",
"archiver",
".",
"name",
"if",
"not",
"root",
".",
"exists",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"Creating wily cache\"",
")",
"root",
".",
"mkdir",
"(",
")",
"# fix absolute path references.",
"if",
"config",
".",
"path",
"!=",
"\".\"",
":",
"for",
"operator",
",",
"operator_data",
"in",
"list",
"(",
"stats",
"[",
"\"operator_data\"",
"]",
".",
"items",
"(",
")",
")",
":",
"if",
"operator_data",
":",
"new_operator_data",
"=",
"operator_data",
".",
"copy",
"(",
")",
"for",
"k",
",",
"v",
"in",
"list",
"(",
"operator_data",
".",
"items",
"(",
")",
")",
":",
"new_key",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"str",
"(",
"k",
")",
",",
"str",
"(",
"config",
".",
"path",
")",
")",
"del",
"new_operator_data",
"[",
"k",
"]",
"new_operator_data",
"[",
"new_key",
"]",
"=",
"v",
"del",
"stats",
"[",
"\"operator_data\"",
"]",
"[",
"operator",
"]",
"stats",
"[",
"\"operator_data\"",
"]",
"[",
"operator",
"]",
"=",
"new_operator_data",
"logger",
".",
"debug",
"(",
"f\"Creating {revision.key} output\"",
")",
"filename",
"=",
"root",
"/",
"(",
"revision",
".",
"key",
"+",
"\".json\"",
")",
"if",
"filename",
".",
"exists",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"f\"File {filename} already exists, index may be corrupt.\"",
")",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"out",
":",
"out",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"stats",
",",
"indent",
"=",
"2",
")",
")",
"return",
"filename"
] |
Logging versions of required tools .
|
def process ( self , document ) : content = json . dumps ( document ) versions = { } versions . update ( { 'Spline' : Version ( VERSION ) } ) versions . update ( self . get_version ( "Bash" , self . BASH_VERSION ) ) if content . find ( '"docker(container)":' ) >= 0 or content . find ( '"docker(image)":' ) >= 0 : versions . update ( VersionsCheck . get_version ( "Docker" , self . DOCKER_VERSION ) ) if content . find ( '"packer":' ) >= 0 : versions . update ( VersionsCheck . get_version ( "Packer" , self . PACKER_VERSION ) ) if content . find ( '"ansible(simple)":' ) >= 0 : versions . update ( VersionsCheck . get_version ( 'Ansible' , self . ANSIBLE_VERSION ) ) return versions
| 2,329
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/version.py#L70-L85
|
[
"def",
"login",
"(",
"self",
")",
":",
"access_token",
"=",
"self",
".",
"_get_access_token",
"(",
")",
"try",
":",
"super",
"(",
"IAMSession",
",",
"self",
")",
".",
"request",
"(",
"'POST'",
",",
"self",
".",
"_session_url",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'access_token'",
":",
"access_token",
"}",
")",
")",
".",
"raise_for_status",
"(",
")",
"except",
"RequestException",
":",
"raise",
"CloudantException",
"(",
"'Failed to exchange IAM token with Cloudant'",
")"
] |
Get name and version of a tool defined by given command .
|
def get_version ( tool_name , tool_command ) : result = { } for line in Bash ( ShellConfig ( script = tool_command , internal = True ) ) . process ( ) : if line . find ( "command not found" ) >= 0 : VersionsCheck . LOGGER . error ( "Required tool '%s' not found (stopping pipeline)!" , tool_name ) sys . exit ( 1 ) else : version = list ( re . findall ( r'(\d+(\.\d+)+)+' , line ) ) [ 0 ] [ 0 ] result = { tool_name : Version ( str ( version ) ) } break return result
| 2,330
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/version.py#L88-L108
|
[
"def",
"get_inconsistent_fieldnames",
"(",
")",
":",
"field_name_list",
"=",
"[",
"]",
"for",
"fieldset_title",
",",
"fields_list",
"in",
"settings",
".",
"CONFIG_FIELDSETS",
".",
"items",
"(",
")",
":",
"for",
"field_name",
"in",
"fields_list",
":",
"field_name_list",
".",
"append",
"(",
"field_name",
")",
"if",
"not",
"field_name_list",
":",
"return",
"{",
"}",
"return",
"set",
"(",
"set",
"(",
"settings",
".",
"CONFIG",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"field_name_list",
")",
")"
] |
Logging version sorted ascending by tool name .
|
def process ( self , versions ) : for tool_name in sorted ( versions . keys ( ) ) : version = versions [ tool_name ] self . _log ( "Using tool '%s', %s" % ( tool_name , version ) )
| 2,331
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/version.py#L117-L121
|
[
"def",
"set_reload_on_exception_params",
"(",
"self",
",",
"do_reload",
"=",
"None",
",",
"etype",
"=",
"None",
",",
"evalue",
"=",
"None",
",",
"erepr",
"=",
"None",
")",
":",
"self",
".",
"_set",
"(",
"'reload-on-exception'",
",",
"do_reload",
",",
"cast",
"=",
"bool",
")",
"self",
".",
"_set",
"(",
"'reload-on-exception-type'",
",",
"etype",
")",
"self",
".",
"_set",
"(",
"'reload-on-exception-value'",
",",
"evalue",
")",
"self",
".",
"_set",
"(",
"'reload-on-exception-repr'",
",",
"erepr",
")",
"return",
"self",
".",
"_section"
] |
Registers new events after instance creation
|
def register_event ( self , * names ) : for name in names : if name in self . __events : continue self . __events [ name ] = Event ( name )
| 2,332
|
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L125-L134
|
[
"def",
"_read",
"(",
"self",
")",
":",
"while",
"self",
".",
"_rxactive",
":",
"try",
":",
"rv",
"=",
"self",
".",
"_ep_in",
".",
"read",
"(",
"self",
".",
"_ep_in",
".",
"wMaxPacketSize",
")",
"if",
"self",
".",
"_isFTDI",
":",
"status",
"=",
"rv",
"[",
":",
"2",
"]",
"# FTDI prepends 2 flow control characters,",
"# modem status and line status of the UART",
"if",
"status",
"[",
"0",
"]",
"!=",
"1",
"or",
"status",
"[",
"1",
"]",
"!=",
"0x60",
":",
"log",
".",
"info",
"(",
"\"USB Status: 0x{0:02X} 0x{1:02X}\"",
".",
"format",
"(",
"*",
"status",
")",
")",
"rv",
"=",
"rv",
"[",
"2",
":",
"]",
"for",
"rvi",
"in",
"rv",
":",
"self",
".",
"_rxqueue",
".",
"put",
"(",
"rvi",
")",
"except",
"usb",
".",
"USBError",
"as",
"e",
":",
"log",
".",
"warn",
"(",
"\"USB Error on _read {}\"",
".",
"format",
"(",
"e",
")",
")",
"return",
"time",
".",
"sleep",
"(",
"self",
".",
"_rxinterval",
")"
] |
Dispatches an event to any subscribed listeners
|
def emit ( self , name , * args , * * kwargs ) : e = self . __property_events . get ( name ) if e is None : e = self . __events [ name ] return e ( * args , * * kwargs )
| 2,333
|
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L236-L251
|
[
"def",
"skeleton",
"(",
"files",
",",
"metadata",
",",
"sqlite_extensions",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"metadata",
")",
":",
"click",
".",
"secho",
"(",
"\"File {} already exists, will not over-write\"",
".",
"format",
"(",
"metadata",
")",
",",
"bg",
"=",
"\"red\"",
",",
"fg",
"=",
"\"white\"",
",",
"bold",
"=",
"True",
",",
"err",
"=",
"True",
",",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"app",
"=",
"Datasette",
"(",
"files",
",",
"sqlite_extensions",
"=",
"sqlite_extensions",
")",
"databases",
"=",
"{",
"}",
"for",
"database_name",
",",
"info",
"in",
"app",
".",
"inspect",
"(",
")",
".",
"items",
"(",
")",
":",
"databases",
"[",
"database_name",
"]",
"=",
"{",
"\"title\"",
":",
"None",
",",
"\"description\"",
":",
"None",
",",
"\"description_html\"",
":",
"None",
",",
"\"license\"",
":",
"None",
",",
"\"license_url\"",
":",
"None",
",",
"\"source\"",
":",
"None",
",",
"\"source_url\"",
":",
"None",
",",
"\"queries\"",
":",
"{",
"}",
",",
"\"tables\"",
":",
"{",
"table_name",
":",
"{",
"\"title\"",
":",
"None",
",",
"\"description\"",
":",
"None",
",",
"\"description_html\"",
":",
"None",
",",
"\"license\"",
":",
"None",
",",
"\"license_url\"",
":",
"None",
",",
"\"source\"",
":",
"None",
",",
"\"source_url\"",
":",
"None",
",",
"\"units\"",
":",
"{",
"}",
",",
"}",
"for",
"table_name",
"in",
"(",
"info",
".",
"get",
"(",
"\"tables\"",
")",
"or",
"{",
"}",
")",
"}",
",",
"}",
"open",
"(",
"metadata",
",",
"\"w\"",
")",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"{",
"\"title\"",
":",
"None",
",",
"\"description\"",
":",
"None",
",",
"\"description_html\"",
":",
"None",
",",
"\"license\"",
":",
"None",
",",
"\"license_url\"",
":",
"None",
",",
"\"source\"",
":",
"None",
",",
"\"source_url\"",
":",
"None",
",",
"\"databases\"",
":",
"databases",
",",
"}",
",",
"indent",
"=",
"4",
",",
")",
")",
"click",
".",
"echo",
"(",
"\"Wrote skeleton to {}\"",
".",
"format",
"(",
"metadata",
")",
")"
] |
Retrieves an Event object by name
|
def get_dispatcher_event ( self , name ) : e = self . __property_events . get ( name ) if e is None : e = self . __events [ name ] return e
| 2,334
|
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L252-L267
|
[
"def",
"_generate_question",
"(",
"self",
")",
":",
"x",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"10",
")",
"y",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"10",
")",
"operator",
"=",
"random",
".",
"choice",
"(",
"(",
"'+'",
",",
"'-'",
",",
"'*'",
",",
")",
")",
"if",
"operator",
"==",
"'+'",
":",
"answer",
"=",
"x",
"+",
"y",
"elif",
"operator",
"==",
"'-'",
":",
"# Ensure we'll get a non-negative answer",
"if",
"x",
"<",
"y",
":",
"x",
",",
"y",
"=",
"y",
",",
"x",
"answer",
"=",
"x",
"-",
"y",
"else",
":",
"# Multiplication is hard, make it easier",
"x",
"=",
"math",
".",
"ceil",
"(",
"x",
"/",
"2",
")",
"y",
"=",
"math",
".",
"ceil",
"(",
"y",
"/",
"2",
")",
"answer",
"=",
"x",
"*",
"y",
"# Use a prettied-up HTML multiplication character",
"operator",
"=",
"'×'",
"# Format the answer nicely, then mark it as safe so Django won't escape it",
"question",
"=",
"'{} {} {}'",
".",
"format",
"(",
"x",
",",
"operator",
",",
"y",
")",
"return",
"mark_safe",
"(",
"question",
")",
",",
"answer"
] |
Holds emission of events and dispatches the last event on release
|
def emission_lock ( self , name ) : e = self . __property_events . get ( name ) if e is None : e = self . __events [ name ] return e . emission_lock
| 2,335
|
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L268-L309
|
[
"def",
"tmatrix_cov",
"(",
"C",
",",
"k",
"=",
"None",
")",
":",
"if",
"issparse",
"(",
"C",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Covariance matrix will be dense for sparse input\"",
")",
"C",
"=",
"C",
".",
"toarray",
"(",
")",
"return",
"dense",
".",
"covariance",
".",
"tmatrix_cov",
"(",
"C",
",",
"row",
"=",
"k",
")"
] |
Test function to step through all functions in order to try and identify all features on a map This test function should be placed in a main section later
|
def TEST ( fname ) : #fname = os.path.join(os.getcwd(), '..','..', # os.path.join(os.path.getcwd(), ' m = MapObject ( fname , os . path . join ( os . getcwd ( ) , 'img_prog_results' ) ) m . add_layer ( ImagePathFollow ( 'border' ) ) m . add_layer ( ImagePathFollow ( 'river' ) ) m . add_layer ( ImagePathFollow ( 'road' ) ) m . add_layer ( ImageArea ( 'sea' , col = 'Blue' , density = 'light' ) ) m . add_layer ( ImageArea ( 'desert' , col = 'Yellow' , density = 'med' ) ) m . add_layer ( ImageArea ( 'forest' , col = 'Drak Green' , density = 'light' ) ) m . add_layer ( ImageArea ( 'fields' , col = 'Green' , density = 'light' ) ) m . add_layer ( ImageObject ( 'mountains' ) ) m . add_layer ( ImageObject ( 'trees' ) ) m . add_layer ( ImageObject ( 'towns' ) )
| 2,336
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/image_detection_tools.py#L41-L61
|
[
"def",
"loadInternalSheet",
"(",
"klass",
",",
"p",
",",
"*",
"*",
"kwargs",
")",
":",
"vs",
"=",
"klass",
"(",
"p",
".",
"name",
",",
"source",
"=",
"p",
",",
"*",
"*",
"kwargs",
")",
"options",
".",
"_set",
"(",
"'encoding'",
",",
"'utf8'",
",",
"vs",
")",
"if",
"p",
".",
"exists",
"(",
")",
":",
"vd",
".",
"sheets",
".",
"insert",
"(",
"0",
",",
"vs",
")",
"vs",
".",
"reload",
".",
"__wrapped__",
"(",
"vs",
")",
"vd",
".",
"sheets",
".",
"pop",
"(",
"0",
")",
"return",
"vs"
] |
describes various contents of data table
|
def describe_contents ( self ) : print ( '======================================================================' ) print ( self ) print ( 'Table = ' , str ( len ( self . header ) ) + ' cols x ' + str ( len ( self . arr ) ) + ' rows' ) print ( 'HEADER = ' , self . get_header ( ) ) print ( 'arr = ' , self . arr [ 0 : 2 ] )
| 2,337
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L68-L74
|
[
"def",
"_verify",
"(",
"vm_",
")",
":",
"log",
".",
"info",
"(",
"'Verifying credentials for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"win_installer",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'win_installer'",
",",
"vm_",
",",
"__opts__",
")",
"if",
"win_installer",
":",
"log",
".",
"debug",
"(",
"'Testing Windows authentication method for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"if",
"not",
"HAS_IMPACKET",
":",
"log",
".",
"error",
"(",
"'Impacket library not found'",
")",
"return",
"False",
"# Test Windows connection",
"kwargs",
"=",
"{",
"'host'",
":",
"vm_",
"[",
"'ssh_host'",
"]",
",",
"'username'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'win_username'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'Administrator'",
")",
",",
"'password'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'win_password'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"''",
")",
"}",
"# Test SMB connection",
"try",
":",
"log",
".",
"debug",
"(",
"'Testing SMB protocol for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"if",
"__utils__",
"[",
"'smb.get_conn'",
"]",
"(",
"*",
"*",
"kwargs",
")",
"is",
"False",
":",
"return",
"False",
"except",
"(",
"smbSessionError",
",",
"smb3SessionError",
")",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Exception: %s'",
",",
"exc",
")",
"return",
"False",
"# Test WinRM connection",
"use_winrm",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'use_winrm'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"False",
")",
"if",
"use_winrm",
":",
"log",
".",
"debug",
"(",
"'WinRM protocol requested for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"if",
"not",
"HAS_WINRM",
":",
"log",
".",
"error",
"(",
"'WinRM library not found'",
")",
"return",
"False",
"kwargs",
"[",
"'port'",
"]",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'winrm_port'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"5986",
")",
"kwargs",
"[",
"'timeout'",
"]",
"=",
"10",
"try",
":",
"log",
".",
"debug",
"(",
"'Testing WinRM protocol for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"return",
"__utils__",
"[",
"'cloud.wait_for_winrm'",
"]",
"(",
"*",
"*",
"kwargs",
")",
"is",
"not",
"None",
"except",
"(",
"ConnectionError",
",",
"ConnectTimeout",
",",
"ReadTimeout",
",",
"SSLError",
",",
"ProxyError",
",",
"RetryError",
",",
"InvalidSchema",
",",
"WinRMTransportError",
")",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Exception: %s'",
",",
"exc",
")",
"return",
"False",
"return",
"True",
"else",
":",
"log",
".",
"debug",
"(",
"'Testing SSH authentication method for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"# Test SSH connection",
"kwargs",
"=",
"{",
"'host'",
":",
"vm_",
"[",
"'ssh_host'",
"]",
",",
"'port'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_port'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"22",
")",
",",
"'username'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_username'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'root'",
")",
",",
"'password'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'password'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
",",
"'key_filename'",
":",
"config",
".",
"get_cloud_config_value",
"(",
"'key_filename'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_keyfile'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"None",
")",
")",
",",
"'gateway'",
":",
"vm_",
".",
"get",
"(",
"'gateway'",
",",
"None",
")",
",",
"'maxtries'",
":",
"1",
"}",
"log",
".",
"debug",
"(",
"'Testing SSH protocol for %s'",
",",
"vm_",
"[",
"'name'",
"]",
")",
"try",
":",
"return",
"__utils__",
"[",
"'cloud.wait_for_passwd'",
"]",
"(",
"*",
"*",
"kwargs",
")",
"is",
"True",
"except",
"SaltCloudException",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Exception: %s'",
",",
"exc",
")",
"return",
"False"
] |
returns the list of distinct combinations in a dataset based on the columns in the list . Note that this is currently implemented as MAX permutations of the combo so it is not guarenteed to have values in each case .
|
def get_distinct_values_from_cols ( self , l_col_list ) : uniq_vals = [ ] for l_col_name in l_col_list : #print('col_name: ' + l_col_name) uniq_vals . append ( set ( self . get_col_data_by_name ( l_col_name ) ) ) #print(' unique values = ', uniq_vals) #print(' unique values[0] = ', uniq_vals[0]) #print(' unique values[1] = ', uniq_vals[1]) if len ( l_col_list ) == 0 : return [ ] elif len ( l_col_list ) == 1 : return sorted ( [ v for v in uniq_vals ] ) elif len ( l_col_list ) == 2 : res = [ ] res = [ ( a , b ) for a in uniq_vals [ 0 ] for b in uniq_vals [ 1 ] ] return res else : print ( "TODO " ) return - 44
| 2,338
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L79-L104
|
[
"def",
"setLog",
"(",
"self",
",",
"fileName",
",",
"writeName",
"=",
"False",
")",
":",
"self",
".",
"log",
"=",
"1",
"self",
".",
"logFile",
"=",
"fileName",
"self",
".",
"_logPtr",
"=",
"open",
"(",
"fileName",
",",
"\"w\"",
")",
"if",
"writeName",
":",
"self",
".",
"_namePtr",
"=",
"open",
"(",
"fileName",
"+",
"\".name\"",
",",
"\"w\"",
")"
] |
selects rows from the array where col_list == val_list
|
def select_where ( self , where_col_list , where_value_list , col_name = '' ) : res = [ ] # list of rows to be returned col_ids = [ ] # ids of the columns to check #print('select_where : arr = ', len(self.arr), 'where_value_list = ', where_value_list) for col_id , col in enumerate ( self . header ) : if col in where_col_list : col_ids . append ( [ col_id , col ] ) #print('select_where : col_ids = ', col_ids) # correctly prints [[0, 'TERM'], [2, 'ID']] for row_num , row in enumerate ( self . arr ) : keep_this_row = True #print('col_ids=', col_ids, ' row = ', row_num, row) for ndx , where_col in enumerate ( col_ids ) : #print('type where_value_list[ndx] = ', type(where_value_list[ndx])) #print('type row[where_col[0]] = ', type(row[where_col[0]])) if row [ where_col [ 0 ] ] != where_value_list [ ndx ] : keep_this_row = False if keep_this_row is True : if col_name == '' : res . append ( [ row_num , row ] ) else : # extracting a single column only l_dat = self . get_col_by_name ( col_name ) if l_dat is not None : res . append ( row [ l_dat ] ) return res
| 2,339
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L117-L145
|
[
"def",
"device_info",
"(",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"(",
"device_info",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"_pa",
".",
"Pa_GetDeviceCount",
"(",
")",
")",
")",
"else",
":",
"info",
"=",
"_pa",
".",
"Pa_GetDeviceInfo",
"(",
"index",
")",
"if",
"not",
"info",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid device\"",
")",
"assert",
"info",
".",
"structVersion",
"==",
"2",
"if",
"'DirectSound'",
"in",
"hostapi_info",
"(",
"info",
".",
"hostApi",
")",
"[",
"'name'",
"]",
":",
"enc",
"=",
"'mbcs'",
"else",
":",
"enc",
"=",
"'utf-8'",
"return",
"{",
"'name'",
":",
"ffi",
".",
"string",
"(",
"info",
".",
"name",
")",
".",
"decode",
"(",
"encoding",
"=",
"enc",
",",
"errors",
"=",
"'ignore'",
")",
",",
"'hostapi'",
":",
"info",
".",
"hostApi",
",",
"'max_input_channels'",
":",
"info",
".",
"maxInputChannels",
",",
"'max_output_channels'",
":",
"info",
".",
"maxOutputChannels",
",",
"'default_low_input_latency'",
":",
"info",
".",
"defaultLowInputLatency",
",",
"'default_low_output_latency'",
":",
"info",
".",
"defaultLowOutputLatency",
",",
"'default_high_input_latency'",
":",
"info",
".",
"defaultHighInputLatency",
",",
"'default_high_output_latency'",
":",
"info",
".",
"defaultHighOutputLatency",
",",
"'default_samplerate'",
":",
"info",
".",
"defaultSampleRate",
"}"
] |
updates the array to set cell = value where col_list == val_list
|
def update_where ( self , col , value , where_col_list , where_value_list ) : if type ( col ) is str : col_ndx = self . get_col_by_name ( col ) else : col_ndx = col #print('col_ndx = ', col_ndx ) #print("updating " + col + " to " , value, " where " , where_col_list , " = " , where_value_list) new_arr = self . select_where ( where_col_list , where_value_list ) #print('new_arr', new_arr) for r in new_arr : self . arr [ r [ 0 ] ] [ col_ndx ] = value
| 2,340
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L171-L184
|
[
"def",
"sections",
"(",
"self",
")",
":",
"secs",
"=",
"OrderedDict",
"(",
")",
"secs",
"[",
"'Overview'",
"]",
"=",
"self",
".",
"sec_overview",
"secs",
"[",
"'Communication Channels'",
"]",
"=",
"self",
".",
"sec_com_channels",
"secs",
"[",
"'Detailed Activity by Project'",
"]",
"=",
"self",
".",
"sec_projects",
"return",
"secs"
] |
calculates the num percentile of the items in the list
|
def percentile ( self , lst_data , percent , key = lambda x : x ) : new_list = sorted ( lst_data ) #print('new list = ' , new_list) #n = float(len(lst_data)) k = ( len ( new_list ) - 1 ) * percent f = math . floor ( k ) c = math . ceil ( k ) if f == c : #print(key(new_list[int(k)])) return key ( new_list [ int ( k ) ] ) d0 = float ( key ( new_list [ int ( f ) ] ) ) * ( c - k ) d1 = float ( key ( new_list [ int ( c ) ] ) ) * ( k - f ) return d0 + d1
| 2,341
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L206-L219
|
[
"def",
"cli",
"(",
"ctx",
",",
"board",
",",
"serial_port",
",",
"ftdi_id",
",",
"sram",
",",
"project_dir",
",",
"verbose",
",",
"verbose_yosys",
",",
"verbose_arachne",
")",
":",
"drivers",
"=",
"Drivers",
"(",
")",
"drivers",
".",
"pre_upload",
"(",
")",
"# Run scons",
"exit_code",
"=",
"SCons",
"(",
"project_dir",
")",
".",
"upload",
"(",
"{",
"'board'",
":",
"board",
",",
"'verbose'",
":",
"{",
"'all'",
":",
"verbose",
",",
"'yosys'",
":",
"verbose_yosys",
",",
"'arachne'",
":",
"verbose_arachne",
"}",
"}",
",",
"serial_port",
",",
"ftdi_id",
",",
"sram",
")",
"drivers",
".",
"post_upload",
"(",
")",
"ctx",
".",
"exit",
"(",
"exit_code",
")"
] |
default is to save a file from list of lines
|
def save ( self , filename , content ) : with open ( filename , "w" ) as f : if hasattr ( content , '__iter__' ) : f . write ( '\n' . join ( [ row for row in content ] ) ) else : print ( 'WRINGI CONTWETESWREWR' ) f . write ( str ( content ) )
| 2,342
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L230-L239
|
[
"def",
"sys_check_for_event",
"(",
"mask",
":",
"int",
",",
"k",
":",
"Optional",
"[",
"Key",
"]",
",",
"m",
":",
"Optional",
"[",
"Mouse",
"]",
")",
"->",
"int",
":",
"return",
"int",
"(",
"lib",
".",
"TCOD_sys_check_for_event",
"(",
"mask",
",",
"k",
".",
"key_p",
"if",
"k",
"else",
"ffi",
".",
"NULL",
",",
"m",
".",
"mouse_p",
"if",
"m",
"else",
"ffi",
".",
"NULL",
")",
")"
] |
save the default array as a CSV file
|
def save_csv ( self , filename , write_header_separately = True ) : txt = '' #print("SAVING arr = ", self.arr) with open ( filename , "w" ) as f : if write_header_separately : f . write ( ',' . join ( [ c for c in self . header ] ) + '\n' ) for row in self . arr : #print('save_csv: saving row = ', row) txt = ',' . join ( [ self . force_to_string ( col ) for col in row ] ) #print(txt) f . write ( txt + '\n' ) f . write ( '\n' )
| 2,343
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L241-L256
|
[
"def",
"wait_for",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"TIMEOUT",
")",
"start",
"=",
"None",
"while",
"True",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"AssertionError",
":",
"# The function took some time to test the assertion, however,",
"# the result might correspond to the state of the world at any",
"# point in time, perhaps earlier than the timeout. Therefore,",
"# start counting time from the first assertion fail, not from",
"# before the function was called.",
"if",
"not",
"start",
":",
"start",
"=",
"time",
"(",
")",
"if",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"sleep",
"(",
"CHECK_EVERY",
")",
"continue",
"else",
":",
"raise",
"return",
"wrapped"
] |
drop the table view or delete the file
|
def drop ( self , fname ) : if self . dataset_type == 'file' : import os try : os . remove ( fname ) except Exception as ex : print ( 'cant drop file "' + fname + '" : ' + str ( ex ) )
| 2,344
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L258-L267
|
[
"def",
"add_intersection",
"(",
"s",
",",
"t",
",",
"intersections",
")",
":",
"if",
"not",
"intersections",
":",
"intersections",
".",
"append",
"(",
"(",
"s",
",",
"t",
")",
")",
"return",
"if",
"s",
"<",
"_intersection_helpers",
".",
"ZERO_THRESHOLD",
":",
"candidate_s",
"=",
"1.0",
"-",
"s",
"else",
":",
"candidate_s",
"=",
"s",
"if",
"t",
"<",
"_intersection_helpers",
".",
"ZERO_THRESHOLD",
":",
"candidate_t",
"=",
"1.0",
"-",
"t",
"else",
":",
"candidate_t",
"=",
"t",
"norm_candidate",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"[",
"candidate_s",
",",
"candidate_t",
"]",
",",
"ord",
"=",
"2",
")",
"for",
"existing_s",
",",
"existing_t",
"in",
"intersections",
":",
"# NOTE: |(1 - s1) - (1 - s2)| = |s1 - s2| in exact arithmetic, so",
"# we just compute ``s1 - s2`` rather than using",
"# ``candidate_s`` / ``candidate_t``. Due to round-off, these",
"# differences may be slightly different, but only up to machine",
"# precision.",
"delta_s",
"=",
"s",
"-",
"existing_s",
"delta_t",
"=",
"t",
"-",
"existing_t",
"norm_update",
"=",
"np",
".",
"linalg",
".",
"norm",
"(",
"[",
"delta_s",
",",
"delta_t",
"]",
",",
"ord",
"=",
"2",
")",
"if",
"(",
"norm_update",
"<",
"_intersection_helpers",
".",
"NEWTON_ERROR_RATIO",
"*",
"norm_candidate",
")",
":",
"return",
"intersections",
".",
"append",
"(",
"(",
"s",
",",
"t",
")",
")"
] |
returns the values of col_name according to where
|
def get_col_data_by_name ( self , col_name , WHERE_Clause = '' ) : #print('get_col_data_by_name: col_name = ', col_name, ' WHERE = ', WHERE_Clause) col_key = self . get_col_by_name ( col_name ) if col_key is None : print ( 'get_col_data_by_name: col_name = ' , col_name , ' NOT FOUND' ) return [ ] #print('get_col_data_by_name: col_key =', col_key) res = [ ] for row in self . arr : #print('col_key=',col_key, ' len(row)=', len(row), ' row=', row) res . append ( row [ col_key ] ) # need to convert to int for calcs but leave as string for lookups return res
| 2,345
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L311-L323
|
[
"async",
"def",
"expand",
"(",
"self",
",",
"request",
":",
"Request",
",",
"layer",
":",
"BaseLayer",
")",
":",
"if",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"RawText",
")",
":",
"t",
"=",
"self",
".",
"reading_time",
"(",
"layer",
".",
"text",
")",
"yield",
"layer",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"elif",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"MultiText",
")",
":",
"texts",
"=",
"await",
"render",
"(",
"layer",
".",
"text",
",",
"request",
",",
"True",
")",
"for",
"text",
"in",
"texts",
":",
"t",
"=",
"self",
".",
"reading_time",
"(",
"text",
")",
"yield",
"lyr",
".",
"RawText",
"(",
"text",
")",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"elif",
"isinstance",
"(",
"layer",
",",
"lyr",
".",
"Text",
")",
":",
"text",
"=",
"await",
"render",
"(",
"layer",
".",
"text",
",",
"request",
")",
"t",
"=",
"self",
".",
"reading_time",
"(",
"text",
")",
"yield",
"lyr",
".",
"RawText",
"(",
"text",
")",
"yield",
"lyr",
".",
"Sleep",
"(",
"t",
")",
"else",
":",
"yield",
"layer"
] |
return table in RST format
|
def format_rst ( self ) : res = '' num_cols = len ( self . header ) col_width = 25 for _ in range ( num_cols ) : res += '' . join ( [ '=' for _ in range ( col_width - 1 ) ] ) + ' ' res += '\n' for c in self . header : res += c . ljust ( col_width ) res += '\n' for _ in range ( num_cols ) : res += '' . join ( [ '=' for _ in range ( col_width - 1 ) ] ) + ' ' res += '\n' for row in self . arr : for c in row : res += self . force_to_string ( c ) . ljust ( col_width ) res += '\n' for _ in range ( num_cols ) : res += '' . join ( [ '=' for _ in range ( col_width - 1 ) ] ) + ' ' res += '\n' return res
| 2,346
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/dataTools/cls_datatable.py#L325-L348
|
[
"def",
"_get_supervisorctl_bin",
"(",
"bin_env",
")",
":",
"cmd",
"=",
"'supervisorctl'",
"if",
"not",
"bin_env",
":",
"which_result",
"=",
"__salt__",
"[",
"'cmd.which_bin'",
"]",
"(",
"[",
"cmd",
"]",
")",
"if",
"which_result",
"is",
"None",
":",
"raise",
"CommandNotFoundError",
"(",
"'Could not find a `{0}` binary'",
".",
"format",
"(",
"cmd",
")",
")",
"return",
"which_result",
"# try to get binary from env",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"bin_env",
")",
":",
"cmd_bin",
"=",
"os",
".",
"path",
".",
"join",
"(",
"bin_env",
",",
"'bin'",
",",
"cmd",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"cmd_bin",
")",
":",
"return",
"cmd_bin",
"raise",
"CommandNotFoundError",
"(",
"'Could not find a `{0}` binary'",
".",
"format",
"(",
"cmd",
")",
")",
"return",
"bin_env"
] |
Returns NBCI s Homolog Gene tables .
|
def getHomoloGene ( taxfile = "build_inputs/taxid_taxname" , genefile = "homologene.data" , proteinsfile = "build_inputs/all_proteins.data" , proteinsclusterfile = "build_inputs/proteins_for_clustering.data" , baseURL = "http://ftp.ncbi.nih.gov/pub/HomoloGene/current/" ) : def getDf ( inputfile ) : if os . path . isfile ( inputfile ) : df = pd . read_table ( inputfile , header = None ) else : df = urllib2 . urlopen ( baseURL + inputfile ) df = df . read ( ) . split ( "\n" ) df = [ s for s in df if len ( s ) > 0 ] df = [ s . split ( "\t" ) for s in df ] df = pd . DataFrame ( df ) return df taxdf = getDf ( taxfile ) taxdf . set_index ( [ 0 ] , inplace = True ) taxdi = taxdf . to_dict ( ) . get ( 1 ) genedf = getDf ( genefile ) genecols = [ "HID" , "Taxonomy ID" , "Gene ID" , "Gene Symbol" , "Protein gi" , "Protein accession" ] genedf . columns = genecols genedf [ "organism" ] = genedf [ "Taxonomy ID" ] . apply ( lambda x : taxdi . get ( x ) ) proteinsdf = getDf ( proteinsfile ) proteinscols = [ "taxid" , "entrez GeneID" , "gene symbol" , "gene description" , "protein accession.ver" , "mrna accession.ver" , "length of protein listed in column 5" , "-11) contains data about gene location on the genome" , "starting position of gene in 0-based coordinate" , "end position of the gene in 0-based coordinate" , "strand" , "nucleotide gi of genomic sequence where this gene is annotated" ] proteinsdf . columns = proteinscols proteinsdf [ "organism" ] = proteinsdf [ "taxid" ] . apply ( lambda x : taxdi . get ( x ) ) protclusdf = getDf ( proteinsclusterfile ) protclustercols = [ "taxid" , "entrez GeneID" , "gene symbol" , "gene description" , "protein accession.ver" , "mrna accession.ver" , "length of protein listed in column 5" , "-11) contains data about gene location on the genome" , "starting position of gene in 0-based coordinate" , "end position of the gene in 0-based coordinate" , "strand" , "nucleotide gi of genomic sequence where this gene is annotated" ] protclusdf . columns = proteinscols protclusdf [ "organism" ] = protclusdf [ "taxid" ] . apply ( lambda x : taxdi . get ( x ) ) return genedf , protclusdf , proteinsdf
| 2,347
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/homology.py#L6-L66
|
[
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Retrieves a sequence from an opened multifasta file
|
def getFasta ( opened_file , sequence_name ) : lines = opened_file . readlines ( ) seq = str ( "" ) for i in range ( 0 , len ( lines ) ) : line = lines [ i ] if line [ 0 ] == ">" : fChr = line . split ( " " ) [ 0 ] . split ( "\n" ) [ 0 ] fChr = fChr [ 1 : ] if fChr == sequence_name : s = i code = [ 'N' , 'A' , 'C' , 'T' , 'G' ] firstbase = lines [ s + 1 ] [ 0 ] while firstbase in code : s = s + 1 seq = seq + lines [ s ] firstbase = lines [ s + 1 ] [ 0 ] if len ( seq ) == 0 : seq = None else : seq = seq . split ( "\n" ) seq = "" . join ( seq ) return seq
| 2,348
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/fasta.py#L2-L34
|
[
"def",
"check_extraneous",
"(",
"config",
",",
"schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"Config {} is not a dictionary\"",
".",
"format",
"(",
"config",
")",
")",
"for",
"k",
"in",
"config",
":",
"if",
"k",
"not",
"in",
"schema",
":",
"raise",
"ValueError",
"(",
"\"Unexpected config key `{}` not in {}\"",
".",
"format",
"(",
"k",
",",
"list",
"(",
"schema",
".",
"keys",
"(",
")",
")",
")",
")",
"v",
",",
"kreq",
"=",
"schema",
"[",
"k",
"]",
"if",
"v",
"is",
"None",
":",
"continue",
"elif",
"isinstance",
"(",
"v",
",",
"type",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
"[",
"k",
"]",
",",
"v",
")",
":",
"if",
"v",
"is",
"str",
"and",
"isinstance",
"(",
"config",
"[",
"k",
"]",
",",
"string_types",
")",
":",
"continue",
"raise",
"ValueError",
"(",
"\"Config key `{}` has wrong type {}, expected {}\"",
".",
"format",
"(",
"k",
",",
"type",
"(",
"config",
"[",
"k",
"]",
")",
".",
"__name__",
",",
"v",
".",
"__name__",
")",
")",
"else",
":",
"check_extraneous",
"(",
"config",
"[",
"k",
"]",
",",
"v",
")"
] |
Writes a fasta sequence into a file .
|
def writeFasta ( sequence , sequence_name , output_file ) : i = 0 f = open ( output_file , 'w' ) f . write ( ">" + str ( sequence_name ) + "\n" ) while i <= len ( sequence ) : f . write ( sequence [ i : i + 60 ] + "\n" ) i = i + 60 f . close ( )
| 2,349
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/fasta.py#L36-L52
|
[
"def",
"uniform_partition_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"False",
")",
":",
"grid",
"=",
"uniform_grid_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"nodes_on_bdry",
")",
"return",
"RectPartition",
"(",
"intv_prod",
",",
"grid",
")"
] |
Rewrites a specific sequence in a multifasta file while keeping the sequence header .
|
def rewriteFasta ( sequence , sequence_name , fasta_in , fasta_out ) : f = open ( fasta_in , 'r+' ) f2 = open ( fasta_out , 'w' ) lines = f . readlines ( ) i = 0 while i < len ( lines ) : line = lines [ i ] if line [ 0 ] == ">" : f2 . write ( line ) fChr = line . split ( " " ) [ 0 ] fChr = fChr [ 1 : ] if fChr == sequence_name : code = [ 'N' , 'A' , 'C' , 'T' , 'G' ] firstbase = lines [ i + 1 ] [ 0 ] while firstbase in code : i = i + 1 firstbase = lines [ i ] [ 0 ] s = 0 while s <= len ( sequence ) : f2 . write ( sequence [ s : s + 60 ] + "\n" ) s = s + 60 else : i = i + 1 else : f2 . write ( line ) i = i + 1 f2 . close f . close
| 2,350
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/fasta.py#L54-L92
|
[
"def",
"perturb_vec",
"(",
"q",
",",
"cone_half_angle",
"=",
"2",
")",
":",
"rand_vec",
"=",
"tan_rand",
"(",
"q",
")",
"cross_vector",
"=",
"attitude",
".",
"unit_vector",
"(",
"np",
".",
"cross",
"(",
"q",
",",
"rand_vec",
")",
")",
"s",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
",",
"1",
")",
"r",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"0",
",",
"1",
",",
"1",
")",
"h",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"deg2rad",
"(",
"cone_half_angle",
")",
")",
"phi",
"=",
"2",
"*",
"np",
".",
"pi",
"*",
"s",
"z",
"=",
"h",
"+",
"(",
"1",
"-",
"h",
")",
"*",
"r",
"sinT",
"=",
"np",
".",
"sqrt",
"(",
"1",
"-",
"z",
"**",
"2",
")",
"x",
"=",
"np",
".",
"cos",
"(",
"phi",
")",
"*",
"sinT",
"y",
"=",
"np",
".",
"sin",
"(",
"phi",
")",
"*",
"sinT",
"perturbed",
"=",
"rand_vec",
"*",
"x",
"+",
"cross_vector",
"*",
"y",
"+",
"q",
"*",
"z",
"return",
"perturbed"
] |
get a string representation of the tool
|
def _get_tool_str ( self , tool ) : res = tool [ 'file' ] try : res += '.' + tool [ 'function' ] except Exception as ex : print ( 'Warning - no function defined for tool ' + str ( tool ) ) res += '\n' return res
| 2,351
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/Toolbox.py#L42-L52
|
[
"def",
"merge_entities",
"(",
"self",
",",
"from_entity_ids",
",",
"to_entity_id",
",",
"force",
"=",
"False",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"params",
"=",
"{",
"'from_entity_ids'",
":",
"from_entity_ids",
",",
"'to_entity_id'",
":",
"to_entity_id",
",",
"'force'",
":",
"force",
",",
"}",
"api_path",
"=",
"'/v1/{mount_point}/entity/merge'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
")",
"return",
"self",
".",
"_adapter",
".",
"post",
"(",
"url",
"=",
"api_path",
",",
"json",
"=",
"params",
",",
")"
] |
get the tool object by name or file
|
def get_tool_by_name ( self , nme ) : for t in self . lstTools : if 'name' in t : if t [ 'name' ] == nme : return t if 'file' in t : if t [ 'file' ] == nme : return t return None
| 2,352
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/Toolbox.py#L54-L65
|
[
"def",
"last_seen",
"(",
"self",
")",
":",
"\"\"\"\n These values seem to be rarely updated correctly in the API.\n Don't expect accurate results from this property.\n \"\"\"",
"try",
":",
"if",
"self",
".",
"side",
"==",
"'left'",
":",
"lastseen",
"=",
"self",
".",
"device",
".",
"device_data",
"[",
"'leftPresenceEnd'",
"]",
"elif",
"self",
".",
"side",
"==",
"'right'",
":",
"lastseen",
"=",
"self",
".",
"device",
".",
"device_data",
"[",
"'rightPresenceEnd'",
"]",
"date",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"int",
"(",
"lastseen",
")",
")",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%S'",
")",
"return",
"date",
"except",
"TypeError",
":",
"return",
"None"
] |
Save the list of tools to AIKIF core and optionally to local file fname
|
def save ( self , fname = '' ) : if fname != '' : with open ( fname , 'w' ) as f : for t in self . lstTools : self . verify ( t ) f . write ( self . tool_as_string ( t ) )
| 2,353
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/Toolbox.py#L88-L96
|
[
"def",
"create_or_update",
"(",
"cls",
",",
"bucket",
",",
"key",
",",
"value",
")",
":",
"obj",
"=",
"cls",
".",
"get",
"(",
"bucket",
",",
"key",
")",
"if",
"obj",
":",
"obj",
".",
"value",
"=",
"value",
"db",
".",
"session",
".",
"merge",
"(",
"obj",
")",
"else",
":",
"obj",
"=",
"cls",
".",
"create",
"(",
"bucket",
",",
"key",
",",
"value",
")",
"return",
"obj"
] |
check that the tool exists
|
def verify ( self , tool ) : if os . path . isfile ( tool [ 'file' ] ) : print ( 'Toolbox: program exists = TOK :: ' + tool [ 'file' ] ) return True else : print ( 'Toolbox: program exists = FAIL :: ' + tool [ 'file' ] ) return False
| 2,354
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/Toolbox.py#L98-L107
|
[
"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"
] |
import the tool and call the function passing the args .
|
def run ( self , tool , args , new_import_path = '' ) : if new_import_path != '' : #print('APPENDING PATH = ', new_import_path) sys . path . append ( new_import_path ) #if silent == 'N': print ( 'main called ' + tool [ 'file' ] + '->' + tool [ 'function' ] + ' with ' , args , ' = ' , tool [ 'return' ] ) mod = __import__ ( os . path . basename ( tool [ 'file' ] ) . split ( '.' ) [ 0 ] ) # for absolute folder names # mod = __import__( tool['file'][:-2]) # for aikif folders (doesnt work) func = getattr ( mod , tool [ 'function' ] ) tool [ 'return' ] = func ( args ) return tool [ 'return' ]
| 2,355
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/Toolbox.py#L109-L123
|
[
"def",
"get_inconsistent_fieldnames",
"(",
")",
":",
"field_name_list",
"=",
"[",
"]",
"for",
"fieldset_title",
",",
"fields_list",
"in",
"settings",
".",
"CONFIG_FIELDSETS",
".",
"items",
"(",
")",
":",
"for",
"field_name",
"in",
"fields_list",
":",
"field_name_list",
".",
"append",
"(",
"field_name",
")",
"if",
"not",
"field_name_list",
":",
"return",
"{",
"}",
"return",
"set",
"(",
"set",
"(",
"settings",
".",
"CONFIG",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"field_name_list",
")",
")"
] |
The Pipeline tool .
|
def main ( * * kwargs ) : options = ApplicationOptions ( * * kwargs ) Event . configure ( is_logging_enabled = options . event_logging ) application = Application ( options ) application . run ( options . definition )
| 2,356
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L209-L214
|
[
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Setup of application logging .
|
def setup_logging ( self ) : is_custom_logging = len ( self . options . logging_config ) > 0 is_custom_logging = is_custom_logging and os . path . isfile ( self . options . logging_config ) is_custom_logging = is_custom_logging and not self . options . dry_run if is_custom_logging : Logger . configure_by_file ( self . options . logging_config ) else : logging_format = "%(asctime)-15s - %(name)s - %(message)s" if self . options . dry_run : logging_format = "%(name)s - %(message)s" Logger . configure_default ( logging_format , self . logging_level )
| 2,357
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L56-L68
|
[
"def",
"get_response_content_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"_best_response_match",
"is",
"None",
":",
"settings",
"=",
"get_settings",
"(",
"self",
".",
"application",
",",
"force_instance",
"=",
"True",
")",
"acceptable",
"=",
"headers",
".",
"parse_accept",
"(",
"self",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Accept'",
",",
"settings",
".",
"default_content_type",
"if",
"settings",
".",
"default_content_type",
"else",
"'*/*'",
")",
")",
"try",
":",
"selected",
",",
"_",
"=",
"algorithms",
".",
"select_content_type",
"(",
"acceptable",
",",
"settings",
".",
"available_content_types",
")",
"self",
".",
"_best_response_match",
"=",
"'/'",
".",
"join",
"(",
"[",
"selected",
".",
"content_type",
",",
"selected",
".",
"content_subtype",
"]",
")",
"if",
"selected",
".",
"content_suffix",
"is",
"not",
"None",
":",
"self",
".",
"_best_response_match",
"=",
"'+'",
".",
"join",
"(",
"[",
"self",
".",
"_best_response_match",
",",
"selected",
".",
"content_suffix",
"]",
")",
"except",
"errors",
".",
"NoMatch",
":",
"self",
".",
"_best_response_match",
"=",
"settings",
".",
"default_content_type",
"return",
"self",
".",
"_best_response_match"
] |
Validate given pipeline document .
|
def validate_document ( self , definition ) : initial_document = { } try : initial_document = Loader . load ( definition ) except RuntimeError as exception : self . logger . error ( str ( exception ) ) sys . exit ( 1 ) document = Validator ( ) . validate ( initial_document ) if document is None : self . logger . info ( "Schema validation for '%s' has failed" , definition ) sys . exit ( 1 ) self . logger . info ( "Schema validation for '%s' succeeded" , definition ) return document
| 2,358
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L70-L101
|
[
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
Running pipeline via a matrix .
|
def run_matrix ( self , matrix_definition , document ) : matrix = Matrix ( matrix_definition , 'matrix(parallel)' in document ) process_data = MatrixProcessData ( ) process_data . options = self . options process_data . pipeline = document [ 'pipeline' ] process_data . model = { } if 'model' not in document else document [ 'model' ] process_data . hooks = Hooks ( document ) return matrix . process ( process_data )
| 2,359
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L103-L119
|
[
"def",
"get_last_live_chat",
"(",
"self",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"lcqs",
"=",
"self",
".",
"get_query_set",
"(",
")",
"lcqs",
"=",
"lcqs",
".",
"filter",
"(",
"chat_ends_at__lte",
"=",
"now",
",",
")",
".",
"order_by",
"(",
"'-chat_ends_at'",
")",
"for",
"itm",
"in",
"lcqs",
":",
"if",
"itm",
".",
"chat_ends_at",
"+",
"timedelta",
"(",
"days",
"=",
"3",
")",
">",
"now",
":",
"return",
"itm",
"return",
"None"
] |
Shutdown of the application .
|
def shutdown ( self , collector , success ) : self . event . delegate ( success ) if collector is not None : collector . queue . put ( None ) collector . join ( ) if not success : sys . exit ( 1 )
| 2,360
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L121-L128
|
[
"def",
"_assign_numbers",
"(",
"self",
")",
":",
"first",
"=",
"self",
".",
"select_related",
"(",
"'point_of_sales'",
",",
"'receipt_type'",
")",
".",
"first",
"(",
")",
"next_num",
"=",
"Receipt",
".",
"objects",
".",
"fetch_last_receipt_number",
"(",
"first",
".",
"point_of_sales",
",",
"first",
".",
"receipt_type",
",",
")",
"+",
"1",
"for",
"receipt",
"in",
"self",
".",
"filter",
"(",
"receipt_number__isnull",
"=",
"True",
")",
":",
"# Atomically update receipt number",
"Receipt",
".",
"objects",
".",
"filter",
"(",
"pk",
"=",
"receipt",
".",
"id",
",",
"receipt_number__isnull",
"=",
"True",
",",
")",
".",
"update",
"(",
"receipt_number",
"=",
"next_num",
",",
")",
"next_num",
"+=",
"1"
] |
When configured trying to ensure that path does exist .
|
def provide_temporary_scripts_path ( self ) : if len ( self . options . temporary_scripts_path ) > 0 : if os . path . isfile ( self . options . temporary_scripts_path ) : self . logger . error ( "Error: configured script path seems to be a file!" ) # it's ok to leave because called before the collector runs sys . exit ( 1 ) if not os . path . isdir ( self . options . temporary_scripts_path ) : os . makedirs ( self . options . temporary_scripts_path )
| 2,361
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L162-L171
|
[
"def",
"select_models",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'columns'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"don't pass 'columns' to select_models\"",
")",
"return",
"(",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"row",
")",
")",
"for",
"row",
"in",
"clas",
".",
"select",
"(",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
")"
] |
Create and run collector process for report data .
|
def create_and_run_collector ( document , options ) : collector = None if not options . report == 'off' : collector = Collector ( ) collector . store . configure ( document ) Event . configure ( collector_queue = collector . queue ) collector . start ( ) return collector
| 2,362
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/application.py#L174-L182
|
[
"def",
"create_core",
"(",
"self",
",",
"thing_name",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"cert_dir",
"=",
"None",
",",
"account_id",
"=",
"None",
",",
"policy_name",
"=",
"'ggc-default-policy'",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"config",
".",
"is_fresh",
"(",
")",
"is",
"False",
":",
"raise",
"ValueError",
"(",
"\"Config file already tracking previously created core or group\"",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
"self",
".",
"_region",
"if",
"account_id",
"is",
"None",
":",
"account_id",
"=",
"self",
".",
"_account_id",
"keys_cert",
",",
"thing",
"=",
"self",
".",
"create_thing",
"(",
"thing_name",
",",
"region",
",",
"cert_dir",
")",
"cert_arn",
"=",
"keys_cert",
"[",
"'certificateArn'",
"]",
"config",
"[",
"'core'",
"]",
"=",
"{",
"'thing_arn'",
":",
"thing",
"[",
"'thingArn'",
"]",
",",
"'cert_arn'",
":",
"cert_arn",
",",
"'cert_id'",
":",
"keys_cert",
"[",
"'certificateId'",
"]",
",",
"'thing_name'",
":",
"thing_name",
"}",
"logging",
".",
"debug",
"(",
"\"create_core cfg:{0}\"",
".",
"format",
"(",
"config",
")",
")",
"logging",
".",
"info",
"(",
"\"Thing:'{0}' associated with cert:'{1}'\"",
".",
"format",
"(",
"thing_name",
",",
"cert_arn",
")",
")",
"core_policy",
"=",
"self",
".",
"get_core_policy",
"(",
"core_name",
"=",
"thing_name",
",",
"account_id",
"=",
"account_id",
",",
"region",
"=",
"region",
")",
"iot_client",
"=",
"_get_iot_session",
"(",
"region",
"=",
"region",
",",
"profile_name",
"=",
"profile_name",
")",
"self",
".",
"_create_attach_thing_policy",
"(",
"cert_arn",
",",
"core_policy",
",",
"iot_client",
"=",
"iot_client",
",",
"policy_name",
"=",
"policy_name",
")",
"misc",
"=",
"config",
"[",
"'misc'",
"]",
"misc",
"[",
"'policy_name'",
"]",
"=",
"policy_name",
"config",
"[",
"'misc'",
"]",
"=",
"misc"
] |
Transform dictionary of environment variables into Docker - e parameters .
|
def docker_environment ( env ) : return ' ' . join ( [ "-e \"%s=%s\"" % ( key , value . replace ( "$" , "\\$" ) . replace ( "\"" , "\\\"" ) . replace ( "`" , "\\`" ) ) for key , value in env . items ( ) ] )
| 2,363
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/filters.py#L60-L70
|
[
"def",
"_get_max_page",
"(",
"self",
",",
"url",
")",
":",
"html",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text",
"pq",
"=",
"PyQuery",
"(",
"html",
")",
"try",
":",
"tds",
"=",
"int",
"(",
"pq",
"(",
"\"h2\"",
")",
".",
"text",
"(",
")",
".",
"split",
"(",
")",
"[",
"-",
"1",
"]",
")",
"if",
"tds",
"%",
"25",
":",
"return",
"tds",
"/",
"25",
"+",
"1",
"return",
"tds",
"/",
"25",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"No results found!\"",
")"
] |
Retrieves download location for FEH data zip file from hosted json configuration file .
|
def _retrieve_download_url ( ) : try : # Try to obtain the url from the Open Hydrology json config file. with urlopen ( config [ 'nrfa' ] [ 'oh_json_url' ] , timeout = 10 ) as f : remote_config = json . loads ( f . read ( ) . decode ( 'utf-8' ) ) # This is just for testing, assuming a relative local file path starting with ./ if remote_config [ 'nrfa_url' ] . startswith ( '.' ) : remote_config [ 'nrfa_url' ] = 'file:' + pathname2url ( os . path . abspath ( remote_config [ 'nrfa_url' ] ) ) # Save retrieved config data _update_nrfa_metadata ( remote_config ) return remote_config [ 'nrfa_url' ] except URLError : # If that fails (for whatever reason) use the fallback constant. return config [ 'nrfa' ] [ 'url' ]
| 2,364
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L58-L79
|
[
"def",
"dict_delta",
"(",
"old",
",",
"new",
")",
":",
"r",
"=",
"{",
"}",
"oldkeys",
"=",
"set",
"(",
"old",
".",
"keys",
"(",
")",
")",
"newkeys",
"=",
"set",
"(",
"new",
".",
"keys",
"(",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"new",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"newkeys",
".",
"difference",
"(",
"oldkeys",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"oldkeys",
".",
"difference",
"(",
"newkeys",
")",
")",
"for",
"k",
"in",
"oldkeys",
".",
"intersection",
"(",
"newkeys",
")",
":",
"if",
"old",
"[",
"k",
"]",
"!=",
"new",
"[",
"k",
"]",
":",
"r",
"[",
"k",
"]",
"=",
"new",
"[",
"k",
"]",
"return",
"r"
] |
Check whether updated NRFA data is available .
|
def update_available ( after_days = 1 ) : never_downloaded = not bool ( config . get ( 'nrfa' , 'downloaded_on' , fallback = None ) or None ) if never_downloaded : config . set_datetime ( 'nrfa' , 'update_checked_on' , datetime . utcnow ( ) ) config . save ( ) return True last_checked_on = config . get_datetime ( 'nrfa' , 'update_checked_on' , fallback = None ) or datetime . fromtimestamp ( 0 ) if datetime . utcnow ( ) < last_checked_on + timedelta ( days = after_days ) : return False current_version = LooseVersion ( config . get ( 'nrfa' , 'version' , fallback = '0' ) or '0' ) try : with urlopen ( config [ 'nrfa' ] [ 'oh_json_url' ] , timeout = 10 ) as f : remote_version = LooseVersion ( json . loads ( f . read ( ) . decode ( 'utf-8' ) ) [ 'nrfa_version' ] ) config . set_datetime ( 'nrfa' , 'update_checked_on' , datetime . utcnow ( ) ) config . save ( ) return remote_version > current_version except URLError : return None
| 2,365
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L82-L109
|
[
"def",
"remove_for_target",
"(",
"self",
",",
"target",
",",
"classpath_elements",
")",
":",
"self",
".",
"_classpaths",
".",
"remove_for_target",
"(",
"target",
",",
"self",
".",
"_wrap_path_elements",
"(",
"classpath_elements",
")",
")"
] |
Downloads complete station dataset including catchment descriptors and amax records . And saves it into a cache folder .
|
def download_data ( ) : with urlopen ( _retrieve_download_url ( ) ) as f : with open ( os . path . join ( CACHE_FOLDER , CACHE_ZIP ) , "wb" ) as local_file : local_file . write ( f . read ( ) )
| 2,366
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L112-L119
|
[
"def",
"diff_values",
"(",
"value_a",
",",
"value_b",
",",
"raw",
"=",
"False",
")",
":",
"if",
"not",
"raw",
":",
"value_a",
"=",
"_process_value",
"(",
"value_a",
")",
"value_b",
"=",
"_process_value",
"(",
"value_b",
")",
"# No changes",
"if",
"value_a",
"==",
"value_b",
":",
"return",
"None",
"diffs",
"=",
"[",
"]",
"# N.B.: the choice for the tuple data structure is to enable in the future",
"# more granular diffs, e.g. the changed values within a dictionary etc.",
"diffs",
".",
"append",
"(",
"(",
"value_a",
",",
"value_b",
")",
")",
"return",
"diffs"
] |
Save NRFA metadata to local config file using retrieved config data
|
def _update_nrfa_metadata ( remote_config ) : config [ 'nrfa' ] [ 'oh_json_url' ] = remote_config [ 'nrfa_oh_json_url' ] config [ 'nrfa' ] [ 'version' ] = remote_config [ 'nrfa_version' ] config [ 'nrfa' ] [ 'url' ] = remote_config [ 'nrfa_url' ] config . set_datetime ( 'nrfa' , 'published_on' , datetime . utcfromtimestamp ( remote_config [ 'nrfa_published_on' ] ) ) config . set_datetime ( 'nrfa' , 'downloaded_on' , datetime . utcnow ( ) ) config . set_datetime ( 'nrfa' , 'update_checked_on' , datetime . utcnow ( ) ) config . save ( )
| 2,367
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L122-L134
|
[
"def",
"dict_delta",
"(",
"old",
",",
"new",
")",
":",
"r",
"=",
"{",
"}",
"oldkeys",
"=",
"set",
"(",
"old",
".",
"keys",
"(",
")",
")",
"newkeys",
"=",
"set",
"(",
"new",
".",
"keys",
"(",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"new",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"newkeys",
".",
"difference",
"(",
"oldkeys",
")",
")",
"r",
".",
"update",
"(",
"(",
"k",
",",
"None",
")",
"for",
"k",
"in",
"oldkeys",
".",
"difference",
"(",
"newkeys",
")",
")",
"for",
"k",
"in",
"oldkeys",
".",
"intersection",
"(",
"newkeys",
")",
":",
"if",
"old",
"[",
"k",
"]",
"!=",
"new",
"[",
"k",
"]",
":",
"r",
"[",
"k",
"]",
"=",
"new",
"[",
"k",
"]",
"return",
"r"
] |
Return metadata on the NRFA data .
|
def nrfa_metadata ( ) : result = { 'url' : config . get ( 'nrfa' , 'url' , fallback = None ) or None , # Empty strings '' become None 'version' : config . get ( 'nrfa' , 'version' , fallback = None ) or None , 'published_on' : config . get_datetime ( 'nrfa' , 'published_on' , fallback = None ) or None , 'downloaded_on' : config . get_datetime ( 'nrfa' , 'downloaded_on' , fallback = None ) or None } return result
| 2,368
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L137-L157
|
[
"def",
"promote_owner",
"(",
"self",
",",
"stream_id",
",",
"user_id",
")",
":",
"req_hook",
"=",
"'pod/v1/room/'",
"+",
"stream_id",
"+",
"'/membership/promoteOwner'",
"req_args",
"=",
"'{ \"id\": %s }'",
"%",
"user_id",
"status_code",
",",
"response",
"=",
"self",
".",
"__rest__",
".",
"POST_query",
"(",
"req_hook",
",",
"req_args",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s: %s'",
"%",
"(",
"status_code",
",",
"response",
")",
")",
"return",
"status_code",
",",
"response"
] |
Extract all files from downloaded FEH data zip file .
|
def unzip_data ( ) : with ZipFile ( os . path . join ( CACHE_FOLDER , CACHE_ZIP ) , 'r' ) as zf : zf . extractall ( path = CACHE_FOLDER )
| 2,369
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/fehdata.py#L160-L165
|
[
"def",
"extract_keypairs",
"(",
"lines",
",",
"regexer",
")",
":",
"updates",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"# for consistency we must match the replacer and strip whitespace / newlines",
"match",
"=",
"regexer",
".",
"match",
"(",
"line",
".",
"strip",
"(",
")",
")",
"if",
"not",
"match",
":",
"continue",
"k_v",
"=",
"match",
".",
"groupdict",
"(",
")",
"updates",
"[",
"k_v",
"[",
"Constants",
".",
"KEY_GROUP",
"]",
"]",
"=",
"k_v",
"[",
"Constants",
".",
"VALUE_GROUP",
"]",
"return",
"updates"
] |
return a dictionary of statistics about an XML file including size in bytes num lines number of elements count by elements
|
def get_xml_stats ( fname ) : f = mod_file . TextFile ( fname ) res = { } res [ 'shortname' ] = f . name res [ 'folder' ] = f . path res [ 'filesize' ] = str ( f . size ) + ' bytes' res [ 'num_lines' ] = str ( f . lines ) + ' lines' res [ 'date_modified' ] = f . GetDateAsString ( f . date_modified ) return res
| 2,370
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/xml_tools.py#L18-L32
|
[
"def",
"get_next_invalid_day",
"(",
"self",
",",
"timestamp",
")",
":",
"# pylint: disable=no-else-return",
"if",
"self",
".",
"is_time_day_invalid",
"(",
"timestamp",
")",
":",
"return",
"timestamp",
"next_future_timerange_invalid",
"=",
"self",
".",
"get_next_future_timerange_invalid",
"(",
"timestamp",
")",
"# If today there is no more unavailable timerange, search the next day",
"if",
"next_future_timerange_invalid",
"is",
"None",
":",
"# this day is finish, we check for next period",
"(",
"start_time",
",",
"end_time",
")",
"=",
"self",
".",
"get_start_and_end_time",
"(",
"get_day",
"(",
"timestamp",
")",
")",
"else",
":",
"(",
"start_time",
",",
"end_time",
")",
"=",
"self",
".",
"get_start_and_end_time",
"(",
"timestamp",
")",
"# (start_time, end_time) = self.get_start_and_end_time(t)",
"# The next invalid day can be t day if there a possible",
"# invalid time range (timerange is not 00->24",
"if",
"next_future_timerange_invalid",
"is",
"not",
"None",
":",
"if",
"start_time",
"<=",
"timestamp",
"<=",
"end_time",
":",
"return",
"get_day",
"(",
"timestamp",
")",
"if",
"start_time",
">=",
"timestamp",
":",
"return",
"get_day",
"(",
"start_time",
")",
"else",
":",
"# Else, there is no possibility than in our start_time<->end_time we got",
"# any invalid time (full period out). So it's end_time+1 sec (tomorrow of end_time)",
"return",
"get_day",
"(",
"end_time",
"+",
"1",
")",
"return",
"None"
] |
makes a random xml file mainly for testing the xml_split
|
def make_random_xml_file ( fname , num_elements = 200 , depth = 3 ) : with open ( fname , 'w' ) as f : f . write ( '<?xml version="1.0" ?>\n<random>\n' ) for dep_num , _ in enumerate ( range ( 1 , depth ) ) : f . write ( ' <depth>\n <content>\n' ) #f.write('<depth' + str(dep_num) + '>\n') for num , _ in enumerate ( range ( 1 , num_elements ) ) : f . write ( ' <stuff>data line ' + str ( num ) + '</stuff>\n' ) #f.write('</depth' + str(dep_num) + '>\n') f . write ( ' </content>\n </depth>\n' ) f . write ( '</random>\n' )
| 2,371
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/xml_tools.py#L34-L48
|
[
"def",
"setOverlayRenderModel",
"(",
"self",
",",
"ulOverlayHandle",
",",
"pchRenderModel",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayRenderModel",
"pColor",
"=",
"HmdColor_t",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"pchRenderModel",
",",
"byref",
"(",
"pColor",
")",
")",
"return",
"result",
",",
"pColor"
] |
Lists all organisms present in the KEGG database .
|
def organismsKEGG ( ) : organisms = urlopen ( "http://rest.kegg.jp/list/organism" ) . read ( ) organisms = organisms . split ( "\n" ) #for o in organisms: # print o # sys.stdout.flush() organisms = [ s . split ( "\t" ) for s in organisms ] organisms = pd . DataFrame ( organisms ) return organisms
| 2,372
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L19-L33
|
[
"def",
"request",
"(",
"self",
",",
"message",
",",
"timeout",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"connection_pool",
".",
"full",
"(",
")",
":",
"self",
".",
"connection_pool",
".",
"put",
"(",
"self",
".",
"_register_socket",
"(",
")",
")",
"_socket",
"=",
"self",
".",
"connection_pool",
".",
"get",
"(",
")",
"# setting timeout to None enables the socket to block.",
"if",
"timeout",
"or",
"timeout",
"is",
"None",
":",
"_socket",
".",
"settimeout",
"(",
"timeout",
")",
"data",
"=",
"self",
".",
"send_and_receive",
"(",
"_socket",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"connection",
".",
"proto",
"in",
"Socket",
".",
"streams",
":",
"_socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"return",
"Response",
"(",
"data",
",",
"None",
",",
"None",
")"
] |
Finds KEGG database identifiers for a respective organism given example ensembl ids .
|
def databasesKEGG ( organism , ens_ids ) : all_genes = urlopen ( "http://rest.kegg.jp/list/" + organism ) . read ( ) all_genes = all_genes . split ( "\n" ) dbs = [ ] while len ( dbs ) == 0 : for g in all_genes : if len ( dbs ) == 0 : kid = g . split ( "\t" ) [ 0 ] gene = urlopen ( "http://rest.kegg.jp/get/" + kid ) . read ( ) DBLINKS = gene . split ( "\n" ) DBLINKS = [ s for s in DBLINKS if ":" in s ] for d in DBLINKS : test = d . split ( " " ) test = test [ len ( test ) - 1 ] if test in ens_ids : DBLINK = [ s for s in DBLINKS if test in s ] DBLINK = DBLINK [ 0 ] . split ( ":" ) DBLINK = DBLINK [ len ( DBLINK ) - 2 ] dbs . append ( DBLINK ) else : break ens_db = dbs [ 0 ] . split ( " " ) ens_db = ens_db [ len ( ens_db ) - 1 ] test_db = urlopen ( "http://rest.genome.jp/link/" + ens_db + "/" + organism ) . read ( ) test_db = test_db . split ( "\n" ) if len ( test_db ) == 1 : print ( "For " + organism + " the following db was found: " + ens_db ) print ( "This database does not seem to be valid KEGG-linked database identifier" ) print ( "For \n'hsa' use 'ensembl-hsa'\n'mmu' use 'ensembl-mmu'\n'cel' use 'EnsemblGenomes-Gn'\n'dme' use 'FlyBase'" ) sys . stdout . flush ( ) ens_db = None else : print ( "For " + organism + " the following db was found: " + ens_db ) sys . stdout . flush ( ) return ens_db
| 2,373
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L36-L80
|
[
"def",
"WaitForVirtualMachineShutdown",
"(",
"self",
",",
"vm_to_poll",
",",
"timeout_seconds",
",",
"sleep_period",
"=",
"5",
")",
":",
"seconds_waited",
"=",
"0",
"# wait counter",
"while",
"seconds_waited",
"<",
"timeout_seconds",
":",
"# sleep first, since nothing shuts down instantly",
"seconds_waited",
"+=",
"sleep_period",
"time",
".",
"sleep",
"(",
"sleep_period",
")",
"vm",
"=",
"self",
".",
"get_vm",
"(",
"vm_to_poll",
".",
"name",
")",
"if",
"vm",
".",
"runtime",
".",
"powerState",
"==",
"vim",
".",
"VirtualMachinePowerState",
".",
"poweredOff",
":",
"return",
"True",
"return",
"False"
] |
Looks up KEGG mappings of KEGG ids to ensembl ids
|
def ensembl_to_kegg ( organism , kegg_db ) : print ( "KEGG API: http://rest.genome.jp/link/" + kegg_db + "/" + organism ) sys . stdout . flush ( ) kegg_ens = urlopen ( "http://rest.genome.jp/link/" + kegg_db + "/" + organism ) . read ( ) kegg_ens = kegg_ens . split ( "\n" ) final = [ ] for i in kegg_ens : final . append ( i . split ( "\t" ) ) df = pd . DataFrame ( final [ 0 : len ( final ) - 1 ] ) [ [ 0 , 1 ] ] ens_id = pd . DataFrame ( df [ 1 ] . str . split ( ":" ) . tolist ( ) ) [ 1 ] df = pd . concat ( [ df , ens_id ] , axis = 1 ) df . columns = [ 'KEGGid' , 'ensDB' , 'ENSid' ] df = df [ [ 'KEGGid' , 'ENSid' ] ] return df
| 2,374
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L83-L105
|
[
"def",
"request",
"(",
"self",
",",
"message",
",",
"timeout",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"connection_pool",
".",
"full",
"(",
")",
":",
"self",
".",
"connection_pool",
".",
"put",
"(",
"self",
".",
"_register_socket",
"(",
")",
")",
"_socket",
"=",
"self",
".",
"connection_pool",
".",
"get",
"(",
")",
"# setting timeout to None enables the socket to block.",
"if",
"timeout",
"or",
"timeout",
"is",
"None",
":",
"_socket",
".",
"settimeout",
"(",
"timeout",
")",
"data",
"=",
"self",
".",
"send_and_receive",
"(",
"_socket",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"connection",
".",
"proto",
"in",
"Socket",
".",
"streams",
":",
"_socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"return",
"Response",
"(",
"data",
",",
"None",
",",
"None",
")"
] |
Uses KEGG to retrieve all ids and respective ecs for a given KEGG organism
|
def ecs_idsKEGG ( organism ) : kegg_ec = urlopen ( "http://rest.kegg.jp/link/" + organism + "/enzyme" ) . read ( ) kegg_ec = kegg_ec . split ( "\n" ) final = [ ] for k in kegg_ec : final . append ( k . split ( "\t" ) ) df = pd . DataFrame ( final [ 0 : len ( final ) - 1 ] ) [ [ 0 , 1 ] ] df . columns = [ 'ec' , 'KEGGid' ] return df
| 2,375
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L107-L123
|
[
"def",
"saveSession",
"(",
"self",
",",
"filepath",
")",
":",
"try",
":",
"session_module",
".",
"Save",
"(",
"self",
".",
"session",
",",
"filepath",
")",
"except",
"RuntimeError",
"as",
"e",
":",
"log",
".",
"exception",
"(",
"e",
")",
"os",
".",
"remove",
"(",
"filepath",
")",
"log",
".",
"warning",
"(",
"\"Session not saved\"",
")"
] |
Uses KEGG to retrieve all ids for a given KEGG organism
|
def idsKEGG ( organism ) : ORG = urlopen ( "http://rest.kegg.jp/list/" + organism ) . read ( ) ORG = ORG . split ( "\n" ) final = [ ] for k in ORG : final . append ( k . split ( "\t" ) ) df = pd . DataFrame ( final [ 0 : len ( final ) - 1 ] ) [ [ 0 , 1 ] ] df . columns = [ 'KEGGid' , 'description' ] field = pd . DataFrame ( df [ 'description' ] . str . split ( ';' , 1 ) . tolist ( ) ) [ 0 ] field = pd . DataFrame ( field ) df = pd . concat ( [ df [ [ 'KEGGid' ] ] , field ] , axis = 1 ) df . columns = [ 'KEGGid' , 'gene_name' ] df = df [ [ 'gene_name' , 'KEGGid' ] ] return df
| 2,376
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L126-L147
|
[
"def",
"validate_wrap",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"self",
".",
"_fail_validation_type",
"(",
"value",
",",
"datetime",
")",
"if",
"self",
".",
"use_tz",
"and",
"value",
".",
"tzinfo",
"is",
"None",
":",
"self",
".",
"_fail_validation",
"(",
"value",
",",
"'''datetime is not timezone aware and use_tz is on. make sure timezone is set on the session'''",
")",
"# if using timezone support it isn't clear how min and max should work,",
"# so the problem is being punted on for now.",
"if",
"self",
".",
"use_tz",
":",
"return",
"# min/max",
"if",
"self",
".",
"min",
"is",
"not",
"None",
"and",
"value",
"<",
"self",
".",
"min",
":",
"self",
".",
"_fail_validation",
"(",
"value",
",",
"'DateTime too old'",
")",
"if",
"self",
".",
"max",
"is",
"not",
"None",
"and",
"value",
">",
"self",
".",
"max",
":",
"self",
".",
"_fail_validation",
"(",
"value",
",",
"'DateTime too new'",
")"
] |
Transforms a pandas dataframe with the columns ensembl_gene_id kegg_enzyme to dataframe ready for use in ...
|
def biomaRtTOkegg ( df ) : df = df . dropna ( ) ECcols = df . columns . tolist ( ) df . reset_index ( inplace = True , drop = True ) # field = ECsb[['kegg_enzyme']] field = pd . DataFrame ( df [ 'kegg_enzyme' ] . str . split ( '+' , 1 ) . tolist ( ) ) [ 1 ] field = pd . DataFrame ( field ) df = pd . concat ( [ df [ [ 'ensembl_gene_id' ] ] , field ] , axis = 1 ) df . columns = ECcols df . drop_duplicates ( inplace = True ) df . reset_index ( inplace = True , drop = True ) plus = df [ 'kegg_enzyme' ] . tolist ( ) plus = [ s for s in plus if "+" in s ] noPlus = df [ ~ df [ 'kegg_enzyme' ] . isin ( plus ) ] plus = df [ df [ 'kegg_enzyme' ] . isin ( plus ) ] noPlus . reset_index ( inplace = True , drop = True ) plus . reset_index ( inplace = True , drop = True ) for p in range ( 0 , len ( plus ) ) : enz = plus . ix [ p ] [ 'kegg_enzyme' ] enz = enz . split ( "+" ) enz = pd . DataFrame ( enz ) enz . colums = [ 'kegg_enzyme' ] enz [ 'ensembl_gene_id' ] = plus . ix [ p ] [ 'kegg_enzyme' ] noPlus = pd . concat ( [ noPlus , enz ] ) noPlus = noPlus . drop_duplicates ( ) noPlus = noPlus [ [ 'ensembl_gene_id' , 'kegg_enzyme' ] ] noPlus [ 'fake' ] = 'ec:' noPlus [ 'kegg_enzyme' ] = noPlus [ 'fake' ] + noPlus [ 'kegg_enzyme' ] noPlus = noPlus [ [ 'ensembl_gene_id' , 'kegg_enzyme' ] ] return noPlus
| 2,377
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L194-L232
|
[
"async",
"def",
"refresh",
"(",
"self",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"5",
"/",
"6",
"*",
"self",
".",
"lifetime",
")",
"request",
"=",
"stun",
".",
"Message",
"(",
"message_method",
"=",
"stun",
".",
"Method",
".",
"REFRESH",
",",
"message_class",
"=",
"stun",
".",
"Class",
".",
"REQUEST",
")",
"request",
".",
"attributes",
"[",
"'LIFETIME'",
"]",
"=",
"self",
".",
"lifetime",
"await",
"self",
".",
"request",
"(",
"request",
")",
"logger",
".",
"info",
"(",
"'TURN allocation refreshed %s'",
",",
"self",
".",
"relayed_address",
")"
] |
Gets all KEGG pathways for an organism
|
def expKEGG ( organism , names_KEGGids ) : #print "KEGG API: http://rest.kegg.jp/list/pathway/"+organism #sys.stdout.flush() kegg_paths = urlopen ( "http://rest.kegg.jp/list/pathway/" + organism ) . read ( ) kegg_paths = kegg_paths . split ( "\n" ) final = [ ] for k in kegg_paths : final . append ( k . split ( "\t" ) ) df = pd . DataFrame ( final [ 0 : len ( final ) - 1 ] ) [ [ 0 , 1 ] ] df . columns = [ 'pathID' , 'pathName' ] print ( "Collecting genes for pathways" ) sys . stdout . flush ( ) df_pg = pd . DataFrame ( ) for i in df [ 'pathID' ] . tolist ( ) : print ( i ) sys . stdout . flush ( ) path_genes = urlopen ( "http://rest.kegg.jp/link/genes/" + i ) . read ( ) path_genes = path_genes . split ( "\n" ) final = [ ] for k in path_genes : final . append ( k . split ( "\t" ) ) if len ( final [ 0 ] ) > 1 : df_tmp = pd . DataFrame ( final [ 0 : len ( final ) - 1 ] ) [ [ 0 , 1 ] ] df_tmp . columns = [ 'pathID' , 'KEGGid' ] df_pg = pd . concat ( [ df_pg , df_tmp ] ) df = pd . merge ( df , df_pg , on = [ "pathID" ] , how = "outer" ) df = df [ df [ 'KEGGid' ] . isin ( names_KEGGids [ 'KEGGid' ] . tolist ( ) ) ] df = pd . merge ( df , names_KEGGids , how = 'left' , on = [ 'KEGGid' ] ) df_fA = pd . DataFrame ( columns = [ 'KEGGid' ] ) paths = [ ] for k in df [ [ 'pathID' ] ] . drop_duplicates ( ) [ 'pathID' ] . tolist ( ) : df_tmp = df [ df [ 'pathID' ] == k ] pathName = df_tmp [ 'pathName' ] . tolist ( ) [ 0 ] pathName = " : " . join ( [ k , pathName ] ) keggIDs_in_path = df_tmp [ [ 'KEGGid' ] ] . drop_duplicates ( ) [ 'KEGGid' ] . tolist ( ) a = { pathName : keggIDs_in_path } a = pd . DataFrame ( a , index = range ( len ( keggIDs_in_path ) ) ) a [ 'KEGGid' ] = a [ pathName ] . copy ( ) df_fA = pd . merge ( df_fA , a , how = 'outer' , on = [ 'KEGGid' ] ) paths . append ( pathName ) return df_fA , paths
| 2,378
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/kegg.py#L236-L287
|
[
"def",
"request",
"(",
"self",
",",
"message",
",",
"timeout",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"connection_pool",
".",
"full",
"(",
")",
":",
"self",
".",
"connection_pool",
".",
"put",
"(",
"self",
".",
"_register_socket",
"(",
")",
")",
"_socket",
"=",
"self",
".",
"connection_pool",
".",
"get",
"(",
")",
"# setting timeout to None enables the socket to block.",
"if",
"timeout",
"or",
"timeout",
"is",
"None",
":",
"_socket",
".",
"settimeout",
"(",
"timeout",
")",
"data",
"=",
"self",
".",
"send_and_receive",
"(",
"_socket",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"connection",
".",
"proto",
"in",
"Socket",
".",
"streams",
":",
"_socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"return",
"Response",
"(",
"data",
",",
"None",
",",
"None",
")"
] |
Lists BioMart databases through a RPY2 connection .
|
def RdatabasesBM ( host = rbiomart_host ) : biomaRt = importr ( "biomaRt" ) print ( biomaRt . listMarts ( host = host ) )
| 2,379
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/rbiom.py#L16-L26
|
[
"def",
"wait_for_batches",
"(",
"self",
",",
"batch_ids",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_batch_tracker",
".",
"watch_statuses",
"(",
"self",
",",
"batch_ids",
")",
"timeout",
"=",
"timeout",
"or",
"DEFAULT_TIMEOUT",
"start_time",
"=",
"time",
"(",
")",
"with",
"self",
".",
"_wait_condition",
":",
"while",
"True",
":",
"if",
"self",
".",
"_statuses",
"is",
"not",
"None",
":",
"return",
"_format_batch_statuses",
"(",
"self",
".",
"_statuses",
",",
"batch_ids",
",",
"self",
".",
"_batch_tracker",
")",
"if",
"time",
"(",
")",
"-",
"start_time",
">",
"timeout",
":",
"statuses",
"=",
"self",
".",
"_batch_tracker",
".",
"get_statuses",
"(",
"batch_ids",
")",
"return",
"_format_batch_statuses",
"(",
"statuses",
",",
"batch_ids",
",",
"self",
".",
"_batch_tracker",
")",
"self",
".",
"_wait_condition",
".",
"wait",
"(",
"timeout",
"-",
"(",
"time",
"(",
")",
"-",
"start_time",
")",
")"
] |
Lists BioMart datasets through a RPY2 connection .
|
def RdatasetsBM ( database , host = rbiomart_host ) : biomaRt = importr ( "biomaRt" ) ensemblMart = biomaRt . useMart ( database , host = host ) print ( biomaRt . listDatasets ( ensemblMart ) )
| 2,380
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/rbiom.py#L28-L40
|
[
"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"
] |
Lists BioMart filters through a RPY2 connection .
|
def RfiltersBM ( dataset , database , host = rbiomart_host ) : biomaRt = importr ( "biomaRt" ) ensemblMart = biomaRt . useMart ( database , host = host ) ensembl = biomaRt . useDataset ( dataset , mart = ensemblMart ) print ( biomaRt . listFilters ( ensembl ) )
| 2,381
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/rbiom.py#L42-L56
|
[
"def",
"filter_ambiguity",
"(",
"records",
",",
"percent",
"=",
"0.5",
")",
":",
"# , repeats=6)",
"seqs",
"=",
"[",
"]",
"# Ns = ''.join(['N' for _ in range(repeats)])",
"count",
"=",
"0",
"for",
"record",
"in",
"records",
":",
"if",
"record",
".",
"seq",
".",
"count",
"(",
"'N'",
")",
"/",
"float",
"(",
"len",
"(",
"record",
")",
")",
"<",
"percent",
":",
"# pos = record.seq.find(Ns)",
"# if pos >= 0:",
"# record.seq = Seq(str(record.seq)[:pos])",
"seqs",
".",
"append",
"(",
"record",
")",
"count",
"+=",
"1",
"return",
"seqs",
",",
"count"
] |
Lists BioMart attributes through a RPY2 connection .
|
def RattributesBM ( dataset , database , host = rbiomart_host ) : biomaRt = importr ( "biomaRt" ) ensemblMart = biomaRt . useMart ( database , host = rbiomart_host ) ensembl = biomaRt . useDataset ( dataset , mart = ensemblMart ) print ( biomaRt . listAttributes ( ensembl ) )
| 2,382
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/rbiom.py#L58-L72
|
[
"def",
"OneHot",
"(",
"*",
"xs",
",",
"simplify",
"=",
"True",
",",
"conj",
"=",
"True",
")",
":",
"xs",
"=",
"[",
"Expression",
".",
"box",
"(",
"x",
")",
".",
"node",
"for",
"x",
"in",
"xs",
"]",
"terms",
"=",
"list",
"(",
")",
"if",
"conj",
":",
"for",
"x0",
",",
"x1",
"in",
"itertools",
".",
"combinations",
"(",
"xs",
",",
"2",
")",
":",
"terms",
".",
"append",
"(",
"exprnode",
".",
"or_",
"(",
"exprnode",
".",
"not_",
"(",
"x0",
")",
",",
"exprnode",
".",
"not_",
"(",
"x1",
")",
")",
")",
"terms",
".",
"append",
"(",
"exprnode",
".",
"or_",
"(",
"*",
"xs",
")",
")",
"y",
"=",
"exprnode",
".",
"and_",
"(",
"*",
"terms",
")",
"else",
":",
"for",
"i",
",",
"xi",
"in",
"enumerate",
"(",
"xs",
")",
":",
"zeros",
"=",
"[",
"exprnode",
".",
"not_",
"(",
"x",
")",
"for",
"x",
"in",
"xs",
"[",
":",
"i",
"]",
"+",
"xs",
"[",
"i",
"+",
"1",
":",
"]",
"]",
"terms",
".",
"append",
"(",
"exprnode",
".",
"and_",
"(",
"xi",
",",
"*",
"zeros",
")",
")",
"y",
"=",
"exprnode",
".",
"or_",
"(",
"*",
"terms",
")",
"if",
"simplify",
":",
"y",
"=",
"y",
".",
"simplify",
"(",
")",
"return",
"_expr",
"(",
"y",
")"
] |
Get list of applications
|
def get_list_of_applications ( ) : apps = mod_prg . Programs ( 'Applications' , 'C:\\apps' ) fl = mod_fl . FileList ( [ 'C:\\apps' ] , [ '*.exe' ] , [ "\\bk\\" ] ) for f in fl . get_list ( ) : apps . add ( f , 'autogenerated list' ) apps . list ( ) apps . save ( )
| 2,383
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/scripts/examples/document_AIKIF.py#L147-L156
|
[
"def",
"recover",
"(",
"options",
")",
":",
"event_format",
"=",
"options",
".",
"kwargs",
"[",
"'omode'",
"]",
"buffer_size",
"=",
"64",
"*",
"1024",
"fpd",
"=",
"open",
"(",
"options",
".",
"kwargs",
"[",
"'output'",
"]",
",",
"\"r+\"",
")",
"fpd",
".",
"seek",
"(",
"0",
",",
"2",
")",
"# seek to end",
"fptr",
"=",
"max",
"(",
"fpd",
".",
"tell",
"(",
")",
"-",
"buffer_size",
",",
"0",
")",
"fptr_eof",
"=",
"0",
"while",
"(",
"fptr",
">",
"0",
")",
":",
"fpd",
".",
"seek",
"(",
"fptr",
")",
"event_buffer",
"=",
"fpd",
".",
"read",
"(",
"buffer_size",
")",
"(",
"event_start",
",",
"next_event_start",
",",
"last_time",
")",
"=",
"get_event_start",
"(",
"event_buffer",
",",
"event_format",
")",
"if",
"(",
"event_start",
"!=",
"-",
"1",
")",
":",
"fptr_eof",
"=",
"event_start",
"+",
"fptr",
"break",
"fptr",
"=",
"fptr",
"-",
"buffer_size",
"if",
"fptr",
"<",
"0",
":",
"# didn't find a valid event, so start over",
"fptr_eof",
"=",
"0",
"last_time",
"=",
"0",
"# truncate file here",
"fpd",
".",
"truncate",
"(",
"fptr_eof",
")",
"fpd",
".",
"seek",
"(",
"fptr_eof",
")",
"fpd",
".",
"write",
"(",
"\"\\n\"",
")",
"fpd",
".",
"close",
"(",
")",
"return",
"last_time"
] |
Add the field to the internal configuration dictionary .
|
def add_field ( self , name , label , field_type , * args , * * kwargs ) : if name in self . _dyn_fields : raise AttributeError ( 'Field already added to the form.' ) else : self . _dyn_fields [ name ] = { 'label' : label , 'type' : field_type , 'args' : args , 'kwargs' : kwargs }
| 2,384
|
https://github.com/Timusan/wtforms-dynamic-fields/blob/d984a646075219a6f8a0e931c96035ca3e44be56/wtforms_dynamic_fields/wtforms_dynamic_fields.py#L44-L50
|
[
"def",
"conditions",
"(",
"self",
",",
"start",
",",
"last_attempt",
")",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"start",
">",
"self",
".",
"timeout",
":",
"yield",
"WaitCondition",
".",
"Timedout",
"return",
"if",
"last_attempt",
"is",
"not",
"None",
"and",
"time",
".",
"time",
"(",
")",
"-",
"last_attempt",
"<",
"self",
".",
"wait_between_attempts",
":",
"yield",
"WaitCondition",
".",
"KeepWaiting",
"return",
"if",
"self",
".",
"greps",
"is",
"not",
"NotSpecified",
":",
"for",
"name",
",",
"val",
"in",
"self",
".",
"greps",
".",
"items",
"(",
")",
":",
"yield",
"'grep \"{0}\" \"{1}\"'",
".",
"format",
"(",
"val",
",",
"name",
")",
"if",
"self",
".",
"file_value",
"is",
"not",
"NotSpecified",
":",
"for",
"name",
",",
"val",
"in",
"self",
".",
"file_value",
".",
"items",
"(",
")",
":",
"command",
"=",
"'diff <(echo {0}) <(cat {1})'",
".",
"format",
"(",
"val",
",",
"name",
")",
"if",
"not",
"self",
".",
"harpoon",
".",
"debug",
":",
"command",
"=",
"\"{0} > /dev/null\"",
".",
"format",
"(",
"command",
")",
"yield",
"command",
"if",
"self",
".",
"port_open",
"is",
"not",
"NotSpecified",
":",
"for",
"port",
"in",
"self",
".",
"port_open",
":",
"yield",
"'nc -z 127.0.0.1 {0}'",
".",
"format",
"(",
"port",
")",
"if",
"self",
".",
"curl_result",
"is",
"not",
"NotSpecified",
":",
"for",
"url",
",",
"content",
"in",
"self",
".",
"curl_result",
".",
"items",
"(",
")",
":",
"yield",
"'diff <(curl \"{0}\") <(echo {1})'",
".",
"format",
"(",
"url",
",",
"content",
")",
"if",
"self",
".",
"file_exists",
"is",
"not",
"NotSpecified",
":",
"for",
"path",
"in",
"self",
".",
"file_exists",
":",
"yield",
"'cat {0} > /dev/null'",
".",
"format",
"(",
"path",
")",
"if",
"self",
".",
"command",
"not",
"in",
"(",
"None",
",",
"\"\"",
",",
"NotSpecified",
")",
":",
"for",
"command",
"in",
"self",
".",
"command",
":",
"yield",
"command"
] |
Add the validator to the internal configuration dictionary .
|
def add_validator ( self , name , validator , * args , * * kwargs ) : if name in self . _dyn_fields : if 'validators' in self . _dyn_fields [ name ] : self . _dyn_fields [ name ] [ 'validators' ] . append ( validator ) self . _dyn_fields [ name ] [ validator . __name__ ] = { } if args : self . _dyn_fields [ name ] [ validator . __name__ ] [ 'args' ] = args if kwargs : self . _dyn_fields [ name ] [ validator . __name__ ] [ 'kwargs' ] = kwargs else : self . _dyn_fields [ name ] [ 'validators' ] = [ ] self . add_validator ( name , validator , * args , * * kwargs ) else : raise AttributeError ( 'Field "{0}" does not exist. ' 'Did you forget to add it?' . format ( name ) )
| 2,385
|
https://github.com/Timusan/wtforms-dynamic-fields/blob/d984a646075219a6f8a0e931c96035ca3e44be56/wtforms_dynamic_fields/wtforms_dynamic_fields.py#L52-L76
|
[
"def",
"_find_start_time",
"(",
"hdr",
",",
"s_freq",
")",
":",
"start_time",
"=",
"hdr",
"[",
"'stc'",
"]",
"[",
"'creation_time'",
"]",
"for",
"one_stamp",
"in",
"hdr",
"[",
"'stamps'",
"]",
":",
"if",
"one_stamp",
"[",
"'segment_name'",
"]",
".",
"decode",
"(",
")",
"==",
"hdr",
"[",
"'erd'",
"]",
"[",
"'filename'",
"]",
":",
"offset",
"=",
"one_stamp",
"[",
"'start_stamp'",
"]",
"break",
"erd_time",
"=",
"(",
"hdr",
"[",
"'erd'",
"]",
"[",
"'creation_time'",
"]",
"-",
"timedelta",
"(",
"seconds",
"=",
"offset",
"/",
"s_freq",
")",
")",
".",
"replace",
"(",
"microsecond",
"=",
"0",
")",
"stc_erd_diff",
"=",
"(",
"start_time",
"-",
"erd_time",
")",
".",
"total_seconds",
"(",
")",
"if",
"stc_erd_diff",
">",
"START_TIME_TOL",
":",
"lg",
".",
"warn",
"(",
"'Time difference between ERD and STC is {} s so using ERD time'",
"' at {}'",
".",
"format",
"(",
"stc_erd_diff",
",",
"erd_time",
")",
")",
"start_time",
"=",
"erd_time",
"return",
"start_time"
] |
Process the given WTForm Form object .
|
def process ( self , form , post ) : if not isinstance ( form , FormMeta ) : raise TypeError ( 'Given form is not a valid WTForm.' ) re_field_name = re . compile ( r'\%([a-zA-Z0-9_]*)\%' ) class F ( form ) : pass for field , data in post . iteritems ( ) : if field in F ( ) : # Skip it if the POST field is one of the standard form fields. continue else : if field in self . _dyn_fields : # If we can find the field name directly, it means the field # is not a set so just set the canonical name and go on. field_cname = field # Since we are not in a set, (re)set the current set. current_set_number = None elif ( field . split ( '_' ) [ - 1 ] . isdigit ( ) and field [ : - ( len ( field . split ( '_' ) [ - 1 ] ) ) - 1 ] in self . _dyn_fields . keys ( ) ) : # If the field can be split on underscore characters, # the last part contains only digits and the # everything *but* the last part is found in the # field configuration, we are good to go. # (Cowardly refusing to use regex here). field_cname = field [ : - ( len ( field . split ( '_' ) [ - 1 ] ) ) - 1 ] # Since we apparently are in a set, remember the # the set number we are at. current_set_number = str ( field . split ( '_' ) [ - 1 ] ) else : # The field did not match to a canonical name # from the fields dictionary or the name # was malformed, throw it out. continue # Since the field seems to be a valid one, let us # prepare the validator arguments and, if we are in a set # replace the %field_name% convention where we find it. validators = [ ] if 'validators' in self . _dyn_fields [ field_cname ] : for validator in self . _dyn_fields [ field_cname ] [ 'validators' ] : args = [ ] kwargs = { } if 'args' in self . _dyn_fields [ field_cname ] [ validator . __name__ ] : if not current_set_number : args = self . _dyn_fields [ field_cname ] [ validator . __name__ ] [ 'args' ] else : # If we are currently in a set, append the set number # to all the words that are decorated with %'s within # the arguments. for arg in self . _dyn_fields [ field_cname ] [ validator . __name__ ] [ 'args' ] : try : arg = re_field_name . sub ( r'\1' + '_' + current_set_number , arg ) except : # The argument does not seem to be regex-able # Probably not a string, thus we can skip it. pass args . append ( arg ) if 'kwargs' in self . _dyn_fields [ field_cname ] [ validator . __name__ ] : if not current_set_number : kwargs = self . _dyn_fields [ field_cname ] [ validator . __name__ ] [ 'kwargs' ] else : # If we are currently in a set, append the set number # to all the words that are decorated with %'s within # the arguments. for key , arg in self . iteritems ( self . _dyn_fields [ field_cname ] [ validator . __name__ ] [ 'kwargs' ] ) : try : arg = re_field_name . sub ( r'\1' + '_' + current_set_number , arg ) except : # The argument does not seem to be regex-able # Probably not a string, thus we can skip it. pass kwargs [ key ] = arg # Finally, bind arguments to the validator # and add it to the list validators . append ( validator ( * args , * * kwargs ) ) # The field is setup, it is time to add it to the form. field_type = self . _dyn_fields [ field_cname ] [ 'type' ] field_label = self . _dyn_fields [ field_cname ] [ 'label' ] field_args = self . _dyn_fields [ field_cname ] [ 'args' ] field_kwargs = self . _dyn_fields [ field_cname ] [ 'kwargs' ] setattr ( F , field , field_type ( field_label , validators = validators , * field_args , * * field_kwargs ) ) # Create an instance of the form with the newly # created fields and give it back to the caller. if self . flask_wtf : # Flask WTF overrides the form initialization # and already injects the POST variables. form = F ( ) else : form = F ( post ) return form
| 2,386
|
https://github.com/Timusan/wtforms-dynamic-fields/blob/d984a646075219a6f8a0e931c96035ca3e44be56/wtforms_dynamic_fields/wtforms_dynamic_fields.py#L90-L214
|
[
"def",
"get_correlation_table",
"(",
"self",
",",
"chain",
"=",
"0",
",",
"parameters",
"=",
"None",
",",
"caption",
"=",
"\"Parameter Correlations\"",
",",
"label",
"=",
"\"tab:parameter_correlations\"",
")",
":",
"parameters",
",",
"cor",
"=",
"self",
".",
"get_correlations",
"(",
"chain",
"=",
"chain",
",",
"parameters",
"=",
"parameters",
")",
"return",
"self",
".",
"_get_2d_latex_table",
"(",
"parameters",
",",
"cor",
",",
"caption",
",",
"label",
")"
] |
Reads a gz compressed BED narrow peak file from a web address or local file
|
def GetBEDnarrowPeakgz ( URL_or_PATH_TO_file ) : if os . path . isfile ( URL_or_PATH_TO_file ) : response = open ( URL_or_PATH_TO_file , "r" ) compressedFile = StringIO . StringIO ( response . read ( ) ) else : response = urllib2 . urlopen ( URL_or_PATH_TO_file ) compressedFile = StringIO . StringIO ( response . read ( ) ) decompressedFile = gzip . GzipFile ( fileobj = compressedFile ) out = decompressedFile . read ( ) . split ( "\n" ) out = [ s . split ( "\t" ) for s in out ] out = pd . DataFrame ( out ) out . columns = [ "chrom" , "chromStart" , "chromEnd" , "name" , "score" , "strand" , "signalValue" , "-log10(pValue)" , "-log10(qvalue)" , "peak" ] out [ "name" ] = out . index . tolist ( ) out [ "name" ] = "Peak_" + out [ "name" ] . astype ( str ) out = out [ : - 1 ] return out
| 2,387
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/bed.py#L30-L53
|
[
"def",
"rebalance_replication_groups",
"(",
"self",
")",
":",
"# Balance replicas over replication-groups for each partition",
"if",
"any",
"(",
"b",
".",
"inactive",
"for",
"b",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"cluster_topology",
".",
"brokers",
")",
")",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"Impossible to rebalance replication groups because of inactive \"",
"\"brokers.\"",
")",
"raise",
"RebalanceError",
"(",
"\"Impossible to rebalance replication groups because of inactive \"",
"\"brokers\"",
")",
"# Balance replica-count over replication-groups",
"self",
".",
"rebalance_replicas",
"(",
")",
"# Balance partition-count over replication-groups",
"self",
".",
"_rebalance_groups_partition_cnt",
"(",
")"
] |
Transforms a pandas dataframe into a bedtool
|
def dfTObedtool ( df ) : df = df . astype ( str ) df = df . drop_duplicates ( ) df = df . values . tolist ( ) df = [ "\t" . join ( s ) for s in df ] df = "\n" . join ( df ) df = BedTool ( df , from_string = True ) return df
| 2,388
|
https://github.com/mpg-age-bioinformatics/AGEpy/blob/887808a7a2c1504f39ce8d8cb36c15c1721cd29f/AGEpy/bed.py#L55-L70
|
[
"def",
"_cleanup_container",
"(",
"self",
",",
"cinfo",
")",
":",
"# I'm not a fan of doing this again here.",
"env",
"=",
"cinfo",
"[",
"'Config'",
"]",
"[",
"'Env'",
"]",
"if",
"(",
"env",
"and",
"'_ATOMIC_TEMP_CONTAINER'",
"not",
"in",
"env",
")",
"or",
"not",
"env",
":",
"return",
"iid",
"=",
"cinfo",
"[",
"'Image'",
"]",
"self",
".",
"client",
".",
"remove_container",
"(",
"cinfo",
"[",
"'Id'",
"]",
")",
"try",
":",
"labels",
"=",
"self",
".",
"client",
".",
"inspect_image",
"(",
"iid",
")",
"[",
"'Config'",
"]",
"[",
"'Labels'",
"]",
"except",
"TypeError",
":",
"labels",
"=",
"{",
"}",
"if",
"labels",
"and",
"'io.projectatomic.Temporary'",
"in",
"labels",
":",
"if",
"labels",
"[",
"'io.projectatomic.Temporary'",
"]",
"==",
"'true'",
":",
"self",
".",
"client",
".",
"remove_image",
"(",
"iid",
")"
] |
Global configuration for event handling .
|
def configure ( * * kwargs ) : for key in kwargs : if key == 'is_logging_enabled' : Event . is_logging_enabled = kwargs [ key ] elif key == 'collector_queue' : Event . collector_queue = kwargs [ key ] else : Logger . get_logger ( __name__ ) . error ( "Unknown key %s in configure or bad type %s" , key , type ( kwargs [ key ] ) )
| 2,389
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/event.py#L46-L55
|
[
"def",
"save",
"(",
"self",
",",
"create_multiple_renditions",
"=",
"True",
",",
"preserve_source_rendition",
"=",
"True",
",",
"encode_to",
"=",
"enums",
".",
"EncodeToEnum",
".",
"FLV",
")",
":",
"if",
"is_ftp_connection",
"(",
"self",
".",
"connection",
")",
"and",
"len",
"(",
"self",
".",
"assets",
")",
">",
"0",
":",
"self",
".",
"connection",
".",
"post",
"(",
"xml",
"=",
"self",
".",
"to_xml",
"(",
")",
",",
"assets",
"=",
"self",
".",
"assets",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"self",
".",
"_filename",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"self",
".",
"_filename",
",",
"create_multiple_renditions",
"=",
"create_multiple_renditions",
",",
"preserve_source_rendition",
"=",
"preserve_source_rendition",
",",
"encode_to",
"=",
"encode_to",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"len",
"(",
"self",
".",
"renditions",
")",
">",
"0",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'update_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"if",
"data",
":",
"self",
".",
"_load",
"(",
"data",
")"
] |
Finish event as failed with optional additional information .
|
def failed ( self , * * kwargs ) : self . finished = datetime . now ( ) self . status = 'failed' self . information . update ( kwargs ) self . logger . info ( "Failed - took %f seconds." , self . duration ( ) ) self . update_report_collector ( int ( time . mktime ( self . finished . timetuple ( ) ) ) )
| 2,390
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/event.py#L69-L75
|
[
"def",
"generate_pattern_properties",
"(",
"self",
")",
":",
"self",
".",
"create_variable_is_dict",
"(",
")",
"with",
"self",
".",
"l",
"(",
"'if {variable}_is_dict:'",
")",
":",
"self",
".",
"create_variable_keys",
"(",
")",
"for",
"pattern",
",",
"definition",
"in",
"self",
".",
"_definition",
"[",
"'patternProperties'",
"]",
".",
"items",
"(",
")",
":",
"self",
".",
"_compile_regexps",
"[",
"pattern",
"]",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"with",
"self",
".",
"l",
"(",
"'for {variable}_key, {variable}_val in {variable}.items():'",
")",
":",
"for",
"pattern",
",",
"definition",
"in",
"self",
".",
"_definition",
"[",
"'patternProperties'",
"]",
".",
"items",
"(",
")",
":",
"with",
"self",
".",
"l",
"(",
"'if REGEX_PATTERNS[\"{}\"].search({variable}_key):'",
",",
"pattern",
")",
":",
"with",
"self",
".",
"l",
"(",
"'if {variable}_key in {variable}_keys:'",
")",
":",
"self",
".",
"l",
"(",
"'{variable}_keys.remove({variable}_key)'",
")",
"self",
".",
"generate_func_code_block",
"(",
"definition",
",",
"'{}_val'",
".",
"format",
"(",
"self",
".",
"_variable",
")",
",",
"'{}.{{{}_key}}'",
".",
"format",
"(",
"self",
".",
"_variable_name",
",",
"self",
".",
"_variable",
")",
",",
")"
] |
Updating report collector for pipeline details .
|
def update_report_collector ( self , timestamp ) : report_enabled = 'report' in self . information and self . information [ 'report' ] == 'html' report_enabled = report_enabled and 'stage' in self . information report_enabled = report_enabled and Event . collector_queue is not None if report_enabled : Event . collector_queue . put ( CollectorUpdate ( matrix = self . information [ 'matrix' ] if 'matrix' in self . information else 'default' , stage = self . information [ 'stage' ] , status = self . status , timestamp = timestamp , information = self . information ) )
| 2,391
|
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/event.py#L89-L102
|
[
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
test function .
|
def count_lines_in_file ( src_file ) : tot = 0 res = '' try : with open ( src_file , 'r' ) as f : for line in f : tot += 1 res = str ( tot ) + ' recs read' except : res = 'ERROR -couldnt open file' return res
| 2,392
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/sql_tools.py#L10-L23
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
creates a SQL loader script to load a text file into a database and then executes it . Note that src_file is
|
def load_txt_to_sql ( tbl_name , src_file_and_path , src_file , op_folder ) : if op_folder == '' : pth = '' else : pth = op_folder + os . sep fname_create_script = pth + 'CREATE_' + tbl_name + '.SQL' fname_backout_file = pth + 'BACKOUT_' + tbl_name + '.SQL' fname_control_file = pth + tbl_name + '.CTL' cols = read_csv_cols_to_table_cols ( src_file ) create_script_staging_table ( fname_create_script , tbl_name , cols ) create_file ( fname_backout_file , 'DROP TABLE ' + tbl_name + ' CASCADE CONSTRAINTS;\n' ) create_CTL ( fname_control_file , tbl_name , cols , 'TRUNCATE' )
| 2,393
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/aikif/toolbox/sql_tools.py#L26-L44
|
[
"def",
"list_supported_categories",
"(",
")",
":",
"categories",
"=",
"get_supported_categories",
"(",
"api",
")",
"category_names",
"=",
"[",
"category",
".",
"name",
"for",
"category",
"in",
"categories",
"]",
"print",
"(",
"\"Supported account categories by name: {0}\"",
".",
"format",
"(",
"COMMA_WITH_SPACE",
".",
"join",
"(",
"map",
"(",
"str",
",",
"category_names",
")",
")",
")",
")"
] |
Return the next item from an async iterator .
|
async def anext ( * args ) : if not args : raise TypeError ( 'anext() expected at least 1 arguments, got 0' ) if len ( args ) > 2 : raise TypeError ( 'anext() expected at most 2 arguments, got {}' . format ( len ( args ) ) ) iterable , default , has_default = args [ 0 ] , None , False if len ( args ) == 2 : iterable , default = args has_default = True try : return await iterable . __anext__ ( ) except StopAsyncIteration as exc : if has_default : return default raise StopAsyncIteration ( ) from exc
| 2,394
|
https://github.com/asyncdef/aitertools/blob/26a6c7e71e87dd1ddc4acb755d70ca30894f7928/aitertools/__init__.py#L102-L146
|
[
"def",
"split_call",
"(",
"lines",
",",
"open_paren_line",
"=",
"0",
")",
":",
"num_open",
"=",
"0",
"num_closed",
"=",
"0",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lines",
")",
":",
"c",
"=",
"line",
".",
"count",
"(",
"'('",
")",
"num_open",
"+=",
"c",
"if",
"not",
"c",
"and",
"i",
"==",
"open_paren_line",
":",
"raise",
"Exception",
"(",
"'Exception open parenthesis in line %d but there is not one there: %s'",
"%",
"(",
"i",
",",
"str",
"(",
"lines",
")",
")",
")",
"num_closed",
"+=",
"line",
".",
"count",
"(",
"')'",
")",
"if",
"num_open",
"==",
"num_closed",
":",
"return",
"(",
"lines",
"[",
":",
"i",
"+",
"1",
"]",
",",
"lines",
"[",
"i",
"+",
"1",
":",
"]",
")",
"print",
"(",
"''",
".",
"join",
"(",
"lines",
")",
")",
"raise",
"Exception",
"(",
"'parenthesis are mismatched (%d open, %d closed found)'",
"%",
"(",
"num_open",
",",
"num_closed",
")",
")"
] |
Make an iterator that returns object over and over again .
|
def repeat ( obj , times = None ) : if times is None : return AsyncIterWrapper ( sync_itertools . repeat ( obj ) ) return AsyncIterWrapper ( sync_itertools . repeat ( obj , times ) )
| 2,395
|
https://github.com/asyncdef/aitertools/blob/26a6c7e71e87dd1ddc4acb755d70ca30894f7928/aitertools/__init__.py#L240-L246
|
[
"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"
] |
Ensure the callable is an async def .
|
def _async_callable ( func ) : if isinstance ( func , types . CoroutineType ) : return func @ functools . wraps ( func ) async def _async_def_wrapper ( * args , * * kwargs ) : """Wrap a a sync callable in an async def.""" return func ( * args , * * kwargs ) return _async_def_wrapper
| 2,396
|
https://github.com/asyncdef/aitertools/blob/26a6c7e71e87dd1ddc4acb755d70ca30894f7928/aitertools/__init__.py#L249-L260
|
[
"def",
"delete_classifier",
"(",
"self",
",",
"classifier_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"classifier_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'classifier_id must be provided'",
")",
"headers",
"=",
"{",
"}",
"if",
"'headers'",
"in",
"kwargs",
":",
"headers",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'headers'",
")",
")",
"sdk_headers",
"=",
"get_sdk_headers",
"(",
"'watson_vision_combined'",
",",
"'V3'",
",",
"'delete_classifier'",
")",
"headers",
".",
"update",
"(",
"sdk_headers",
")",
"params",
"=",
"{",
"'version'",
":",
"self",
".",
"version",
"}",
"url",
"=",
"'/v3/classifiers/{0}'",
".",
"format",
"(",
"*",
"self",
".",
"_encode_path_vars",
"(",
"classifier_id",
")",
")",
"response",
"=",
"self",
".",
"request",
"(",
"method",
"=",
"'DELETE'",
",",
"url",
"=",
"url",
",",
"headers",
"=",
"headers",
",",
"params",
"=",
"params",
",",
"accept_json",
"=",
"True",
")",
"return",
"response"
] |
Return n independent iterators from a single iterable .
|
def tee ( iterable , n = 2 ) : tees = tuple ( AsyncTeeIterable ( iterable ) for _ in range ( n ) ) for tee in tees : tee . _siblings = tees return tees
| 2,397
|
https://github.com/asyncdef/aitertools/blob/26a6c7e71e87dd1ddc4acb755d70ca30894f7928/aitertools/__init__.py#L890-L907
|
[
"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",
")"
] |
Called internally to emit changes from the instance object
|
def _on_change ( self , obj , old , value , * * kwargs ) : kwargs [ 'property' ] = self obj . emit ( self . name , obj , value , old = old , * * kwargs )
| 2,398
|
https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/properties.py#L96-L114
|
[
"def",
"tvdb_series_id",
"(",
"token",
",",
"id_tvdb",
",",
"lang",
"=",
"\"en\"",
",",
"cache",
"=",
"True",
")",
":",
"if",
"lang",
"not",
"in",
"TVDB_LANGUAGE_CODES",
":",
"raise",
"MapiProviderException",
"(",
"\"'lang' must be one of %s\"",
"%",
"\",\"",
".",
"join",
"(",
"TVDB_LANGUAGE_CODES",
")",
")",
"try",
":",
"url",
"=",
"\"https://api.thetvdb.com/series/%d\"",
"%",
"int",
"(",
"id_tvdb",
")",
"except",
"ValueError",
":",
"raise",
"MapiProviderException",
"(",
"\"id_tvdb must be numeric\"",
")",
"headers",
"=",
"{",
"\"Accept-Language\"",
":",
"lang",
",",
"\"Authorization\"",
":",
"\"Bearer %s\"",
"%",
"token",
"}",
"status",
",",
"content",
"=",
"_request_json",
"(",
"url",
",",
"headers",
"=",
"headers",
",",
"cache",
"=",
"cache",
")",
"if",
"status",
"==",
"401",
":",
"raise",
"MapiProviderException",
"(",
"\"invalid token\"",
")",
"elif",
"status",
"==",
"404",
":",
"raise",
"MapiNotFoundException",
"elif",
"status",
"!=",
"200",
"or",
"not",
"content",
".",
"get",
"(",
"\"data\"",
")",
":",
"raise",
"MapiNetworkException",
"(",
"\"TVDb down or unavailable?\"",
")",
"return",
"content"
] |
Parse string and return relevant object
|
def parse_str ( self , s ) : self . object = self . parsed_class ( ) in_section = None # Holds name of FEH file section while traversing through file. for line in s . split ( '\n' ) : if line . lower ( ) . startswith ( '[end]' ) : # Leave section in_section = None elif line . startswith ( '[' ) : # Enter section, sanitise `[Section Name]` to `section_name` in_section = line . strip ( ) . strip ( '[]' ) . lower ( ) . replace ( ' ' , '_' ) elif in_section : try : # Call method `_section_section_name(line)` getattr ( self , '_section_' + in_section ) ( line . strip ( ) ) except AttributeError : pass # Skip unsupported section return self . object
| 2,399
|
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/parsers.py#L70-L93
|
[
"def",
"run_info",
"(",
"template",
")",
":",
"template",
".",
"project_name",
"=",
"'TowelStuff'",
"# fake project name, always the same",
"name",
"=",
"template_name_from_class_name",
"(",
"template",
".",
"__class__",
".",
"__name__",
")",
"term",
"=",
"TerminalView",
"(",
")",
"term",
".",
"print_info",
"(",
"\"Content of template {} with an example project \"",
"\"named 'TowelStuff':\"",
".",
"format",
"(",
"term",
".",
"text_in_color",
"(",
"name",
",",
"TERM_GREEN",
")",
")",
")",
"dir_name",
"=",
"None",
"for",
"file_info",
"in",
"sorted",
"(",
"template",
".",
"files",
"(",
")",
",",
"key",
"=",
"lambda",
"dir",
":",
"dir",
"[",
"0",
"]",
")",
":",
"directory",
"=",
"file_name",
"=",
"template_name",
"=",
"''",
"if",
"file_info",
"[",
"0",
"]",
":",
"directory",
"=",
"file_info",
"[",
"0",
"]",
"if",
"file_info",
"[",
"1",
"]",
":",
"file_name",
"=",
"file_info",
"[",
"1",
"]",
"if",
"file_info",
"[",
"2",
"]",
":",
"template_name",
"=",
"'\\t\\t - '",
"+",
"file_info",
"[",
"2",
"]",
"if",
"(",
"directory",
"!=",
"dir_name",
")",
":",
"term",
".",
"print_info",
"(",
"'\\n\\t'",
"+",
"term",
".",
"text_in_color",
"(",
"directory",
"+",
"'/'",
",",
"TERM_PINK",
")",
")",
"dir_name",
"=",
"directory",
"term",
".",
"print_info",
"(",
"'\\t\\t'",
"+",
"term",
".",
"text_in_color",
"(",
"file_name",
",",
"TERM_YELLOW",
")",
"+",
"template_name",
")",
"# print substitutions",
"try",
":",
"subs",
"=",
"template",
".",
"substitutes",
"(",
")",
".",
"keys",
"(",
")",
"if",
"len",
"(",
"subs",
")",
">",
"0",
":",
"subs",
".",
"sort",
"(",
")",
"term",
".",
"print_info",
"(",
"\"\\nSubstitutions of this template are: \"",
")",
"max_len",
"=",
"0",
"for",
"key",
"in",
"subs",
":",
"if",
"max_len",
"<",
"len",
"(",
"key",
")",
":",
"max_len",
"=",
"len",
"(",
"key",
")",
"for",
"key",
"in",
"subs",
":",
"term",
".",
"print_info",
"(",
"u\"\\t{0:{1}} -> {2}\"",
".",
"format",
"(",
"key",
",",
"max_len",
",",
"template",
".",
"substitutes",
"(",
")",
"[",
"key",
"]",
")",
")",
"except",
"AttributeError",
":",
"pass"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.