query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
May be overidden to provide custom functionality . Constructs an argparse . ArgumentParser used to parse configuration options from the command line . | def getArgumentParser ( self , configManager , config ) : argParser = argparse . ArgumentParser ( self . description ) for configName , configDict in configManager . configs . items ( ) : cmdName = configName . replace ( "_" , "-" ) argParser . add_argument ( '--%s' % cmdName , default = None , help = configDict [ 'description' ] ) return argParser | 5,600 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/cmdline.py#L41-L61 | [
"def",
"saturation",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"clean_float",
"(",
"value",
")",
"if",
"value",
"is",
"None",
":",
"return",
"try",
":",
"unit_moisture_weight",
"=",
"self",
".",
"unit_moist_weight",
"-",
"self",
".",
"unit_dry_weight",
"unit_moisture_volume",
"=",
"unit_moisture_weight",
"/",
"self",
".",
"_pw",
"saturation",
"=",
"unit_moisture_volume",
"/",
"self",
".",
"_calc_unit_void_volume",
"(",
")",
"if",
"saturation",
"is",
"not",
"None",
"and",
"not",
"ct",
".",
"isclose",
"(",
"saturation",
",",
"value",
",",
"rel_tol",
"=",
"self",
".",
"_tolerance",
")",
":",
"raise",
"ModelError",
"(",
"\"New saturation (%.3f) is inconsistent \"",
"\"with calculated value (%.3f)\"",
"%",
"(",
"value",
",",
"saturation",
")",
")",
"except",
"TypeError",
":",
"pass",
"old_value",
"=",
"self",
".",
"saturation",
"self",
".",
"_saturation",
"=",
"value",
"try",
":",
"self",
".",
"recompute_all_weights_and_void",
"(",
")",
"self",
".",
"_add_to_stack",
"(",
"\"saturation\"",
",",
"value",
")",
"except",
"ModelError",
"as",
"e",
":",
"self",
".",
"_saturation",
"=",
"old_value",
"raise",
"ModelError",
"(",
"e",
")"
] |
Parses commandline arguments given a series of configuration options . | def parse ( self , configManager , config ) : argParser = self . getArgumentParser ( configManager , config ) return vars ( argParser . parse_args ( ) ) | 5,601 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/cmdline.py#L63-L74 | [
"def",
"to_xdr_object",
"(",
"self",
")",
":",
"return",
"Xdr",
".",
"types",
".",
"Memo",
"(",
"type",
"=",
"Xdr",
".",
"const",
".",
"MEMO_HASH",
",",
"hash",
"=",
"self",
".",
"memo_hash",
")"
] |
Given a text string get candidates and context for feature extraction and classification | def candidates ( text ) : for Pmatch in finditer ( TARGET , text ) : # the punctuation mark itself P = Pmatch . group ( 1 ) # is it a boundary? B = bool ( match ( NEWLINE , Pmatch . group ( 5 ) ) ) # L & R start = Pmatch . start ( ) end = Pmatch . end ( ) Lmatch = search ( LTOKEN , text [ max ( 0 , start - BUFSIZE ) : start ] ) if not Lmatch : # this happens when a line begins with '.' continue L = word_tokenize ( " " + Lmatch . group ( 1 ) ) [ - 1 ] Rmatch = search ( RTOKEN , text [ end : end + BUFSIZE ] ) if not Rmatch : # this happens at the end of the file, usually continue R = word_tokenize ( Rmatch . group ( 1 ) + " " ) [ 0 ] # complete observation yield Observation ( L , P , R , B , end ) | 5,602 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L105-L127 | [
"def",
"update",
"(",
"self",
",",
"d",
")",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
"or",
"self",
"[",
"k",
"]",
"!=",
"v",
":",
"self",
"[",
"k",
"]",
"=",
"v"
] |
Given left context L punctuation mark P and right context R extract features . Probability distributions for any quantile - based features will not be modified . | def extract_one ( self , L , P , R ) : yield "*bias*" # L feature(s) if match ( QUOTE , L ) : L = QUOTE_TOKEN elif isnumberlike ( L ) : L = NUMBER_TOKEN else : yield "len(L)={}" . format ( min ( len ( L ) , CLIP ) ) if "." in L : yield "L:*period*" if not self . nocase : cf = case_feature ( R ) if cf : yield "L:{}'" . format ( cf ) L = L . upper ( ) if not any ( char in VOWELS for char in L ) : yield "L:*no-vowel*" L_feat = "L='{}'" . format ( L ) yield L_feat # P feature(s) yield "P='{}'" . format ( P ) # R feature(s) if match ( QUOTE , R ) : R = QUOTE_TOKEN elif isnumberlike ( R ) : R = NUMBER_TOKEN else : if not self . nocase : cf = case_feature ( R ) if cf : yield "R:{}'" . format ( cf ) R = R . upper ( ) R_feat = "R='{}'" . format ( R ) yield R_feat # the combined L,R feature yield "{},{}" . format ( L_feat , R_feat ) | 5,603 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L132-L173 | [
"def",
"_clones",
"(",
"self",
")",
":",
"vbox",
"=",
"VirtualBox",
"(",
")",
"machines",
"=",
"[",
"]",
"for",
"machine",
"in",
"vbox",
".",
"machines",
":",
"if",
"machine",
".",
"name",
"==",
"self",
".",
"machine_name",
":",
"continue",
"if",
"machine",
".",
"name",
".",
"startswith",
"(",
"self",
".",
"machine_name",
")",
":",
"machines",
".",
"append",
"(",
"machine",
")",
"return",
"machines"
] |
Given a string text use it to train the segmentation classifier for epochs iterations . | def fit ( self , text , epochs = EPOCHS ) : logger . debug ( "Extracting features and classifications." ) Phi = [ ] Y = [ ] for ( L , P , R , gold , _ ) in Detector . candidates ( text ) : Phi . append ( self . extract_one ( L , P , R ) ) Y . append ( gold ) self . classifier . fit ( Y , Phi , epochs ) logger . debug ( "Fitting complete." ) | 5,604 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L177-L187 | [
"def",
"hide",
"(",
"self",
",",
"selections",
")",
":",
"if",
"'atoms'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'atoms'",
"]",
"=",
"selections",
"[",
"'atoms'",
"]",
"self",
".",
"on_atom_hidden_changed",
"(",
")",
"if",
"'bonds'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'bonds'",
"]",
"=",
"selections",
"[",
"'bonds'",
"]",
"self",
".",
"on_bond_hidden_changed",
"(",
")",
"if",
"'box'",
"in",
"selections",
":",
"self",
".",
"hidden_state",
"[",
"'box'",
"]",
"=",
"box_s",
"=",
"selections",
"[",
"'box'",
"]",
"if",
"box_s",
".",
"mask",
"[",
"0",
"]",
":",
"if",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"remove_renderer",
"(",
"self",
".",
"box_renderer",
")",
"else",
":",
"if",
"not",
"self",
".",
"viewer",
".",
"has_renderer",
"(",
"self",
".",
"box_renderer",
")",
":",
"self",
".",
"viewer",
".",
"add_renderer",
"(",
"self",
".",
"box_renderer",
")",
"return",
"self",
".",
"hidden_state"
] |
Given an left context L punctuation mark P and right context R return True iff this observation is hypothesized to be a sentence boundary . | def predict ( self , L , P , R ) : phi = self . extract_one ( L , P , R ) return self . classifier . predict ( phi ) | 5,605 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L189-L196 | [
"def",
"_refresh",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'refreshing directory cache'",
")",
"self",
".",
"_users",
".",
"update",
"(",
"list",
"(",
"self",
".",
"_user_gen",
"(",
")",
")",
")",
"self",
".",
"_channels",
".",
"update",
"(",
"list",
"(",
"self",
".",
"_channel_gen",
"(",
")",
")",
")"
] |
Given a string of text return a generator yielding each hypothesized sentence string | def segments ( self , text ) : start = 0 for ( L , P , R , B , end ) in Detector . candidates ( text ) : # if there's already a newline there, we have nothing to do if B : continue if self . predict ( L , P , R ) : yield text [ start : end ] . rstrip ( ) start = end # otherwise, there's probably not a sentence boundary here yield text [ start : ] . rstrip ( ) | 5,606 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L198-L212 | [
"def",
"unwrap",
"(",
"self",
",",
"val",
")",
":",
"if",
"val",
".",
"getID",
"(",
")",
"!=",
"self",
".",
"id",
":",
"self",
".",
"_update",
"(",
"val",
")",
"return",
"self",
".",
"_unwrap",
"(",
"val",
")"
] |
Given a string of text compute confusion matrix for the classification task . | def evaluate ( self , text ) : cx = BinaryConfusion ( ) for ( L , P , R , gold , _ ) in Detector . candidates ( text ) : guess = self . predict ( L , P , R ) cx . update ( gold , guess ) if not gold and guess : logger . debug ( "False pos.: L='{}', R='{}'." . format ( L , R ) ) elif gold and not guess : logger . debug ( "False neg.: L='{}', R='{}'." . format ( L , R ) ) return cx | 5,607 | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/detector_morse.py#L214-L227 | [
"def",
"update",
"(",
"self",
",",
"new_options",
")",
":",
"for",
"option",
"in",
"new_options",
":",
"if",
"option",
".",
"key",
"in",
"self",
".",
"options",
":",
"del",
"self",
".",
"options",
"[",
"option",
".",
"key",
"]",
"self",
".",
"options",
"[",
"option",
".",
"key",
"]",
"=",
"option"
] |
Scale the completeness depth of a mask such that mag_new = mag + mag_scale . Input is a full HEALPix map . Optionally write out the scaled mask as an sparse HEALPix map . | def scale ( mask , mag_scale , outfile = None ) : msg = "'mask.scale': ADW 2018-05-05" DeprecationWarning ( msg ) mask_new = hp . UNSEEN * np . ones ( len ( mask ) ) mask_new [ mask == 0. ] = 0. mask_new [ mask > 0. ] = mask [ mask > 0. ] + mag_scale if outfile is not None : pix = np . nonzero ( mask_new > 0. ) [ 0 ] data_dict = { 'MAGLIM' : mask_new [ pix ] } nside = hp . npix2nside ( len ( mask_new ) ) ugali . utils . skymap . writeSparseHealpixMap ( pix , data_dict , nside , outfile ) return mask_new | 5,608 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L1007-L1025 | [
"def",
"_ReportSameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")",
":",
"self",
".",
"feed_merger",
".",
"problem_reporter",
".",
"SameIdButNotMerged",
"(",
"self",
",",
"entity_id",
",",
"reason",
")"
] |
Assemble a set of unique magnitude tuples for the ROI | def mask_roi_unique ( self ) : # There is no good inherent way in numpy to do this... # http://stackoverflow.com/q/16970982/ # Also possible and simple: #return np.unique(zip(self.mask_1.mask_roi_sparse,self.mask_2.mask_roi_sparse)) A = np . vstack ( [ self . mask_1 . mask_roi_sparse , self . mask_2 . mask_roi_sparse ] ) . T B = A [ np . lexsort ( A . T [ : : - 1 ] ) ] return B [ np . concatenate ( ( [ True ] , np . any ( B [ 1 : ] != B [ : - 1 ] , axis = 1 ) ) ) ] | 5,609 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L55-L67 | [
"def",
"normalize_windows_fname",
"(",
"fname",
",",
"_force",
"=",
"False",
")",
":",
"if",
"(",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"!=",
"\"windows\"",
")",
"and",
"(",
"not",
"_force",
")",
":",
"# pragma: no cover",
"return",
"fname",
"# Replace unintended escape sequences that could be in",
"# the file name, like \"C:\\appdata\"",
"rchars",
"=",
"{",
"\"\\x07\"",
":",
"r\"\\\\a\"",
",",
"\"\\x08\"",
":",
"r\"\\\\b\"",
",",
"\"\\x0C\"",
":",
"r\"\\\\f\"",
",",
"\"\\x0A\"",
":",
"r\"\\\\n\"",
",",
"\"\\x0D\"",
":",
"r\"\\\\r\"",
",",
"\"\\x09\"",
":",
"r\"\\\\t\"",
",",
"\"\\x0B\"",
":",
"r\"\\\\v\"",
",",
"}",
"ret",
"=",
"\"\"",
"for",
"char",
"in",
"os",
".",
"path",
".",
"normpath",
"(",
"fname",
")",
":",
"ret",
"=",
"ret",
"+",
"rchars",
".",
"get",
"(",
"char",
",",
"char",
")",
"# Remove superfluous double backslashes",
"network_share",
"=",
"False",
"tmp",
"=",
"None",
"network_share",
"=",
"fname",
".",
"startswith",
"(",
"r\"\\\\\"",
")",
"while",
"tmp",
"!=",
"ret",
":",
"tmp",
",",
"ret",
"=",
"ret",
",",
"ret",
".",
"replace",
"(",
"r\"\\\\\\\\\"",
",",
"r\"\\\\\"",
")",
"ret",
"=",
"ret",
".",
"replace",
"(",
"r\"\\\\\\\\\"",
",",
"r\"\\\\\"",
")",
"# Put back network share if needed",
"if",
"network_share",
":",
"ret",
"=",
"r\"\\\\\"",
"+",
"ret",
".",
"lstrip",
"(",
"r\"\\\\\"",
")",
"return",
"ret"
] |
Get the index of the unique magnitude tuple for each pixel in the ROI . | def mask_roi_digi ( self ) : # http://stackoverflow.com/q/24205045/#24206440 A = np . vstack ( [ self . mask_1 . mask_roi_sparse , self . mask_2 . mask_roi_sparse ] ) . T B = self . mask_roi_unique AA = np . ascontiguousarray ( A ) BB = np . ascontiguousarray ( B ) dt = np . dtype ( ( np . void , AA . dtype . itemsize * AA . shape [ 1 ] ) ) a = AA . view ( dt ) . ravel ( ) b = BB . view ( dt ) . ravel ( ) idx = np . argsort ( b ) indices = np . searchsorted ( b [ idx ] , a ) return idx [ indices ] | 5,610 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L70-L87 | [
"def",
"normalize_windows_fname",
"(",
"fname",
",",
"_force",
"=",
"False",
")",
":",
"if",
"(",
"platform",
".",
"system",
"(",
")",
".",
"lower",
"(",
")",
"!=",
"\"windows\"",
")",
"and",
"(",
"not",
"_force",
")",
":",
"# pragma: no cover",
"return",
"fname",
"# Replace unintended escape sequences that could be in",
"# the file name, like \"C:\\appdata\"",
"rchars",
"=",
"{",
"\"\\x07\"",
":",
"r\"\\\\a\"",
",",
"\"\\x08\"",
":",
"r\"\\\\b\"",
",",
"\"\\x0C\"",
":",
"r\"\\\\f\"",
",",
"\"\\x0A\"",
":",
"r\"\\\\n\"",
",",
"\"\\x0D\"",
":",
"r\"\\\\r\"",
",",
"\"\\x09\"",
":",
"r\"\\\\t\"",
",",
"\"\\x0B\"",
":",
"r\"\\\\v\"",
",",
"}",
"ret",
"=",
"\"\"",
"for",
"char",
"in",
"os",
".",
"path",
".",
"normpath",
"(",
"fname",
")",
":",
"ret",
"=",
"ret",
"+",
"rchars",
".",
"get",
"(",
"char",
",",
"char",
")",
"# Remove superfluous double backslashes",
"network_share",
"=",
"False",
"tmp",
"=",
"None",
"network_share",
"=",
"fname",
".",
"startswith",
"(",
"r\"\\\\\"",
")",
"while",
"tmp",
"!=",
"ret",
":",
"tmp",
",",
"ret",
"=",
"ret",
",",
"ret",
".",
"replace",
"(",
"r\"\\\\\\\\\"",
",",
"r\"\\\\\"",
")",
"ret",
"=",
"ret",
".",
"replace",
"(",
"r\"\\\\\\\\\"",
",",
"r\"\\\\\"",
")",
"# Put back network share if needed",
"if",
"network_share",
":",
"ret",
"=",
"r\"\\\\\"",
"+",
"ret",
".",
"lstrip",
"(",
"r\"\\\\\"",
")",
"return",
"ret"
] |
Calculate an approximate pixel coverage fraction from the two masks . | def _fracRoiSparse ( self ) : self . frac_roi_sparse = np . min ( [ self . mask_1 . frac_roi_sparse , self . mask_2 . frac_roi_sparse ] , axis = 0 ) return self . frac_roi_sparse | 5,611 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L97-L113 | [
"def",
"cublasDestroy",
"(",
"handle",
")",
":",
"status",
"=",
"_libcublas",
".",
"cublasDestroy_v2",
"(",
"ctypes",
".",
"c_void_p",
"(",
"handle",
")",
")",
"cublasCheckStatus",
"(",
"status",
")"
] |
Remove regions of magnitude - magnitude space where the unmasked solid angle is statistically insufficient to estimate the background . | def _pruneMMD ( self , minimum_solid_angle ) : logger . info ( 'Pruning mask based on minimum solid angle of %.2f deg^2' % ( minimum_solid_angle ) ) solid_angle_mmd = self . solid_angle_mmd * ( self . solid_angle_mmd > minimum_solid_angle ) if solid_angle_mmd . sum ( ) == 0 : msg = "Pruned mask contains no solid angle." logger . error ( msg ) raise Exception ( msg ) self . solid_angle_mmd = solid_angle_mmd # Compute which magnitudes the clipping correspond to index_mag_1 , index_mag_2 = np . nonzero ( self . solid_angle_mmd ) self . mag_1_clip = self . roi . bins_mag [ 1 : ] [ np . max ( index_mag_1 ) ] self . mag_2_clip = self . roi . bins_mag [ 1 : ] [ np . max ( index_mag_2 ) ] logger . info ( 'Clipping mask 1 at %.2f mag' % ( self . mag_1_clip ) ) logger . info ( 'Clipping mask 2 at %.2f mag' % ( self . mag_2_clip ) ) self . mask_1 . mask_roi_sparse = np . clip ( self . mask_1 . mask_roi_sparse , 0. , self . mag_1_clip ) self . mask_2 . mask_roi_sparse = np . clip ( self . mask_2 . mask_roi_sparse , 0. , self . mag_2_clip ) | 5,612 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L135-L162 | [
"def",
"remote_list",
"(",
"timestamps",
"=",
"True",
")",
":",
"r",
"=",
"get_remote_file",
"(",
"DICTS_URL",
")",
"lst",
"=",
"[",
"]",
"for",
"f",
"in",
"r",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"f",
":",
"continue",
"name",
",",
"date",
"=",
"f",
".",
"split",
"(",
"':'",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'.txt'",
",",
"''",
")",
"lst",
".",
"append",
"(",
"(",
"name",
",",
"int",
"(",
"date",
")",
")",
"if",
"timestamps",
"else",
"name",
")",
"return",
"lst"
] |
Remove regions of color - magnitude space where the unmasked solid angle is statistically insufficient to estimate the background . | def _pruneCMD ( self , minimum_solid_angle ) : logger . info ( 'Pruning mask based on minimum solid angle of %.2f deg^2' % ( minimum_solid_angle ) ) self . solid_angle_cmd *= self . solid_angle_cmd > minimum_solid_angle if self . solid_angle_cmd . sum ( ) == 0 : msg = "Pruned mask contains no solid angle." logger . error ( msg ) raise Exception ( msg ) # Compute which magnitudes the clipping correspond to index_mag , index_color = np . nonzero ( self . solid_angle_cmd ) mag = self . roi . centers_mag [ index_mag ] color = self . roi . centers_color [ index_color ] if self . config . params [ 'catalog' ] [ 'band_1_detection' ] : mag_1 = mag mag_2 = mag_1 - color self . mag_1_clip = np . max ( mag_1 ) + ( 0.5 * self . roi . delta_mag ) self . mag_2_clip = np . max ( mag_2 ) + ( 0.5 * self . roi . delta_color ) else : mag_2 = mag mag_1 = color + mag_2 self . mag_1_clip = np . max ( mag_1 ) + ( 0.5 * self . roi . delta_color ) self . mag_2_clip = np . max ( mag_2 ) + ( 0.5 * self . roi . delta_mag ) logger . info ( 'Clipping mask 1 at %.2f mag' % ( self . mag_1_clip ) ) logger . info ( 'Clipping mask 2 at %.2f mag' % ( self . mag_2_clip ) ) self . mask_1 . mask_roi_sparse = np . clip ( self . mask_1 . mask_roi_sparse , 0. , self . mag_1_clip ) self . mask_2 . mask_roi_sparse = np . clip ( self . mask_2 . mask_roi_sparse , 0. , self . mag_2_clip ) | 5,613 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L257-L294 | [
"def",
"remote_list",
"(",
"timestamps",
"=",
"True",
")",
":",
"r",
"=",
"get_remote_file",
"(",
"DICTS_URL",
")",
"lst",
"=",
"[",
"]",
"for",
"f",
"in",
"r",
".",
"text",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"not",
"f",
":",
"continue",
"name",
",",
"date",
"=",
"f",
".",
"split",
"(",
"':'",
")",
"name",
"=",
"name",
".",
"replace",
"(",
"'.txt'",
",",
"''",
")",
"lst",
".",
"append",
"(",
"(",
"name",
",",
"int",
"(",
"date",
")",
")",
"if",
"timestamps",
"else",
"name",
")",
"return",
"lst"
] |
Plot the magnitude depth . | def plot ( self ) : msg = "'%s.plot': ADW 2018-05-05" % self . __class__ . __name__ DeprecationWarning ( msg ) import ugali . utils . plotting mask = hp . UNSEEN * np . ones ( hp . nside2npix ( self . nside ) ) mask [ self . roi . pixels ] = self . mask_roi_sparse mask [ mask == 0. ] = hp . UNSEEN ugali . utils . plotting . zoomedHealpixMap ( 'Completeness Depth' , mask , self . roi . lon , self . roi . lat , self . roi . config . params [ 'coords' ] [ 'roi_radius' ] ) | 5,614 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/observation/mask.py#L850-L865 | [
"def",
"return_port",
"(",
"port",
")",
":",
"if",
"port",
"in",
"_random_ports",
":",
"_random_ports",
".",
"remove",
"(",
"port",
")",
"elif",
"port",
"in",
"_owned_ports",
":",
"_owned_ports",
".",
"remove",
"(",
"port",
")",
"_free_ports",
".",
"add",
"(",
"port",
")",
"elif",
"port",
"in",
"_free_ports",
":",
"logging",
".",
"info",
"(",
"\"Returning a port that was already returned: %s\"",
",",
"port",
")",
"else",
":",
"logging",
".",
"info",
"(",
"\"Returning a port that wasn't given by portpicker: %s\"",
",",
"port",
")"
] |
Build the Expected parameters from a dict | def build_expected ( dynamizer , expected ) : ret = { } for k , v in six . iteritems ( expected ) : if is_null ( v ) : ret [ k ] = { 'Exists' : False , } else : ret [ k ] = { 'Exists' : True , 'Value' : dynamizer . encode ( v ) , } return ret | 5,615 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L19-L32 | [
"def",
"setOverlayTextureColorSpace",
"(",
"self",
",",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTextureColorSpace",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"eTextureColorSpace",
")",
"return",
"result"
] |
Build ExpresionAttributeValues from a value or kwargs | def build_expression_values ( dynamizer , expr_values , kwargs ) : if expr_values : values = expr_values return dynamizer . encode_keys ( values ) elif kwargs : values = dict ( ( ( ':' + k , v ) for k , v in six . iteritems ( kwargs ) ) ) return dynamizer . encode_keys ( values ) | 5,616 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L35-L42 | [
"def",
"_gcd_array",
"(",
"X",
")",
":",
"greatest_common_divisor",
"=",
"0.0",
"for",
"x",
"in",
"X",
":",
"greatest_common_divisor",
"=",
"_gcd",
"(",
"greatest_common_divisor",
",",
"x",
")",
"return",
"greatest_common_divisor"
] |
Connect to a specific host . | def connect_to_host ( cls , host = 'localhost' , port = 8000 , is_secure = False , session = None , access_key = None , secret_key = None , * * kwargs ) : warnings . warn ( "connect_to_host is deprecated and will be removed. " "Use connect instead." ) if session is None : session = botocore . session . get_session ( ) if access_key is not None : session . set_credentials ( access_key , secret_key ) url = "http://%s:%d" % ( host , port ) client = session . create_client ( 'dynamodb' , 'local' , endpoint_url = url , use_ssl = is_secure ) return cls ( client , * * kwargs ) | 5,617 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L121-L156 | [
"def",
"_wrap_definition_section",
"(",
"source",
",",
"width",
")",
":",
"# type: (str, int) -> str",
"index",
"=",
"source",
".",
"index",
"(",
"'\\n'",
")",
"+",
"1",
"definitions",
",",
"max_len",
"=",
"_get_definitions",
"(",
"source",
"[",
"index",
":",
"]",
")",
"sep",
"=",
"'\\n'",
"+",
"' '",
"*",
"(",
"max_len",
"+",
"4",
")",
"lines",
"=",
"[",
"source",
"[",
":",
"index",
"]",
".",
"strip",
"(",
")",
"]",
"for",
"arg",
",",
"desc",
"in",
"six",
".",
"iteritems",
"(",
"definitions",
")",
":",
"wrapped_desc",
"=",
"sep",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"desc",
",",
"width",
"-",
"max_len",
"-",
"4",
")",
")",
"lines",
".",
"append",
"(",
"' {arg:{size}} {desc}'",
".",
"format",
"(",
"arg",
"=",
"arg",
",",
"size",
"=",
"str",
"(",
"max_len",
")",
",",
"desc",
"=",
"wrapped_desc",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] |
Make a request to DynamoDB using the raw botocore API | def call ( self , command , * * kwargs ) : for hook in self . _hooks [ 'precall' ] : hook ( self , command , kwargs ) op = getattr ( self . client , command ) attempt = 0 while True : try : data = op ( * * kwargs ) break except ClientError as e : exc = translate_exception ( e , kwargs ) attempt += 1 if isinstance ( exc , ThroughputException ) : if attempt > self . request_retries : exc . re_raise ( ) self . exponential_sleep ( attempt ) else : exc . re_raise ( ) for hook in self . _hooks [ 'postcall' ] : hook ( self , command , kwargs , data ) if 'ConsumedCapacity' in data : is_read = command in READ_COMMANDS consumed = data [ 'ConsumedCapacity' ] if isinstance ( consumed , list ) : data [ 'consumed_capacity' ] = [ ConsumedCapacity . from_response ( cap , is_read ) for cap in consumed ] else : capacity = ConsumedCapacity . from_response ( consumed , is_read ) data [ 'consumed_capacity' ] = capacity if 'consumed_capacity' in data : if isinstance ( data [ 'consumed_capacity' ] , list ) : all_caps = data [ 'consumed_capacity' ] else : all_caps = [ data [ 'consumed_capacity' ] ] for hook in self . _hooks [ 'capacity' ] : for cap in all_caps : hook ( self , command , kwargs , data , cap ) return data | 5,618 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L196-L254 | [
"def",
"is_vert_aligned_center",
"(",
"c",
")",
":",
"return",
"all",
"(",
"[",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
".",
"sentence",
".",
"is_visual",
"(",
")",
"and",
"bbox_vert_aligned_center",
"(",
"bbox_from_span",
"(",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
")",
",",
"bbox_from_span",
"(",
"_to_span",
"(",
"c",
"[",
"0",
"]",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"c",
")",
")",
"]",
")"
] |
Subscribe a callback to an event | def subscribe ( self , event , hook ) : if hook not in self . _hooks [ event ] : self . _hooks [ event ] . append ( hook ) | 5,619 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L261-L276 | [
"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"
] |
Unsubscribe a hook from an event | def unsubscribe ( self , event , hook ) : if hook in self . _hooks [ event ] : self . _hooks [ event ] . remove ( hook ) | 5,620 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L278-L281 | [
"def",
"ConfigureUrls",
"(",
"config",
",",
"external_hostname",
"=",
"None",
")",
":",
"print",
"(",
"\"\\n\\n-=GRR URLs=-\\n\"",
"\"For GRR to work each client has to be able to communicate with the\\n\"",
"\"server. To do this we normally need a public dns name or IP address\\n\"",
"\"to communicate with. In the standard configuration this will be used\\n\"",
"\"to host both the client facing server and the admin user interface.\\n\"",
")",
"existing_ui_urn",
"=",
"grr_config",
".",
"CONFIG",
".",
"Get",
"(",
"\"AdminUI.url\"",
",",
"default",
"=",
"None",
")",
"existing_frontend_urns",
"=",
"grr_config",
".",
"CONFIG",
".",
"Get",
"(",
"\"Client.server_urls\"",
")",
"if",
"not",
"existing_frontend_urns",
":",
"# Port from older deprecated setting Client.control_urls.",
"existing_control_urns",
"=",
"grr_config",
".",
"CONFIG",
".",
"Get",
"(",
"\"Client.control_urls\"",
",",
"default",
"=",
"None",
")",
"if",
"existing_control_urns",
"is",
"not",
"None",
":",
"existing_frontend_urns",
"=",
"[",
"]",
"for",
"existing_control_urn",
"in",
"existing_control_urns",
":",
"if",
"not",
"existing_control_urn",
".",
"endswith",
"(",
"\"control\"",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Invalid existing control URL: %s\"",
"%",
"existing_control_urn",
")",
"existing_frontend_urns",
".",
"append",
"(",
"existing_control_urn",
".",
"rsplit",
"(",
"\"/\"",
",",
"1",
")",
"[",
"0",
"]",
"+",
"\"/\"",
")",
"config",
".",
"Set",
"(",
"\"Client.server_urls\"",
",",
"existing_frontend_urns",
")",
"config",
".",
"Set",
"(",
"\"Client.control_urls\"",
",",
"[",
"\"deprecated use Client.server_urls\"",
"]",
")",
"if",
"not",
"existing_frontend_urns",
"or",
"not",
"existing_ui_urn",
":",
"ConfigureHostnames",
"(",
"config",
",",
"external_hostname",
"=",
"external_hostname",
")",
"else",
":",
"print",
"(",
"\"Found existing settings:\\n AdminUI URL: %s\\n \"",
"\"Frontend URL(s): %s\\n\"",
"%",
"(",
"existing_ui_urn",
",",
"existing_frontend_urns",
")",
")",
"if",
"not",
"RetryBoolQuestion",
"(",
"\"Do you want to keep this configuration?\"",
",",
"True",
")",
":",
"ConfigureHostnames",
"(",
"config",
",",
"external_hostname",
"=",
"external_hostname",
")"
] |
Add a RateLimit to the connection | def add_rate_limit ( self , limiter ) : if limiter not in self . rate_limiters : self . subscribe ( 'capacity' , limiter . on_capacity ) self . rate_limiters . append ( limiter ) | 5,621 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L283-L287 | [
"def",
"_read",
"(",
"self",
",",
"directory",
",",
"filename",
",",
"session",
",",
"path",
",",
"name",
",",
"extension",
",",
"spatial",
"=",
"None",
",",
"spatialReferenceID",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"yml_events",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
")",
"as",
"fo",
":",
"yml_events",
"=",
"yaml",
".",
"load",
"(",
"fo",
")",
"for",
"yml_event",
"in",
"yml_events",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"yml_event",
".",
"subfolder",
")",
")",
":",
"orm_event",
"=",
"yml_event",
".",
"as_orm",
"(",
")",
"if",
"not",
"self",
".",
"_similar_event_exists",
"(",
"orm_event",
".",
"subfolder",
")",
":",
"session",
".",
"add",
"(",
"orm_event",
")",
"self",
".",
"events",
".",
"append",
"(",
"orm_event",
")",
"session",
".",
"commit",
"(",
")"
] |
Remove a RateLimit from the connection | def remove_rate_limit ( self , limiter ) : if limiter in self . rate_limiters : self . unsubscribe ( 'capacity' , limiter . on_capacity ) self . rate_limiters . remove ( limiter ) | 5,622 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L289-L293 | [
"def",
"_read",
"(",
"self",
",",
"directory",
",",
"filename",
",",
"session",
",",
"path",
",",
"name",
",",
"extension",
",",
"spatial",
"=",
"None",
",",
"spatialReferenceID",
"=",
"None",
",",
"replaceParamFile",
"=",
"None",
")",
":",
"yml_events",
"=",
"[",
"]",
"with",
"open",
"(",
"path",
")",
"as",
"fo",
":",
"yml_events",
"=",
"yaml",
".",
"load",
"(",
"fo",
")",
"for",
"yml_event",
"in",
"yml_events",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"directory",
",",
"yml_event",
".",
"subfolder",
")",
")",
":",
"orm_event",
"=",
"yml_event",
".",
"as_orm",
"(",
")",
"if",
"not",
"self",
".",
"_similar_event_exists",
"(",
"orm_event",
".",
"subfolder",
")",
":",
"session",
".",
"add",
"(",
"orm_event",
")",
"self",
".",
"events",
".",
"append",
"(",
"orm_event",
")",
"session",
".",
"commit",
"(",
")"
] |
Get the value for ReturnConsumedCapacity from provided value | def _default_capacity ( self , value ) : if value is not None : return value if self . default_return_capacity or self . rate_limiters : return INDEXES return NONE | 5,623 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L312-L318 | [
"def",
"load_projects",
"(",
"self",
")",
":",
"server_config",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_section_config",
"(",
"\"Server\"",
")",
"projects_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"server_config",
".",
"get",
"(",
"\"projects_path\"",
",",
"\"~/GNS3/projects\"",
")",
")",
"os",
".",
"makedirs",
"(",
"projects_path",
",",
"exist_ok",
"=",
"True",
")",
"try",
":",
"for",
"project_path",
"in",
"os",
".",
"listdir",
"(",
"projects_path",
")",
":",
"project_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"projects_path",
",",
"project_path",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"project_dir",
")",
":",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
"project_dir",
")",
":",
"if",
"file",
".",
"endswith",
"(",
"\".gns3\"",
")",
":",
"try",
":",
"yield",
"from",
"self",
".",
"load_project",
"(",
"os",
".",
"path",
".",
"join",
"(",
"project_dir",
",",
"file",
")",
",",
"load",
"=",
"False",
")",
"except",
"(",
"aiohttp",
".",
"web_exceptions",
".",
"HTTPConflict",
",",
"NotImplementedError",
")",
":",
"pass",
"# Skip not compatible projects",
"except",
"OSError",
"as",
"e",
":",
"log",
".",
"error",
"(",
"str",
"(",
"e",
")",
")"
] |
Do a scan or query and aggregate the results into a Count | def _count ( self , method , limit , keywords ) : # The limit will be mutated, so copy it and leave the original intact limit = limit . copy ( ) has_more = True count = None while has_more : limit . set_request_args ( keywords ) response = self . call ( method , * * keywords ) limit . post_fetch ( response ) count += Count . from_response ( response ) last_evaluated_key = response . get ( 'LastEvaluatedKey' ) has_more = last_evaluated_key is not None and not limit . complete if has_more : keywords [ 'ExclusiveStartKey' ] = last_evaluated_key return count | 5,624 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L320-L335 | [
"def",
"create_dirs",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"_path",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"_path",
")",
"for",
"dir_name",
"in",
"[",
"self",
".",
"OBJ_DIR",
",",
"self",
".",
"TMP_OBJ_DIR",
",",
"self",
".",
"PKG_DIR",
",",
"self",
".",
"CACHE_DIR",
"]",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_path",
",",
"dir_name",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"os",
".",
"mkdir",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_version_path",
"(",
")",
")",
":",
"self",
".",
"_write_format_version",
"(",
")"
] |
Get the details about a table | def describe_table ( self , tablename ) : try : response = self . call ( 'describe_table' , TableName = tablename ) [ 'Table' ] return Table . from_response ( response ) except DynamoDBError as e : if e . kwargs [ 'Code' ] == 'ResourceNotFoundException' : return None else : # pragma: no cover raise | 5,625 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L354-L376 | [
"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",
")"
] |
Store an item overwriting existing data | def put_item ( self , tablename , item , expected = None , returns = NONE , return_capacity = None , expect_or = False , * * kwargs ) : keywords = { } if kwargs : keywords [ 'Expected' ] = encode_query_kwargs ( self . dynamizer , kwargs ) if len ( keywords [ 'Expected' ] ) > 1 : keywords [ 'ConditionalOperator' ] = 'OR' if expect_or else 'AND' elif expected is not None : keywords [ 'Expected' ] = build_expected ( self . dynamizer , expected ) keywords [ 'ReturnConsumedCapacity' ] = self . _default_capacity ( return_capacity ) item = self . dynamizer . encode_keys ( item ) ret = self . call ( 'put_item' , TableName = tablename , Item = item , ReturnValues = returns , * * keywords ) if ret : return Result ( self . dynamizer , ret , 'Attributes' ) | 5,626 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L466-L513 | [
"def",
"on_websocket_message",
"(",
"message",
":",
"str",
")",
"->",
"None",
":",
"msgs",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"for",
"msg",
"in",
"msgs",
":",
"if",
"not",
"isinstance",
"(",
"msg",
",",
"dict",
")",
":",
"logger",
".",
"error",
"(",
"'Invalid WS message format: {}'",
".",
"format",
"(",
"message",
")",
")",
"continue",
"_type",
"=",
"msg",
".",
"get",
"(",
"'type'",
")",
"if",
"_type",
"==",
"'log'",
":",
"log_handler",
"(",
"msg",
"[",
"'level'",
"]",
",",
"msg",
"[",
"'message'",
"]",
")",
"elif",
"_type",
"==",
"'event'",
":",
"event_handler",
"(",
"msg",
"[",
"'event'",
"]",
")",
"elif",
"_type",
"==",
"'response'",
":",
"response_handler",
"(",
"msg",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unkown message type: {}'",
".",
"format",
"(",
"message",
")",
")"
] |
Delete an item from a table | def delete_item2 ( self , tablename , key , expr_values = None , alias = None , condition = None , returns = NONE , return_capacity = None , return_item_collection_metrics = NONE , * * kwargs ) : keywords = { 'TableName' : tablename , 'Key' : self . dynamizer . encode_keys ( key ) , 'ReturnValues' : returns , 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , 'ReturnItemCollectionMetrics' : return_item_collection_metrics , } values = build_expression_values ( self . dynamizer , expr_values , kwargs ) if values : keywords [ 'ExpressionAttributeValues' ] = values if alias : keywords [ 'ExpressionAttributeNames' ] = alias if condition : keywords [ 'ConditionExpression' ] = condition result = self . call ( 'delete_item' , * * keywords ) if result : return Result ( self . dynamizer , result , 'Attributes' ) | 5,627 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L695-L749 | [
"def",
"ValidateEndConfig",
"(",
"self",
",",
"config_obj",
",",
"errors_fatal",
"=",
"True",
")",
":",
"errors",
"=",
"super",
"(",
"WindowsClientRepacker",
",",
"self",
")",
".",
"ValidateEndConfig",
"(",
"config_obj",
",",
"errors_fatal",
"=",
"errors_fatal",
")",
"install_dir",
"=",
"config_obj",
"[",
"\"Client.install_path\"",
"]",
"for",
"path",
"in",
"config_obj",
"[",
"\"Client.tempdir_roots\"",
"]",
":",
"if",
"path",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"errors",
".",
"append",
"(",
"\"Client.tempdir_root %s starts with /, probably has Unix path.\"",
"%",
"path",
")",
"if",
"not",
"path",
".",
"startswith",
"(",
"install_dir",
")",
":",
"errors",
".",
"append",
"(",
"\"Client.tempdir_root %s is not inside the install_dir %s, this is \"",
"\"a security risk\"",
"%",
"(",
"(",
"path",
",",
"install_dir",
")",
")",
")",
"if",
"config_obj",
".",
"Get",
"(",
"\"Logging.path\"",
")",
".",
"startswith",
"(",
"\"/\"",
")",
":",
"errors",
".",
"append",
"(",
"\"Logging.path starts with /, probably has Unix path. %s\"",
"%",
"config_obj",
"[",
"\"Logging.path\"",
"]",
")",
"if",
"\"Windows\\\\\"",
"in",
"config_obj",
".",
"GetRaw",
"(",
"\"Logging.path\"",
")",
":",
"errors",
".",
"append",
"(",
"\"Windows in Logging.path, you probably want \"",
"\"%(WINDIR|env) instead\"",
")",
"if",
"not",
"config_obj",
"[",
"\"Client.binary_name\"",
"]",
".",
"endswith",
"(",
"\".exe\"",
")",
":",
"errors",
".",
"append",
"(",
"\"Missing .exe extension on binary_name %s\"",
"%",
"config_obj",
"[",
"\"Client.binary_name\"",
"]",
")",
"if",
"not",
"config_obj",
"[",
"\"Nanny.binary\"",
"]",
".",
"endswith",
"(",
"\".exe\"",
")",
":",
"errors",
".",
"append",
"(",
"\"Missing .exe extension on nanny_binary\"",
")",
"if",
"errors_fatal",
"and",
"errors",
":",
"for",
"error",
"in",
"errors",
":",
"logging",
".",
"error",
"(",
"\"Build Config Error: %s\"",
",",
"error",
")",
"raise",
"RuntimeError",
"(",
"\"Bad configuration generated. Terminating.\"",
")",
"else",
":",
"return",
"errors"
] |
Perform a batch write on a table | def batch_write ( self , tablename , return_capacity = None , return_item_collection_metrics = NONE ) : return_capacity = self . _default_capacity ( return_capacity ) return BatchWriter ( self , tablename , return_capacity = return_capacity , return_item_collection_metrics = return_item_collection_metrics ) | 5,628 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L751-L779 | [
"def",
"get_license_assignment_manager",
"(",
"service_instance",
")",
":",
"log",
".",
"debug",
"(",
"'Retrieving license assignment manager'",
")",
"try",
":",
"lic_assignment_manager",
"=",
"service_instance",
".",
"content",
".",
"licenseManager",
".",
"licenseAssignmentManager",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"if",
"not",
"lic_assignment_manager",
":",
"raise",
"salt",
".",
"exceptions",
".",
"VMwareObjectRetrievalError",
"(",
"'License assignment manager was not retrieved'",
")",
"return",
"lic_assignment_manager"
] |
Perform a batch get of many items in a table | def batch_get ( self , tablename , keys , attributes = None , alias = None , consistent = False , return_capacity = None ) : keys = [ self . dynamizer . encode_keys ( k ) for k in keys ] return_capacity = self . _default_capacity ( return_capacity ) ret = GetResultSet ( self , tablename , keys , consistent = consistent , attributes = attributes , alias = alias , return_capacity = return_capacity ) return ret | 5,629 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L781-L811 | [
"def",
"create_stream_subscription",
"(",
"self",
",",
"stream",
",",
"on_data",
",",
"timeout",
"=",
"60",
")",
":",
"options",
"=",
"rest_pb2",
".",
"StreamSubscribeRequest",
"(",
")",
"options",
".",
"stream",
"=",
"stream",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
".",
"_client",
",",
"resource",
"=",
"'stream'",
",",
"options",
"=",
"options",
")",
"# Represent subscription as a future",
"subscription",
"=",
"WebSocketSubscriptionFuture",
"(",
"manager",
")",
"wrapped_callback",
"=",
"functools",
".",
"partial",
"(",
"_wrap_callback_parse_stream_data",
",",
"subscription",
",",
"on_data",
")",
"manager",
".",
"open",
"(",
"wrapped_callback",
",",
"instance",
"=",
"self",
".",
"_instance",
")",
"# Wait until a reply or exception is received",
"subscription",
".",
"reply",
"(",
"timeout",
"=",
"timeout",
")",
"return",
"subscription"
] |
Update a single item in a table | def update_item ( self , tablename , key , updates , returns = NONE , return_capacity = None , expect_or = False , * * kwargs ) : key = self . dynamizer . encode_keys ( key ) attr_updates = { } expected = { } keywords = { 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , } for update in updates : attr_updates . update ( update . attrs ( self . dynamizer ) ) expected . update ( update . expected ( self . dynamizer ) ) # Pull the 'expected' constraints from the kwargs for k , v in six . iteritems ( encode_query_kwargs ( self . dynamizer , kwargs ) ) : if k in expected : raise ValueError ( "Cannot have more than one condition on a single field" ) expected [ k ] = v if expected : keywords [ 'Expected' ] = expected if len ( expected ) > 1 : keywords [ 'ConditionalOperator' ] = 'OR' if expect_or else 'AND' result = self . call ( 'update_item' , TableName = tablename , Key = key , AttributeUpdates = attr_updates , ReturnValues = returns , * * keywords ) if result : return Result ( self . dynamizer , result , 'Attributes' ) | 5,630 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L813-L880 | [
"def",
"_restart_session",
"(",
"self",
",",
"session",
")",
":",
"# remove old session key, if socket is None, that means the",
"# session was closed by user and there is no need to restart.",
"if",
"session",
".",
"socket",
"is",
"not",
"None",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Attempting restart session for Monitor Id %s.\"",
"%",
"session",
".",
"monitor_id",
")",
"del",
"self",
".",
"sessions",
"[",
"session",
".",
"socket",
".",
"fileno",
"(",
")",
"]",
"session",
".",
"stop",
"(",
")",
"session",
".",
"start",
"(",
")",
"self",
".",
"sessions",
"[",
"session",
".",
"socket",
".",
"fileno",
"(",
")",
"]",
"=",
"session"
] |
Perform an index query on a table | def query ( self , tablename , attributes = None , consistent = False , count = False , index = None , limit = None , desc = False , return_capacity = None , filter = None , filter_or = False , exclusive_start_key = None , * * kwargs ) : keywords = { 'TableName' : tablename , 'ReturnConsumedCapacity' : self . _default_capacity ( return_capacity ) , 'ConsistentRead' : consistent , 'ScanIndexForward' : not desc , 'KeyConditions' : encode_query_kwargs ( self . dynamizer , kwargs ) , } if attributes is not None : keywords [ 'AttributesToGet' ] = attributes if index is not None : keywords [ 'IndexName' ] = index if filter is not None : if len ( filter ) > 1 : keywords [ 'ConditionalOperator' ] = 'OR' if filter_or else 'AND' keywords [ 'QueryFilter' ] = encode_query_kwargs ( self . dynamizer , filter ) if exclusive_start_key is not None : keywords [ 'ExclusiveStartKey' ] = self . dynamizer . maybe_encode_keys ( exclusive_start_key ) if not isinstance ( limit , Limit ) : limit = Limit ( limit ) if count : keywords [ 'Select' ] = COUNT return self . _count ( 'query' , limit , keywords ) else : return ResultSet ( self , limit , 'query' , * * keywords ) | 5,631 | https://github.com/stevearc/dynamo3/blob/f897c40ece28586272dbcab8f0d99a14a1831dda/dynamo3/connection.py#L1099-L1178 | [
"def",
"private_messenger",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"WebSocketHandler",
".",
"send_private_message",
"(",
"user_id",
"=",
"message",
"[",
"'user_id'",
"]",
",",
"message",
"=",
"message",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Get weblogo data for a sequence alignment . | def read_logodata ( handle ) : seqs = weblogolib . read_seq_data ( handle , alphabet = unambiguous_protein_alphabet ) ldata = weblogolib . LogoData . from_seqs ( seqs ) letters = ldata . alphabet . letters ( ) counts = ldata . counts . array logodata = [ ] for i , coldata , entropy , weight in zip ( range ( len ( counts ) ) , counts , ldata . entropy , ldata . weight ) : cnts = dict ( ( let , int ( cnt ) ) for let , cnt in zip ( letters , coldata ) ) logodata . append ( ( i + 1 , cnts , entropy , weight ) ) return logodata | 5,632 | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/logoutils.py#L9-L25 | [
"def",
"set_value",
"(",
"self",
",",
"dry_wet",
":",
"LeakSensorState",
")",
":",
"value",
"=",
"0",
"if",
"dry_wet",
"==",
"self",
".",
"_dry_wet_type",
":",
"value",
"=",
"1",
"self",
".",
"_update_subscribers",
"(",
"value",
")"
] |
Get weblogo data for an alignment object . | def aln2logodata ( aln ) : handle = StringIO ( aln . format ( 'fasta' ) ) logodata = read_logodata ( handle ) handle . close ( ) return logodata | 5,633 | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/logoutils.py#L28-L36 | [
"def",
"makeCubiccFunc",
"(",
"self",
",",
"mNrm",
",",
"cNrm",
")",
":",
"EndOfPrdvPP",
"=",
"self",
".",
"DiscFacEff",
"*",
"self",
".",
"Rfree",
"*",
"self",
".",
"Rfree",
"*",
"self",
".",
"PermGroFac",
"**",
"(",
"-",
"self",
".",
"CRRA",
"-",
"1.0",
")",
"*",
"np",
".",
"sum",
"(",
"self",
".",
"PermShkVals_temp",
"**",
"(",
"-",
"self",
".",
"CRRA",
"-",
"1.0",
")",
"*",
"self",
".",
"vPPfuncNext",
"(",
"self",
".",
"mNrmNext",
")",
"*",
"self",
".",
"ShkPrbs_temp",
",",
"axis",
"=",
"0",
")",
"dcda",
"=",
"EndOfPrdvPP",
"/",
"self",
".",
"uPP",
"(",
"np",
".",
"array",
"(",
"cNrm",
"[",
"1",
":",
"]",
")",
")",
"MPC",
"=",
"dcda",
"/",
"(",
"dcda",
"+",
"1.",
")",
"MPC",
"=",
"np",
".",
"insert",
"(",
"MPC",
",",
"0",
",",
"self",
".",
"MPCmaxNow",
")",
"cFuncNowUnc",
"=",
"CubicInterp",
"(",
"mNrm",
",",
"cNrm",
",",
"MPC",
",",
"self",
".",
"MPCminNow",
"*",
"self",
".",
"hNrmNow",
",",
"self",
".",
"MPCminNow",
")",
"return",
"cFuncNowUnc"
] |
Convert letter counts to frequencies sorted increasing . | def letter_scales ( counts ) : try : scale = 1.0 / sum ( counts . values ( ) ) except ZeroDivisionError : # This logo is all gaps, nothing can be done return [ ] freqs = [ ( aa , cnt * scale ) for aa , cnt in counts . iteritems ( ) if cnt ] freqs . sort ( key = lambda pair : pair [ 1 ] ) return freqs | 5,634 | https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/logoutils.py#L46-L55 | [
"def",
"_download_and_clean_file",
"(",
"filename",
",",
"url",
")",
":",
"temp_file",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"url",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"temp_file",
",",
"'r'",
")",
"as",
"temp_eval_file",
":",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
",",
"'w'",
")",
"as",
"eval_file",
":",
"for",
"line",
"in",
"temp_eval_file",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"line",
"=",
"line",
".",
"replace",
"(",
"', '",
",",
"','",
")",
"if",
"not",
"line",
"or",
"','",
"not",
"in",
"line",
":",
"continue",
"if",
"line",
"[",
"-",
"1",
"]",
"==",
"'.'",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"line",
"+=",
"'\\n'",
"eval_file",
".",
"write",
"(",
"line",
")",
"tf",
".",
"gfile",
".",
"Remove",
"(",
"temp_file",
")"
] |
Replace element from sequence member from mapping . | def replace ( doc , pointer , value ) : return Target ( doc ) . replace ( pointer , value ) . document | 5,635 | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/operations/__init__.py#L49-L64 | [
"def",
"make_tstore_conn",
"(",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"setLevel",
"(",
"params",
".",
"get",
"(",
"'log_level'",
",",
"__LOG_LEVEL__",
")",
")",
"log",
".",
"debug",
"(",
"\"\\n%s\"",
",",
"params",
")",
"params",
".",
"update",
"(",
"kwargs",
")",
"try",
":",
"vendor",
"=",
"RdfwConnections",
"[",
"'triplestore'",
"]",
"[",
"params",
".",
"get",
"(",
"'vendor'",
")",
"]",
"except",
"KeyError",
":",
"vendor",
"=",
"RdfwConnections",
"[",
"'triplestore'",
"]",
"[",
"'blazegraph'",
"]",
"conn",
"=",
"vendor",
"(",
"*",
"*",
"params",
")",
"return",
"conn"
] |
r Set Parser options . | def set_options ( self , * * kw ) : for k , v in kw . iteritems ( ) : if k in self . __options : self . __options [ k ] = v | 5,636 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L39-L47 | [
"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",
",",
")"
] |
r Convert xml content to python object . | def xml2object ( self , content ) : content = self . xml_filter ( content ) element = ET . fromstring ( content ) tree = self . parse ( element ) if self . __options [ 'strip_attr' ] else self . parse_full ( element ) if not self . __options [ 'strip_root' ] : node = self . get_node ( element ) if not self . __options [ 'strip_attr' ] : tree [ 'attrs' ] = node [ 'attr' ] return { node [ 'tag' ] : tree } return tree | 5,637 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L64-L80 | [
"def",
"handleServerEvents",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'MSG %s'",
",",
"msg",
")",
"self",
".",
"handleConnectionState",
"(",
"msg",
")",
"if",
"msg",
".",
"typeName",
"==",
"\"error\"",
":",
"self",
".",
"handleErrorEvents",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CURRENT_TIME\"",
"]",
":",
"if",
"self",
".",
"time",
"<",
"msg",
".",
"time",
":",
"self",
".",
"time",
"=",
"msg",
".",
"time",
"elif",
"(",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_MKT_DEPTH\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_MKT_DEPTH_L2\"",
"]",
")",
":",
"self",
".",
"handleMarketDepth",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_STRING\"",
"]",
":",
"self",
".",
"handleTickString",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_PRICE\"",
"]",
":",
"self",
".",
"handleTickPrice",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_GENERIC\"",
"]",
":",
"self",
".",
"handleTickGeneric",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_SIZE\"",
"]",
":",
"self",
".",
"handleTickSize",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_TICK_OPTION\"",
"]",
":",
"self",
".",
"handleTickOptionComputation",
"(",
"msg",
")",
"elif",
"(",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_OPEN_ORDER\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_OPEN_ORDER_END\"",
"]",
"or",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_ORDER_STATUS\"",
"]",
")",
":",
"self",
".",
"handleOrders",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_HISTORICAL_DATA\"",
"]",
":",
"self",
".",
"handleHistoricalData",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_ACCOUNT_UPDATES\"",
"]",
":",
"self",
".",
"handleAccount",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_PORTFOLIO_UPDATES\"",
"]",
":",
"self",
".",
"handlePortfolio",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_POSITION\"",
"]",
":",
"self",
".",
"handlePosition",
"(",
"msg",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TYPE_NEXT_ORDER_ID\"",
"]",
":",
"self",
".",
"handleNextValidId",
"(",
"msg",
".",
"orderId",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONNECTION_CLOSED\"",
"]",
":",
"self",
".",
"handleConnectionClosed",
"(",
"msg",
")",
"# elif msg.typeName == dataTypes[\"MSG_TYPE_MANAGED_ACCOUNTS\"]:",
"# self.accountCode = msg.accountsList",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_COMMISSION_REPORT\"",
"]",
":",
"self",
".",
"commission",
"=",
"msg",
".",
"commissionReport",
".",
"m_commission",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONTRACT_DETAILS\"",
"]",
":",
"self",
".",
"handleContractDetails",
"(",
"msg",
",",
"end",
"=",
"False",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_CONTRACT_DETAILS_END\"",
"]",
":",
"self",
".",
"handleContractDetails",
"(",
"msg",
",",
"end",
"=",
"True",
")",
"elif",
"msg",
".",
"typeName",
"==",
"dataTypes",
"[",
"\"MSG_TICK_SNAPSHOT_END\"",
"]",
":",
"self",
".",
"ibCallback",
"(",
"caller",
"=",
"\"handleTickSnapshotEnd\"",
",",
"msg",
"=",
"msg",
")",
"else",
":",
"# log handler msg",
"self",
".",
"log_msg",
"(",
"\"server\"",
",",
"msg",
")"
] |
r Filter and preprocess xml content | def xml_filter ( self , content ) : content = utils . strip_whitespace ( content , True ) if self . __options [ 'strip' ] else content . strip ( ) if not self . __options [ 'encoding' ] : encoding = self . guess_xml_encoding ( content ) or self . __encoding self . set_options ( encoding = encoding ) if self . __options [ 'encoding' ] . lower ( ) != self . __encoding : # 编码转换去除xml头 content = self . strip_xml_header ( content . decode ( self . __options [ 'encoding' ] , errors = self . __options [ 'errors' ] ) ) if self . __options [ 'unescape' ] : content = utils . html_entity_decode ( content ) return content | 5,638 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L82-L100 | [
"def",
"_wikipedia_known_port_ranges",
"(",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"WIKIPEDIA_PAGE",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"\"Magic Browser\"",
"}",
")",
"page",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf8'",
")",
"# just find all numbers in table cells",
"ports",
"=",
"re",
".",
"findall",
"(",
"'<td>((\\d+)(\\W(\\d+))?)</td>'",
",",
"page",
",",
"re",
".",
"U",
")",
"return",
"(",
"(",
"int",
"(",
"p",
"[",
"1",
"]",
")",
",",
"int",
"(",
"p",
"[",
"3",
"]",
"if",
"p",
"[",
"3",
"]",
"else",
"p",
"[",
"1",
"]",
")",
")",
"for",
"p",
"in",
"ports",
")"
] |
r Guess encoding from xml header declaration . | def guess_xml_encoding ( self , content ) : matchobj = self . __regex [ 'xml_encoding' ] . match ( content ) return matchobj and matchobj . group ( 1 ) . lower ( ) | 5,639 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L102-L109 | [
"def",
"_run_module_code",
"(",
"code",
",",
"init_globals",
"=",
"None",
",",
"mod_name",
"=",
"None",
",",
"mod_fname",
"=",
"None",
",",
"mod_loader",
"=",
"None",
",",
"pkg_name",
"=",
"None",
")",
":",
"with",
"_ModifiedArgv0",
"(",
"mod_fname",
")",
":",
"with",
"_TempModule",
"(",
"mod_name",
")",
"as",
"temp_module",
":",
"mod_globals",
"=",
"temp_module",
".",
"module",
".",
"__dict__",
"_run_code",
"(",
"code",
",",
"mod_globals",
",",
"init_globals",
",",
"mod_name",
",",
"mod_fname",
",",
"mod_loader",
",",
"pkg_name",
")",
"# Copy the globals of the temporary module, as they",
"# may be cleared when the temporary module goes away",
"return",
"mod_globals",
".",
"copy",
"(",
")"
] |
r Parse xml element . | def parse ( self , element ) : values = { } for child in element : node = self . get_node ( child ) subs = self . parse ( child ) value = subs or node [ 'value' ] if node [ 'tag' ] not in values : values [ node [ 'tag' ] ] = value else : if not isinstance ( values [ node [ 'tag' ] ] , list ) : values [ node [ 'tag' ] ] = [ values . pop ( node [ 'tag' ] ) ] values [ node [ 'tag' ] ] . append ( value ) return values | 5,640 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L119-L136 | [
"def",
"solveConsRepAgentMarkov",
"(",
"solution_next",
",",
"MrkvArray",
",",
"DiscFac",
",",
"CRRA",
",",
"IncomeDstn",
",",
"CapShare",
",",
"DeprFac",
",",
"PermGroFac",
",",
"aXtraGrid",
")",
":",
"# Define basic objects",
"StateCount",
"=",
"MrkvArray",
".",
"shape",
"[",
"0",
"]",
"aNrmNow",
"=",
"aXtraGrid",
"aNrmCount",
"=",
"aNrmNow",
".",
"size",
"EndOfPrdvP_cond",
"=",
"np",
".",
"zeros",
"(",
"(",
"StateCount",
",",
"aNrmCount",
")",
")",
"+",
"np",
".",
"nan",
"# Loop over *next period* states, calculating conditional EndOfPrdvP",
"for",
"j",
"in",
"range",
"(",
"StateCount",
")",
":",
"# Define next-period-state conditional objects",
"vPfuncNext",
"=",
"solution_next",
".",
"vPfunc",
"[",
"j",
"]",
"ShkPrbsNext",
"=",
"IncomeDstn",
"[",
"j",
"]",
"[",
"0",
"]",
"PermShkValsNext",
"=",
"IncomeDstn",
"[",
"j",
"]",
"[",
"1",
"]",
"TranShkValsNext",
"=",
"IncomeDstn",
"[",
"j",
"]",
"[",
"2",
"]",
"# Make tiled versions of end-of-period assets, shocks, and probabilities",
"ShkCount",
"=",
"ShkPrbsNext",
".",
"size",
"aNrm_tiled",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"reshape",
"(",
"aNrmNow",
",",
"(",
"aNrmCount",
",",
"1",
")",
")",
",",
"(",
"1",
",",
"ShkCount",
")",
")",
"# Tile arrays of the income shocks and put them into useful shapes",
"PermShkVals_tiled",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"reshape",
"(",
"PermShkValsNext",
",",
"(",
"1",
",",
"ShkCount",
")",
")",
",",
"(",
"aNrmCount",
",",
"1",
")",
")",
"TranShkVals_tiled",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"reshape",
"(",
"TranShkValsNext",
",",
"(",
"1",
",",
"ShkCount",
")",
")",
",",
"(",
"aNrmCount",
",",
"1",
")",
")",
"ShkPrbs_tiled",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"reshape",
"(",
"ShkPrbsNext",
",",
"(",
"1",
",",
"ShkCount",
")",
")",
",",
"(",
"aNrmCount",
",",
"1",
")",
")",
"# Calculate next period's capital-to-permanent-labor ratio under each combination",
"# of end-of-period assets and shock realization",
"kNrmNext",
"=",
"aNrm_tiled",
"/",
"(",
"PermGroFac",
"[",
"j",
"]",
"*",
"PermShkVals_tiled",
")",
"# Calculate next period's market resources",
"KtoLnext",
"=",
"kNrmNext",
"/",
"TranShkVals_tiled",
"RfreeNext",
"=",
"1.",
"-",
"DeprFac",
"+",
"CapShare",
"*",
"KtoLnext",
"**",
"(",
"CapShare",
"-",
"1.",
")",
"wRteNext",
"=",
"(",
"1.",
"-",
"CapShare",
")",
"*",
"KtoLnext",
"**",
"CapShare",
"mNrmNext",
"=",
"RfreeNext",
"*",
"kNrmNext",
"+",
"wRteNext",
"*",
"TranShkVals_tiled",
"# Calculate end-of-period marginal value of assets for the RA",
"vPnext",
"=",
"vPfuncNext",
"(",
"mNrmNext",
")",
"EndOfPrdvP_cond",
"[",
"j",
",",
":",
"]",
"=",
"DiscFac",
"*",
"np",
".",
"sum",
"(",
"RfreeNext",
"*",
"(",
"PermGroFac",
"[",
"j",
"]",
"*",
"PermShkVals_tiled",
")",
"**",
"(",
"-",
"CRRA",
")",
"*",
"vPnext",
"*",
"ShkPrbs_tiled",
",",
"axis",
"=",
"1",
")",
"# Apply the Markov transition matrix to get unconditional end-of-period marginal value",
"EndOfPrdvP",
"=",
"np",
".",
"dot",
"(",
"MrkvArray",
",",
"EndOfPrdvP_cond",
")",
"# Construct the consumption function and marginal value function for each discrete state",
"cFuncNow_list",
"=",
"[",
"]",
"vPfuncNow_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"StateCount",
")",
":",
"# Invert the first order condition to get consumption, then find endogenous gridpoints",
"cNrmNow",
"=",
"EndOfPrdvP",
"[",
"i",
",",
":",
"]",
"**",
"(",
"-",
"1.",
"/",
"CRRA",
")",
"mNrmNow",
"=",
"aNrmNow",
"+",
"cNrmNow",
"# Construct the consumption function and the marginal value function",
"cFuncNow_list",
".",
"append",
"(",
"LinearInterp",
"(",
"np",
".",
"insert",
"(",
"mNrmNow",
",",
"0",
",",
"0.0",
")",
",",
"np",
".",
"insert",
"(",
"cNrmNow",
",",
"0",
",",
"0.0",
")",
")",
")",
"vPfuncNow_list",
".",
"append",
"(",
"MargValueFunc",
"(",
"cFuncNow_list",
"[",
"-",
"1",
"]",
",",
"CRRA",
")",
")",
"# Construct and return the solution for this period",
"solution_now",
"=",
"ConsumerSolution",
"(",
"cFunc",
"=",
"cFuncNow_list",
",",
"vPfunc",
"=",
"vPfuncNow_list",
")",
"return",
"solution_now"
] |
r Parse xml element include the node attributes . | def parse_full ( self , element ) : values = collections . defaultdict ( dict ) for child in element : node = self . get_node ( child ) subs = self . parse_full ( child ) value = subs or { 'values' : node [ 'value' ] } value [ 'attrs' ] = node [ 'attr' ] if node [ 'tag' ] not in values [ 'values' ] : values [ 'values' ] [ node [ 'tag' ] ] = value else : if not isinstance ( values [ 'values' ] [ node [ 'tag' ] ] , list ) : values [ 'values' ] [ node [ 'tag' ] ] = [ values [ 'values' ] . pop ( node [ 'tag' ] ) ] values [ 'values' ] [ node [ 'tag' ] ] . append ( value ) return values | 5,641 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L138-L158 | [
"def",
"Run",
"(",
"self",
")",
":",
"global",
"DB",
"# pylint: disable=global-statement",
"global",
"REL_DB",
"# pylint: disable=global-statement",
"global",
"BLOBS",
"# pylint: disable=global-statement",
"if",
"flags",
".",
"FLAGS",
".",
"list_storage",
":",
"self",
".",
"_ListStorageOptions",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"try",
":",
"cls",
"=",
"DataStore",
".",
"GetPlugin",
"(",
"config",
".",
"CONFIG",
"[",
"\"Datastore.implementation\"",
"]",
")",
"except",
"KeyError",
":",
"msg",
"=",
"(",
"\"No Storage System %s found.\"",
"%",
"config",
".",
"CONFIG",
"[",
"\"Datastore.implementation\"",
"]",
")",
"if",
"config",
".",
"CONFIG",
"[",
"\"Datastore.implementation\"",
"]",
"==",
"\"SqliteDataStore\"",
":",
"msg",
"=",
"\"The SQLite datastore is no longer supported.\"",
"print",
"(",
"msg",
")",
"print",
"(",
"\"Available options:\"",
")",
"self",
".",
"_ListStorageOptions",
"(",
")",
"raise",
"ValueError",
"(",
"msg",
")",
"DB",
"=",
"cls",
"(",
")",
"# pylint: disable=g-bad-name",
"DB",
".",
"Initialize",
"(",
")",
"atexit",
".",
"register",
"(",
"DB",
".",
"Flush",
")",
"monitor_port",
"=",
"config",
".",
"CONFIG",
"[",
"\"Monitoring.http_port\"",
"]",
"if",
"monitor_port",
"!=",
"0",
":",
"DB",
".",
"InitializeMonitorThread",
"(",
")",
"# Initialize the blobstore.",
"blobstore_name",
"=",
"config",
".",
"CONFIG",
".",
"Get",
"(",
"\"Blobstore.implementation\"",
")",
"try",
":",
"cls",
"=",
"blob_store",
".",
"REGISTRY",
"[",
"blobstore_name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"No blob store %s found.\"",
"%",
"blobstore_name",
")",
"BLOBS",
"=",
"blob_store",
".",
"BlobStoreValidationWrapper",
"(",
"cls",
"(",
")",
")",
"# Initialize a relational DB if configured.",
"rel_db_name",
"=",
"config",
".",
"CONFIG",
"[",
"\"Database.implementation\"",
"]",
"if",
"not",
"rel_db_name",
":",
"return",
"try",
":",
"cls",
"=",
"registry_init",
".",
"REGISTRY",
"[",
"rel_db_name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"Database %s not found.\"",
"%",
"rel_db_name",
")",
"logging",
".",
"info",
"(",
"\"Using database implementation %s\"",
",",
"rel_db_name",
")",
"REL_DB",
"=",
"db",
".",
"DatabaseValidationWrapper",
"(",
"cls",
"(",
")",
")"
] |
r Get node info . | def get_node ( self , element ) : ns , tag = self . split_namespace ( element . tag ) return { 'tag' : tag , 'value' : ( element . text or '' ) . strip ( ) , 'attr' : element . attrib , 'namespace' : ns } | 5,642 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L160-L169 | [
"def",
"removefromreadergroup",
"(",
"self",
",",
"groupname",
")",
":",
"hresult",
",",
"hcontext",
"=",
"SCardEstablishContext",
"(",
"SCARD_SCOPE_USER",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"EstablishContextException",
"(",
"hresult",
")",
"try",
":",
"hresult",
"=",
"SCardRemoveReaderFromGroup",
"(",
"hcontext",
",",
"self",
".",
"name",
",",
"groupname",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"RemoveReaderFromGroupException",
"(",
"hresult",
",",
"self",
".",
"name",
",",
"groupname",
")",
"finally",
":",
"hresult",
"=",
"SCardReleaseContext",
"(",
"hcontext",
")",
"if",
"0",
"!=",
"hresult",
":",
"raise",
"ReleaseContextException",
"(",
"hresult",
")"
] |
r Split tag namespace . | def split_namespace ( self , tag ) : matchobj = self . __regex [ 'xml_ns' ] . search ( tag ) return matchobj . groups ( ) if matchobj else ( '' , tag ) | 5,643 | https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L171-L179 | [
"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",
")",
")"
] |
Creates instances of the probes inputed ; | def instantiate_probes ( probes , instruments ) : probe_instances = { } for name , sub_dict in probes . items ( ) : assert isinstance ( sub_dict , dict ) assert "probe_name" in sub_dict assert "instrument_name" in sub_dict probe_name = sub_dict [ 'probe_name' ] instrument_name = sub_dict [ 'instrument_name' ] if "probe_info" in sub_dict : probe_info = sub_dict [ 'probe_info' ] else : probe_info = '' assert instrument_name in instruments , "{:s} not in {:s}" . format ( instrument_name , list ( instruments . keys ( ) ) ) assert probe_name in instruments [ instrument_name ] . _PROBES probe_instances . update ( { name : Probe ( instruments [ instrument_name ] , probe_name , name , probe_info ) } ) return probe_instances | 5,644 | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/loading.py#L22-L58 | [
"def",
"read_struct",
"(",
"fstream",
")",
":",
"line",
"=",
"fstream",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"fragments",
"=",
"line",
".",
"split",
"(",
"\",\"",
")",
"fragments",
"=",
"[",
"x",
"for",
"x",
"in",
"fragments",
"if",
"x",
"is",
"not",
"None",
"]",
"partition",
"=",
"dict",
"(",
")",
"if",
"not",
"len",
"(",
"fragments",
")",
">=",
"3",
":",
"return",
"None",
"partition",
"[",
"\"struct\"",
"]",
"=",
"fragments",
"[",
"0",
"]",
"partition",
"[",
"\"info\"",
"]",
"=",
"fragments",
"[",
"1",
"]",
"partition",
"[",
"\"num_lines\"",
"]",
"=",
"fragments",
"[",
"2",
"]",
"struct",
"=",
"None",
"if",
"partition",
"is",
"not",
"None",
"and",
"partition",
"[",
"\"struct\"",
"]",
"==",
"\"STRUCT\"",
":",
"num_lines",
"=",
"int",
"(",
"partition",
"[",
"\"num_lines\"",
"]",
".",
"strip",
"(",
")",
")",
"struct",
"=",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"num_lines",
")",
":",
"cols",
"=",
"fetch_cols",
"(",
"fstream",
")",
"struct",
".",
"update",
"(",
"{",
"cols",
"[",
"0",
"]",
":",
"cols",
"[",
"1",
":",
"]",
"}",
")",
"return",
"struct"
] |
Derive compressed public key | def compressed ( self ) : order = ecdsa . SECP256k1 . generator . order ( ) p = ecdsa . VerifyingKey . from_string ( compat_bytes ( self ) , curve = ecdsa . SECP256k1 ) . pubkey . point x_str = ecdsa . util . number_to_string ( p . x ( ) , order ) # y_str = ecdsa.util.number_to_string(p.y(), order) compressed = hexlify ( compat_bytes ( chr ( 2 + ( p . y ( ) & 1 ) ) , 'ascii' ) + x_str ) . decode ( 'ascii' ) return ( compressed ) | 5,645 | https://github.com/emre/lightsteem/blob/0fc29a517c20d881cbdbb15b43add4bcf3af242e/lightsteem/broadcast/key_objects.py#L106-L116 | [
"def",
"tan_rand",
"(",
"q",
",",
"seed",
"=",
"9",
")",
":",
"# probably need a check in case we get a parallel vector",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"qd",
"=",
"np",
".",
"cross",
"(",
"rvec",
",",
"q",
")",
"qd",
"=",
"qd",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"qd",
")",
"while",
"np",
".",
"dot",
"(",
"q",
",",
"qd",
")",
">",
"1e-6",
":",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"qd",
"=",
"np",
".",
"cross",
"(",
"rvec",
",",
"q",
")",
"qd",
"=",
"qd",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"qd",
")",
"return",
"qd"
] |
Derive uncompressed key | def unCompressed ( self ) : public_key = repr ( self . _pk ) prefix = public_key [ 0 : 2 ] if prefix == "04" : return public_key assert prefix == "02" or prefix == "03" x = int ( public_key [ 2 : ] , 16 ) y = self . _derive_y_from_x ( x , ( prefix == "02" ) ) key = '04' + '%064x' % x + '%064x' % y return key | 5,646 | https://github.com/emre/lightsteem/blob/0fc29a517c20d881cbdbb15b43add4bcf3af242e/lightsteem/broadcast/key_objects.py#L118-L128 | [
"def",
"get_closest_sibling_state",
"(",
"state_m",
",",
"from_logical_port",
"=",
"None",
")",
":",
"if",
"not",
"state_m",
".",
"parent",
":",
"logger",
".",
"warning",
"(",
"\"A state can not have a closest sibling state if it has not parent as {0}\"",
".",
"format",
"(",
"state_m",
")",
")",
"return",
"margin",
"=",
"cal_margin",
"(",
"state_m",
".",
"parent",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'size'",
"]",
")",
"pos",
"=",
"state_m",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'rel_pos'",
"]",
"size",
"=",
"state_m",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'size'",
"]",
"# otherwise measure from reference state itself",
"if",
"from_logical_port",
"in",
"[",
"\"outcome\"",
",",
"\"income\"",
"]",
":",
"size",
"=",
"(",
"margin",
",",
"margin",
")",
"if",
"from_logical_port",
"==",
"\"outcome\"",
":",
"outcomes_m",
"=",
"[",
"outcome_m",
"for",
"outcome_m",
"in",
"state_m",
".",
"outcomes",
"if",
"outcome_m",
".",
"outcome",
".",
"outcome_id",
">=",
"0",
"]",
"free_outcomes_m",
"=",
"[",
"oc_m",
"for",
"oc_m",
"in",
"outcomes_m",
"if",
"not",
"state_m",
".",
"state",
".",
"parent",
".",
"get_transition_for_outcome",
"(",
"state_m",
".",
"state",
",",
"oc_m",
".",
"outcome",
")",
"]",
"if",
"free_outcomes_m",
":",
"outcome_m",
"=",
"free_outcomes_m",
"[",
"0",
"]",
"else",
":",
"outcome_m",
"=",
"outcomes_m",
"[",
"0",
"]",
"pos",
"=",
"add_pos",
"(",
"pos",
",",
"outcome_m",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'rel_pos'",
"]",
")",
"elif",
"from_logical_port",
"==",
"\"income\"",
":",
"pos",
"=",
"add_pos",
"(",
"pos",
",",
"state_m",
".",
"income",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'rel_pos'",
"]",
")",
"min_distance",
"=",
"None",
"for",
"sibling_state_m",
"in",
"state_m",
".",
"parent",
".",
"states",
".",
"values",
"(",
")",
":",
"if",
"sibling_state_m",
"is",
"state_m",
":",
"continue",
"sibling_pos",
"=",
"sibling_state_m",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'rel_pos'",
"]",
"sibling_size",
"=",
"sibling_state_m",
".",
"get_meta_data_editor",
"(",
")",
"[",
"'size'",
"]",
"distance",
"=",
"geometry",
".",
"cal_dist_between_2_coord_frame_aligned_boxes",
"(",
"pos",
",",
"size",
",",
"sibling_pos",
",",
"sibling_size",
")",
"if",
"not",
"min_distance",
"or",
"min_distance",
"[",
"0",
"]",
">",
"distance",
":",
"min_distance",
"=",
"(",
"distance",
",",
"sibling_state_m",
")",
"return",
"min_distance"
] |
Derive uncompressed public key | def compressedpubkey ( self ) : secret = unhexlify ( repr ( self . _wif ) ) order = ecdsa . SigningKey . from_string ( secret , curve = ecdsa . SECP256k1 ) . curve . generator . order ( ) p = ecdsa . SigningKey . from_string ( secret , curve = ecdsa . SECP256k1 ) . verifying_key . pubkey . point x_str = ecdsa . util . number_to_string ( p . x ( ) , order ) y_str = ecdsa . util . number_to_string ( p . y ( ) , order ) compressed = hexlify ( chr ( 2 + ( p . y ( ) & 1 ) ) . encode ( 'ascii' ) + x_str ) . decode ( 'ascii' ) uncompressed = hexlify ( chr ( 4 ) . encode ( 'ascii' ) + x_str + y_str ) . decode ( 'ascii' ) return [ compressed , uncompressed ] | 5,647 | https://github.com/emre/lightsteem/blob/0fc29a517c20d881cbdbb15b43add4bcf3af242e/lightsteem/broadcast/key_objects.py#L174-L189 | [
"def",
"tan_rand",
"(",
"q",
",",
"seed",
"=",
"9",
")",
":",
"# probably need a check in case we get a parallel vector",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"qd",
"=",
"np",
".",
"cross",
"(",
"rvec",
",",
"q",
")",
"qd",
"=",
"qd",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"qd",
")",
"while",
"np",
".",
"dot",
"(",
"q",
",",
"qd",
")",
">",
"1e-6",
":",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"0",
"]",
")",
"qd",
"=",
"np",
".",
"cross",
"(",
"rvec",
",",
"q",
")",
"qd",
"=",
"qd",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"qd",
")",
"return",
"qd"
] |
Derive private key from the brain key and the current sequence number | def get_private ( self ) : a = compat_bytes ( self . account + self . role + self . password , 'utf8' ) s = hashlib . sha256 ( a ) . digest ( ) return PrivateKey ( hexlify ( s ) . decode ( 'ascii' ) ) | 5,648 | https://github.com/emre/lightsteem/blob/0fc29a517c20d881cbdbb15b43add4bcf3af242e/lightsteem/broadcast/key_objects.py#L224-L230 | [
"def",
"clean",
"(",
"file_",
",",
"imports",
")",
":",
"modules_not_imported",
"=",
"compare_modules",
"(",
"file_",
",",
"imports",
")",
"re_remove",
"=",
"re",
".",
"compile",
"(",
"\"|\"",
".",
"join",
"(",
"modules_not_imported",
")",
")",
"to_write",
"=",
"[",
"]",
"try",
":",
"f",
"=",
"open_func",
"(",
"file_",
",",
"\"r+\"",
")",
"except",
"OSError",
":",
"logging",
".",
"error",
"(",
"\"Failed on file: {}\"",
".",
"format",
"(",
"file_",
")",
")",
"raise",
"else",
":",
"for",
"i",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"if",
"re_remove",
".",
"match",
"(",
"i",
")",
"is",
"None",
":",
"to_write",
".",
"append",
"(",
"i",
")",
"f",
".",
"seek",
"(",
"0",
")",
"f",
".",
"truncate",
"(",
")",
"for",
"i",
"in",
"to_write",
":",
"f",
".",
"write",
"(",
"i",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"logging",
".",
"info",
"(",
"\"Successfully cleaned up requirements in \"",
"+",
"file_",
")"
] |
find downslope coordinate for D8 direction . | def downstream_index ( dir_value , i , j , alg = 'taudem' ) : assert alg . lower ( ) in FlowModelConst . d8_deltas delta = FlowModelConst . d8_deltas . get ( alg . lower ( ) ) drow , dcol = delta [ int ( dir_value ) ] return i + drow , j + dcol | 5,649 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/hydro.py#L130-L135 | [
"def",
"load",
"(",
"cls",
",",
"path",
":",
"str",
",",
"password",
":",
"str",
"=",
"None",
")",
"->",
"'Account'",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"keystore",
"=",
"json",
".",
"load",
"(",
"f",
")",
"if",
"not",
"check_keystore_json",
"(",
"keystore",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid keystore file'",
")",
"return",
"Account",
"(",
"keystore",
",",
"password",
",",
"path",
"=",
"path",
")"
] |
Converts parseResult from to ConfGroup type . | def convert_group ( tokens ) : tok = tokens . asList ( ) dic = dict ( tok ) if not ( len ( dic ) == len ( tok ) ) : raise ParseFatalException ( "Names in group must be unique: %s" % tokens ) return ConfGroup ( dic ) | 5,650 | https://github.com/heinzK1X/pylibconfig2/blob/f3a851ac780da28a42264c24aac51b54fbd63f81/pylibconfig2/parsing.py#L64-L70 | [
"def",
"detach_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"not",
"None",
":",
"self",
".",
"_session",
".",
"unsubscribe",
"(",
"self",
")",
"self",
".",
"_session",
"=",
"None"
] |
loads the elements from file filename | def load_elements ( self , filename ) : input_data = load_b26_file ( filename ) if isinstance ( input_data , dict ) and self . elements_type in input_data : return input_data [ self . elements_type ] else : return { } | 5,651 | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_load_dialog.py#L178-L186 | [
"def",
"_retry",
"(",
"function",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"last_exception",
"=",
"None",
"#for host in self.router.get_hosts(**kwargs):",
"for",
"host",
"in",
"self",
".",
"host",
":",
"try",
":",
"return",
"function",
"(",
"self",
",",
"host",
",",
"*",
"*",
"kwargs",
")",
"except",
"SolrError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"e",
")",
"raise",
"except",
"ConnectionError",
"as",
"e",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"\"Tried connecting to Solr, but couldn't because of the following exception.\"",
")",
"if",
"'401'",
"in",
"e",
".",
"__str__",
"(",
")",
":",
"raise",
"last_exception",
"=",
"e",
"# raise the last exception after contacting all hosts instead of returning None",
"if",
"last_exception",
"is",
"not",
"None",
":",
"raise",
"last_exception",
"return",
"inner"
] |
creates a script sequence based on the script iterator type selected and the selected scripts and sends it to the tree self . tree_loaded | def add_script_sequence ( self ) : def empty_tree ( tree_model ) : # COMMENT_ME def add_children_to_list ( item , somelist ) : if item . hasChildren ( ) : for rownum in range ( 0 , item . rowCount ( ) ) : somelist . append ( str ( item . child ( rownum , 0 ) . text ( ) ) ) output_list = [ ] root = tree_model . invisibleRootItem ( ) add_children_to_list ( root , output_list ) tree_model . clear ( ) return output_list name = str ( self . txt_script_sequence_name . text ( ) ) new_script_list = empty_tree ( self . tree_script_sequence_model ) new_script_dict = { } for script in new_script_list : if script in self . elements_old : new_script_dict . update ( { script : self . elements_old [ script ] } ) elif script in self . elements_from_file : new_script_dict . update ( { script : self . elements_from_file [ script ] } ) new_script_parameter_dict = { } for index , script in enumerate ( new_script_list ) : new_script_parameter_dict . update ( { script : index } ) # QtGui.QTextEdit.toPlainText() # get the module of the current dialogue package = get_python_package ( inspect . getmodule ( self ) . __file__ ) assert package is not None # check that we actually find a module # class_name = Script.set_up_dynamic_script(factory_scripts, new_script_parameter_list, self.cmb_looping_variable.currentText() == 'Parameter Sweep') new_script_dict = { name : { 'class' : 'ScriptIterator' , 'package' : package , 'scripts' : new_script_dict , 'info' : str ( self . txt_info . toPlainText ( ) ) , 'settings' : { 'script_order' : new_script_parameter_dict , 'iterator_type' : str ( self . cmb_looping_variable . currentText ( ) ) } } } self . selected_element_name = name self . fill_tree ( self . tree_loaded , new_script_dict ) self . elements_from_file . update ( new_script_dict ) | 5,652 | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/gui/qt_b26_load_dialog.py#L247-L295 | [
"def",
"last_room_temp",
"(",
"self",
")",
":",
"try",
":",
"rmtemps",
"=",
"self",
".",
"intervals",
"[",
"1",
"]",
"[",
"'timeseries'",
"]",
"[",
"'tempRoomC'",
"]",
"except",
"KeyError",
":",
"return",
"None",
"tmp",
"=",
"0",
"num_temps",
"=",
"len",
"(",
"rmtemps",
")",
"if",
"num_temps",
"==",
"0",
":",
"return",
"None",
"for",
"temp",
"in",
"rmtemps",
":",
"tmp",
"+=",
"temp",
"[",
"1",
"]",
"rmtemp",
"=",
"tmp",
"/",
"num_temps",
"return",
"rmtemp"
] |
Cli for testing the ped parser . | def cli ( family_file , family_type , to_json , to_madeline , to_ped , to_dict , outfile , logfile , loglevel ) : from pprint import pprint as pp my_parser = FamilyParser ( family_file , family_type ) if to_json : if outfile : outfile . write ( my_parser . to_json ( ) ) else : print ( my_parser . to_json ( ) ) elif to_madeline : for line in my_parser . to_madeline ( ) : if outfile : outfile . write ( line + '\n' ) else : print ( line ) elif to_ped : for line in my_parser . to_ped ( ) : if outfile : outfile . write ( line + '\n' ) else : print ( line ) elif to_dict : pp ( my_parser . to_dict ( ) ) | 5,653 | https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/parser.py#L641-L668 | [
"def",
"init_attachment_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"request",
".",
"method",
"==",
"'GET'",
":",
"# Invalidates previous attachments",
"attachments_cache",
".",
"delete",
"(",
"self",
".",
"get_attachments_cache_key",
"(",
"self",
".",
"request",
")",
")",
"return",
"# Try to restore previous uploaded attachments if applicable",
"attachments_cache_key",
"=",
"self",
".",
"get_attachments_cache_key",
"(",
"self",
".",
"request",
")",
"restored_attachments_dict",
"=",
"attachments_cache",
".",
"get",
"(",
"attachments_cache_key",
")",
"if",
"restored_attachments_dict",
":",
"restored_attachments_dict",
".",
"update",
"(",
"self",
".",
"request",
".",
"FILES",
")",
"self",
".",
"request",
".",
"_files",
"=",
"restored_attachments_dict",
"# Updates the attachment cache if files are available",
"if",
"self",
".",
"request",
".",
"FILES",
":",
"attachments_cache",
".",
"set",
"(",
"attachments_cache_key",
",",
"self",
".",
"request",
".",
"FILES",
")"
] |
Check if the line is correctly formated . Throw a SyntaxError if it is not . | def check_line_length ( self , splitted_line , expected_length ) : if len ( splitted_line ) != expected_length : raise WrongLineFormat ( message = 'WRONG FORMATED PED LINE!' , ped_line = '\t' . join ( splitted_line ) ) return | 5,654 | https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/parser.py#L195-L203 | [
"def",
"apply_caching",
"(",
"response",
")",
":",
"for",
"k",
",",
"v",
"in",
"config",
".",
"get",
"(",
"'HTTP_HEADERS'",
")",
".",
"items",
"(",
")",
":",
"response",
".",
"headers",
"[",
"k",
"]",
"=",
"v",
"return",
"response"
] |
deck vote tag address | def deck_vote_tag ( deck : Deck ) -> str : if deck . id is None : raise Exception ( "deck.id is required" ) deck_vote_tag_privkey = sha256 ( unhexlify ( deck . id ) + b"vote_init" ) . hexdigest ( ) deck_vote_tag_address = Kutil ( network = deck . network , privkey = bytearray . fromhex ( deck_vote_tag_privkey ) ) return deck_vote_tag_address . address | 5,655 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L14-L22 | [
"def",
"recv",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
":",
"try",
":",
"testsock",
"=",
"self",
".",
"_zmq",
".",
"select",
"(",
"[",
"self",
".",
"socket",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"[",
"0",
"]",
"except",
"zmq",
".",
"ZMQError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EINTR",
":",
"testsock",
"=",
"None",
"else",
":",
"raise",
"if",
"not",
"testsock",
":",
"return",
"rv",
"=",
"self",
".",
"socket",
".",
"recv",
"(",
"self",
".",
"_zmq",
".",
"NOBLOCK",
")",
"return",
"LogRecord",
".",
"from_dict",
"(",
"json",
".",
"loads",
"(",
"rv",
")",
")",
"else",
":",
"return",
"super",
"(",
"ZeroMQPullSubscriber",
",",
"self",
")",
".",
"recv",
"(",
"timeout",
")"
] |
decode vote init tx op_return protobuf message and validate it . | def parse_vote_info ( protobuf : bytes ) -> dict : vote = pavoteproto . Vote ( ) vote . ParseFromString ( protobuf ) assert vote . version > 0 , { "error" : "Vote info incomplete, version can't be 0." } assert vote . start_block < vote . end_block , { "error" : "vote can't end in the past." } return { "version" : vote . version , "description" : vote . description , "count_mode" : vote . MODE . Name ( vote . count_mode ) , "choices" : vote . choices , "start_block" : vote . start_block , "end_block" : vote . end_block , "vote_metainfo" : vote . vote_metainfo } | 5,656 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L101-L118 | [
"def",
"wind_speed_hub",
"(",
"self",
",",
"weather_df",
")",
":",
"if",
"self",
".",
"power_plant",
".",
"hub_height",
"in",
"weather_df",
"[",
"'wind_speed'",
"]",
":",
"wind_speed_hub",
"=",
"weather_df",
"[",
"'wind_speed'",
"]",
"[",
"self",
".",
"power_plant",
".",
"hub_height",
"]",
"elif",
"self",
".",
"wind_speed_model",
"==",
"'logarithmic'",
":",
"logging",
".",
"debug",
"(",
"'Calculating wind speed using logarithmic wind '",
"'profile.'",
")",
"closest_height",
"=",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
"[",
"min",
"(",
"range",
"(",
"len",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
")",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"abs",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
"[",
"i",
"]",
"-",
"self",
".",
"power_plant",
".",
"hub_height",
")",
")",
"]",
"wind_speed_hub",
"=",
"wind_speed",
".",
"logarithmic_profile",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
"[",
"closest_height",
"]",
",",
"closest_height",
",",
"self",
".",
"power_plant",
".",
"hub_height",
",",
"weather_df",
"[",
"'roughness_length'",
"]",
".",
"iloc",
"[",
":",
",",
"0",
"]",
",",
"self",
".",
"obstacle_height",
")",
"elif",
"self",
".",
"wind_speed_model",
"==",
"'hellman'",
":",
"logging",
".",
"debug",
"(",
"'Calculating wind speed using hellman equation.'",
")",
"closest_height",
"=",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
"[",
"min",
"(",
"range",
"(",
"len",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
")",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"abs",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
".",
"columns",
"[",
"i",
"]",
"-",
"self",
".",
"power_plant",
".",
"hub_height",
")",
")",
"]",
"wind_speed_hub",
"=",
"wind_speed",
".",
"hellman",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
"[",
"closest_height",
"]",
",",
"closest_height",
",",
"self",
".",
"power_plant",
".",
"hub_height",
",",
"weather_df",
"[",
"'roughness_length'",
"]",
".",
"iloc",
"[",
":",
",",
"0",
"]",
",",
"self",
".",
"hellman_exp",
")",
"elif",
"self",
".",
"wind_speed_model",
"==",
"'interpolation_extrapolation'",
":",
"logging",
".",
"debug",
"(",
"'Calculating wind speed using linear inter- or '",
"'extrapolation.'",
")",
"wind_speed_hub",
"=",
"tools",
".",
"linear_interpolation_extrapolation",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
",",
"self",
".",
"power_plant",
".",
"hub_height",
")",
"elif",
"self",
".",
"wind_speed_model",
"==",
"'log_interpolation_extrapolation'",
":",
"logging",
".",
"debug",
"(",
"'Calculating wind speed using logarithmic inter- or '",
"'extrapolation.'",
")",
"wind_speed_hub",
"=",
"tools",
".",
"logarithmic_interpolation_extrapolation",
"(",
"weather_df",
"[",
"'wind_speed'",
"]",
",",
"self",
".",
"power_plant",
".",
"hub_height",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is an invalid value. \"",
".",
"format",
"(",
"self",
".",
"wind_speed_model",
")",
"+",
"\"`wind_speed_model` must be \"",
"\"'logarithmic', 'hellman', 'interpolation_extrapolation' \"",
"+",
"\"or 'log_interpolation_extrapolation'.\"",
")",
"return",
"wind_speed_hub"
] |
initialize vote transaction must be signed by the deck_issuer privkey | def vote_init ( vote : Vote , inputs : dict , change_address : str ) -> bytes : network_params = net_query ( vote . deck . network ) deck_vote_tag_address = deck_vote_tag ( vote . deck ) tx_fee = network_params . min_tx_fee # settle for min tx fee for now for utxo in inputs [ 'utxos' ] : utxo [ 'txid' ] = unhexlify ( utxo [ 'txid' ] ) utxo [ 'scriptSig' ] = unhexlify ( utxo [ 'scriptSig' ] ) outputs = [ { "redeem" : 0.01 , "outputScript" : transactions . monosig_script ( deck_vote_tag_address ) } , { "redeem" : 0 , "outputScript" : transactions . op_return_script ( vote . to_protobuf ) } , { "redeem" : float ( inputs [ 'total' ] ) - float ( tx_fee ) - float ( 0.01 ) , "outputScript" : transactions . monosig_script ( change_address ) } ] return transactions . make_raw_transaction ( inputs [ 'utxos' ] , outputs ) | 5,657 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L121-L140 | [
"def",
"str",
"(",
"self",
",",
"local",
")",
":",
"s",
"=",
"self",
".",
"start_time",
".",
"str",
"(",
"local",
")",
"+",
"u\" to \"",
"+",
"self",
".",
"end_time",
".",
"str",
"(",
"local",
")",
"return",
"s"
] |
find vote_inits on this deck | def find_vote_inits ( provider : Provider , deck : Deck ) -> Iterable [ Vote ] : vote_ints = provider . listtransactions ( deck_vote_tag ( deck ) ) for txid in vote_ints : try : raw_vote = provider . getrawtransaction ( txid ) vote = parse_vote_info ( read_tx_opreturn ( raw_vote ) ) vote [ "vote_id" ] = txid vote [ "sender" ] = find_tx_sender ( provider , raw_vote ) vote [ "deck" ] = deck yield Vote ( * * vote ) except AssertionError : pass | 5,658 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L143-L157 | [
"def",
"roles_dict",
"(",
"path",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"\"\"",
")",
":",
"exit_if_path_not_found",
"(",
"path",
")",
"aggregated_roles",
"=",
"{",
"}",
"roles",
"=",
"os",
".",
"walk",
"(",
"path",
")",
".",
"next",
"(",
")",
"[",
"1",
"]",
"# First scan all directories",
"for",
"role",
"in",
"roles",
":",
"for",
"sub_role",
"in",
"roles_dict",
"(",
"path",
"+",
"\"/\"",
"+",
"role",
",",
"repo_prefix",
"=",
"\"\"",
",",
"repo_sub_dir",
"=",
"role",
"+",
"\"/\"",
")",
":",
"aggregated_roles",
"[",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"]",
"=",
"role",
"+",
"\"/\"",
"+",
"sub_role",
"# Then format them",
"for",
"role",
"in",
"roles",
":",
"if",
"is_role",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"role",
")",
")",
":",
"if",
"isinstance",
"(",
"role",
",",
"basestring",
")",
":",
"role_repo",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"repo_prefix",
",",
"role_name",
"(",
"role",
")",
")",
"aggregated_roles",
"[",
"role",
"]",
"=",
"role_repo",
"return",
"aggregated_roles"
] |
vote cast transaction | def vote_cast ( vote : Vote , choice_index : int , inputs : dict , change_address : str ) -> bytes : network_params = net_query ( vote . deck . network ) vote_cast_addr = vote . vote_choice_address [ choice_index ] tx_fee = network_params . min_tx_fee # settle for min tx fee for now for utxo in inputs [ 'utxos' ] : utxo [ 'txid' ] = unhexlify ( utxo [ 'txid' ] ) utxo [ 'scriptSig' ] = unhexlify ( utxo [ 'scriptSig' ] ) outputs = [ { "redeem" : 0.01 , "outputScript" : transactions . monosig_script ( vote_cast_addr ) } , { "redeem" : float ( inputs [ 'total' ] ) - float ( tx_fee ) - float ( 0.01 ) , "outputScript" : transactions . monosig_script ( change_address ) } ] return transactions . make_raw_transaction ( inputs [ 'utxos' ] , outputs ) | 5,659 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L160-L179 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
"closedEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
"publicEvents",
"=",
"allEvents",
".",
"instance_of",
"(",
"PublicEvent",
")",
"allSeries",
"=",
"allEvents",
".",
"instance_of",
"(",
"Series",
")",
"self",
".",
"listing",
"=",
"{",
"'allEvents'",
":",
"allEvents",
",",
"'openEvents'",
":",
"openEvents",
",",
"'closedEvents'",
":",
"closedEvents",
",",
"'publicEvents'",
":",
"publicEvents",
",",
"'allSeries'",
":",
"allSeries",
",",
"'regOpenEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"publicevent__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateEvents'",
":",
"publicEvents",
".",
"filter",
"(",
"publicevent__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'publicevent__category'",
")",
",",
"'regOpenSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'regClosedSeries'",
":",
"allSeries",
".",
"filter",
"(",
"registrationOpen",
"=",
"False",
")",
".",
"filter",
"(",
"Q",
"(",
"series__category__isnull",
"=",
"True",
")",
"|",
"Q",
"(",
"series__category__separateOnRegistrationPage",
"=",
"False",
")",
")",
",",
"'categorySeparateSeries'",
":",
"allSeries",
".",
"filter",
"(",
"series__category__separateOnRegistrationPage",
"=",
"True",
")",
".",
"order_by",
"(",
"'series__category'",
")",
",",
"}",
"return",
"self",
".",
"listing"
] |
find and verify vote_casts on this vote_choice_address | def find_vote_casts ( provider : Provider , vote : Vote , choice_index : int ) -> Iterable [ VoteCast ] : vote_casts = provider . listtransactions ( vote . vote_choice_address [ choice_index ] ) for tx in vote_casts : raw_tx = provider . getrawtransaction ( tx , 1 ) sender = find_tx_sender ( provider , raw_tx ) confirmations = raw_tx [ "confirmations" ] blocknum = provider . getblock ( raw_tx [ "blockhash" ] ) [ "height" ] yield VoteCast ( vote , sender , blocknum , confirmations , raw_tx [ "blocktime" ] ) | 5,660 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L207-L217 | [
"def",
"get_last_components_by_type",
"(",
"component_types",
",",
"topic_id",
",",
"db_conn",
"=",
"None",
")",
":",
"db_conn",
"=",
"db_conn",
"or",
"flask",
".",
"g",
".",
"db_conn",
"schedule_components_ids",
"=",
"[",
"]",
"for",
"ct",
"in",
"component_types",
":",
"where_clause",
"=",
"sql",
".",
"and_",
"(",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"type",
"==",
"ct",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"topic_id",
"==",
"topic_id",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"export_control",
"==",
"True",
",",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"state",
"==",
"'active'",
")",
"# noqa",
"query",
"=",
"(",
"sql",
".",
"select",
"(",
"[",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"id",
"]",
")",
".",
"where",
"(",
"where_clause",
")",
".",
"order_by",
"(",
"sql",
".",
"desc",
"(",
"models",
".",
"COMPONENTS",
".",
"c",
".",
"created_at",
")",
")",
")",
"cmpt_id",
"=",
"db_conn",
".",
"execute",
"(",
"query",
")",
".",
"fetchone",
"(",
")",
"if",
"cmpt_id",
"is",
"None",
":",
"msg",
"=",
"'Component of type \"%s\" not found or not exported.'",
"%",
"ct",
"raise",
"dci_exc",
".",
"DCIException",
"(",
"msg",
",",
"status_code",
"=",
"412",
")",
"cmpt_id",
"=",
"cmpt_id",
"[",
"0",
"]",
"if",
"cmpt_id",
"in",
"schedule_components_ids",
":",
"msg",
"=",
"(",
"'Component types %s malformed: type %s duplicated.'",
"%",
"(",
"component_types",
",",
"ct",
")",
")",
"raise",
"dci_exc",
".",
"DCIException",
"(",
"msg",
",",
"status_code",
"=",
"412",
")",
"schedule_components_ids",
".",
"append",
"(",
"cmpt_id",
")",
"return",
"schedule_components_ids"
] |
encode vote into protobuf | def to_protobuf ( self ) -> str : vote = pavoteproto . Vote ( ) vote . version = self . version vote . description = self . description vote . count_mode = vote . MODE . Value ( self . count_mode ) vote . start_block = self . start_block vote . end_block = self . end_block vote . choices . extend ( self . choices ) if not isinstance ( self . vote_metainfo , bytes ) : vote . vote_metainfo = self . vote_metainfo . encode ( ) else : vote . vote_metainfo = self . vote_metainfo proto = vote . SerializeToString ( ) if len ( proto ) > 80 : warnings . warn ( '\nMetainfo size exceeds maximum of 80 bytes allowed by OP_RETURN.' ) return proto | 5,661 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L44-L65 | [
"def",
"getMetastable",
"(",
"rates",
",",
"ver",
":",
"np",
".",
"ndarray",
",",
"lamb",
",",
"br",
",",
"reactfn",
":",
"Path",
")",
":",
"with",
"h5py",
".",
"File",
"(",
"reactfn",
",",
"'r'",
")",
"as",
"f",
":",
"A",
"=",
"f",
"[",
"'/metastable/A'",
"]",
"[",
":",
"]",
"lambnew",
"=",
"f",
"[",
"'/metastable/lambda'",
"]",
".",
"value",
".",
"ravel",
"(",
"order",
"=",
"'F'",
")",
"# some are not 1-D!",
"vnew",
"=",
"np",
".",
"concatenate",
"(",
"(",
"A",
"[",
":",
"2",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'no1s'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
",",
"A",
"[",
"2",
":",
"4",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'no1d'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
",",
"A",
"[",
"4",
":",
"]",
"*",
"rates",
".",
"loc",
"[",
"...",
",",
"'noii2p'",
"]",
".",
"values",
"[",
":",
",",
"None",
"]",
")",
",",
"axis",
"=",
"-",
"1",
")",
"assert",
"vnew",
".",
"shape",
"==",
"(",
"rates",
".",
"shape",
"[",
"0",
"]",
",",
"A",
".",
"size",
")",
"return",
"catvl",
"(",
"rates",
".",
"alt_km",
",",
"ver",
",",
"vnew",
",",
"lamb",
",",
"lambnew",
",",
"br",
")"
] |
vote info as dict | def to_dict ( self ) -> dict : return { "version" : self . version , "description" : self . description , "count_mode" : self . count_mode , "start_block" : self . start_block , "end_block" : self . end_block , "choices" : self . choices , "vote_metainfo" : self . vote_metainfo } | 5,662 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L68-L79 | [
"def",
"fill_sampling",
"(",
"slice_list",
",",
"N",
")",
":",
"A",
"=",
"[",
"len",
"(",
"s",
".",
"inliers",
")",
"for",
"s",
"in",
"slice_list",
"]",
"N_max",
"=",
"np",
".",
"sum",
"(",
"A",
")",
"if",
"N",
">",
"N_max",
":",
"raise",
"ValueError",
"(",
"\"Tried to draw {:d} samples from a pool of only {:d} items\"",
".",
"format",
"(",
"N",
",",
"N_max",
")",
")",
"samples_from",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"A",
")",
",",
")",
",",
"dtype",
"=",
"'int'",
")",
"# Number of samples to draw from each group",
"remaining",
"=",
"N",
"while",
"remaining",
">",
"0",
":",
"remaining_groups",
"=",
"np",
".",
"flatnonzero",
"(",
"samples_from",
"-",
"np",
".",
"array",
"(",
"A",
")",
")",
"if",
"remaining",
"<",
"len",
"(",
"remaining_groups",
")",
":",
"np",
".",
"random",
".",
"shuffle",
"(",
"remaining_groups",
")",
"for",
"g",
"in",
"remaining_groups",
"[",
":",
"remaining",
"]",
":",
"samples_from",
"[",
"g",
"]",
"+=",
"1",
"else",
":",
"# Give each group the allowed number of samples. Constrain to their max size.",
"to_each",
"=",
"max",
"(",
"1",
",",
"int",
"(",
"remaining",
"/",
"len",
"(",
"remaining_groups",
")",
")",
")",
"samples_from",
"=",
"np",
".",
"min",
"(",
"np",
".",
"vstack",
"(",
"(",
"samples_from",
"+",
"to_each",
",",
"A",
")",
")",
",",
"axis",
"=",
"0",
")",
"# Update remaining count",
"remaining",
"=",
"int",
"(",
"N",
"-",
"np",
".",
"sum",
"(",
"samples_from",
")",
")",
"if",
"not",
"remaining",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Still {:d} samples left! This is an error in the selection.\"",
")",
"# Construct index list of selected samples",
"samples",
"=",
"[",
"]",
"for",
"s",
",",
"a",
",",
"n",
"in",
"zip",
"(",
"slice_list",
",",
"A",
",",
"samples_from",
")",
":",
"if",
"a",
"==",
"n",
":",
"samples",
".",
"append",
"(",
"np",
".",
"array",
"(",
"s",
".",
"inliers",
")",
")",
"# all",
"elif",
"a",
"==",
"0",
":",
"samples",
".",
"append",
"(",
"np",
".",
"arange",
"(",
"[",
"]",
")",
")",
"else",
":",
"chosen",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"s",
".",
"inliers",
",",
"n",
",",
"replace",
"=",
"False",
")",
"samples",
".",
"append",
"(",
"np",
".",
"array",
"(",
"chosen",
")",
")",
"return",
"samples"
] |
calculate the addresses on which the vote is casted . | def vote_choice_address ( self ) -> List [ str ] : if self . vote_id is None : raise Exception ( "vote_id is required" ) addresses = [ ] vote_init_txid = unhexlify ( self . vote_id ) for choice in self . choices : vote_cast_privkey = sha256 ( vote_init_txid + bytes ( list ( self . choices ) . index ( choice ) ) ) . hexdigest ( ) addresses . append ( Kutil ( network = self . deck . network , privkey = bytearray . fromhex ( vote_cast_privkey ) ) . address ) return addresses | 5,663 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L82-L98 | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"run_plugins",
"(",
")",
"while",
"True",
":",
"# Reload plugins and config if either the config file or plugin",
"# directory are modified.",
"if",
"self",
".",
"_config_mod_time",
"!=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_config_file_path",
")",
"or",
"self",
".",
"_plugin_mod_time",
"!=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_plugin_path",
")",
":",
"self",
".",
"thread_manager",
".",
"kill_all_threads",
"(",
")",
"self",
".",
"output_dict",
".",
"clear",
"(",
")",
"self",
".",
"reload",
"(",
")",
"self",
".",
"run_plugins",
"(",
")",
"self",
".",
"output_to_bar",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_remove_empty_output",
"(",
")",
")",
")",
"time",
".",
"sleep",
"(",
"self",
".",
"config",
".",
"general",
"[",
"'interval'",
"]",
")"
] |
check if VoteCast is valid | def is_valid ( self ) -> bool : if not ( self . blocknum >= self . vote . start_block and self . blocknum <= self . vote . end_block ) : return False if not self . confirmations >= 6 : return False return True | 5,664 | https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/voting.py#L194-L204 | [
"def",
"update",
"(",
"self",
")",
":",
"# Spawn new particles if required",
"if",
"self",
".",
"time_left",
">",
"0",
":",
"self",
".",
"time_left",
"-=",
"1",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_count",
")",
":",
"new_particle",
"=",
"self",
".",
"_new_particle",
"(",
")",
"if",
"new_particle",
"is",
"not",
"None",
":",
"self",
".",
"particles",
".",
"append",
"(",
"new_particle",
")",
"# Now draw them all",
"for",
"particle",
"in",
"self",
".",
"particles",
":",
"# Clear our the old particle",
"last",
"=",
"particle",
".",
"last",
"(",
")",
"if",
"last",
"is",
"not",
"None",
":",
"char",
",",
"x",
",",
"y",
",",
"fg",
",",
"attr",
",",
"bg",
"=",
"last",
"screen_data",
"=",
"self",
".",
"_screen",
".",
"get_from",
"(",
"x",
",",
"y",
")",
"if",
"self",
".",
"_blend",
"and",
"screen_data",
":",
"index",
"=",
"self",
".",
"_find_colour",
"(",
"particle",
",",
"0",
",",
"screen_data",
")",
"-",
"1",
"fg",
",",
"attr",
",",
"bg",
"=",
"particle",
".",
"colours",
"[",
"max",
"(",
"index",
",",
"0",
")",
"]",
"self",
".",
"_screen",
".",
"print_at",
"(",
"\" \"",
",",
"x",
",",
"y",
",",
"fg",
",",
"attr",
",",
"bg",
")",
"if",
"particle",
".",
"time",
"<",
"particle",
".",
"life_time",
":",
"# Draw the new one",
"char",
",",
"x",
",",
"y",
",",
"fg",
",",
"attr",
",",
"bg",
"=",
"particle",
".",
"next",
"(",
")",
"screen_data",
"=",
"self",
".",
"_screen",
".",
"get_from",
"(",
"x",
",",
"y",
")",
"if",
"self",
".",
"_blend",
"and",
"screen_data",
":",
"index",
"=",
"self",
".",
"_find_colour",
"(",
"particle",
",",
"-",
"1",
",",
"screen_data",
")",
"+",
"1",
"fg",
",",
"attr",
",",
"bg",
"=",
"particle",
".",
"colours",
"[",
"min",
"(",
"index",
",",
"len",
"(",
"particle",
".",
"colours",
")",
"-",
"1",
")",
"]",
"self",
".",
"_screen",
".",
"print_at",
"(",
"char",
",",
"x",
",",
"y",
",",
"fg",
",",
"attr",
",",
"bg",
")",
"else",
":",
"self",
".",
"particles",
".",
"remove",
"(",
"particle",
")"
] |
This checks to see if a sequence already exists in the reference data . If it does then it ll return the known annotation . | def search_refdata ( self , seq , locus ) : # TODO: ONLY MAKE ONE CONNECTION # TODO: add try statement # TODO: take password from environment variable if self . server_avail : hla , loc = locus . split ( '-' ) p1 = "SELECT ent.name " p2 = "FROM bioentry ent,biosequence seq,biodatabase dbb " p3 = "WHERE dbb.biodatabase_id = ent.biodatabase_id AND seq.bioentry_id = ent.bioentry_id " p4 = " AND dbb.name = \"" + self . dbversion + "_" + loc + "\"" p5 = " AND seq.seq = \"" + str ( seq . seq ) + "\"" select_stm = p1 + p2 + p3 + p4 + p5 # TODO: add try statement conn = pymysql . connect ( host = biosqlhost , port = biosqlport , user = biosqluser , passwd = biosqlpass , db = biosqldb ) cur = conn . cursor ( ) cur . execute ( select_stm ) typ = '' for row in cur : typ = row [ 0 ] cur . close ( ) conn . close ( ) if typ : if self . verbose : self . logger . info ( "Exact typing found in BioSQL database" ) seqrecord = self . seqrecord ( typ , loc ) return self . seqannotation ( seqrecord , typ , loc ) else : return else : if str ( seq . seq ) in self . seqref : if self . verbose : self . logger . info ( "Exact typing found in dat file" ) seqrec = self . hlaref [ self . seqref [ str ( seq . seq ) ] ] return self . seqannotation ( seqrec , self . seqref [ str ( seq . seq ) ] , locus ) else : return | 5,665 | https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/models/reference_data.py#L621-L679 | [
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",
"query",
"[",
"'workspace_members'",
"]",
"=",
"userid",
"workspaces",
"=",
"[",
"IWorkspace",
"(",
"b",
".",
"_unrestrictedGetObject",
"(",
")",
")",
"for",
"b",
"in",
"catalog",
".",
"unrestrictedSearchResults",
"(",
"query",
")",
"]",
"for",
"workspace",
"in",
"workspaces",
":",
"workspace",
".",
"remove_from_team",
"(",
"userid",
")"
] |
updates the values of the parameter just as a regular dictionary | def update ( self , * args ) : for d in args : for ( key , value ) in d . items ( ) : self . __setitem__ ( key , value ) | 5,666 | https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/parameter.py#L110-L116 | [
"def",
"read_stb",
"(",
"library",
",",
"session",
")",
":",
"status",
"=",
"ViUInt16",
"(",
")",
"ret",
"=",
"library",
".",
"viReadSTB",
"(",
"session",
",",
"byref",
"(",
"status",
")",
")",
"return",
"status",
".",
"value",
",",
"ret"
] |
Print output error message and raise RuntimeError . | def error ( msg , log_file = None ) : UtilClass . print_msg ( msg + os . linesep ) if log_file is not None : UtilClass . writelog ( log_file , msg , 'append' ) raise RuntimeError ( msg ) | 5,667 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L96-L101 | [
"def",
"customer_discount_webhook_handler",
"(",
"event",
")",
":",
"crud_type",
"=",
"CrudType",
".",
"determine",
"(",
"event",
"=",
"event",
")",
"discount_data",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"object\"",
",",
"{",
"}",
")",
"coupon_data",
"=",
"discount_data",
".",
"get",
"(",
"\"coupon\"",
",",
"{",
"}",
")",
"customer",
"=",
"event",
".",
"customer",
"if",
"crud_type",
".",
"created",
"or",
"crud_type",
".",
"updated",
":",
"coupon",
",",
"_",
"=",
"_handle_crud_like_event",
"(",
"target_cls",
"=",
"models",
".",
"Coupon",
",",
"event",
"=",
"event",
",",
"data",
"=",
"coupon_data",
",",
"id",
"=",
"coupon_data",
".",
"get",
"(",
"\"id\"",
")",
")",
"coupon_start",
"=",
"discount_data",
".",
"get",
"(",
"\"start\"",
")",
"coupon_end",
"=",
"discount_data",
".",
"get",
"(",
"\"end\"",
")",
"else",
":",
"coupon",
"=",
"None",
"coupon_start",
"=",
"None",
"coupon_end",
"=",
"None",
"customer",
".",
"coupon",
"=",
"coupon",
"customer",
".",
"coupon_start",
"=",
"convert_tstamp",
"(",
"coupon_start",
")",
"customer",
".",
"coupon_end",
"=",
"convert_tstamp",
"(",
"coupon_end",
")",
"customer",
".",
"save",
"(",
")"
] |
Output log message . | def log ( lines , log_file = None ) : err = False for line in lines : print ( line ) if log_file is not None : UtilClass . writelog ( log_file , line , 'append' ) if 'BAD TERMINATION' in line . upper ( ) : err = True break if err : TauDEM . error ( 'Error occurred when calling TauDEM function, please check!' , log_file ) | 5,668 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L104-L115 | [
"def",
"verify",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"database",
".",
"cursor",
"(",
")",
"non_exist",
"=",
"set",
"(",
")",
"no_db_entry",
"=",
"set",
"(",
"os",
".",
"listdir",
"(",
"self",
".",
"cache_dir",
")",
")",
"try",
":",
"no_db_entry",
".",
"remove",
"(",
"'file_database.db'",
")",
"no_db_entry",
".",
"remove",
"(",
"'file_database.db-journal'",
")",
"except",
":",
"pass",
"for",
"row",
"in",
"c",
".",
"execute",
"(",
"\"SELECT path FROM files\"",
")",
":",
"path",
"=",
"row",
"[",
"0",
"]",
"repo_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_dir",
",",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"repo_path",
")",
":",
"no_db_entry",
".",
"remove",
"(",
"path",
")",
"else",
":",
"non_exist",
".",
"add",
"(",
"path",
")",
"if",
"len",
"(",
"non_exist",
")",
">",
"0",
":",
"raise",
"Exception",
"(",
"\"Found {} records in db for files that don't exist: {}\"",
".",
"format",
"(",
"len",
"(",
"non_exist",
")",
",",
"','",
".",
"join",
"(",
"non_exist",
")",
")",
")",
"if",
"len",
"(",
"no_db_entry",
")",
">",
"0",
":",
"raise",
"Exception",
"(",
"\"Found {} files that don't have db entries: {}\"",
".",
"format",
"(",
"len",
"(",
"no_db_entry",
")",
",",
"','",
".",
"join",
"(",
"no_db_entry",
")",
")",
")"
] |
Write time log . | def write_time_log ( logfile , time ) : if os . path . exists ( logfile ) : log_status = open ( logfile , 'a' , encoding = 'utf-8' ) else : log_status = open ( logfile , 'w' , encoding = 'utf-8' ) log_status . write ( 'Function Name\tRead Time\tCompute Time\tWrite Time\tTotal Time\t\n' ) log_status . write ( '%s\t%.5f\t%.5f\t%.5f\t%.5f\t\n' % ( time [ 'name' ] , time [ 'readt' ] , time [ 'computet' ] , time [ 'writet' ] , time [ 'totalt' ] ) ) log_status . flush ( ) log_status . close ( ) | 5,669 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L118-L130 | [
"def",
"configure_materials_manager",
"(",
"graph",
",",
"key_provider",
")",
":",
"if",
"graph",
".",
"config",
".",
"materials_manager",
".",
"enable_cache",
":",
"return",
"CachingCryptoMaterialsManager",
"(",
"cache",
"=",
"LocalCryptoMaterialsCache",
"(",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_capacity",
")",
",",
"master_key_provider",
"=",
"key_provider",
",",
"max_age",
"=",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_max_age",
",",
"max_messages_encrypted",
"=",
"graph",
".",
"config",
".",
"materials_manager",
".",
"cache_max_messages_encrypted",
",",
")",
"return",
"DefaultCryptoMaterialsManager",
"(",
"master_key_provider",
"=",
"key_provider",
")"
] |
Check the existence of the given file and directory path . 1 . Raise Runtime exception of both not existed . 2 . If the curwp is None the set the base folder of curinf to it . | def check_infile_and_wp ( curinf , curwp ) : if not os . path . exists ( curinf ) : if curwp is None : TauDEM . error ( 'You must specify one of the workspace and the ' 'full path of input file!' ) curinf = curwp + os . sep + curinf curinf = os . path . abspath ( curinf ) if not os . path . exists ( curinf ) : TauDEM . error ( 'Input files parameter %s is not existed!' % curinf ) else : curinf = os . path . abspath ( curinf ) if curwp is None : curwp = os . path . dirname ( curinf ) return curinf , curwp | 5,670 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L163-L180 | [
"def",
"need_rejoin",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_subscription",
".",
"partitions_auto_assigned",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"_auto_assign_all_partitions",
"(",
")",
":",
"return",
"False",
"# we need to rejoin if we performed the assignment and metadata has changed",
"if",
"(",
"self",
".",
"_assignment_snapshot",
"is",
"not",
"None",
"and",
"self",
".",
"_assignment_snapshot",
"!=",
"self",
".",
"_metadata_snapshot",
")",
":",
"return",
"True",
"# we need to join if our subscription has changed since the last join",
"if",
"(",
"self",
".",
"_joined_subscription",
"is",
"not",
"None",
"and",
"self",
".",
"_joined_subscription",
"!=",
"self",
".",
"_subscription",
".",
"subscription",
")",
":",
"return",
"True",
"return",
"super",
"(",
"ConsumerCoordinator",
",",
"self",
")",
".",
"need_rejoin",
"(",
")"
] |
Run pit remove using the flooding approach | def pitremove ( np , dem , filleddem , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'pitremove' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-z' : dem } , workingdir , None , { '-fel' : filleddem } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,671 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L377-L386 | [
"def",
"process",
"(",
"self",
",",
"items_block",
")",
":",
"logger",
".",
"info",
"(",
"self",
".",
"__log_prefix",
"+",
"\" Authors to process: \"",
"+",
"str",
"(",
"len",
"(",
"items_block",
")",
")",
")",
"onion_enrich",
"=",
"Onion",
"(",
"items_block",
")",
"df_onion",
"=",
"onion_enrich",
".",
"enrich",
"(",
"member_column",
"=",
"ESOnionConnector",
".",
"AUTHOR_UUID",
",",
"events_column",
"=",
"ESOnionConnector",
".",
"CONTRIBUTIONS",
")",
"# Get and store Quarter as String",
"df_onion",
"[",
"'quarter'",
"]",
"=",
"df_onion",
"[",
"ESOnionConnector",
".",
"TIMEFRAME",
"]",
".",
"map",
"(",
"lambda",
"x",
":",
"str",
"(",
"pandas",
".",
"Period",
"(",
"x",
",",
"'Q'",
")",
")",
")",
"# Add metadata: enriched on timestamp",
"df_onion",
"[",
"'metadata__enriched_on'",
"]",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"df_onion",
"[",
"'data_source'",
"]",
"=",
"self",
".",
"data_source",
"df_onion",
"[",
"'grimoire_creation_date'",
"]",
"=",
"df_onion",
"[",
"ESOnionConnector",
".",
"TIMEFRAME",
"]",
"logger",
".",
"info",
"(",
"self",
".",
"__log_prefix",
"+",
"\" Final new events: \"",
"+",
"str",
"(",
"len",
"(",
"df_onion",
")",
")",
")",
"return",
"self",
".",
"ProcessResults",
"(",
"processed",
"=",
"len",
"(",
"df_onion",
")",
",",
"out_items",
"=",
"df_onion",
")"
] |
Run D8 flow direction | def d8flowdir ( np , filleddem , flowdir , slope , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'd8flowdir' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : filleddem } , workingdir , None , { '-p' : flowdir , '-sd8' : slope } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,672 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L389-L398 | [
"def",
"transform",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"objid",
"=",
"id",
"(",
"value",
")",
"if",
"objid",
"in",
"self",
".",
"context",
":",
"return",
"'<...>'",
"self",
".",
"context",
".",
"add",
"(",
"objid",
")",
"try",
":",
"for",
"serializer",
"in",
"self",
".",
"serializers",
":",
"try",
":",
"if",
"serializer",
".",
"can",
"(",
"value",
")",
":",
"return",
"serializer",
".",
"serialize",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"return",
"text_type",
"(",
"type",
"(",
"value",
")",
")",
"# if all else fails, lets use the repr of the object",
"try",
":",
"return",
"repr",
"(",
"value",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"# It's common case that a model's __unicode__ definition",
"# may try to query the database which if it was not",
"# cleaned up correctly, would hit a transaction aborted",
"# exception",
"return",
"text_type",
"(",
"type",
"(",
"value",
")",
")",
"finally",
":",
"self",
".",
"context",
".",
"remove",
"(",
"objid",
")"
] |
Run Dinf flow direction | def dinfflowdir ( np , filleddem , flowangle , slope , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'dinfflowdir' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : filleddem } , workingdir , None , { '-ang' : flowangle , '-slp' : slope } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,673 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L401-L410 | [
"def",
"on_close",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Calling '{0}' Component Framework 'on_close' method.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"map",
"(",
"self",
".",
"unregister_file",
",",
"self",
".",
"list_files",
"(",
")",
")",
"if",
"self",
".",
"store_session",
"(",
")",
"and",
"self",
".",
"close_all_files",
"(",
"leave_first_editor",
"=",
"False",
")",
":",
"return",
"True"
] |
Run Accumulate area according to D8 flow direction | def aread8 ( np , flowdir , acc , outlet = None , streamskeleton = None , edgecontaimination = False , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : # -nc means do not consider edge contaimination if not edgecontaimination : in_params = { '-nc' : None } else : in_params = None fname = TauDEM . func_name ( 'aread8' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-p' : flowdir , '-o' : outlet , '-wg' : streamskeleton } , workingdir , in_params , { '-ad8' : acc } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,674 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L413-L428 | [
"def",
"reboot",
"(",
"self",
",",
"nodes",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_connected",
"(",
")",
":",
"return",
"None",
"nodes",
"=",
"nodes",
"or",
"self",
".",
"nodes",
"result",
"=",
"[",
"]",
"for",
"node",
"in",
"nodes",
":",
"if",
"node",
".",
"state",
"==",
"'stopped'",
":",
"logging",
".",
"warning",
"(",
"'Node %s is \"stopped\" and can not be rebooted.'",
",",
"node",
".",
"name",
")",
"continue",
"try",
":",
"status",
"=",
"self",
".",
"gce",
".",
"reboot_node",
"(",
"node",
")",
"if",
"status",
":",
"result",
".",
"append",
"(",
"node",
")",
"except",
"InvalidRequestError",
"as",
"err",
":",
"raise",
"ComputeEngineManagerException",
"(",
"err",
")",
"return",
"result"
] |
Run Accumulate area according to Dinf flow direction | def areadinf ( np , angfile , sca , outlet = None , wg = None , edgecontaimination = False , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : # -nc means do not consider edge contaimination if edgecontaimination : in_params = { '-nc' : None } else : in_params = None fname = TauDEM . func_name ( 'areadinf' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-ang' : angfile , '-o' : outlet , '-wg' : wg } , workingdir , in_params , { '-sca' : sca } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,675 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L431-L446 | [
"def",
"on_close",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"> Calling '{0}' Component Framework 'on_close' method.\"",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"map",
"(",
"self",
".",
"unregister_file",
",",
"self",
".",
"list_files",
"(",
")",
")",
"if",
"self",
".",
"store_session",
"(",
")",
"and",
"self",
".",
"close_all_files",
"(",
"leave_first_editor",
"=",
"False",
")",
":",
"return",
"True"
] |
Reads an ad8 contributing area file identifies the location of the largest ad8 value as the outlet of the largest watershed | def connectdown ( np , p , acc , outlet , wtsd = None , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : # If watershed is not specified, use acc to generate a mask layer. if wtsd is None or not os . path . isfile ( wtsd ) : p , workingdir = TauDEM . check_infile_and_wp ( p , workingdir ) wtsd = workingdir + os . sep + 'wtsd_default.tif' RasterUtilClass . get_mask_from_raster ( p , wtsd , True ) fname = TauDEM . func_name ( 'connectdown' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-p' : p , '-ad8' : acc , '-w' : wtsd } , workingdir , None , { '-o' : outlet } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,676 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L449-L465 | [
"def",
"invalidate",
"(",
"self",
")",
":",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"for",
"key",
"in",
"row",
".",
"keys",
":",
"key",
".",
"state",
"=",
"0"
] |
Run threshold for stream raster | def threshold ( np , acc , stream_raster , threshold = 100. , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'threshold' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-ssa' : acc } , workingdir , { '-thresh' : threshold } , { '-src' : stream_raster } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,677 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L480-L489 | [
"def",
"get_indices",
"(",
"self",
",",
"include_aliases",
"=",
"False",
")",
":",
"state",
"=",
"self",
".",
"conn",
".",
"cluster",
".",
"state",
"(",
")",
"status",
"=",
"self",
".",
"status",
"(",
")",
"result",
"=",
"{",
"}",
"indices_status",
"=",
"status",
"[",
"'indices'",
"]",
"indices_metadata",
"=",
"state",
"[",
"'metadata'",
"]",
"[",
"'indices'",
"]",
"for",
"index",
"in",
"sorted",
"(",
"indices_status",
".",
"keys",
"(",
")",
")",
":",
"info",
"=",
"indices_status",
"[",
"index",
"]",
"try",
":",
"num_docs",
"=",
"info",
"[",
"'docs'",
"]",
"[",
"'num_docs'",
"]",
"except",
"KeyError",
":",
"num_docs",
"=",
"0",
"result",
"[",
"index",
"]",
"=",
"dict",
"(",
"num_docs",
"=",
"num_docs",
")",
"if",
"not",
"include_aliases",
":",
"continue",
"try",
":",
"metadata",
"=",
"indices_metadata",
"[",
"index",
"]",
"except",
"KeyError",
":",
"continue",
"for",
"alias",
"in",
"metadata",
".",
"get",
"(",
"'aliases'",
",",
"[",
"]",
")",
":",
"try",
":",
"alias_obj",
"=",
"result",
"[",
"alias",
"]",
"except",
"KeyError",
":",
"alias_obj",
"=",
"{",
"}",
"result",
"[",
"alias",
"]",
"=",
"alias_obj",
"alias_obj",
"[",
"'num_docs'",
"]",
"=",
"alias_obj",
".",
"get",
"(",
"'num_docs'",
",",
"0",
")",
"+",
"num_docs",
"try",
":",
"alias_obj",
"[",
"'alias_for'",
"]",
".",
"append",
"(",
"index",
")",
"except",
"KeyError",
":",
"alias_obj",
"[",
"'alias_for'",
"]",
"=",
"[",
"index",
"]",
"return",
"result"
] |
Run move the given outlets to stream | def moveoutletstostrm ( np , flowdir , streamRaster , outlet , modifiedOutlet , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'moveoutletstostrm' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-p' : flowdir , '-src' : streamRaster , '-o' : outlet } , workingdir , None , { '-om' : modifiedOutlet } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,678 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L507-L518 | [
"def",
"symmetrize",
"(",
"W",
",",
"method",
"=",
"'average'",
")",
":",
"if",
"W",
".",
"shape",
"[",
"0",
"]",
"!=",
"W",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Matrix must be square.'",
")",
"if",
"method",
"==",
"'average'",
":",
"return",
"(",
"W",
"+",
"W",
".",
"T",
")",
"/",
"2",
"elif",
"method",
"==",
"'maximum'",
":",
"if",
"sparse",
".",
"issparse",
"(",
"W",
")",
":",
"bigger",
"=",
"(",
"W",
".",
"T",
">",
"W",
")",
"return",
"W",
"-",
"W",
".",
"multiply",
"(",
"bigger",
")",
"+",
"W",
".",
"T",
".",
"multiply",
"(",
"bigger",
")",
"else",
":",
"return",
"np",
".",
"maximum",
"(",
"W",
",",
"W",
".",
"T",
")",
"elif",
"method",
"==",
"'fill'",
":",
"A",
"=",
"(",
"W",
">",
"0",
")",
"# Boolean type.",
"if",
"sparse",
".",
"issparse",
"(",
"W",
")",
":",
"mask",
"=",
"(",
"A",
"+",
"A",
".",
"T",
")",
"-",
"A",
"W",
"=",
"W",
"+",
"mask",
".",
"multiply",
"(",
"W",
".",
"T",
")",
"else",
":",
"# Numpy boolean subtract is deprecated.",
"mask",
"=",
"np",
".",
"logical_xor",
"(",
"np",
".",
"logical_or",
"(",
"A",
",",
"A",
".",
"T",
")",
",",
"A",
")",
"W",
"=",
"W",
"+",
"mask",
"*",
"W",
".",
"T",
"return",
"symmetrize",
"(",
"W",
",",
"method",
"=",
"'average'",
")",
"# Resolve ambiguous entries.",
"elif",
"method",
"in",
"[",
"'tril'",
",",
"'triu'",
"]",
":",
"if",
"sparse",
".",
"issparse",
"(",
"W",
")",
":",
"tri",
"=",
"getattr",
"(",
"sparse",
",",
"method",
")",
"else",
":",
"tri",
"=",
"getattr",
"(",
"np",
",",
"method",
")",
"W",
"=",
"tri",
"(",
"W",
")",
"return",
"symmetrize",
"(",
"W",
",",
"method",
"=",
"'maximum'",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown symmetrization method {}.'",
".",
"format",
"(",
"method",
")",
")"
] |
Convert distance method to h v p and s . | def convertdistmethod ( method_str ) : if StringClass . string_match ( method_str , 'Horizontal' ) : return 'h' elif StringClass . string_match ( method_str , 'Vertical' ) : return 'v' elif StringClass . string_match ( method_str , 'Pythagoras' ) : return 'p' elif StringClass . string_match ( method_str , 'Surface' ) : return 's' elif method_str . lower ( ) in [ 'h' , 'v' , 'p' , 's' ] : return method_str . lower ( ) else : return 's' | 5,679 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L521-L534 | [
"def",
"_generate_examples_validation",
"(",
"self",
",",
"archive",
",",
"labels",
")",
":",
"# Get the current random seeds.",
"numpy_st0",
"=",
"np",
".",
"random",
".",
"get_state",
"(",
")",
"# Set new random seeds.",
"np",
".",
"random",
".",
"seed",
"(",
"135",
")",
"logging",
".",
"warning",
"(",
"'Overwriting cv2 RNG seed.'",
")",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"setRNGSeed",
"(",
"357",
")",
"for",
"example",
"in",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_generate_examples_validation",
"(",
"archive",
",",
"labels",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"tf_img",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"example",
"[",
"'image'",
"]",
".",
"read",
"(",
")",
",",
"channels",
"=",
"3",
")",
"image_np",
"=",
"tfds",
".",
"as_numpy",
"(",
"tf_img",
")",
"example",
"[",
"'image'",
"]",
"=",
"self",
".",
"_get_corrupted_example",
"(",
"image_np",
")",
"yield",
"example",
"# Reset the seeds back to their original values.",
"np",
".",
"random",
".",
"set_state",
"(",
"numpy_st0",
")"
] |
Convert statistics method to ave min and max . | def convertstatsmethod ( method_str ) : if StringClass . string_match ( method_str , 'Average' ) : return 'ave' elif StringClass . string_match ( method_str , 'Maximum' ) : return 'max' elif StringClass . string_match ( method_str , 'Minimum' ) : return 'min' elif method_str . lower ( ) in [ 'ave' , 'max' , 'min' ] : return method_str . lower ( ) else : return 'ave' | 5,680 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L537-L548 | [
"def",
"_GetDecodedStreamSize",
"(",
"self",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decoder",
"=",
"self",
".",
"_GetDecoder",
"(",
")",
"self",
".",
"_decoded_data",
"=",
"b''",
"encoded_data_offset",
"=",
"0",
"encoded_data_size",
"=",
"self",
".",
"_file_object",
".",
"get_size",
"(",
")",
"decoded_stream_size",
"=",
"0",
"while",
"encoded_data_offset",
"<",
"encoded_data_size",
":",
"read_count",
"=",
"self",
".",
"_ReadEncodedData",
"(",
"self",
".",
"_ENCODED_DATA_BUFFER_SIZE",
")",
"if",
"read_count",
"==",
"0",
":",
"break",
"encoded_data_offset",
"+=",
"read_count",
"decoded_stream_size",
"+=",
"self",
".",
"_decoded_data_size",
"return",
"decoded_stream_size"
] |
Run D8 horizontal distance down to stream . | def d8hdisttostrm ( np , p , src , dist , thresh , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'd8hdisttostrm' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-p' : p , '-src' : src } , workingdir , { '-thresh' : thresh } , { '-dist' : dist } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,681 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L551-L562 | [
"def",
"placeOrder",
"(",
"self",
",",
"contract",
":",
"Contract",
",",
"order",
":",
"Order",
")",
"->",
"Trade",
":",
"orderId",
"=",
"order",
".",
"orderId",
"or",
"self",
".",
"client",
".",
"getReqId",
"(",
")",
"self",
".",
"client",
".",
"placeOrder",
"(",
"orderId",
",",
"contract",
",",
"order",
")",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
"datetime",
".",
"timezone",
".",
"utc",
")",
"key",
"=",
"self",
".",
"wrapper",
".",
"orderKey",
"(",
"self",
".",
"wrapper",
".",
"clientId",
",",
"orderId",
",",
"order",
".",
"permId",
")",
"trade",
"=",
"self",
".",
"wrapper",
".",
"trades",
".",
"get",
"(",
"key",
")",
"if",
"trade",
":",
"# this is a modification of an existing order",
"assert",
"trade",
".",
"orderStatus",
".",
"status",
"not",
"in",
"OrderStatus",
".",
"DoneStates",
"logEntry",
"=",
"TradeLogEntry",
"(",
"now",
",",
"trade",
".",
"orderStatus",
".",
"status",
",",
"'Modify'",
")",
"trade",
".",
"log",
".",
"append",
"(",
"logEntry",
")",
"self",
".",
"_logger",
".",
"info",
"(",
"f'placeOrder: Modify order {trade}'",
")",
"trade",
".",
"modifyEvent",
".",
"emit",
"(",
"trade",
")",
"self",
".",
"orderModifyEvent",
".",
"emit",
"(",
"trade",
")",
"else",
":",
"# this is a new order",
"order",
".",
"clientId",
"=",
"self",
".",
"wrapper",
".",
"clientId",
"order",
".",
"orderId",
"=",
"orderId",
"orderStatus",
"=",
"OrderStatus",
"(",
"status",
"=",
"OrderStatus",
".",
"PendingSubmit",
")",
"logEntry",
"=",
"TradeLogEntry",
"(",
"now",
",",
"orderStatus",
".",
"status",
",",
"''",
")",
"trade",
"=",
"Trade",
"(",
"contract",
",",
"order",
",",
"orderStatus",
",",
"[",
"]",
",",
"[",
"logEntry",
"]",
")",
"self",
".",
"wrapper",
".",
"trades",
"[",
"key",
"]",
"=",
"trade",
"self",
".",
"_logger",
".",
"info",
"(",
"f'placeOrder: New order {trade}'",
")",
"self",
".",
"newOrderEvent",
".",
"emit",
"(",
"trade",
")",
"return",
"trade"
] |
Run D8 distance down to stream by different method for distance . This function is extended from d8hdisttostrm by Liangjun . | def d8distdowntostream ( np , p , fel , src , dist , distancemethod , thresh , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'd8distdowntostream' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : fel , '-p' : p , '-src' : src } , workingdir , { '-thresh' : thresh , '-m' : TauDEM . convertdistmethod ( distancemethod ) } , { '-dist' : dist } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,682 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L565-L583 | [
"def",
"bands",
"(",
"self",
")",
":",
"bands",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"stars",
".",
"columns",
":",
"if",
"re",
".",
"search",
"(",
"'_mag'",
",",
"c",
")",
":",
"bands",
".",
"append",
"(",
"c",
")",
"return",
"bands"
] |
Run D - inf distance down to stream | def dinfdistdown ( np , ang , fel , slp , src , statsm , distm , edgecontamination , wg , dist , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : in_params = { '-m' : '%s %s' % ( TauDEM . convertstatsmethod ( statsm ) , TauDEM . convertdistmethod ( distm ) ) } if StringClass . string_match ( edgecontamination , 'false' ) or edgecontamination is False : in_params [ '-nc' ] = None fname = TauDEM . func_name ( 'dinfdistdown' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : fel , '-slp' : slp , '-ang' : ang , '-src' : src , '-wg' : wg } , workingdir , in_params , { '-dd' : dist } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,683 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L586-L601 | [
"def",
"write",
"(",
"filename",
",",
"data",
",",
"extname",
"=",
"None",
",",
"extver",
"=",
"None",
",",
"units",
"=",
"None",
",",
"compress",
"=",
"None",
",",
"table_type",
"=",
"'binary'",
",",
"header",
"=",
"None",
",",
"clobber",
"=",
"False",
",",
"*",
"*",
"keys",
")",
":",
"with",
"FITS",
"(",
"filename",
",",
"'rw'",
",",
"clobber",
"=",
"clobber",
",",
"*",
"*",
"keys",
")",
"as",
"fits",
":",
"fits",
".",
"write",
"(",
"data",
",",
"table_type",
"=",
"table_type",
",",
"units",
"=",
"units",
",",
"extname",
"=",
"extname",
",",
"extver",
"=",
"extver",
",",
"compress",
"=",
"compress",
",",
"header",
"=",
"header",
",",
"*",
"*",
"keys",
")"
] |
Run peuker - douglas function | def peukerdouglas ( np , fel , streamSkeleton , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : fname = TauDEM . func_name ( 'peukerdouglas' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : fel } , workingdir , None , { '-ss' : streamSkeleton } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,684 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L604-L613 | [
"def",
"print_pretty",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"text",
"=",
"_prepare",
"(",
"text",
")",
"print",
"(",
"'{}{}'",
".",
"format",
"(",
"text",
".",
"format",
"(",
"*",
"*",
"styles",
")",
".",
"replace",
"(",
"styles",
"[",
"'END'",
"]",
",",
"styles",
"[",
"'ALL_OFF'",
"]",
")",
",",
"styles",
"[",
"'ALL_OFF'",
"]",
")",
")"
] |
Drop analysis for optimal threshold for extracting stream . | def dropanalysis ( np , fel , p , ad8 , ssa , outlet , minthresh , maxthresh , numthresh , logspace , drp , workingdir = None , mpiexedir = None , exedir = None , log_file = None , runtime_file = None , hostfile = None ) : parstr = '%f %f %f' % ( minthresh , maxthresh , numthresh ) if logspace == 'false' : parstr += ' 1' else : parstr += ' 0' fname = TauDEM . func_name ( 'dropanalysis' ) return TauDEM . run ( FileClass . get_executable_fullpath ( fname , exedir ) , { '-fel' : fel , '-p' : p , '-ad8' : ad8 , '-ssa' : ssa , '-o' : outlet } , workingdir , { '-par' : parstr } , { '-drp' : drp } , { 'mpipath' : mpiexedir , 'hostfile' : hostfile , 'n' : np } , { 'logfile' : log_file , 'runtimefile' : runtime_file } ) | 5,685 | https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/TauDEM.py#L616-L632 | [
"def",
"_swap_rows",
"(",
"self",
",",
"i",
",",
"j",
")",
":",
"L",
"=",
"np",
".",
"eye",
"(",
"3",
",",
"dtype",
"=",
"'intc'",
")",
"L",
"[",
"i",
",",
"i",
"]",
"=",
"0",
"L",
"[",
"j",
",",
"j",
"]",
"=",
"0",
"L",
"[",
"i",
",",
"j",
"]",
"=",
"1",
"L",
"[",
"j",
",",
"i",
"]",
"=",
"1",
"self",
".",
"_L",
".",
"append",
"(",
"L",
".",
"copy",
"(",
")",
")",
"self",
".",
"_A",
"=",
"np",
".",
"dot",
"(",
"L",
",",
"self",
".",
"_A",
")"
] |
Resolve from documents . | def resolve ( self , pointer ) : dp = DocumentPointer ( pointer ) obj , fetcher = self . prototype ( dp ) for token in dp . pointer : obj = token . extract ( obj , bypass_ref = True ) reference = ref ( obj ) if reference : obj = fetcher . resolve ( reference ) return obj | 5,686 | https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/reference/bases.py#L37-L52 | [
"def",
"augment_audio_with_sox",
"(",
"path",
",",
"sample_rate",
",",
"tempo",
",",
"gain",
")",
":",
"with",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".wav\"",
")",
"as",
"augmented_file",
":",
"augmented_filename",
"=",
"augmented_file",
".",
"name",
"sox_augment_params",
"=",
"[",
"\"tempo\"",
",",
"\"{:.3f}\"",
".",
"format",
"(",
"tempo",
")",
",",
"\"gain\"",
",",
"\"{:.3f}\"",
".",
"format",
"(",
"gain",
")",
"]",
"sox_params",
"=",
"\"sox \\\"{}\\\" -r {} -c 1 -b 16 {} {} >/dev/null 2>&1\"",
".",
"format",
"(",
"path",
",",
"sample_rate",
",",
"augmented_filename",
",",
"\" \"",
".",
"join",
"(",
"sox_augment_params",
")",
")",
"os",
".",
"system",
"(",
"sox_params",
")",
"y",
"=",
"load_audio",
"(",
"augmented_filename",
")",
"return",
"y"
] |
count_diffs - Counts the number of mismatches gaps and insertions and then determines if those are within an acceptable range . | def count_diffs ( align , feats , inseq , locus , cutoff , verbose = False , verbosity = 0 ) : nfeats = len ( feats . keys ( ) ) mm = 0 insr = 0 dels = 0 gaps = 0 match = 0 lastb = '' l = len ( align [ 0 ] ) if len ( align [ 0 ] ) > len ( align [ 1 ] ) else len ( align [ 1 ] ) # Counting gaps, mismatches and insertions for i in range ( 0 , l ) : if align [ 0 ] [ i ] == "-" or align [ 1 ] [ i ] == "-" : if align [ 0 ] [ i ] == "-" : insr += 1 if lastb != '-' : gaps += 1 lastb = "-" if align [ 1 ] [ i ] == "-" : dels += 1 if lastb != '-' : gaps += 1 lastb = "-" else : lastb = '' if align [ 0 ] [ i ] != align [ 1 ] [ i ] : mm += 1 else : match += 1 gper = gaps / nfeats delper = dels / l iper = insr / l mmper = mm / l mper = match / l mper2 = match / len ( inseq ) logger = logging . getLogger ( "Logger." + __name__ ) if verbose and verbosity > 0 : logger . info ( "Features algined = " + "," . join ( list ( feats . keys ( ) ) ) ) logger . info ( '{:<22}{:<6d}' . format ( "Number of feats: " , nfeats ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of gaps: " , gaps , gper ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of deletions: " , dels , delper ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of insertions: " , insr , iper ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of mismatches: " , mm , mmper ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of matches: " , match , mper ) ) logger . info ( '{:<22}{:<6d}{:<1.2f}' . format ( "Number of matches: " , match , mper2 ) ) indel = iper + delper # ** HARD CODED LOGIC ** # if len ( inseq ) > 6000 and mmper < .10 and mper2 > .80 : if verbose : logger . info ( "Alignment coverage high enough to complete annotation 11" ) return insr , dels else : # TODO: These numbers need to be fine tuned indel_mm = indel + mper2 if ( indel > 0.5 or mmper > 0.05 ) and mper2 < cutoff and indel_mm != 1 : if verbose : logger . info ( "Alignment coverage NOT high enough to return annotation" ) return Annotation ( complete_annotation = False ) else : if verbose : logger . info ( "Alignment coverage high enough to complete annotation" ) return insr , dels | 5,687 | https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/align.py#L394-L480 | [
"def",
"cancelled",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state",
"==",
"self",
".",
"S_EXCEPTION",
"and",
"isinstance",
"(",
"self",
".",
"_result",
",",
"Cancelled",
")"
] |
Stops the instance | def cmd_stop ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s stop" % self . progname , description = help , ) instances = self . get_instances ( command = 'stop' ) parser . add_argument ( "instance" , nargs = 1 , metavar = "instance" , help = "Name of the instance from the config." , choices = sorted ( instances ) ) args = parser . parse_args ( argv ) instance = instances [ args . instance [ 0 ] ] instance . stop ( ) | 5,688 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L219-L232 | [
"def",
"search_for_port",
"(",
"port_glob",
",",
"req",
",",
"expected_res",
")",
":",
"# Check that the USB port actually exists, based on the known vendor and",
"# product ID.",
"if",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"0x0403",
",",
"idProduct",
"=",
"0x6001",
")",
"is",
"None",
":",
"return",
"None",
"# Find ports matching the supplied glob.",
"ports",
"=",
"glob",
".",
"glob",
"(",
"port_glob",
")",
"if",
"len",
"(",
"ports",
")",
"==",
"0",
":",
"return",
"None",
"for",
"port",
"in",
"ports",
":",
"with",
"r12_serial_port",
"(",
"port",
")",
"as",
"ser",
":",
"if",
"not",
"ser",
".",
"isOpen",
"(",
")",
":",
"ser",
".",
"open",
"(",
")",
"# Write a request out.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"ser",
".",
"write",
"(",
"str",
"(",
"req",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"ser",
".",
"write",
"(",
"bytes",
"(",
"req",
",",
"'utf-8'",
")",
")",
"# Wait a short period to allow the connection to generate output.",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# Read output from the serial connection check if it's what we want.",
"res",
"=",
"ser",
".",
"read",
"(",
"ser",
".",
"in_waiting",
")",
".",
"decode",
"(",
"OUTPUT_ENCODING",
")",
"if",
"expected_res",
"in",
"res",
":",
"return",
"port",
"raise",
"ArmException",
"(",
"'ST Robotics connection found, but is not responsive.'",
"+",
"' Is the arm powered on?'",
")",
"return",
"None"
] |
Terminates the instance | def cmd_terminate ( self , argv , help ) : from ploy . common import yesno parser = argparse . ArgumentParser ( prog = "%s terminate" % self . progname , description = help , ) instances = self . get_instances ( command = 'terminate' ) parser . add_argument ( "instance" , nargs = 1 , metavar = "instance" , help = "Name of the instance from the config." , choices = sorted ( instances ) ) args = parser . parse_args ( argv ) instance = instances [ args . instance [ 0 ] ] if not yesno ( "Are you sure you want to terminate '%s'?" % instance . config_id ) : return instance . hooks . before_terminate ( instance ) instance . terminate ( ) instance . hooks . after_terminate ( instance ) | 5,689 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L234-L252 | [
"def",
"cmd_playtune",
"(",
"self",
",",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"print",
"(",
"\"Usage: playtune TUNE\"",
")",
"return",
"tune",
"=",
"args",
"[",
"0",
"]",
"str1",
"=",
"tune",
"[",
"0",
":",
"30",
"]",
"str2",
"=",
"tune",
"[",
"30",
":",
"]",
"if",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
"and",
"not",
"isinstance",
"(",
"str1",
",",
"bytes",
")",
":",
"str1",
"=",
"bytes",
"(",
"str1",
",",
"\"ascii\"",
")",
"if",
"sys",
".",
"version_info",
".",
"major",
">=",
"3",
"and",
"not",
"isinstance",
"(",
"str2",
",",
"bytes",
")",
":",
"str2",
"=",
"bytes",
"(",
"str2",
",",
"\"ascii\"",
")",
"self",
".",
"master",
".",
"mav",
".",
"play_tune_send",
"(",
"self",
".",
"settings",
".",
"target_system",
",",
"self",
".",
"settings",
".",
"target_component",
",",
"str1",
",",
"str2",
")"
] |
Starts the instance | def cmd_start ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s start" % self . progname , description = help , ) instances = self . get_instances ( command = 'start' ) parser . add_argument ( "instance" , nargs = 1 , metavar = "instance" , help = "Name of the instance from the config." , choices = sorted ( instances ) ) parser . add_argument ( "-o" , "--override" , nargs = "*" , type = str , dest = "overrides" , metavar = "OVERRIDE" , help = "Option to override in instance config for startup script (name=value)." ) args = parser . parse_args ( argv ) overrides = self . _parse_overrides ( args ) overrides [ 'instances' ] = self . instances instance = instances [ args . instance [ 0 ] ] instance . hooks . before_start ( instance ) result = instance . start ( overrides ) instance . hooks . after_start ( instance ) if result is None : return instance . status ( ) | 5,690 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L270-L293 | [
"def",
"search_for_port",
"(",
"port_glob",
",",
"req",
",",
"expected_res",
")",
":",
"# Check that the USB port actually exists, based on the known vendor and",
"# product ID.",
"if",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"0x0403",
",",
"idProduct",
"=",
"0x6001",
")",
"is",
"None",
":",
"return",
"None",
"# Find ports matching the supplied glob.",
"ports",
"=",
"glob",
".",
"glob",
"(",
"port_glob",
")",
"if",
"len",
"(",
"ports",
")",
"==",
"0",
":",
"return",
"None",
"for",
"port",
"in",
"ports",
":",
"with",
"r12_serial_port",
"(",
"port",
")",
"as",
"ser",
":",
"if",
"not",
"ser",
".",
"isOpen",
"(",
")",
":",
"ser",
".",
"open",
"(",
")",
"# Write a request out.",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"ser",
".",
"write",
"(",
"str",
"(",
"req",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"else",
":",
"ser",
".",
"write",
"(",
"bytes",
"(",
"req",
",",
"'utf-8'",
")",
")",
"# Wait a short period to allow the connection to generate output.",
"time",
".",
"sleep",
"(",
"0.1",
")",
"# Read output from the serial connection check if it's what we want.",
"res",
"=",
"ser",
".",
"read",
"(",
"ser",
".",
"in_waiting",
")",
".",
"decode",
"(",
"OUTPUT_ENCODING",
")",
"if",
"expected_res",
"in",
"res",
":",
"return",
"port",
"raise",
"ArmException",
"(",
"'ST Robotics connection found, but is not responsive.'",
"+",
"' Is the arm powered on?'",
")",
"return",
"None"
] |
Prints annotated config | def cmd_annotate ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s annotate" % self . progname , description = help , ) parser . parse_args ( argv ) list ( self . instances . values ( ) ) # trigger instance augmentation for global_section in sorted ( self . config ) : for sectionname in sorted ( self . config [ global_section ] ) : print ( "[%s:%s]" % ( global_section , sectionname ) ) section = self . config [ global_section ] [ sectionname ] for option , value in sorted ( section . _dict . items ( ) ) : print ( "%s = %s" % ( option , value . value ) ) print ( " %s" % value . src ) print ( ) | 5,691 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L295-L310 | [
"def",
"revoke_session",
"(",
"self",
",",
"sid",
"=",
"''",
",",
"token",
"=",
"''",
")",
":",
"if",
"not",
"sid",
":",
"if",
"token",
":",
"sid",
"=",
"self",
".",
"handler",
".",
"sid",
"(",
"token",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Need one of \"sid\" or \"token\"'",
")",
"for",
"typ",
"in",
"[",
"'access_token'",
",",
"'refresh_token'",
",",
"'code'",
"]",
":",
"try",
":",
"self",
".",
"revoke_token",
"(",
"self",
"[",
"sid",
"]",
"[",
"typ",
"]",
",",
"typ",
")",
"except",
"KeyError",
":",
"# If no such token has been issued",
"pass",
"self",
".",
"update",
"(",
"sid",
",",
"revoked",
"=",
"True",
")"
] |
Prints some debug info for this script | def cmd_debug ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s debug" % self . progname , description = help , ) instances = self . instances parser . add_argument ( "instance" , nargs = 1 , metavar = "instance" , help = "Name of the instance from the config." , choices = sorted ( instances ) ) parser . add_argument ( "-v" , "--verbose" , dest = "verbose" , action = "store_true" , help = "Print more info and output the startup script" ) parser . add_argument ( "-c" , "--console-output" , dest = "console_output" , action = "store_true" , help = "Prints the console output of the instance if available" ) parser . add_argument ( "-i" , "--interactive" , dest = "interactive" , action = "store_true" , help = "Creates a connection and drops you into an interactive Python session" ) parser . add_argument ( "-r" , "--raw" , dest = "raw" , action = "store_true" , help = "Outputs the raw possibly compressed startup script" ) parser . add_argument ( "-o" , "--override" , nargs = "*" , type = str , dest = "overrides" , metavar = "OVERRIDE" , help = "Option to override instance config for startup script (name=value)." ) args = parser . parse_args ( argv ) overrides = self . _parse_overrides ( args ) overrides [ 'instances' ] = self . instances instance = instances [ args . instance [ 0 ] ] if hasattr ( instance , 'startup_script' ) : startup_script = instance . startup_script ( overrides = overrides , debug = True ) max_size = getattr ( instance , 'max_startup_script_size' , 16 * 1024 ) log . info ( "Length of startup script: %s/%s" , len ( startup_script [ 'raw' ] ) , max_size ) if args . verbose : if 'startup_script' in instance . config : if startup_script [ 'original' ] == startup_script [ 'raw' ] : log . info ( "Startup script:" ) elif args . raw : log . info ( "Compressed startup script:" ) else : log . info ( "Uncompressed startup script:" ) else : log . info ( "No startup script specified" ) if args . raw : print ( startup_script [ 'raw' ] , end = '' ) elif args . verbose : print ( startup_script [ 'original' ] , end = '' ) if args . console_output : if hasattr ( instance , 'get_console_output' ) : print ( instance . get_console_output ( ) ) else : log . error ( "The instance doesn't support console output." ) if args . interactive : # pragma: no cover import readline from pprint import pprint local = dict ( ctrl = self , instances = self . instances , instance = instance , pprint = pprint ) readline . parse_and_bind ( 'tab: complete' ) try : import rlcompleter readline . set_completer ( rlcompleter . Completer ( local ) . complete ) except ImportError : pass __import__ ( "code" ) . interact ( local = local ) | 5,692 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L312-L375 | [
"def",
"_reset_offset",
"(",
"self",
",",
"partition",
")",
":",
"timestamp",
"=",
"self",
".",
"_subscriptions",
".",
"assignment",
"[",
"partition",
"]",
".",
"reset_strategy",
"if",
"timestamp",
"is",
"OffsetResetStrategy",
".",
"EARLIEST",
":",
"strategy",
"=",
"'earliest'",
"elif",
"timestamp",
"is",
"OffsetResetStrategy",
".",
"LATEST",
":",
"strategy",
"=",
"'latest'",
"else",
":",
"raise",
"NoOffsetForPartitionError",
"(",
"partition",
")",
"log",
".",
"debug",
"(",
"\"Resetting offset for partition %s to %s offset.\"",
",",
"partition",
",",
"strategy",
")",
"offsets",
"=",
"self",
".",
"_retrieve_offsets",
"(",
"{",
"partition",
":",
"timestamp",
"}",
")",
"if",
"partition",
"not",
"in",
"offsets",
":",
"raise",
"NoOffsetForPartitionError",
"(",
"partition",
")",
"offset",
"=",
"offsets",
"[",
"partition",
"]",
"[",
"0",
"]",
"# we might lose the assignment while fetching the offset,",
"# so check it is still active",
"if",
"self",
".",
"_subscriptions",
".",
"is_assigned",
"(",
"partition",
")",
":",
"self",
".",
"_subscriptions",
".",
"seek",
"(",
"partition",
",",
"offset",
")"
] |
Return a list of various things | def cmd_list ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s list" % self . progname , description = help , ) parser . add_argument ( "list" , nargs = 1 , metavar = "listname" , help = "Name of list to show." , choices = sorted ( self . list_cmds ) ) parser . add_argument ( "listopts" , metavar = "..." , nargs = argparse . REMAINDER , help = "list command options" ) args = parser . parse_args ( argv ) for name , func in sorted ( self . list_cmds [ args . list [ 0 ] ] ) : func ( args . listopts , func . __doc__ ) | 5,693 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L377-L393 | [
"def",
"ReadFD",
"(",
"self",
",",
"Channel",
")",
":",
"try",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"msg",
"=",
"TPCANMsgFDMac",
"(",
")",
"else",
":",
"msg",
"=",
"TPCANMsgFD",
"(",
")",
"timestamp",
"=",
"TPCANTimestampFD",
"(",
")",
"res",
"=",
"self",
".",
"__m_dllBasic",
".",
"CAN_ReadFD",
"(",
"Channel",
",",
"byref",
"(",
"msg",
")",
",",
"byref",
"(",
"timestamp",
")",
")",
"return",
"TPCANStatus",
"(",
"res",
")",
",",
"msg",
",",
"timestamp",
"except",
":",
"logger",
".",
"error",
"(",
"\"Exception on PCANBasic.ReadFD\"",
")",
"raise"
] |
Log into the instance with ssh using the automatically generated known hosts | def cmd_ssh ( self , argv , help ) : parser = argparse . ArgumentParser ( prog = "%s ssh" % self . progname , description = help , ) instances = self . get_instances ( command = 'init_ssh_key' ) parser . add_argument ( "instance" , nargs = 1 , metavar = "instance" , help = "Name of the instance from the config." , choices = sorted ( instances ) ) parser . add_argument ( "..." , nargs = argparse . REMAINDER , help = "ssh options" ) iargs = enumerate ( argv ) sid_index = None user = None for i , arg in iargs : if not arg . startswith ( '-' ) : sid_index = i break if arg [ 1 ] in '1246AaCfgKkMNnqsTtVvXxYy' : continue elif arg [ 1 ] in 'bcDeFiLlmOopRSw' : value = iargs . next ( ) if arg [ 1 ] == 'l' : user = value [ 1 ] continue # fake parsing for nice error messages if sid_index is None : parser . parse_args ( [ ] ) else : sid = argv [ sid_index ] if '@' in sid : user , sid = sid . split ( '@' , 1 ) parser . parse_args ( [ sid ] ) instance = instances [ sid ] if user is None : user = instance . config . get ( 'user' ) try : ssh_info = instance . init_ssh_key ( user = user ) except ( instance . paramiko . SSHException , socket . error ) as e : log . error ( "Couldn't validate fingerprint for ssh connection." ) log . error ( unicode ( e ) ) log . error ( "Is the instance finished starting up?" ) sys . exit ( 1 ) client = ssh_info [ 'client' ] client . get_transport ( ) . sock . close ( ) client . close ( ) argv [ sid_index : sid_index + 1 ] = instance . ssh_args_from_info ( ssh_info ) argv [ 0 : 0 ] = [ 'ssh' ] os . execvp ( 'ssh' , argv ) | 5,694 | https://github.com/ployground/ploy/blob/9295b5597c09c434f170afbfd245d73f09affc39/ploy/__init__.py#L395-L445 | [
"def",
"map_eigenvalues",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
"func",
":",
"Callable",
"[",
"[",
"complex",
"]",
",",
"complex",
"]",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"np",
".",
"ndarray",
":",
"vals",
",",
"vecs",
"=",
"_perp_eigendecompose",
"(",
"matrix",
",",
"rtol",
"=",
"rtol",
",",
"atol",
"=",
"atol",
")",
"pieces",
"=",
"[",
"np",
".",
"outer",
"(",
"vec",
",",
"np",
".",
"conj",
"(",
"vec",
".",
"T",
")",
")",
"for",
"vec",
"in",
"vecs",
"]",
"out_vals",
"=",
"np",
".",
"vectorize",
"(",
"func",
")",
"(",
"vals",
".",
"astype",
"(",
"complex",
")",
")",
"total",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"matrix",
".",
"shape",
")",
"for",
"piece",
",",
"val",
"in",
"zip",
"(",
"pieces",
",",
"out_vals",
")",
":",
"total",
"=",
"np",
".",
"add",
"(",
"total",
",",
"piece",
"*",
"val",
")",
"return",
"total"
] |
Common initialization of handlers happens here . If additional initialization is required this method must either be called with super or the child class must assign the store attribute and register itself with the store . | def initialize ( self , store ) : assert isinstance ( store , stores . BaseStore ) self . messages = Queue ( ) self . store = store self . store . register ( self ) | 5,695 | https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/handlers.py#L22-L32 | [
"def",
"_tab",
"(",
"content",
")",
":",
"response",
"=",
"_data_frame",
"(",
"content",
")",
".",
"to_csv",
"(",
"index",
"=",
"False",
",",
"sep",
"=",
"'\\t'",
")",
"return",
"response"
] |
Log access . | def prepare ( self ) : request_time = 1000.0 * self . request . request_time ( ) access_log . info ( "%d %s %.2fms" , self . get_status ( ) , self . _request_summary ( ) , request_time ) | 5,696 | https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/handlers.py#L69-L74 | [
"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"
] |
Pushes data to a listener . | async def publish ( self , message ) : try : self . write ( 'data: {}\n\n' . format ( message ) ) await self . flush ( ) except StreamClosedError : self . finished = True | 5,697 | https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/handlers.py#L76-L82 | [
"async",
"def",
"create_collection",
"(",
"db",
",",
"model_class",
":",
"MongoCollectionMixin",
")",
":",
"name",
"=",
"model_class",
".",
"get_collection_name",
"(",
")",
"if",
"name",
":",
"try",
":",
"# create collection",
"coll",
"=",
"await",
"db",
".",
"create_collection",
"(",
"name",
",",
"*",
"*",
"model_class",
".",
"_meta",
".",
"creation_args",
")",
"except",
"CollectionInvalid",
":",
"# collection already exists",
"coll",
"=",
"db",
"[",
"name",
"]",
"# create indices",
"if",
"hasattr",
"(",
"model_class",
".",
"_meta",
",",
"'indices'",
")",
"and",
"isinstance",
"(",
"model_class",
".",
"_meta",
".",
"indices",
",",
"list",
")",
":",
"for",
"index",
"in",
"model_class",
".",
"_meta",
".",
"indices",
":",
"try",
":",
"index_kwargs",
"=",
"{",
"'name'",
":",
"index",
".",
"get",
"(",
"'name'",
",",
"'_'",
".",
"join",
"(",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"index",
"[",
"'fields'",
"]",
"]",
")",
")",
",",
"'unique'",
":",
"index",
".",
"get",
"(",
"'unique'",
",",
"False",
")",
",",
"'sparse'",
":",
"index",
".",
"get",
"(",
"'sparse'",
",",
"False",
")",
",",
"'expireAfterSeconds'",
":",
"index",
".",
"get",
"(",
"'expireAfterSeconds'",
",",
"None",
")",
",",
"'background'",
":",
"True",
"}",
"if",
"'partialFilterExpression'",
"in",
"index",
":",
"index_kwargs",
"[",
"'partialFilterExpression'",
"]",
"=",
"index",
".",
"get",
"(",
"'partialFilterExpression'",
",",
"{",
"}",
")",
"await",
"db",
"[",
"name",
"]",
".",
"create_index",
"(",
"index",
"[",
"'fields'",
"]",
",",
"*",
"*",
"index_kwargs",
")",
"except",
"OperationFailure",
"as",
"ex",
":",
"pass",
"# index already exists ? TODO: do something with this",
"return",
"coll",
"return",
"None"
] |
Register with the publisher . | async def open ( self ) : self . store . register ( self ) while not self . finished : message = await self . messages . get ( ) await self . publish ( message ) | 5,698 | https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/handlers.py#L102-L107 | [
"def",
"removeAllChildrenAtIndex",
"(",
"self",
",",
"parentIndex",
")",
":",
"if",
"not",
"parentIndex",
".",
"isValid",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"No valid item selected for deletion (ignored).\"",
")",
"return",
"parentItem",
"=",
"self",
".",
"getItem",
"(",
"parentIndex",
",",
"None",
")",
"logger",
".",
"debug",
"(",
"\"Removing children of {!r}\"",
".",
"format",
"(",
"parentItem",
")",
")",
"assert",
"parentItem",
",",
"\"parentItem not found\"",
"#firstChildRow = self.index(0, 0, parentIndex).row()",
"#lastChildRow = self.index(parentItem.nChildren()-1, 0, parentIndex).row()",
"#logger.debug(\"Removing rows: {} to {}\".format(firstChildRow, lastChildRow))",
"#self.beginRemoveRows(parentIndex, firstChildRow, lastChildRow)",
"self",
".",
"beginRemoveRows",
"(",
"parentIndex",
",",
"0",
",",
"parentItem",
".",
"nChildren",
"(",
")",
"-",
"1",
")",
"try",
":",
"parentItem",
".",
"removeAllChildren",
"(",
")",
"finally",
":",
"self",
".",
"endRemoveRows",
"(",
")",
"logger",
".",
"debug",
"(",
"\"removeAllChildrenAtIndex completed\"",
")"
] |
Push a new message to the client . The data will be available as a JSON object with the key data . | async def publish ( self , message ) : try : self . write_message ( dict ( data = message ) ) except WebSocketClosedError : self . _close ( ) | 5,699 | https://github.com/mivade/tornadose/blob/d220e0e3040d24c98997eee7a8a236602b4c5159/tornadose/handlers.py#L116-L124 | [
"def",
"setOverlayTexelAspect",
"(",
"self",
",",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTexelAspect",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
"return",
"result"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.