code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
env = copy.copy(os.environ)
try:
for mod in execution.get('modules') or []:
Module.load(mod)
os.environ.update(execution.get('environment') or {})
yield
finally:
os.environ = env | def _module_env(self, execution) | Set current process environment according
to execution `environment` and `modules` | 4.175234 | 3.390454 | 1.231468 |
for run_dirs in runs.values():
with open(JSON_METRICS_FILE, 'w') as ostr:
ostr.write('[\n')
for i in range(len(run_dirs)):
with open(osp.join(run_dirs[i], YAML_REPORT_FILE)) as istr:
data = yaml.safe_load(istr)
... | def gather_metrics(self, runs) | Write a JSON file with the result of every runs | 2.684121 | 2.580223 | 1.040267 |
for name, value in metrics.items():
metric = schema.get(name)
if not metric:
message = "Unexpected metric '{}' returned".format(name)
raise Exception(message)
cls._check_metric(schema, metric, name, value) | def _check_metrics(cls, schema, metrics) | Ensure that returned metrics are properly exposed | 3.559652 | 3.083913 | 1.154265 |
for item in obj.inputs:
if hasattr(obj, item):
# print(item)
setattr(obj, item, values[item]) | def add_inputs_to_object(obj, values) | A generic function to load object parameters based on a dictionary list.
:param obj: Object
:param values: Dictionary
:return: | 3.856122 | 4.471145 | 0.862446 |
load_soil_sample_data(sss.sp) # soil
load_foundation_sample_data(sss.fd) # foundation
load_structure_sample_data(sss.bd) # structure
load_hazard_sample_data(sss.hz) | def load_sample_data(sss) | Sample data for the SoilStructureSystem object
:param sss:
:return: | 5.562729 | 5.012841 | 1.109696 |
# soil
sp.g_mod = 60.0e6 # [Pa]
sp.phi = 30 # [degrees]
sp.relative_density = .40 # [decimal]
sp.gwl = 2. # [m], ground water level
sp.unit_dry_weight = 17000 # [N/m3]
sp.unit_sat_weight = 18000 # [N/m3]
sp.unit_weight_water = 9800 # [N/m3]
sp.cohesion = 10.0 # [Pa]
... | def load_soil_sample_data(sp) | Sample data for the Soil object
:param sp: Soil Object
:return: | 4.186157 | 4.164332 | 1.005241 |
# foundation
fd.width = 16.0 # m
fd.length = 18.0 # m
fd.depth = 0.0 # m
fd.mass = 0.0 | def load_foundation_sample_data(fd) | Sample data for the Foundation object
:param fd: Foundation Object
:return: | 4.272372 | 4.022162 | 1.062208 |
# structure
st.h_eff = 9.0 # m
st.mass_eff = 120e3 # kg
st.t_eff = 1.0 # s
st.mass_ratio = 1.0 | def load_structure_sample_data(st) | Sample data for the Structure object
:param st: Structure Object
:return: | 5.826765 | 6.663142 | 0.874477 |
# hazard
hz.z_factor = 0.3 # Hazard factor
hz.r_factor = 1.0 # Return period factor
hz.n_factor = 1.0 # Near-fault factor
hz.magnitude = 7.5 # Magnitude of earthquake
hz.corner_period = 4.0 # s
hz.corner_acc_factor = 0.55
return hz | def load_hazard_sample_data(hz) | Sample data for the Hazard object
:param hz: Hazard Object
:return: | 4.914461 | 4.865759 | 1.010009 |
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
bd.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
bd.floor_length = 18.0 # m
bd.floor_width = 16.0 # m
bd.storey_masses = masses * np.ones(number_of_storeys) | def load_building_sample_data(bd) | Sample data for the Building object
:param bd:
:return: | 3.320822 | 3.465595 | 0.958226 |
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
n_bays = 3
fb = models.BuildingFrame(number_of_storeys, n_bays)
fb.interstorey_heights = interstorey_height * np.ones(number_of_storeys)
fb.floor_length = 18.0 # m
fb.floor_width = 16.0 # m
fb.storey_ma... | def load_frame_building_sample_data() | Sample data for the BuildingFrame object
:return: | 2.911202 | 2.896573 | 1.00505 |
'''
生成随机的原始指纹列表
'''
fp_list = []
fp_list.append(get_random_ua()) # ua
fp_list.append('zh-CN') # language
fp_list.append('24') # color depth
fp_list.append(__get_random_screen_resolution())
fp_list.append('-480') # time zone offsite
fp_list.append('true') # session storag... | def _get_random_fp_raw() | 生成随机的原始指纹列表 | 6.383559 | 5.837391 | 1.093564 |
'''
生成fp_raw_str
'''
fp_file_path = os.path.expanduser('~/.xunleipy_fp')
fp_list = []
try:
with open(fp_file_path, 'r') as fp_file:
fp_str = fp_file.readline()
if len(fp_str) > 0:
fp_list = fp_str.split('###')
except IOError:
pass
... | def get_fp_raw() | 生成fp_raw_str | 2.673749 | 2.541604 | 1.051993 |
def _compose2(f, g): # pylint: disable=invalid-name
return lambda x: f(g(x))
return functools.reduce(_compose2, functions, lambda x: x) | def compose(*functions) | Define functions composition like f ∘ g ∘ h
:return: callable object that will perform
function composition of callables given in argument. | 3.332657 | 3.256594 | 1.023357 |
for item in iterator:
yield [item] + list(islice(iterator, size - 1)) | def chunks(iterator, size) | Split an iterator into chunks with `size` elements each.
Warning:
``size`` must be an actual iterator, if you pass this a
concrete sequence will get you repeating elements.
So ``chunks(iter(range(1000)), 10)`` is fine, but
``chunks(range(1000), 10)`` is not.
Example:
# si... | 4.032237 | 7.595917 | 0.530843 |
def _listify_return(func):
@functools.wraps(func)
def _listify_helper(*args, **kw):
return wrapper(func(*args, **kw))
return _listify_helper
if func is None:
return _listify_return
return _listify_return(func) | def listify(func=None, wrapper=list) | A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
... for i in iterable:
... yield... | 2.184647 | 2.41434 | 0.904863 |
for element in sequence:
match = re.match(pattern, element)
if match:
yield match.groupdict() | def match_subgroup(sequence, pattern) | Yield the sub-group element dictionary that match a regex pattern. | 4.11835 | 2.662471 | 1.546815 |
@wraps(pattern_function)
def func_wrapper(*args, **kwargs):
return r'^{}$'.format(pattern_function(*args, **kwargs))
return func_wrapper | def add_regex_start_end(pattern_function) | Decorator for adding regex pattern start and end characters. | 3.12202 | 2.66347 | 1.172163 |
mass = q * width * length / gravity
return mass | def convert_stress_to_mass(q, width, length, gravity) | Converts a foundation stress to an equivalent mass.
:param q: applied stress [Pa]
:param width: foundation width [m]
:param length: foundation length [m]
:param gravity: applied gravitational acceleration [m/s2]
:return: | 5.232216 | 19.046215 | 0.274712 |
if exceptions is None:
exceptions = []
for item in dictionary:
if item in exceptions:
continue
if dictionary[item] is not None:
if verbose:
print("process: ", item, dictionary[item])
key, value = get_key_value(dictionary[item], obj... | def add_to_obj(obj, dictionary, objs=None, exceptions=None, verbose=0) | Cycles through a dictionary and adds the key-value pairs to an object.
:param obj:
:param dictionary:
:param exceptions:
:param verbose:
:return: | 2.777138 | 3.049242 | 0.910763 |
interval = (upper_bound - lower_bound) / len(items)
quantiles = ((g, (x - interval, x)) for g, x in
zip(items, accumulate(repeat(interval, len(items)))))
return quantiles | def create_quantiles(items: Sequence, lower_bound, upper_bound) | Create quantile start and end boundaries. | 6.600283 | 5.290065 | 1.247675 |
if hasattr(element, '__iter__') and not isinstance(element, ignore_types):
return element
else:
return tuple((element,)) | def tupleize(element, ignore_types=(str, bytes)) | Cast a single element to a tuple. | 3.157242 | 2.333033 | 1.353278 |
return (dict(zip(fields, rec)) for rec in records) | def dictionize(fields: Sequence, records: Sequence) -> Generator | Create dictionaries mapping fields to record data. | 6.409733 | 4.054302 | 1.580971 |
value_keys = disjoint_union((cartesian_product((v, k))
for k, v in d.items()))
return dict(value_keys) | def flip_iterable_dict(d: dict) -> dict | Transform dictionary to unpack values to map to respective key. | 11.713132 | 10.153705 | 1.153582 |
accum = 0.0
for i in range(len(self.verts)):
j = (i + 1) % len(self.verts)
accum += (
self.verts[j][0] * self.verts[i][1] -
self.verts[i][0] * self.verts[j][1])
return accum / 2 | def get_signed_area(self) | Return area of a simple (ie. non-self-intersecting) polygon.
If verts wind anti-clockwise, this returns a negative number.
Assume y-axis points up. | 2.185715 | 1.927664 | 1.133867 |
all_results = []
for ext in self.next_extensions:
LOG.debug(" %s ", ext)
results = ext(*args, **kwargs)
LOG.debug(" %s => %s", ext, results)
if results is None:
LOG.warning("No result from: %s", ext)
continue
... | def call_next(self, *args, **kwargs) -> t.List[run.RunInfo] | Call all child extensions with the given arguments.
This calls all child extensions and collects the results for
our own parent. Use this to control the execution of your
nested extensions from your own extension.
Returns:
:obj:`list` of :obj:`RunInfo`: A list of collected
... | 2.857651 | 2.865688 | 0.997195 |
LOG.info("%s:: %s", indent * " ", self.__class__)
for ext in self.next_extensions:
ext.print(indent=indent + 2) | def print(self, indent=0) | Print a structural view of the registered extensions. | 6.251238 | 4.66494 | 1.340047 |
output = ""
for n, match in enumerate(matches):
matched_text = match[0][:40]+"..." if len(match[0]) > 40 else match[0]
search_result = match[1]
if search_result.uri==surf.ns.EFRBROO['F10_Person']:
label = unicode(search_result)[:40]+"..." if len(unicode(search_result)) >... | def print_results(matches) | :param matches: a list of tuples. | 3.684865 | 3.63147 | 1.014704 |
if resource.uri == surf.ns.EFRBROO['F10_Person']:
print("\n{} ({})\n".format(unicode(resource), resource.get_urn()))
works = resource.get_works()
print("Works by {} ({}):\n".format(resource, len(works)))
[show_result(work) for work in works]
print("\n")
elif resource... | def show_result(resource, verbose=False) | TODO | 3.786067 | 3.759873 | 1.006967 |
arguments = docopt(__doc__)
cfg_filename = pkg_resources.resource_filename(
'knowledge_base',
'config/virtuoso.ini'
)
kb = KnowledgeBase(cfg_filename)
# the user has issued a `find` command
if arguments["find"]:
search_string = arguments["<search_string>"]
t... | def main() | Define the CLI inteface/commands. | 4.656655 | 4.592124 | 1.014053 |
ret = None
def call_or_cache(*args, **kwargs):
nonlocal ret
if ret is None:
ret = func(*args, **kwargs)
return ret
return call_or_cache | def cached(func) | Memoize a function result. | 2.758714 | 2.606159 | 1.058536 |
try:
tmp_hash_path = container.filename + ".hash"
with open(tmp_hash_path, 'r') as tmp_file:
tmp_hash = tmp_file.readline()
except IOError:
LOG.info("No .hash-file in the tmp-directory.")
container_hash_path = local.path(path) / "gentoo.tar.bz2.hash"
if containe... | def is_valid(container, path) | Checks if a container exists and is unpacked.
Args:
path: The location where the container is expected.
Returns:
True if the container is valid, False if the container needs to
unpacked or if the path does not exist yet. | 3.439248 | 3.620098 | 0.950043 |
from benchbuild.utils.run import run
from benchbuild.utils.uchroot import no_args
path = local.path(path)
c_filename = local.path(container.filename)
name = c_filename.basename
if not path.exists():
path.mkdir()
with local.cwd(path):
Wget(container.remote, name)
... | def unpack(container, path) | Unpack a container usable by uchroot.
Method that checks if a directory for the container exists,
checks if erlent support is needed and then unpacks the
container accordingly.
Args:
path: The location where the container is, that needs to be unpacked. | 6.04997 | 5.753817 | 1.051471 |
assert self.name in CFG["container"]["images"].value
tmp_dir = local.path(str(CFG["tmp_dir"]))
target_dir = tmp_dir / self.name
if not target_dir.exists() or not is_valid(self, target_dir):
unpack(self, target_dir)
return target_dir | def local(self) | Finds the current location of a container.
Also unpacks the project if necessary.
Returns:
target: The path, where the container lies in the end. | 7.118658 | 6.80304 | 1.046394 |
try:
src_uri = (curl[Gentoo._LATEST_TXT] | tail["-n", "+3"]
| cut["-f1", "-d "])().strip()
except ProcessExecutionError as proc_ex:
src_uri = "NOT-FOUND"
LOG.error("Could not determine latest stage3 src uri: %s",
s... | def src_file(self) | Get the latest src_uri for a stage 3 tarball.
Returns (str):
Latest src_uri from gentoo's distfiles mirror. | 12.201915 | 8.081669 | 1.509826 |
try:
_version = (curl[Gentoo._LATEST_TXT] | \
awk['NR==2{print}'] | \
cut["-f2", "-d="])().strip()
_version = datetime.utcfromtimestamp(int(_version))\
.strftime("%Y-%m-%d")
except ProcessExecutionError as proc_ex:
... | def version(self) | Return the build date of the gentoo container. | 9.562205 | 7.998713 | 1.195468 |
arguments = cli_common(__doc__, argv=argv)
csv_export = CSVExporter(arguments['CAMPAIGN-DIR'], arguments['--output'])
if arguments['--peek']:
csv_export.peek()
else:
fieldsstr = arguments.get('--fields')
fields = fieldsstr.split(',') if fieldsstr else None
csv_export... | def main(argv=None) | ben-csv entry point | 6.222667 | 5.588302 | 1.113517 |
if index is False: # Convert time values into indices
if end != -1:
e_index = int(end / dt) + 1
else:
e_index = end
s_index = int(start / dt)
else:
s_index = start
e_index = end
if e_index > npts:
raise exceptions.ModelWarning("Cu... | def time_indices(npts, dt, start, end, index) | Determine the new start and end indices of the time series.
:param npts: Number of points in original time series
:param dt: Time step of original time series
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if Fal... | 4.382531 | 3.928309 | 1.115628 |
s_index, e_index = time_indices(self.npts, self.dt, start, end, index)
self._values = np.array(self.values[s_index:e_index]) | def cut(self, start=0, end=-1, index=False) | The method cuts the time series to reduce its length.
:param start: int or float, optional, New start point
:param end: int or float, optional, New end point
:param index: bool, optional, if False then start and end are considered values in time. | 5.130454 | 5.245944 | 0.977985 |
output = subprocess.check_output(
[SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)]
)
end = output.strip().decode()
return end not in {'Unknown', ''} | def finished(cls, jobid) | Check whether a SLURM job is finished or not | 8.736587 | 6.810839 | 1.282748 |
from benchbuild.utils.db import create_run_group
from datetime import datetime
group, session = create_run_group(project)
group.begin = datetime.now()
group.status = 'running'
session.commit()
return group, session | def begin_run_group(project) | Begin a run_group in the database.
A run_group groups a set of runs for a given project. This models a series
of runs that form a complete binary runtime test.
Args:
project: The project we begin a new run_group for.
Returns:
``(group, session)`` where group is the created group in th... | 4.841106 | 4.252589 | 1.13839 |
from datetime import datetime
group.end = datetime.now()
group.status = 'completed'
session.commit() | def end_run_group(group, session) | End the run_group successfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish. | 5.400593 | 6.22512 | 0.867548 |
from datetime import datetime
group.end = datetime.now()
group.status = 'failed'
session.commit() | def fail_run_group(group, session) | End the run_group unsuccessfully.
Args:
group: The run_group we want to complete.
session: The database transaction we will finish. | 5.38183 | 6.297592 | 0.854585 |
assert run_infos is not None
if not hasattr(run_infos, "__iter__"):
return run_infos.retcode
rcs = [ri.retcode for ri in run_infos]
max_rc = max(rcs)
min_rc = min(rcs)
if max_rc == 0:
return min_rc
return max_rc | def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int | Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description] | 2.738929 | 2.834535 | 0.966271 |
runner = RunInfo(cmd=cmd, project=project, experiment=experiment, **kwargs)
yield runner
runner.commit() | def track_execution(cmd, project, experiment, **kwargs) | Guard the execution of the given command.
The given command (`cmd`) will be executed inside a database context.
As soon as you leave the context we will commit the transaction.
Any necessary modifications to the database can be identified inside
the context with the RunInfo object.
Args:
c... | 5.884346 | 4.929255 | 1.193759 |
from plumbum.commands.base import BoundCommand, BoundEnvCommand
if isinstance(cmd, BoundCommand):
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
elif isinstance(cmd, BoundEnvCommand):
cmd.envvars.update(envvars)
cmd.cmd = with_env_recursive(cmd.cmd, **envvars)
return cmd | def with_env_recursive(cmd, **envvars) | Recursively updates the environment of cmd and all its subcommands.
Args:
cmd - A plumbum command-like object
**envvars - The environment variables to update
Returns:
The updated command. | 2.528467 | 2.519386 | 1.003605 |
from functools import wraps
def wrap_in_builddir(func):
@wraps(func)
def wrap_in_builddir_func(self, *args, **kwargs):
p = local.path(self.builddir) / sub
if not p.exists():
LOG.error("%s does not exist.", p)
if p ... | def in_builddir(sub='.') | Decorate a project phase with a local working directory change.
Args:
sub: An optional subdirectory to change into. | 2.834208 | 2.715948 | 1.043543 |
from functools import wraps
@wraps(func)
def wrap_store_config(self, *args, **kwargs):
CFG.store(local.path(self.builddir) / ".benchbuild.yml")
return func(self, *args, **kwargs)
return wrap_store_config | def store_config(func) | Decorator for storing the configuration in the project's builddir. | 4.965743 | 3.852998 | 1.2888 |
container_in = local.path(builddir) / "container-in"
container_out = local.path(builddir) / "container-out"
if in_dir and container_in.exists():
if ui.ask("Should I delete '{0}'?".format(container_in)):
container_in.delete()
if out_dir and container_out.exists():
if ui.... | def clean_directories(builddir, in_dir=True, out_dir=True) | Remove the in and out of the container if confirmed by the user. | 2.330759 | 2.03287 | 1.146536 |
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
out_dir = build_dir / "container-out"
if not in_dir.exists():
in_dir.mkdir()
if not out_dir.exists():
out_dir.mkdir() | def setup_directories(builddir) | Create the in and out directories of the container. | 2.321293 | 1.95981 | 1.184448 |
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
container_path = local.path(_container)
with local.cwd(builddir):
container_bin = container_path.basename
container_in = in_dir / container_bin
download.Copy(_container, container_in)
uchrt = uchroo... | def setup_container(builddir, _container) | Prepare the container and returns the path where it can be found. | 6.208381 | 6.105928 | 1.016779 |
container_p = local.path(container_dir)
with local.cwd(container_p):
uchrt = uchroot.with_mounts()
uchrt = uchrt["-E", "-A", "-u", "0", "-g", "0", "-C", "-w", "/", "-r",
container_p]
uchrt = uchrt["--"]
cmd_path = container_p / command[0].lstrip('/')
... | def run_in_container(command, container_dir) | Run a given command inside a container.
Mounts a directory as a container at the given mountpoint and tries to run
the given command inside the new container. | 5.622909 | 5.446734 | 1.032345 |
container_filename = local.path(out_file).basename
out_container = local.cwd / "container-out" / container_filename
out_dir = out_container.dirname
# Pack the results to: container-out
with local.cwd(in_container):
tar("cjf", out_container, ".")
c_hash = download.update_hash(out_co... | def pack_container(in_container, out_file) | Pack a container image into a .tar.bz2 archive.
Args:
in_container (str): Path string to the container image.
out_file (str): Output file name. | 5.513821 | 6.071767 | 0.908108 |
with local.cwd(builddir):
# Switch to bash inside uchroot
print("Entering bash inside User-Chroot. Prepare your image and "
"type 'exit' when you are done. If bash exits with a non-zero"
"exit code, no new container will be stored.")
store_new_container = Tru... | def setup_bash_in_container(builddir, _container, outfile, shell) | Setup a bash environment inside a container.
Creates a new chroot, which the user can use as a bash to run the wanted
projects inside the mounted container, that also gets returned afterwards. | 7.043407 | 7.330242 | 0.96087 |
if not _container:
return False
if _container.exists():
cfg["container"]["input"] = str(_container)
return True
return False | def set_input_container(_container, cfg) | Save the input for the container in the configurations. | 4.887948 | 4.286342 | 1.140354 |
# Don't do something when running non-interactive.
if not sys.stdout.isatty():
return
with local.cwd(context.in_container):
from benchbuild.projects.gentoo import gentoo
gentoo.setup_networking()
gentoo.configure_portage()
se... | def run(self, context) | Setup a gentoo container suitable for PolyJIT. | 5.510997 | 5.155818 | 1.068889 |
p = local.path(_container)
if set_input_container(p, CFG):
return
p = find_hash(CFG["container"]["known"].value, container)
if set_input_container(p, CFG):
return
raise ValueError("The path '{0}' does not exist.".format(p)) | def input_file(self, _container) | Find the input path of a uchroot container. | 10.828153 | 9.292893 | 1.165208 |
p = local.path(_container)
if p.exists():
if not ui.ask("Path '{0}' already exists."
" Overwrite?".format(p)):
sys.exit(0)
CFG["container"]["output"] = str(p) | def output_file(self, _container) | Find and writes the output path of a chroot container. | 8.049999 | 7.261792 | 1.108542 |
if incs is None:
incs = np.ones(sp.n_layers) * target
dd = {}
dd["thickness"] = []
dd["unit_mass"] = []
dd["shear_vel"] = []
cum_thickness = 0
for i in range(sp.n_layers):
sl = sp.layer(i + 1)
thickness = sp.layer_height(i + 1)
n_slices = max(int(thickne... | def discretize_soil_profile(sp, incs=None, target=1.0) | Splits the soil profile into slices and stores as dictionary
:param sp: SoilProfile
:param incs: array_like, increments of depth to use for each layer
:param target: target depth increment size
:return: dict | 2.976306 | 2.942756 | 1.011401 |
if not hasattr(self, item):
raise KeyError("Soil Object does not have property: %s", item)
try:
setattr(self, item, value) # try to set using normal setter method
return []
except ModelError:
pass # if inconsistency, then need to rebuild... | def override(self, item, value) | Can set a parameter to a value that is inconsistent with existing values.
This method sets the inconsistent value and then reapplies all existing values
that are still consistent, all non-consistent (conflicting) values are removed from the object
and returned as a list
:param item: na... | 5.481024 | 5.123868 | 1.069704 |
for item in self.inputs:
setattr(self, "_%s" % item, None)
self.stack = [] | def reset_all(self) | Resets all parameters to None | 7.074537 | 6.732436 | 1.050814 |
p_value = (item, value)
if p_value not in self.stack:
self.stack.append(p_value) | def _add_to_stack(self, item, value) | Add a parameter-value pair to the stack of parameters that have been set.
:param item:
:param value:
:return: | 3.702129 | 3.779033 | 0.97965 |
try:
if saturated:
return np.sqrt(self.g_mod / self.unit_sat_mass)
else:
return np.sqrt(self.g_mod / self.unit_dry_mass)
except TypeError:
return None | def get_shear_vel(self, saturated) | Calculate the shear wave velocity
:param saturated: bool, if true then use saturated mass
:return: | 3.830392 | 4.196991 | 0.912652 |
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_v... | def saturation(self, value) | Volume of water to volume of voids | 4.248176 | 4.133379 | 1.027773 |
value = clean_float(value)
if value is None:
return
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_tol=self._tolerance):
raise ModelError("specific gravity is inconsistent w... | def specific_gravity(self, value) | Set the relative weight of the solid | 5.92527 | 6.174914 | 0.959571 |
self._layers[depth] = soil
self._sort_layers()
if self.hydrostatic:
if depth >= self.gwl:
soil.saturation = 1.0
else:
li = self.get_layer_index_by_depth(depth)
layer_height = self.layer_height(li)
i... | def add_layer(self, depth, soil) | Adds a soil to the SoilProfile at a set depth.
Note, the soils are automatically reordered based on depth from surface.
:param depth: depth from surface to top of soil layer
:param soil: Soil object | 3.079791 | 2.975635 | 1.035003 |
self._layers = OrderedDict(sorted(self._layers.items(), key=lambda t: t[0])) | def _sort_layers(self) | Sort the layers by depth. | 3.259686 | 2.522344 | 1.292324 |
if layer_int == self.n_layers:
if self.height is None:
return None
return self.height - self.layer_depth(layer_int)
else:
return self.layer_depth(layer_int + 1) - self.layer_depth(layer_int) | def layer_height(self, layer_int) | Get the layer height by layer id number.
:param layer_int:
:return: float, height of the soil layer | 2.627342 | 3.161368 | 0.831077 |
deprecation("Will be moved to a function")
if len(self.layers) > 1:
crust = self.layer(0)
crust_phi_r = np.radians(crust.phi)
equivalent_cohesion = crust.cohesion + crust.k_0 * self.crust_effective_unit_weight * \
... | def equivalent_crust_cohesion(self) | Calculate the equivalent crust cohesion strength according to Karamitros et al. 2013 sett, pg 8 eq. 14
:return: equivalent cohesion [Pa] | 6.443659 | 6.4367 | 1.001081 |
if not hasattr(z, "__len__"):
return self.one_vertical_total_stress(z)
else:
sigma_v_effs = []
for value in z:
sigma_v_effs.append(self.one_vertical_total_stress(value))
return np.array(sigma_v_effs) | def get_v_total_stress_at_depth(self, z) | Determine the vertical total stress at depth z, where z can be a number or an array of numbers. | 3.37616 | 3.021764 | 1.117281 |
total_stress = 0.0
depths = self.depths
end = 0
for layer_int in range(1, len(depths) + 1):
l_index = layer_int - 1
if z_c > depths[layer_int - 1]:
if l_index < len(depths) - 1 and z_c > depths[l_index + 1]:
height = de... | def one_vertical_total_stress(self, z_c) | Determine the vertical total stress at a single depth z_c.
:param z_c: depth from surface | 2.557346 | 2.60015 | 0.983538 |
sigma_v_c = self.get_v_total_stress_at_depth(y_c)
pp = self.get_hydrostatic_pressure_at_depth(y_c)
sigma_veff_c = sigma_v_c - pp
return sigma_veff_c | def get_v_eff_stress_at_depth(self, y_c) | Determine the vertical effective stress at a single depth z_c.
:param y_c: float, depth from surface | 3.289057 | 4.048522 | 0.812409 |
sl = self.get_soil_at_depth(y_c)
if y_c <= self.gwl:
saturation = False
else:
saturation = True
if hasattr(sl, "get_shear_vel_at_v_eff_stress"):
v_eff = self.get_v_eff_stress_at_depth(y_c)
vs = sl.get_shear_vel_at_v_eff_stress(v_ef... | def shear_vel_at_depth(self, y_c) | Get the shear wave velocity at a depth.
:param y_c: float, depth from surface
:return: | 3.319508 | 3.517854 | 0.943617 |
package = os.path.split(root)[-1]
text = format_heading(1, '%s Package' % package)
# add each package's module
for py_file in py_files:
if shall_skip(os.path.join(root, py_file)):
continue
is_package = py_file == INIT
py_file = os.path.splitext(py_file)[0]
... | def create_package_file(root, master_package, subroot, py_files, opts, subs) | Build the text of the file and write the file. | 3.30108 | 3.257165 | 1.013482 |
text = format_heading(1, '%s Modules' % opts.header)
text += '.. toctree::\n'
text += ' :maxdepth: %s\n\n' % opts.maxdepth
modules.sort()
prev_module = ''
for module in modules:
# look if the module is a subpackage and, if yes, ignore it
if module.startswith(prev_module +... | def create_modules_toc_file(master_package, modules, opts, name='modules') | Create the module's index. | 3.170241 | 3.204339 | 0.989359 |
# use absolute path for root, as relative paths like '../../foo' cause
# 'if "/." in root ...' to filter out *all* modules otherwise
path = os.path.abspath(path)
# check if the base directory is a package and get is name
if INIT in os.listdir(path):
package_name = path.split(os.path.sep... | def recurse_tree(path, excludes, opts) | Look for every file in the directory tree and create the corresponding
ReST files. | 4.575338 | 4.490182 | 1.018965 |
sep = os.path.sep
f_excludes = []
for exclude in excludes:
if not os.path.isabs(exclude) and not exclude.startswith(rootpath):
exclude = os.path.join(rootpath, exclude)
if not exclude.endswith(sep):
exclude += sep
f_excludes.append(exclude)
return f_e... | def normalize_excludes(rootpath, excludes) | Normalize the excluded directory list:
* must be either an absolute path or start with rootpath,
* otherwise it is joined with rootpath
* with trailing slash | 2.084037 | 1.850739 | 1.126056 |
sep = os.path.sep
if not root.endswith(sep):
root += sep
for exclude in excludes:
if root.startswith(exclude):
return True
return False | def is_excluded(root, excludes) | Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar". | 2.429419 | 2.387824 | 1.01742 |
parser = optparse.OptionParser(usage=)
parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project")
parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="")
pars... | def main() | Parse and check the command line arguments. | 2.562101 | 2.539006 | 1.009096 |
if not isinstance(self.ref, str):
return None
u = parse_app_url(self.ref)
if u.inner.proto != 'file':
return None
return u.path | def path(self) | Return the path to the file, if the ref is a file | 9.318617 | 6.968381 | 1.337271 |
from os.path import abspath
if not self.ref:
return None
u = parse_app_url(self.ref)
return abspath(dirname(u.path)) | def doc_dir(self) | The absolute directory of the document | 8.136663 | 7.335341 | 1.109241 |
try:
self.terms.remove(t)
except ValueError:
pass
if t.section and t.parent_term_lc == 'root':
t.section = self.add_section(t.section)
t.section.remove_term(t, remove_from_doc=False)
if t.parent:
try:
... | def remove_term(self, t) | Only removes top-level terms. Child terms can be removed at the parent. | 4.397368 | 4.130855 | 1.064518 |
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
# Set the default arguments
s = self.sections[name.lower()]
if name.lower() in self.decl_sections:
s.args = self.decl_sections[name.lower()]['args']
return s | def new_section(self, name, params=None) | Return a new section | 5.460084 | 5.535436 | 0.986387 |
if name not in self.sections:
self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self)
return self.sections[name.lower()] | def get_or_new_section(self, name, params=None) | Create a new section or return an existing one of the same name | 5.615391 | 5.331985 | 1.053152 |
order_lc = [e.lower() for e in order]
sections = OrderedDict( (k,self.sections[k]) for k in order_lc if k in self.sections)
sections.update( (k,self.sections[k]) for k in self.sections.keys() if k not in order_lc)
assert len(self.sections) == len(sections)
self.sect... | def sort_sections(self, order) | Sort sections according to the section names in the order list. All remaining sections
are added to the end in their original order
:param order: Iterable of section names
:return: | 2.880108 | 2.859246 | 1.007297 |
import itertools
if kwargs: # Look for terms with particular property values
terms = self.find(term, value, section)
found_terms = []
for t in terms:
if all(t.get_value(k) == v for k, v in kwargs.items()):
found_terms... | def find(self, term, value=False, section=None, _expand_derived=True, **kwargs) | Return a list of terms, possibly in a particular section. Use joined term notation, such as 'Root.Name' The kwargs arg is used to set term properties, all of which match returned terms, so ``name='foobar'`` will match terms that have a ``name`` property of ``foobar``
:param term: The type of term to find, in f... | 3.695072 | 3.555188 | 1.039347 |
v = self.find_first(term)
if not v:
return default
else:
return v | def get(self, term, default=None) | Return the first term, returning the default if no term is found | 7.105355 | 5.756777 | 1.234259 |
term = self.find_first(term, value=False, section=section)
if term is None:
return default
else:
return term.value | def get_value(self, term, default=None, section=None) | Return the first value, returning the default if no term is found | 5.013362 | 3.992427 | 1.255718 |
#if self.root and len(self.root.children) > 0:
# raise MetatabError("Can't run after adding terms to document.")
for t in terms:
t.doc = self
if t.term_is('root.root'):
if not self.root:
self.root = t
... | def load_terms(self, terms) | Create a builder from a sequence of terms, usually a TermInterpreter | 5.022797 | 5.096908 | 0.98546 |
from .util import slugify
self.ensure_identifier()
try:
self.update_name()
except MetatabError:
identifier = self['Root'].find_first('Root.Identifier')
name = self['Root'].find_first('Root.Name')
if name and name.value:
... | def cleanse(self) | Clean up some terms, like ensuring that the name is a slug | 4.754647 | 4.117592 | 1.154715 |
updates = []
self.ensure_identifier()
name_term = self.find_first('Root.Name')
if not name_term:
if create_term:
name_term = self['Root'].new_term('Root.Name','')
else:
updates.append("No Root.Name, can't update name")
... | def update_name(self, force=False, create_term=False, report_unchanged=True) | Generate the Root.Name term from DatasetName, Version, Origin, TIme and Space | 4.571904 | 4.107003 | 1.113197 |
# This function is a hack, due to confusion between the root of the document, which
# should contain all terms, and the root section, which has only terms that are not
# in another section. So, here we are taking the Root section, and adding all of the other
# terms to it, as i... | def as_dict(self, replace_value_names=True) | Iterate, link terms and convert to a dict | 7.951903 | 7.533302 | 1.055567 |
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield [''] # Unecessary, but makes for nice formatting. Should actually be done just before write
yield ['Section', s.value] + s.property_names
... | def rows(self) | Iterate over all of the rows | 10.292772 | 9.703498 | 1.060728 |
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield s
# Yield all of the rows for terms in the section
for rterm in s:
yield rterm
for d in rterm.descendents:
... | def all_terms(self) | Iterate over all of the terms. The self.terms property has only root level terms. This iterator
iterates over all terms | 7.537142 | 7.089008 | 1.063215 |
from io import StringIO
s = StringIO()
w = csv.writer(s)
for row in self.rows:
w.writerow(row)
return s.getvalue() | def as_csv(self) | Return a CSV representation as a string | 3.14867 | 2.704575 | 1.164201 |
out_lines = []
for t,v in self.lines:
# Make the output prettier
if t == 'Section':
out_lines.append('')
out_lines.append('{}: {}'.format(t,v if v is not None else '') )
return '\n'.join(out_lines) | def as_lines(self) | Return a Lines representation as a string | 5.639085 | 5.17573 | 1.089525 |
def _get_volume_keyword_op_and_remaining_subtree(right_subtree):
if isinstance(right_subtree, NotOp) and isinstance(right_subtree.op, KeywordOp) \
and right_subtree.op.left == Keyword('volume'):
return None, None
elif isinstance(right_subtree, AndOp) and isinstance(... | def _restructure_if_volume_follows_journal(left, right) | Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement): The restructured tree, with the volume node removed.
Note... | 2.275142 | 2.09711 | 1.084894 |
def _create_operator_node(value_node):
base_node = value_node.op if isinstance(value_node, NotOp) else value_node
updated_base_node = KeywordOp(keyword, base_node) if keyword else ValueOp(base_node)
return NotOp(updated_base_node) if isinstance(value_node, NotOp) else updated... | def _convert_simple_value_boolean_query_to_and_boolean_queries(tree, keyword) | Chain SimpleValueBooleanQuery values into chained AndOp queries with the given current Keyword. | 3.051887 | 2.794939 | 1.091933 |
left = node.left.accept(self)
right = node.right.accept(self)
is_journal_keyword_op = isinstance(left, KeywordOp) and left.left == Keyword('journal')
if is_journal_keyword_op:
journal_and_volume_conjunction = _restructure_if_volume_follows_journal(left, right)
... | def visit_boolean_query(self, node) | Convert BooleanRule into AndOp or OrOp nodes. | 4.500579 | 4.018643 | 1.119925 |
node.left, node.right = node.left.accept(self), node.right.accept(self)
return node | def visit_simple_value_boolean_query(self, node) | Visits only the children of :class:`SimpleValueBooleanQuery` without substituting the actual node type.
Notes:
Defer conversion from :class:`SimpleValueBooleanQuery` to AndOp or OrOp.
This transformation needs to occur higher in the tree, so that we don't lose the information that this ... | 3.221361 | 3.806013 | 0.846387 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.