code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# delay values is normal 2.99 us with NONE actual MCP delay settings # 1000 is used to convert eV to meV time_s = np.sqrt(81.787 / (array * 1000.)) * source_to_detector_m / 3956. time_record_s = time_s - offset_us * 1e-6 return time_record_s
def ev_to_s(offset_us, source_to_detector_m, array)
convert energy (eV) to time (us) Parameters: =========== array: array (in eV) offset_us: float. Delay of detector in us source_to_detector_m: float. Distance source to detector in m Returns: ======== time: array in s
11.310583
12.356693
0.915341
lambda_a = 3956. * (array + offset_us * 1e-6) / source_to_detector_m return (81.787 / pow(lambda_a, 2)) / 1000.
def s_to_ev(offset_us, source_to_detector_m, array)
convert time (s) to energy (eV) Parameters: =========== numpy array of time in s offset_us: float. Delay of detector in us source_to_detector_m: float. Distance source to detector in m Returns: ======== numpy array of energy in eV
6.20944
7.614726
0.815452
# delay values is normal 2.99 us with NONE actual MCP delay settings time_tot_us = np.sqrt(81.787 / (array * 1000)) * source_to_detector_m * 100 / 0.3956 time_record_us = (time_tot_us + offset_us) image_number = (time_record_us - t_start_us) / time_resolution_us return image_number
def ev_to_image_number(offset_us, source_to_detector_m, time_resolution_us, t_start_us, array)
convert energy (eV) to image numbers (#) Parameters: =========== numpy array of energy in eV offset_us: float. Delay of detector in us source_to_detector_m: float. Distance source to detector in m Returns: ======== image numbers: array of image number
8.617455
10.280573
0.838227
tmp_folder = tempfile.mkdtemp() git.Repo.clone_from( url, tmp_folder, branch=branch ) if commit: git_cmd = git.Git(tmp_folder) git_cmd.checkout(commit) yield tmp_folder shutil.rmtree(tmp_folder)
def temp_repo(url, branch, commit='')
Clone a git repository inside a temporary folder, yield the folder then delete the folder. :param string url: url of the repo to clone. :param string branch: name of the branch to checkout to. :param string commit: Optional commit rev to checkout to. If mentioned, that take over the branch :return: yie...
2.294132
2.32448
0.986944
if not os.path.exists(destination): raise RuntimeError( 'The code could not be moved to {destination} ' 'because the folder does not exist'.format(destination=destination)) destination_folder = os.path.join(destination, os.path.split(source)[-1]) if os.path.exists(dest...
def force_move(source, destination)
Force the move of the source inside the destination even if the destination has already a folder with the name inside. In the case, the folder will be replaced. :param string source: path of the source to move. :param string destination: path of the folder to move the source to.
2.592412
2.920149
0.887767
logger.debug("command: %s", command) # avoid usage of shell = True # see https://docs.openstack.org/bandit/latest/plugins/subprocess_popen_with_shell_equals_true.html process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, cwd=folder) stream_data = process.communicate()[0] logge...
def _run_command_inside_folder(command, folder)
Run a command inside the given folder. :param string command: the command to execute. :param string folder: the folder where to execute the command. :return: the return code of the process. :rtype: Tuple[int, str]
3.870197
4.188934
0.92391
# the url has to be a unicode by pystache's design, but the unicode concept has been rewamped in py3 # we use a try except to make the code compatible with py2 and py3 try: url = unicode(url) except NameError: url = url parsed = pystache.parse(url) # pylint: disable=protect...
def parse_url(url)
Parse the given url and update it with environment value if required. :param basestring url: :rtype: basestring :raise: KeyError if environment variable is needed but not found.
7.487553
7.344177
1.019522
logger.info( "Installing %s@%s to %s", self.repo, self.commit if self.commit else self.branch, destination ) with temp_repo(self.repo, self.branch, self.commit) as tmp: self._apply_patches(tmp) self._move_modules(tmp, destination)
def install(self, destination)
Install a third party odoo add-on :param string destination: the folder where the add-on should end up at.
4.526897
5.081962
0.890777
folders = self._get_module_folders(temp_repo) for folder in folders: force_move(folder, destination)
def _move_modules(self, temp_repo, destination)
Move modules froom the temp directory to the destination. :param string temp_repo: the folder containing the code. :param string destination: the folder where the add-on should end up at.
5.392171
6.157473
0.875712
paths = ( os.path.join(temp_repo, path) for path in os.listdir(temp_repo) if self._is_module_included(path) ) return (path for path in paths if os.path.isdir(path))
def _get_module_folders(self, temp_repo)
Get a list of module paths contained in a temp directory. :param string temp_repo: the folder containing the modules.
3.021244
3.406864
0.886811
if module in self.exclude_modules: return False if self.include_modules is None: return True return module in self.include_modules
def _is_module_included(self, module)
Evaluate if the module must be included in the Odoo addons. :param string module: the name of the module :rtype: bool
3.237231
3.616319
0.895173
tmp_addons = os.path.join(temp_repo, 'addons') tmp_odoo_addons = os.path.join(temp_repo, 'odoo/addons') folders = self._get_module_folders(tmp_addons) for folder in folders: force_move(folder, tmp_odoo_addons) tmp_odoo = os.path.join(temp_repo, 'odoo') ...
def _move_modules(self, temp_repo, destination)
Move odoo modules from the temp directory to the destination. This step is different from a standard repository. In the base code of Odoo, the modules are contained in a addons folder at the root of the git repository. However, when deploying the application, those modules are placed in...
2.711217
2.300587
1.178489
logger.info("Apply Patch %s@%s (commit %s)", self.url, self.branch, self.commit) remote_name = 'patch' commands = [ "git remote add {} {}".format(remote_name, self.url), "git fetch {} {}".format(remote_name, self.branch), 'git merge {} -m "patch"'.for...
def apply(self, folder)
Merge code from the given repo url to the git repo contained in the given folder. :param string folder: path of the folder where is the git repo cloned at. :raise: RuntimeError if the patch could not be applied.
2.980068
2.840685
1.049067
logger.info("Apply Patch File %s", self.file_path) command = "git apply {}".format(self.file_path) return_code, stream_data = _run_command_inside_folder(command, folder) if return_code: msg = "Could not apply patch file at {}. Error: {}".format(self.file_path, strea...
def apply(self, folder)
Apply a patch from a git patch file. :param string folder: path of the folder where is the git repo cloned at. :raise: RuntimeError if the patch could not be applied.
3.304136
3.075735
1.074259
cls.context = AttributeDict() cls.context.new_meta = {} cls.context.new_transitions = {} cls.context.new_methods = {}
def _set_up_context(cls)
Create context to keep all needed variables in.
6.461946
5.067577
1.275155
states_enum_name = cls.context.get_config('states_enum_name') try: cls.context['states_enum'] = getattr( cls.context.new_class, states_enum_name) except AttributeError: raise ValueError('No states enum given!') proper = True try: ...
def _check_states_enum(cls)
Check if states enum exists and is proper one.
4.672112
4.155644
1.124281
for item in list(cls.context.states_enum): if not isinstance(item.value, six.string_types): raise ValueError( 'Item {name} is not string. Only strings are allowed.' .format(name=item.name) )
def _check_if_states_are_strings(cls)
Check if all states are strings.
5.097726
4.445954
1.146599
state_value = cls.context.get_config('initial_state', None) state_value = state_value or getattr( cls.context.new_class, cls.context.state_name, None ) if not state_value: raise ValueError( "Empty state is disallowed, yet no initial state...
def _check_state_value(cls)
Check initial state value - if is proper and translate it. Initial state is required.
5.708922
5.08869
1.121884
setattr( cls.context.new_class, cls.context.new_meta['state_attribute_name'], cls.context.state_value) setattr( cls.context.new_class, cls.context.state_name, utils.state_property) setattr(cls.context.new_class, 'i...
def _add_standard_attributes(cls)
Add attributes common to all state machines. These are methods for setting and checking state etc.
3.727612
3.677883
1.013521
allowed_transitions = cls.context.get_config('transitions', {}) for key, transitions in allowed_transitions.items(): key = cls.context.new_meta['translator'].translate(key) new_transitions = set() for trans in transitions: if not isinstance(t...
def _generate_standard_transitions(cls)
Generate methods used for transitions.
3.096899
2.957957
1.046972
for state in cls.context.states_enum: getter_name = 'is_{name}'.format(name=state.value) cls.context.new_methods[getter_name] = utils.generate_getter(state) setter_name = 'set_{name}'.format(name=state.value) cls.context.new_methods[setter_name] = utils....
def _generate_standard_methods(cls)
Generate standard setters, getters and checkers.
2.585742
2.354799
1.098074
for name, method in cls.context.new_methods.items(): if hasattr(cls.context.new_class, name): raise ValueError( "Name collision in state machine class - '{name}'." .format(name) ) setattr(cls.context.new_cl...
def _add_new_methods(cls)
Add all generated methods to result class.
4.623815
4.307966
1.073317
get_config = cls.context.get_config complete = get_config('complete', None) if complete is None: conditions = [ get_config('transitions', False), get_config('named_transitions', False), ] complete = not any(conditions) ...
def _set_complete_option(cls)
Check and set complete option.
5.624747
4.960707
1.13386
package_directory = os.path.abspath(os.path.dirname(__file__)) return os.path.join(package_directory, "data")
def data_directory()
Return the absolute path to the directory containing the package data.
2.640867
2.222987
1.187981
matches = filterMapAttrs(**tags) if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags) if name: # if name is specified, consider only the best-matching names only matches = filterMapNames(name, excludeRegex=excludeName, closestMatch=closestMatch...
def selectMap(name=None, excludeName=False, closestMatch=True, **tags)
select a map by name and/or critiera
10.349517
10.1895
1.015704
if len(tags) == 0: return records # otherwise if unspecified, all given records match ret = [] for record in records: # attempt to match attributes if matchRecordAttrs(record, tags): ret.append(record) return ret
def filterMapAttrs(records=getIndex(), **tags)
matches available maps if their attributes match as specified
7.191784
6.492127
1.10777
for k,v in iteritems(attrs): try: val = getattr(mapobj, k) except AttributeError: # k isn't an attr of record if bool(v): return False # if k doesn't exist in mapobj but was required, no match else: continue # otherwise ignore attributes that aren't de...
def matchRecordAttrs(mapobj, attrs)
attempt to match given attributes against a single map object's attributes
8.033989
7.621594
1.054109
bestScr = 99999 # a big enough number to not be a valid file system path regex = re.compile(regexText, flags=re.IGNORECASE) ret = [] if excludeRegex: # match only records that do NOT contain regex if regexText and closestMatch: # then maps with fewer characters are better matches ...
def filterMapNames(regexText, records=getIndex(), excludeRegex=False, closestMatch=True)
matches each record against regexText according to parameters NOTE: the code could be written more simply, but this is loop-optimized to scale better with a large number of map records
3.213021
3.227958
0.995372
if isinstance(value, bool): return value elif isinstance(value, int): return value != 0 elif isinstance(value, Decimal): return value != Decimal(0) elif isinstance(value, str): value = value.lower() if value == 'true': return True elif val...
def to_boolean(value, ctx)
Tries conversion of any value to a boolean
1.978243
1.930874
1.024532
if isinstance(value, bool): return 1 if value else 0 elif isinstance(value, int): return value elif isinstance(value, Decimal): try: val = int(value.to_integral_exact(ROUND_HALF_UP)) if isinstance(val, int): return val except Arith...
def to_integer(value, ctx)
Tries conversion of any value to an integer
2.226514
2.153897
1.033714
if isinstance(value, bool): return Decimal(1) if value else Decimal(0) elif isinstance(value, int): return Decimal(value) elif isinstance(value, Decimal): return value elif isinstance(value, str): try: return Decimal(value) except Exception: ...
def to_decimal(value, ctx)
Tries conversion of any value to a decimal
2.113486
2.020397
1.046075
if isinstance(value, bool): return "TRUE" if value else "FALSE" elif isinstance(value, int): return str(value) elif isinstance(value, Decimal): return format_decimal(value) elif isinstance(value, str): return value elif type(value) == datetime.date: retur...
def to_string(value, ctx)
Tries conversion of any value to a string
2.237155
2.195651
1.018903
if isinstance(value, str): temporal = ctx.get_date_parser().auto(value) if temporal is not None: return to_date(temporal, ctx) elif type(value) == datetime.date: return value elif isinstance(value, datetime.datetime): return value.date() # discard time ...
def to_date(value, ctx)
Tries conversion of any value to a date
3.965479
3.723809
1.064899
if isinstance(value, str): temporal = ctx.get_date_parser().auto(value) if temporal is not None: return to_datetime(temporal, ctx) elif type(value) == datetime.date: return ctx.timezone.localize(datetime.datetime.combine(value, datetime.time(0, 0))) elif isinstance(v...
def to_datetime(value, ctx)
Tries conversion of any value to a datetime
3.057815
2.934128
1.042154
if isinstance(value, str): temporal = ctx.get_date_parser().auto(value) if temporal is not None: return temporal elif type(value) == datetime.date: return value elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone) raise Evalua...
def to_date_or_datetime(value, ctx)
Tries conversion of any value to a date or datetime
3.683021
3.494844
1.053844
if isinstance(value, str): time = ctx.get_date_parser().time(value) if time is not None: return time elif isinstance(value, datetime.time): return value elif isinstance(value, datetime.datetime): return value.astimezone(ctx.timezone).time() raise Evaluat...
def to_time(value, ctx)
Tries conversion of any value to a time
3.046733
2.941195
1.035883
if type(value1) == type(value2): return value1, value2 try: # try converting to two decimals return to_decimal(value1, ctx), to_decimal(value2, ctx) except EvaluationError: pass try: # try converting to two dates d1, d2 = to_date_or_datetime(value1,...
def to_same(value1, value2, ctx)
Converts a pair of arguments to their most-likely types. This deviates from Excel which doesn't auto convert values but is necessary for us to intuitively handle contact fields which don't use the correct value type
2.239867
2.202077
1.017161
as_string = to_string(value, ctx) if isinstance(value, str) or isinstance(value, datetime.date) or isinstance(value, datetime.time): as_string = as_string.replace('"', '""') # escape quotes by doubling as_string = '"%s"' % as_string return as_string
def to_repr(value, ctx)
Converts a value back to its representation form, e.g. x -> "x"
3.15392
2.98101
1.058004
# strip trailing fractional zeros normalized = decimal.normalize() sign, digits, exponent = normalized.as_tuple() if exponent >= 1: normalized = normalized.quantize(1) return str(normalized)
def format_decimal(decimal)
Formats a decimal number :param decimal: the decimal value :return: the formatted string value
4.968981
5.796274
0.857272
''' Check if I am running inside a Linux container. ''' try: cginfo = Path('/proc/self/cgroup').read_text() if '/docker/' in cginfo or '/lxc/' in cginfo: return True except IOError: return False
def is_containerized() -> bool
Check if I am running inside a Linux container.
6.144392
3.915882
1.569096
''' Detect the cloud provider where I am running on. ''' # NOTE: Contributions are welcome! # Please add other cloud providers such as Rackspace, IBM BlueMix, etc. if sys.platform.startswith('linux'): # Google Cloud Platform or Amazon AWS (hvm) try: # AWS Nitro-based ...
def detect_cloud() -> str
Detect the cloud provider where I am running on.
5.878565
5.464198
1.075833
''' Add block definition to list of blocks in material Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise), material name (string if root, False otherwise), material type, dictionary of attributes or False if n...
def addBlock(self,branch=None,btype=None,mtype=None,attributes=None)
Add block definition to list of blocks in material Order for list entry: branch level (0=root), block type (material,solid,fluid,etc.), matid (integer if root, False otherwise), material name (string if root, False otherwise), material type, dictionary of attributes or False if none
8.276178
1.913919
4.324205
# FFT of field fshape = len(field.shape) assert fshape in [1, 2], "Dimension of `field` must be 1 or 2." func = fft_propagate names = func.__code__.co_varnames[:func.__code__.co_argcount] loc = locals() vardict = dict() for name in names: if name in loc: vardi...
def refocus(field, d, nm, res, method="helmholtz", num_cpus=1, padding=True)
Refocus a 1D or 2D field Parameters ---------- field : 1d or 2d array 1D or 2D background corrected electric field (Ex/BEx) d : float Distance to be propagated in pixels (negative for backwards) nm : float Refractive index of medium res : float Wavelenth in pixe...
3.72386
3.933559
0.94669
func = refocus names = func.__code__.co_varnames[:func.__code__.co_argcount] loc = locals() vardict = dict() for name in names: if name in loc.keys(): vardict[name] = loc[name] # default keyword arguments func_def = func.__defaults__[::-1] # child processes sh...
def refocus_stack(fieldstack, d, nm, res, method="helmholtz", num_cpus=_cpu_count, copy=True, padding=True)
Refocus a stack of 1D or 2D fields Parameters ---------- fieldstack : 2d or 3d array Stack of 1D or 2D background corrected electric fields (Ex/BEx). The first axis iterates through the individual fields. d : float Distance to be propagated in pixels (negative for backwards) ...
3.15993
3.405847
0.927796
fshape = len(fftfield.shape) assert fshape in [1, 2], "Dimension of `fftfield` must be 1 or 2." if fshape == 1: func = fft_propagate_2d else: func = fft_propagate_3d names = func.__code__.co_varnames[:func.__code__.co_argcount] loc = locals() vardict = dict() for ...
def fft_propagate(fftfield, d, nm, res, method="helmholtz", ret_fft=False)
Propagates a 1D or 2D Fourier transformed field Parameters ---------- fftfield : 1-dimensional or 2-dimensional ndarray Fourier transform of 1D Electric field component d : float Distance to be propagated in pixels (negative for backwards) nm : float Refractive index of med...
2.719031
3.021601
0.899864
assert len(fftfield.shape) == 1, "Dimension of `fftfield` must be 1." km = (2 * np.pi * nm) / res kx = np.fft.fftfreq(len(fftfield)) * 2 * np.pi # free space propagator is if method == "helmholtz": # exp(i*sqrt(km²-kx²)*d) # Also subtract incoming plane wave. We are only consid...
def fft_propagate_2d(fftfield, d, nm, res, method="helmholtz", ret_fft=False)
Propagate a 1D Fourier transformed field in 2D Parameters ---------- fftfield : 1d array Fourier transform of 1D Electric field component d : float Distance to be propagated in pixels (negative for backwards) nm : float Refractive index of medium res : float Wa...
4.429964
4.10374
1.079494
assert len(fftfield.shape) == 2, "Dimension of `fftfield` must be 2." # if fftfield.shape[0] != fftfield.shape[1]: # raise NotImplementedError("Field must be square shaped.") # free space propagator is # exp(i*sqrt(km**2-kx**2-ky**2)*d) km = (2 * np.pi * nm) / res kx = (np.fft.fftfre...
def fft_propagate_3d(fftfield, d, nm, res, method="helmholtz", ret_fft=False)
Propagate a 2D Fourier transformed field in 3D Parameters ---------- fftfield : 2d array Fourier transform of 2D Electric field component d : float Distance to be propagated in pixels (negative for backwards) nm : float Refractive index of medium res : float Wa...
3.273702
3.124656
1.0477
if not self.canRunRemoteCmd(): return None try: fetchInfo = self.repo.remotes.origin.push(no_thin=True)[0] except exc.GitCommandError as e: print(dir(e)) print(e) raise if fetchInfo.flags & fetchInfo.ERROR: ...
def push(self)
Adding the no_thin argument to the GIT push because we had some issues pushing previously. According to http://stackoverflow.com/questions/16586642/git-unpack-error-on-push-to-gerrit#comment42953435_23610917, "a new optimization which causes git to send as little data as possible over the network caus...
6.137762
4.953919
1.238971
if metric == "average gradient": def metric_func(x): return metrics.average_gradient(np.abs(x)) elif metric == "rms contrast": def metric_func(x): return -metrics.contrast_rms(np.angle(x)) elif metric == "spectrum": def metric_func(x): return metrics.spectral(np.abs(x), res) ...
def autofocus(field, nm, res, ival, roi=None, metric="average gradient", padding=True, ret_d=False, ret_grad=False, num_cpus=1)
Numerical autofocusing of a field using the Helmholtz equation. Parameters ---------- field : 1d or 2d ndarray Electric field is BG-Corrected, i.e. field = EX/BEx nm : float Refractive index of medium. res : float Size of wavelength in pixels. ival : tuple of floats ...
2.4924
2.277063
1.094568
dopt = list() grad = list() M = fieldstack.shape[0] # setup arguments stackargs = list() for s in range(M): stackargs.append([fieldstack[s].copy(copy), nm, res, ival, roi, metric, padding, True, True, 1]) # perform first pass p = mp.Pool(num_cpus)...
def autofocus_stack(fieldstack, nm, res, ival, roi=None, metric="average gradient", padding=True, same_dist=False, ret_ds=False, ret_grads=False, num_cpus=_cpu_count, copy=True)
Numerical autofocusing of a stack using the Helmholtz equation. Parameters ---------- fieldstack : 2d or 3d ndarray Electric field is BG-Corrected, i.e. Field = EX/BEx nm : float Refractive index of medium. res : float Size of wavelength in pixels. ival : tuple of float...
2.918133
2.966445
0.983714
# Get Various Lists / Project Waivers lists = get_lists.GetLists() # Get file name black list and project waivers file_audit_list, file_audit_project_list = lists.file_audit_list(project) # Get file content black list and project waivers flag_list, ignore_list = lists.file_content_list(p...
def prepare_project(project, project_dir, binaries, ips, urls)
Generates blacklists / whitelists
3.932648
3.886605
1.011847
logger.info('Found what I believe is an IP Address: %s', line.strip()) logger.info('File %s. Parsed IP Address: %s', split_path, ipaddr) with open(reports_dir + "ips-" + project + ".log", "a") as gate_report: gate_report.write('File {} contains what I believe is an IP Address: {}\n'.format(spli...
def scan_ipaddr(ipaddr, line, project, split_path, apikey)
If an IP Address is found, scan it
3.260847
3.197883
1.019689
logger.info('File %s contains what I believe is a URL: %s', split_path, line.strip()) logger.info('Scanning: %s', url) with open(reports_dir + "urls-" + project + ".log", "a") as gate_report: gate_report.write('File {} contains what I believe is a URL: {}\n'.format(split_path, url)) v_api ...
def scan_url(url, line, project, split_path, apikey)
If URL is found, scan it
3.050731
3.010893
1.013231
try: return cache.structure except AttributeError: pass # if it doesn't exist, generate and cache the map file data if folderPath == None: from sc2maptool.startup import setup folderPath = setup() ############################################################################ de...
def getIndex(folderPath=None)
parse the 'Maps' subfolder directory divining criteria for valid maps
5.660498
5.373878
1.053336
''' Stringify a number, preventing unwanted scientific notations. ''' if isinstance(v, (float, Decimal)): if math.isinf(v) and v > 0: v = 'Infinity' elif math.isinf(v) and v < 0: v = '-Infinity' else: v = '{:f}'.format(v) elif isinstance(v,...
def _stringify_number(v)
Stringify a number, preventing unwanted scientific notations.
2.6191
2.116983
1.237185
''' Resolve the tag using etcd so that the current instance indicates a concrete, latest image. Note that alias resolving does not take the registry component into account. ''' alias_target = None repeats = 0 while repeats < 8: prev_al...
async def resolve_alias(cls, alias_key: str, etcd: etcd.AsyncEtcd)
Resolve the tag using etcd so that the current instance indicates a concrete, latest image. Note that alias resolving does not take the registry component into account.
7.016469
3.233884
2.169672
fileName = os.path.join(os.path.dirname(__file__), "ontoCategories.bin") if not alwaysFetch: try: with open(fileName, "rb") as catFile: ontoCat = pickle.load(catFile) if curie in ontoCat: return ontoCat[curie] ...
def getOntoCategory(curie, alwaysFetch=False)
Accessing web-based ontology service is too long, so we cache the information in a pickle file and query the services only if the info has not already been cached.
2.843008
2.757161
1.031136
LOG.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s - %(name)s - ' '%(levelname)s - %(message)s') ch.setFormatter(formatter) ch.setLevel(logging.DEBUG) # create the directory if it does not exist path = ...
def _init_logging(anteater_log)
Setup root logger for package
1.688089
1.678453
1.005741
try: os.makedirs(reports_dir) logger.info('Creating reports directory: %s', reports_dir) except OSError as e: if e.errno != errno.EEXIST: raise
def check_dir()
Creates a directory for scan reports
2.669462
2.496861
1.069127
_init_logging(config.get('config', 'anteater_log')) check_dir() arguments = docopt(__doc__, version=__version__) if arguments['<patchset>']: prepare_patchset(arguments['<project>'], arguments['<patchset>'], arguments['--binaries'], arguments['--ips'], arguments['--...
def main()
Main function, mostly for passing arguments
4.133591
4.08909
1.010883
kwargs = dict(kwargs) kwargs['model_code'] = model_code if 'n_jobs' not in kwargs: kwargs['n_jobs'] = -1 if model_code in FIT_CACHE: print("Reusing model.") kwargs['fit'] = FIT_CACHE[model_code] else: print("NOT reusing model.") start = time.time() FIT_CA...
def fit(model_code, *args, **kwargs)
Fit a Stan model. Caches the compiled model. *args and **kwargs are passed to the pystan.stan function. Arguments you most likely want to pass: data, init, iter, chains. Unlike pystan.stan, if the n_jobs kwarg is not specified, it defaults to -1. Parameters ------------------- mo...
2.680133
2.700088
0.992609
def feeder(process): self.enum(other, rmax, process, bunch) for r, i, j in makeiter(feeder): yield r, i, j
def enumiter(self, other, rmax, bunch=100000)
cross correlate with other, for all pairs closer than rmax, iterate. for r, i, j in A.enumiter(...): ... where r is the distance, i and j are the original input array index of the data. This uses a thread to convert from KDNode.enum.
9.613967
8.705378
1.104371
rall = None if process is None: rall = [numpy.empty(0, 'f8')] iall = [numpy.empty(0, 'intp')] jall = [numpy.empty(0, 'intp')] def process(r1, i1, j1, **kwargs): rall[0] = numpy.append(rall[0], r1) iall[0] = numpy.ap...
def enum(self, other, rmax, process=None, bunch=100000, **kwargs)
cross correlate with other, for all pairs closer than rmax, iterate. >>> def process(r, i, j, **kwargs): >>> ... >>> A.enum(... process, **kwargs): >>> ... where r is the distance, i and j are the original input array index of t...
2.372769
2.550971
0.930144
r = numpy.array(r, dtype='f8') return _core.KDNode.count(self, other, r, attrs, info=info)
def count(self, other, r, attrs=None, info={})
Gray & Moore based fast dual tree counting. r is the edge of bins: -inf or r[i-1] < count[i] <= r[i] attrs: None or tuple if tuple, attrs = (attr_self, attr_other) Returns: count, count, weight of attrs is not None
7.925901
8.948357
0.885738
if out is None: out = numpy.empty(self.size, dtype='intp') return _core.KDNode.fof(self, linkinglength, out, method)
def fof(self, linkinglength, out=None, method='splay')
Friend-of-Friend clustering with linking length. Returns: the label
5.358139
7.366888
0.727327
if numpy.isscalar(min): min = [min for i in range(self.ndims)] if numpy.isscalar(max): max = [max for i in range(self.ndims)] min = numpy.array(min, dtype='f8', order='C') max = numpy.array(max, dtype='f8', order='C') if (min).shape[-1] != self....
def integrate(self, min, max, attr=None, info={})
Calculate the total number of points between [min, max). If attr is given, also calculate the sum of the weight. This is a M log(N) operation, where M is the number of min/max queries and N is number of points.
2.532722
2.606403
0.971731
heap = [] heappush(heap, (-self.size, self)) while True: w, x = heappop(heap) if w == 0: heappush(heap, (0, x)) break if x.less is None \ or (x.size < chunksize): heappush(heap, (0, x)) ...
def make_forest(self, chunksize)
Divide a tree branch to a forest, each subtree of size at most chunksize
3.306694
3.201435
1.032879
patches = patches or [] patches = [ core.FilePatch(file=patch['file'], work_directory=work_directory) if 'file' in patch else core.Patch(**patch) for patch in patches ] addon_cls = core.Base if base else core.Addon addon = addon_cls( repo_url, branch, commit=comm...
def _install_one( repo_url, branch, destination, commit='', patches=None, exclude_modules=None, include_modules=None, base=False, work_directory='' )
Install a third party odoo add-on :param string repo_url: url of the repo that contains the patch. :param string branch: name of the branch to checkout. :param string destination: the folder where the add-on should end up at. :param string commit: Optional commit rev to checkout to. If mentioned, that ...
3.033962
3.882256
0.781495
dir_path = os.path.dirname(os.path.realpath(__file__)) destination = destination or os.path.join(dir_path, '..', '3rd') conf_file = conf_file or os.path.join(dir_path, '..', "third_party_addons.yaml") work_directory = os.path.dirname(os.path.realpath(conf_file)) with open(conf_file, "r") as co...
def _install_all(destination='', conf_file='')
Use the conf file to list all the third party Odoo add-ons that will be installed and the patches that should be applied. :param string destination: the folder where add-ons should end up at. Default: pwd/3rd :param string conf_file: path to a conf file that describe the add-...
2.647696
2.370943
1.116727
i = bisect.bisect_left(a, x) if i: return a[i-1] raise ValueError
def find_lt(a, x)
Find rightmost value less than x
2.229193
2.608203
0.854685
if os.path.isdir(isatab_ref): fnames = glob.glob(os.path.join(isatab_ref, "i_*.txt")) + \ glob.glob(os.path.join(isatab_ref, "*.idf.txt")) assert len(fnames) == 1 isatab_ref = fnames[0] assert os.path.exists(isatab_ref), "Did not find investigation file: %s" % isata...
def parse(isatab_ref)
Entry point to parse an ISA-Tab directory. isatab_ref can point to a directory of ISA-Tab data, in which case we search for the investigator file, or be a reference to the high level investigation file.
2.716977
2.593731
1.047517
had_info = False keyvals, section = self._parse_keyvals(line_iter) if keyvals: rec.metadata = keyvals[0] while section and section[0] != "STUDY": had_info = True keyvals, next_section = self._parse_keyvals(line_iter) attr_name = s...
def _parse_region(self, rec, line_iter)
Parse a section of an ISA-Tab, assigning information to a supplied record.
3.993483
3.653986
1.092911
reader = csv.reader(in_handle, dialect="excel-tab") for line in reader: if len(line) > 0 and line[0]: # check for section headers; all uppercase and a single value if line[0].upper() == line[0] and "".join(line[1:]) == "": line = [...
def _line_iter(self, in_handle)
Read tab delimited file, handling ISA-Tab special case headers.
4.615853
4.41083
1.046482
out = None line = None for line in line_iter: if len(line) == 1 and line[0].upper() == line[0]: break else: # setup output dictionaries, trimming off blank columns if out is None: while not line[...
def _parse_keyvals(self, line_iter)
Generate dictionary from key/value pairs.
4.254227
4.161188
1.022359
final_studies = [] for study in rec.studies: source_data = self._parse_study(study.metadata["Study File Name"], ["Source Name", "Sample Name", "Comment[ENA_SAMPLE]"]) if source_data: study.nodes = source_data ...
def parse(self, rec)
Retrieve row data from files associated with the ISATabRecord.
4.558005
4.228578
1.077905
if not os.path.exists(os.path.join(self._dir, fname)): return None nodes = {} with open(os.path.join(self._dir, fname), "rU") as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") header = self._swap_synonyms(next(reader)) hgro...
def _parse_study(self, fname, node_types)
Parse study or assay row oriented file around the supplied base node.
3.983008
3.868946
1.029481
final = {} for key, val in iter(node.metadata.items()): #val = list(val) #if isinstance(val[0], tuple): # val = [dict(v) for v in val] final[key] = list(val) node.metadata = final return node
def _finalize_metadata(self, node)
Convert node metadata back into a standard dictionary and list.
3.430573
2.938555
1.167436
for index, htype in ((i, t) for i, t in enumerate(htypes) if t == want_type): col = hgroups[index][0] key = header[col]#self._clean_header(header[col]) if collapse_quals_fn: val = collapse_quals_fn(line, header, hgroups[index]) else: ...
def _line_by_type(self, line, header, hgroups, htypes, out, want_type, collapse_quals_fn = None)
Parse out key value pairs for line information based on a group of values.
2.96562
2.897459
1.023524
names = [] vals = [] pat = re.compile("[\W]+") for i in indexes: names.append(pat.sub("_", self._clean_header(header[i]))) vals.append(line[i]) Attrs = collections.namedtuple('Attrs', names) return Attrs(*vals)
def _collapse_attributes(self, line, header, indexes)
Combine attributes in multiple columns into single named tuple.
3.545137
2.850212
1.243815
if header.find("[") >= 0: header = header.replace("]", "").split("[")[-1] # ISATab can start with numbers but this is not supported in # the python datastructure, so prefix with isa_ to make legal try: int(header[0]) header = "isa_" + header ...
def _clean_header(self, header)
Remove ISA-Tab specific information from Header[real name] headers.
8.237202
7.034198
1.171022
out = [] for h in [header[g[0]] for g in hgroups]: this_ctype = None for ctype, names in self._col_types.items(): if h.startswith(names): this_ctype = ctype break out.append(this_ctype) return ou...
def _characterize_header(self, header, hgroups)
Characterize header groups into different data types.
3.830404
3.560736
1.075734
out = [] for i, h in enumerate(header): if h.startswith(self._col_quals): out[-1].append(i) else: out.append([i]) return out
def _collapse_header(self, header)
Combine header columns into related groups.
4.228898
3.839712
1.101358
specifiedMaps = filterMapNames( options.mapname, records = filterMapAttrs(**params), excludeRegex=options.exclude, closestMatch=options.best ) if specifiedMaps: for v in specifiedMaps: if options.details: v.display() ...
def main(): # mini/unit test options = optionsParser().parse_args() params = getSelectionParams(options) if options.list or options.details
PURPOSE: command-line interface for map information
5.036536
5.0473
0.997867
abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".pickle", ".pk", ".p"]: is_pickle = True elif ext == ".gz": is_pickle = False elif ext == ".tmp": return is_pickle_file(fname) else: raise PickleExtError( "'%s' is not a ...
def is_pickle_file(abspath)
Parse file extension. - *.pickle: uncompressed, utf-8 encode pickle file - *.gz: compressed, utf-8 encode pickle file
3.319988
3.189132
1.041032
if default is None: default = dict() prt("\nLoad from '%s' ..." % abspath, enable_verbose) abspath = lower_ext(str(abspath)) is_pickle = is_pickle_file(abspath) if not os.path.exists(abspath): prt(" File not found, use default value: %r" % default, enable_verbo...
def load(abspath, default=None, enable_verbose=True)
Load Pickle from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle). :type abspath: string :param default: default ``dict()``, if ``abspath`` not exists, return the ...
4.30156
3.852573
1.116542
prt("\nDump to '%s' ..." % abspath, enable_verbose) abspath = lower_ext(str(abspath)) is_pickle = is_pickle_file(abspath) if os.path.exists(abspath): if not overwrite: # 存在, 并且overwrite=False prt(" Stop! File exists and overwrite is not allowed", enable_ver...
def dump(data, abspath, pk_protocol=py23.pk_protocol, overwrite=False, enable_verbose=True)
Dump picklable object to file. Provides multiple choice to customize the behavior. :param data: picklable python object. :type data: dict or list :param abspath: ``save as`` path, file extension has to be ``.pickle`` or ``.gz`` (for compressed Pickle) :type abspath: string :param pk_p...
4.573081
4.478717
1.02107
abspath = lower_ext(str(abspath)) abspath_temp = "%s.tmp" % abspath dump(data, abspath_temp, pk_protocol=pk_protocol, enable_verbose=enable_verbose) shutil.move(abspath_temp, abspath)
def safe_dump(data, abspath, pk_protocol=py23.pk_protocol, enable_verbose=True)
A stable version of :func:`dump`, this method will silently overwrite existing file. There's a issue with :func:`dump`: If your program is interrupted while writing, you got an incomplete file, and you also lose the original file. So this method write pickle to a temporary file first, then rename...
3.196672
3.735508
0.855753
return pickle.dumps(obj, protocol=pk_protocol)
def obj2bytes(obj, pk_protocol=py23.pk_protocol)
Convert arbitrary pickable Python Object to bytes. **中文文档** 将可Pickle化的Python对象转化为bytestr
3.482614
10.165203
0.342601
return base64.urlsafe_b64encode(pickle.dumps( obj, protocol=pk_protocol)).decode("utf-8")
def obj2str(obj, pk_protocol=py23.pk_protocol)
Convert arbitrary object to base64 encoded string. **中文文档** 将可Pickle化的Python对象转化为utf-8编码的 ``纯ASCII字符串``
2.654146
3.493039
0.759839
if numpy.isscalar(weight): return numpy.bincount(dig, minlength=minlength) * weight else: return numpy.bincount(dig, weight, minlength)
def bincount(dig, weight, minlength)
bincount supporting scalar and vector weight
2.604488
2.416874
1.077627
for command in settings.RESTART_NETWORK: try: subprocess.check_call(command) except: pass print(message)
def reset_network(message)
Resets the users network to make changes take effect
5.825942
6.982071
0.834414
with open(settings.HOSTS_FILE, "r+") as hosts_file: contents = hosts_file.read() if not settings.START_TOKEN in contents and not settings.END_TOKEN in contents: hosts_file.write(settings.START_TOKEN + "\n") for site in set(settings.DISTRACTORS): hosts_fil...
def improve()
Disables access to websites that are defined as 'distractors
3.640349
3.371107
1.079868
changed = False with open(settings.HOSTS_FILE, "r") as hosts_file: new_file = [] in_block = False for line in hosts_file: if in_block: if line.strip() == settings.END_TOKEN: in_block = False changed = True ...
def lose()
Enables access to websites that are defined as 'distractors
3.041474
3.218599
0.944968
print("") print("######################################### ARE YOU SURE? #####################################") try: for remaining in range(60, -1, -1): sys.stdout.write("\r") sys.stdout.write("{:2d} seconds to change your mind. Won't you prefer programming? Or a book?"...
def take_break(minutes: hug.types.number=5)
Enables temporarily breaking concentration
5.067918
4.863879
1.04195
if self._local_port_range is None: with open('/proc/sys/net/ipv4/ip_local_port_range', 'r') as f: self._local_port_range = tuple(map(int, f.read().split('\t'))) return self._local_port_range
def local_port_range(self)
Tuple of (low_port, high_port) reflecting the local port range assigned to outbound connections. We use this as part of a heuristic to determine whether a connection is inbound or outbound.
1.988745
1.925688
1.032745
prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] while number > 1024: number /= 1024.0 prefixes.pop(0) return '%0.2f%s' % (number, prefixes.pop(0))
def _si(number)
Format a number using base-2 SI prefixes
2.020355
1.929721
1.046968
try: data = HTTP_SESSION.get(url, stream=True) data.raise_for_status() except requests.exceptions.RequestException as exc: raise FetcherException(exc) return data
def _get_url(url)
Retrieve requested URL
3.824843
3.794852
1.007903
zip_fp.extract(info.filename, path=path) out_path = os.path.join(path, info.filename) perm = info.external_attr >> 16 perm |= stat.S_IREAD # make sure we're not accidentally setting this to 0 os.chmod(out_path, perm)
def _extract_file(zip_fp, info, path)
Extract files while explicitly setting the proper permissions
3.377757
3.038492
1.111656
return (('-ccov' if self.coverage else '') + ('-fuzzing' if self.fuzzing else '') + ('-asan' if self.asan else '') + ('-valgrind' if self.valgrind else '') + ('-debug' if self.debug else '-opt'))
def build_string(self)
Taskcluster denotes builds in one of two formats - i.e. linux64-asan or linux64-asan-opt The latter is generated. If it fails, the caller should try the former.
4.406742
3.827599
1.151307
# if the platform is not native, auto_name would clobber native downloads. # make a prefix to avoid this native_system = std_platform.system() native_machine = self.CPU_ALIASES.get(std_platform.machine(), std_platform.machine()) if native_system == self.system and native...
def auto_name_prefix(self)
Generate platform prefix for cross-platform downloads.
5.734879
4.991002
1.149044