_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q11500 | MagICMenu.on_import1 | train | def on_import1(self, event):
"""
initialize window to import an arbitrary file into the working directory
"""
pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD) | python | {
"resource": ""
} |
q11501 | MagICMenu.orient_import2 | train | def orient_import2(self, event):
"""
initialize window to import an AzDip format file into the working directory
"""
pmag_menu_dialogs.ImportAzDipFile(self.parent, self.parent.WD) | python | {
"resource": ""
} |
q11502 | _UTMLetterDesignator | train | def _UTMLetterDesignator(Lat):
"""
This routine determines the correct UTM letter designator for the given latitude
returns 'Z' if latitude is outside the UTM limits of 84N to 80S
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= Lat >= 72: return 'X'
... | python | {
"resource": ""
} |
q11503 | MainFrame.highlight_problems | train | def highlight_problems(self, has_problems):
"""
Outline grid buttons in red if they have validation errors
"""
if has_problems:
self.validation_mode = set(has_problems)
# highlighting doesn't work with Windows
if sys.platform in ['win32', 'win62']:
... | python | {
"resource": ""
} |
q11504 | MainFrame.reset_highlights | train | def reset_highlights(self):
"""
Remove red outlines from all buttons
"""
for dtype in ["specimens", "samples", "sites", "locations", "ages"]:
wind = self.FindWindowByName(dtype + '_btn')
wind.Unbind(wx.EVT_PAINT, handler=self.highlight_button)
self.Refresh... | python | {
"resource": ""
} |
q11505 | MainFrame.highlight_button | train | def highlight_button(self, event):
"""
Draw a red highlight line around the event object
"""
wind = event.GetEventObject()
pos = wind.GetPosition()
size = wind.GetSize()
try:
dc = wx.PaintDC(self)
except wx._core.PyAssertionError:
#... | python | {
"resource": ""
} |
q11506 | MagICMenu.on_close_grid | train | def on_close_grid(self, event):
"""
If there is an open grid, save its data and close it.
"""
if self.parent.grid_frame:
self.parent.grid_frame.onSave(None)
self.parent.grid_frame.Destroy() | python | {
"resource": ""
} |
q11507 | main | train | def main():
"""
NAME
dipole_plat.py
DESCRIPTION
gives paleolatitude from given inclination, assuming GAD field
SYNTAX
dipole_plat.py [command line options]<filename
OPTIONS
-h prints help message and quits
-i allows interactive entry of latitude
-... | python | {
"resource": ""
} |
q11508 | main | train | def main():
"""
NAME
pmag_results_extract.py
DESCRIPTION
make a tab delimited output file from pmag_results table
SYNTAX
pmag_results_extract.py [command line options]
OPTIONS
-h prints help message and quits
-f RFILE, specify pmag_results table; default ... | python | {
"resource": ""
} |
q11509 | main | train | def main():
"""
NAME
grab_magic_key.py
DESCRIPTION
picks out key and saves to file
SYNTAX
grab_magic_key.py [command line optins]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-key KEY: specify key to print to sta... | python | {
"resource": ""
} |
q11510 | main | train | def main():
"""
NAME
plot_2cdfs.py
DESCRIPTION
makes plots of cdfs of data in input file
SYNTAX
plot_2cdfs.py [-h][command line options]
OPTIONS
-h prints help message and quits
-f FILE1 FILE2
-t TITLE
-fmt [svg,eps,png,pdf,jpg..] specify f... | python | {
"resource": ""
} |
q11511 | main | train | def main():
"""
NAME
reorder_samples.py
DESCRIPTION
takes specimen file and reorders sample file with selected orientation methods placed first
SYNTAX
reorder_samples.py [command line options]
OPTIONS
-h prints help message and quits
-fsp: specimen input pm... | python | {
"resource": ""
} |
q11512 | get_intensity_col | train | def get_intensity_col(data):
"""
Check measurement dataframe for intensity columns 'magn_moment', 'magn_volume', 'magn_mass','magn_uncal'.
Return the first intensity column that is in the dataframe AND has data.
Parameters
----------
data : pandas DataFrame
Returns
---------
str
... | python | {
"resource": ""
} |
q11513 | prep_for_intensity_plot | train | def prep_for_intensity_plot(data, meth_code, dropna=(), reqd_cols=()):
"""
Strip down measurement data to what is needed for an intensity plot.
Find the column with intensity data.
Drop empty columns, and make sure required columns are present.
Keep only records with the specified method code.
... | python | {
"resource": ""
} |
q11514 | Contribution.add_empty_magic_table | train | def add_empty_magic_table(self, dtype, col_names=None, groups=None):
"""
Add a blank MagicDataFrame to the contribution.
You can provide either a list of column names,
or a list of column group names.
If provided, col_names takes precedence.
"""
if dtype not in se... | python | {
"resource": ""
} |
q11515 | Contribution.add_magic_table_from_data | train | def add_magic_table_from_data(self, dtype, data):
"""
Add a MagIC table to the contribution from a data list
Parameters
----------
dtype : str
MagIC table type, i.e. 'specimens'
data : list of dicts
data list with format [{'key1': 'val1', ...}, {'... | python | {
"resource": ""
} |
q11516 | Contribution.add_magic_table | train | def add_magic_table(self, dtype, fname=None, df=None):
"""
Read in a new file to add a table to self.tables.
Requires dtype argument and EITHER filename or df.
Parameters
----------
dtype : str
MagIC table name (plural, i.e. 'specimens')
fname : str
... | python | {
"resource": ""
} |
q11517 | Contribution.propagate_measurement_info | train | def propagate_measurement_info(self):
"""
Take a contribution with a measurement table.
Create specimen, sample, site, and location tables
using the unique names in the measurement table to fill in
the index.
"""
meas_df = self.tables['measurements'].df
na... | python | {
"resource": ""
} |
q11518 | Contribution.get_parent_and_child | train | def get_parent_and_child(self, table_name):
"""
Get the name of the parent table and the child table
for a given MagIC table name.
Parameters
----------
table_name : string of MagIC table name ['specimens', 'samples', 'sites', 'locations']
Returns
------... | python | {
"resource": ""
} |
q11519 | Contribution.propagate_cols_up | train | def propagate_cols_up(self, cols, target_df_name, source_df_name):
"""
Take values from source table, compile them into a colon-delimited list,
and apply them to the target table.
This method won't overwrite values in the target table, it will only
supply values where they are mi... | python | {
"resource": ""
} |
q11520 | Contribution.propagate_ages | train | def propagate_ages(self):
"""
Mine ages table for any age data, and write it into
specimens, samples, sites, locations tables.
Do not overwrite existing age data.
"""
# if there is no age table, skip
if 'ages' not in self.tables:
return
# if ag... | python | {
"resource": ""
} |
q11521 | Contribution.remove_non_magic_cols | train | def remove_non_magic_cols(self):
"""
Remove all non-MagIC columns from all tables.
"""
for table_name in self.tables:
table = self.tables[table_name]
table.remove_non_magic_cols_from_table() | python | {
"resource": ""
} |
q11522 | Contribution.write_table_to_file | train | def write_table_to_file(self, dtype, custom_name=None, append=False, dir_path=None):
"""
Write out a MagIC table to file, using custom filename
as specified in self.filenames.
Parameters
----------
dtype : str
magic table name
"""
if custom_na... | python | {
"resource": ""
} |
q11523 | Contribution.find_missing_items | train | def find_missing_items(self, dtype):
"""
Find any items that are referenced in a child table
but are missing in their own table.
For example, a site that is listed in the samples table,
but has no entry in the sites table.
Parameters
----------
dtype : st... | python | {
"resource": ""
} |
q11524 | Contribution.get_con_id | train | def get_con_id(self):
"""
Return contribution id if available
"""
con_id = ""
if "contribution" in self.tables:
if "id" in self.tables["contribution"].df.columns:
con_id = str(self.tables["contribution"].df["id"].values[0])
return con_id | python | {
"resource": ""
} |
q11525 | MagicDataFrame.remove_non_magic_cols_from_table | train | def remove_non_magic_cols_from_table(self, ignore_cols=()):
"""
Remove all non-magic columns from self.df.
Changes in place.
Parameters
----------
ignore_cols : list-like
columns not to remove, whether they are proper
MagIC columns or not
... | python | {
"resource": ""
} |
q11526 | MagicDataFrame.add_row | train | def add_row(self, label, row_data, columns=""):
"""
Add a row with data.
If any new keys are present in row_data dictionary,
that column will be added to the dataframe.
This is done inplace
"""
# use provided column order, making sure you don't lose any values
... | python | {
"resource": ""
} |
q11527 | MagicDataFrame.add_data | train | def add_data(self, data): # add append option later
"""
Add df to a MagicDataFrame using a data list.
Parameters
----------
data : list of dicts
data list with format [{'key1': 'val1', ...}, {'key1': 'val2', ...}, ... }]
dtype : str
MagIC table t... | python | {
"resource": ""
} |
q11528 | MagicDataFrame.add_blank_row | train | def add_blank_row(self, label):
"""
Add a blank row with only an index value to self.df.
This is done inplace.
"""
col_labels = self.df.columns
blank_item = pd.Series({}, index=col_labels, name=label)
# use .loc to add in place (append won't do that)
self.... | python | {
"resource": ""
} |
q11529 | MagicDataFrame.delete_row | train | def delete_row(self, ind):
"""
remove self.df row at ind
inplace
"""
self.df = pd.concat([self.df[:ind], self.df[ind+1:]], sort=True)
return self.df | python | {
"resource": ""
} |
q11530 | MagicDataFrame.delete_rows | train | def delete_rows(self, condition, info_str=None):
"""
delete all rows with condition==True
inplace
Parameters
----------
condition : pandas DataFrame indexer
all self.df rows that meet this condition will be deleted
info_str : str
descript... | python | {
"resource": ""
} |
q11531 | MagicDataFrame.drop_stub_rows | train | def drop_stub_rows(self, ignore_cols=('specimen',
'sample',
'software_packages',
'num')):
"""
Drop self.df rows that have only null values,
ignoring certain columns.
... | python | {
"resource": ""
} |
q11532 | MagicDataFrame.drop_duplicate_rows | train | def drop_duplicate_rows(self, ignore_cols=['specimen', 'sample']):
"""
Drop self.df rows that have only null values,
ignoring certain columns BUT only if those rows
do not have a unique index.
Different from drop_stub_rows because it only drops
empty rows if there is ano... | python | {
"resource": ""
} |
q11533 | MagicDataFrame.update_record | train | def update_record(self, name, new_data, condition, update_only=False,
debug=False):
"""
Find the first row in self.df with index == name
and condition == True.
Update that record with new_data, then delete any
additional records where index == name and condi... | python | {
"resource": ""
} |
q11534 | MagicDataFrame.sort_dataframe_cols | train | def sort_dataframe_cols(self):
"""
Sort self.df so that self.name is the first column,
and the rest of the columns are sorted by group.
"""
# get the group for each column
cols = self.df.columns
groups = list(map(lambda x: self.data_model.get_group_for_col(self.dt... | python | {
"resource": ""
} |
q11535 | MagicDataFrame.get_non_magic_cols | train | def get_non_magic_cols(self):
"""
Find all columns in self.df that are not real MagIC 3 columns.
Returns
--------
unrecognized_cols : list
"""
table_dm = self.data_model.dm[self.dtype]
approved_cols = table_dm.index
unrecognized_cols = (set(self.d... | python | {
"resource": ""
} |
q11536 | MagicDataFrame.get_first_non_null_value | train | def get_first_non_null_value(self, ind_name, col_name):
"""
For a given index and column, find the first non-null value.
Parameters
----------
self : MagicDataFrame
ind_name : str
index name for indexing
col_name : str
column name for inde... | python | {
"resource": ""
} |
q11537 | get_pmag_dir | train | def get_pmag_dir():
"""
Returns directory in which PmagPy is installed
"""
# this is correct for py2exe (DEPRECATED)
#win_frozen = is_frozen()
#if win_frozen:
# path = os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding()))
# path = os.path.split(path)[0]
# ret... | python | {
"resource": ""
} |
q11538 | main | train | def main():
"""
NAME
plot_magic_keys.py
DESCRIPTION
picks out keys and makes and xy plot
SYNTAX
plot_magic_keys.py [command line options]
OPTIONS
-h prints help message and quits
-f FILE: specify input magic format file
-xkey KEY: specify key for X
... | python | {
"resource": ""
} |
q11539 | main | train | def main():
"""
NAME
eqarea.py
DESCRIPTION
makes equal area projections from declination/inclination data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
eqarea.py [options]
OPTIONS
-f FILE, specify file on command line
... | python | {
"resource": ""
} |
q11540 | MagICMenu.on_quit | train | def on_quit(self, event):
"""
shut down application
"""
if self.parent.grid_frame:
if self.parent.grid_frame.grid.changes:
dlg = wx.MessageDialog(self,caption="Message:", message="Are you sure you want to exit the program?\nYou have a grid open with unsaved ch... | python | {
"resource": ""
} |
q11541 | main | train | def main():
"""
NAME
gobing.py
DESCRIPTION
calculates Bingham parameters from dec inc data
INPUT FORMAT
takes dec/inc as first two columns in space delimited file
SYNTAX
gobing.py [options]
OPTIONS
-f FILE to read from FILE
-F, specifies output f... | python | {
"resource": ""
} |
q11542 | main | train | def main():
"""
NAME
atrm_magic.py
DESCRIPTION
Converts ATRM data to best-fit tensor (6 elements plus sigma)
Original program ARMcrunch written to accomodate ARM anisotropy data
collected from 6 axial directions (+X,+Y,+Z,-X,-Y,-Z) using the
off-axis remanence ... | python | {
"resource": ""
} |
q11543 | OrientFrameGrid3.create_sheet | train | def create_sheet(self):
'''
create an editable grid showing demag_orient.txt
'''
#--------------------------------
# orient.txt supports many other headers
# but we will only initialize with
# the essential headers for
# sample orientation and headers pres... | python | {
"resource": ""
} |
q11544 | main | train | def main():
"""
NAME
mk_redo.py
DESCRIPTION
Makes thellier_redo and zeq_redo files from existing pmag_specimens format file
SYNTAX
mk_redo.py [-h] [command line options]
INPUT
takes specimens.txt formatted input file
OPTIONS
-h: prints help message and... | python | {
"resource": ""
} |
q11545 | find_side | train | def find_side(ls, side):
"""
Given a shapely LineString which is assumed to be rectangular, return the
line corresponding to a given side of the rectangle.
"""
minx, miny, maxx, maxy = ls.bounds
points = {'left': [(minx, miny), (minx, maxy)],
'right': [(maxx, miny), (maxx, max... | python | {
"resource": ""
} |
q11546 | lambert_xticks | train | def lambert_xticks(ax, ticks):
"""Draw ticks on the bottom x-axis of a Lambert Conformal projection."""
te = lambda xy: xy[0]
lc = lambda t, n, b: np.vstack((np.zeros(n) + t, np.linspace(b[2], b[3], n))).T
xticks, xticklabels = _lambert_ticks(ax, ticks, 'bottom', lc, te)
ax.xaxis.tick_bottom()
a... | python | {
"resource": ""
} |
q11547 | lambert_yticks | train | def lambert_yticks(ax, ticks):
"""Draw ricks on the left y-axis of a Lamber Conformal projection."""
te = lambda xy: xy[1]
lc = lambda t, n, b: np.vstack((np.linspace(b[0], b[1], n), np.zeros(n) + t)).T
yticks, yticklabels = _lambert_ticks(ax, ticks, 'left', lc, te)
ax.yaxis.tick_left()
ax.set_y... | python | {
"resource": ""
} |
q11548 | _lambert_ticks | train | def _lambert_ticks(ax, ticks, tick_location, line_constructor, tick_extractor):
"""Get the tick locations and labels for an axis of a Lambert Conformal projection."""
outline_patch = sgeom.LineString(ax.outline_patch.get_path().vertices.tolist())
axis = find_side(outline_patch, tick_location)
n_steps = ... | python | {
"resource": ""
} |
q11549 | main | train | def main():
"""
NAME
dmag_magic.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted measurements.txt files
OPTIONS
-h prints help message and quits
-f... | python | {
"resource": ""
} |
q11550 | main | train | def main():
"""This program prints doubled values!"""
import numpy
X=arange(.1,10.1,.2) #make a list of numbers
Y=myfunc(X) # calls myfunc with argument X
for i in range(len(X)):
print(X[i],Y[i]) | python | {
"resource": ""
} |
q11551 | main | train | def main():
"""
NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line options]
OPTIONS
-h prints help m... | python | {
"resource": ""
} |
q11552 | main | train | def main():
"""
NAME
sundec.py
DESCRIPTION
calculates calculates declination from sun compass measurements
INPUT FORMAT
GMT_offset, lat,long,year,month,day,hours,minutes,shadow_angle
where GMT_offset is the hours to subtract from local time for GMT.
SYNTAX
sun... | python | {
"resource": ""
} |
q11553 | main | train | def main():
"""
NAME
sites_locations.py
DESCRIPTION
reads in er_sites.txt file and finds all locations and bounds of locations
outputs er_locations.txt file
SYNTAX
sites_locations.py [command line options]
OPTIONS
-h prints help message and quits
-f... | python | {
"resource": ""
} |
q11554 | main | train | def main():
"""
NAME
azdip_magic.py
DESCRIPTION
takes space delimited AzDip file and converts to MagIC formatted tables
SYNTAX
azdip_magic.py [command line options]
OPTIONS
-f FILE: specify input file
-Fsa FILE: specify output file, default is: er_samples.t... | python | {
"resource": ""
} |
q11555 | main | train | def main():
"""
NAME
k15_magic.py
DESCRIPTION
converts .k15 format data to magic_measurements format.
assums Jelinek Kappabridge measurement scheme
SYNTAX
k15_magic.py [-h] [command line options]
OPTIONS
-h prints help message and quits
-DM DATA_MO... | python | {
"resource": ""
} |
q11556 | main | train | def main():
"""
NAME
pca.py
DESCRIPTION
calculates best-fit line/plane through demagnetization data
INPUT FORMAT
takes specimen_name treatment intensity declination inclination in space delimited file
SYNTAX
pca.py [command line options][< filename]
OPTIONS
... | python | {
"resource": ""
} |
q11557 | requiredUnless | train | def requiredUnless(col_name, arg, dm, df, *args):
"""
Arg is a string in the format "str1, str2, ..."
Each string will be a column name.
Col_name is required in df unless each column from arg is present.
"""
# if column name is present, no need to check if it is required
if col_name in df.co... | python | {
"resource": ""
} |
q11558 | requiredIfGroup | train | def requiredIfGroup(col_name, arg, dm, df, *args):
"""
Col_name is required if other columns of
the group arg are present.
"""
group_name = arg
groups = set()
columns = df.columns
for col in columns:
if col not in dm.index:
continue
group = dm.loc[col]['group'... | python | {
"resource": ""
} |
q11559 | required | train | def required(col_name, arg, dm, df, *args):
"""
Col_name is required in df.columns.
Return error message if not.
"""
if col_name in df.columns:
return None
else:
return '"{}" column is required'.format(col_name) | python | {
"resource": ""
} |
q11560 | validate_table | train | def validate_table(the_con, dtype, verbose=False, output_dir="."):
"""
Return name of bad table, or False if no errors found.
Calls validate_df then parses its output.
"""
print("-I- Validating {}".format(dtype))
# grab dataframe
current_df = the_con.tables[dtype].df
# grab data model
... | python | {
"resource": ""
} |
q11561 | validate_contribution | train | def validate_contribution(the_con):
"""
Go through a Contribution and validate each table
"""
passing = True
for dtype in list(the_con.tables.keys()):
print("validating {}".format(dtype))
fail = validate_table(the_con, dtype)
if fail:
passing = False
print... | python | {
"resource": ""
} |
q11562 | get_degree_cols | train | def get_degree_cols(df):
"""
Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees.
"""
vals = ['lon_w', 'lon_e', 'lat_lon_precision', 'pole_lon',
'paleolon', 'paleolon_sigma',
'lon', 'lon_sigma', 'vgp_lon', ... | python | {
"resource": ""
} |
q11563 | extract_col_name | train | def extract_col_name(string):
"""
Take a string and split it.
String will be a format like "presence_pass_azimuth",
where "azimuth" is the MagIC column name and "presence_pass"
is the validation.
Return "presence", "azimuth".
"""
prefixes = ["presence_pass_", "value_pass_", "type_pass_"]... | python | {
"resource": ""
} |
q11564 | main | train | def main():
"""
NAME
s_magic.py
DESCRIPTION
converts .s format data to measurements format.
SYNTAX
s_magic.py [command line options]
OPTIONS
-h prints help message and quits
-DM DATA_MODEL_NUM data model number (default is 3)
-f SFILE specifies the... | python | {
"resource": ""
} |
q11565 | main | train | def main():
"""
NAME
incfish.py
DESCRIPTION
calculates fisher parameters from inc only data
INPUT FORMAT
takes inc data
SYNTAX
incfish.py [options] [< filename]
OPTIONS
-h prints help message and quits
-i for interactive filename entry
-f... | python | {
"resource": ""
} |
q11566 | sort_diclist | train | def sort_diclist(undecorated, sort_on):
"""
Sort a list of dictionaries by the value in each
dictionary for the sorting key
Parameters
----------
undecorated : list of dicts
sort_on : str, numeric
key that is present in all dicts to sort on
Returns
---------
ordered lis... | python | {
"resource": ""
} |
q11567 | convert_lat | train | def convert_lat(Recs):
"""
uses lat, for age<5Ma, model_lat if present, else tries to use average_inc to estimate plat.
"""
New = []
for rec in Recs:
if 'model_lat' in list(rec.keys()) and rec['model_lat'] != "":
New.append(rec)
elif 'average_age' in list(rec.keys()) and ... | python | {
"resource": ""
} |
q11568 | convert_directory_2_to_3 | train | def convert_directory_2_to_3(meas_fname="magic_measurements.txt", input_dir=".",
output_dir=".", meas_only=False, data_model=None):
"""
Convert 2.0 measurements file into 3.0 measurements file.
Merge and convert specimen, sample, site, and location data.
Also translates crit... | python | {
"resource": ""
} |
q11569 | convert_criteria_file_2_to_3 | train | def convert_criteria_file_2_to_3(fname="pmag_criteria.txt", input_dir=".",
output_dir=".", data_model=None):
"""
Convert a criteria file from 2.5 to 3.0 format and write it out to file
Parameters
----------
fname : string of filename (default "pmag_criteria.txt")
... | python | {
"resource": ""
} |
q11570 | orient | train | def orient(mag_azimuth, field_dip, or_con):
"""
uses specified orientation convention to convert user supplied orientations
to laboratory azimuth and plunge
"""
or_con = str(or_con)
if mag_azimuth == -999:
return "", ""
if or_con == "1": # lab_mag_az=mag_az; sample_dip = -dip
... | python | {
"resource": ""
} |
q11571 | get_Sb | train | def get_Sb(data):
"""
returns vgp scatter for data set
"""
Sb, N = 0., 0.
for rec in data:
delta = 90. - abs(rec['vgp_lat'])
if rec['average_k'] != 0:
k = rec['average_k']
L = rec['average_lat'] * np.pi / 180. # latitude in radians
Nsi = rec['aver... | python | {
"resource": ""
} |
q11572 | flip | train | def flip(di_block, combine=False):
"""
determines 'normal' direction along the principle eigenvector, then flips the antipodes of
the reverse mode to the antipode
Parameters
___________
di_block : nested list of directions
Return
D1 : normal mode
D2 : flipped reverse mode as two DI ... | python | {
"resource": ""
} |
q11573 | dovds | train | def dovds(data):
"""
calculates vector difference sum for demagnetization data
"""
vds, X = 0, []
for rec in data:
X.append(dir2cart(rec))
for k in range(len(X) - 1):
xdif = X[k + 1][0] - X[k][0]
ydif = X[k + 1][1] - X[k][1]
zdif = X[k + 1][2] - X[k][2]
v... | python | {
"resource": ""
} |
q11574 | get_specs | train | def get_specs(data):
"""
Takes a magic format file and returns a list of unique specimen names
"""
# sort the specimen names
speclist = []
for rec in data:
try:
spec = rec["er_specimen_name"]
except KeyError as e:
spec = rec["specimen"]
if spec not... | python | {
"resource": ""
} |
q11575 | mark_dmag_rec | train | def mark_dmag_rec(s, ind, data):
"""
Edits demagnetization data to mark "bad" points with measurement_flag
"""
datablock = []
for rec in data:
if rec['er_specimen_name'] == s:
meths = rec['magic_method_codes'].split(':')
if 'LT-NO' in meths or 'LT-AF-Z' in meths or 'L... | python | {
"resource": ""
} |
q11576 | open_file | train | def open_file(infile, verbose=True):
"""
Open file and return a list of the file's lines.
Try to use utf-8 encoding, and if that fails use Latin-1.
Parameters
----------
infile : str
full path to file
Returns
----------
data: list
all lines in the file
"""
t... | python | {
"resource": ""
} |
q11577 | putout | train | def putout(ofile, keylist, Rec):
"""
writes out a magic format record to ofile
"""
pmag_out = open(ofile, 'a')
outstring = ""
for key in keylist:
try:
outstring = outstring + '\t' + str(Rec[key]).strip()
except:
print(key, Rec[key])
# raw_input... | python | {
"resource": ""
} |
q11578 | first_rec | train | def first_rec(ofile, Rec, file_type):
"""
opens the file ofile as a magic template file with headers as the keys to Rec
"""
keylist = []
opened = False
# sometimes Windows needs a little extra time to open a file
# or else it throws an error
while not opened:
try:
pma... | python | {
"resource": ""
} |
q11579 | magic_write_old | train | def magic_write_old(ofile, Recs, file_type):
"""
writes out a magic format list of dictionaries to ofile
Parameters
_________
ofile : path to output file
Recs : list of dictionaries in MagIC format
file_type : MagIC table type (e.g., specimens)
Effects :
writes a MagIC formatte... | python | {
"resource": ""
} |
q11580 | dotilt_V | train | def dotilt_V(indat):
"""
Does a tilt correction on an array with rows of dec,inc bedding dip direction and dip.
Parameters
----------
input : declination, inclination, bedding dip direction and bedding dip
nested array of [[dec1, inc1, bed_az1, bed_dip1],[dec2,inc2,bed_az2,bed_dip2]...]
Re... | python | {
"resource": ""
} |
q11581 | find_samp_rec | train | def find_samp_rec(s, data, az_type):
"""
find the orientation info for samp s
"""
datablock, or_error, bed_error = [], 0, 0
orient = {}
orient["sample_dip"] = ""
orient["sample_azimuth"] = ""
orient['sample_description'] = ""
for rec in data:
if rec["er_sample_name"].lower() ... | python | {
"resource": ""
} |
q11582 | vspec | train | def vspec(data):
"""
Takes the vector mean of replicate measurements at a given step
"""
vdata, Dirdata, step_meth = [], [], []
tr0 = data[0][0] # set beginning treatment
data.append("Stop")
k, R = 1, 0
for i in range(k, len(data)):
Dirdata = []
if data[i][0] != tr0:
... | python | {
"resource": ""
} |
q11583 | Vdiff | train | def Vdiff(D1, D2):
"""
finds the vector difference between two directions D1,D2
"""
A = dir2cart([D1[0], D1[1], 1.])
B = dir2cart([D2[0], D2[1], 1.])
C = []
for i in range(3):
C.append(A[i] - B[i])
return cart2dir(C) | python | {
"resource": ""
} |
q11584 | cart2dir | train | def cart2dir(cart):
"""
Converts a direction in cartesian coordinates into declination, inclinations
Parameters
----------
cart : input list of [x,y,z] or list of lists [[x1,y1,z1],[x2,y2,z2]...]
Returns
-------
direction_array : returns an array of [declination, inclination, intensity... | python | {
"resource": ""
} |
q11585 | findrec | train | def findrec(s, data):
"""
finds all the records belonging to s in data
"""
datablock = []
for rec in data:
if s == rec[0]:
datablock.append([rec[1], rec[2], rec[3], rec[4]])
return datablock | python | {
"resource": ""
} |
q11586 | circ | train | def circ(dec, dip, alpha):
"""
function to calculate points on an circle about dec,dip with angle alpha
"""
rad = old_div(np.pi, 180.)
D_out, I_out = [], []
dec, dip, alpha = dec * rad, dip * rad, alpha * rad
dec1 = dec + old_div(np.pi, 2.)
isign = 1
if dip != 0:
isign = (old... | python | {
"resource": ""
} |
q11587 | getnames | train | def getnames():
"""
get mail names
"""
namestring = ""
addmore = 1
while addmore:
scientist = input("Enter name - <Return> when done ")
if scientist != "":
namestring = namestring + ":" + scientist
else:
namestring = namestring[1:]
ad... | python | {
"resource": ""
} |
q11588 | gha | train | def gha(julian_day, f):
"""
returns greenwich hour angle
"""
rad = old_div(np.pi, 180.)
d = julian_day - 2451545.0 + f
L = 280.460 + 0.9856474 * d
g = 357.528 + 0.9856003 * d
L = L % 360.
g = g % 360.
# ecliptic longitude
lamb = L + 1.915 * np.sin(g * rad) + .02 * np.sin(2 * g * ... | python | {
"resource": ""
} |
q11589 | julian | train | def julian(mon, day, year):
"""
returns julian day
"""
ig = 15 + 31 * (10 + 12 * 1582)
if year == 0:
print("Julian no can do")
return
if year < 0:
year = year + 1
if mon > 2:
julian_year = year
julian_month = mon + 1
else:
julian_year = yea... | python | {
"resource": ""
} |
q11590 | fillkeys | train | def fillkeys(Recs):
"""
reconciles keys of dictionaries within Recs.
"""
keylist, OutRecs = [], []
for rec in Recs:
for key in list(rec.keys()):
if key not in keylist:
keylist.append(key)
for rec in Recs:
for key in keylist:
if key not in l... | python | {
"resource": ""
} |
q11591 | fisher_mean | train | def fisher_mean(data):
"""
Calculates the Fisher mean and associated parameter from a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
fpars : dictionary containing the Fisher mean and statistics
dec : mean declination
... | python | {
"resource": ""
} |
q11592 | gausspars | train | def gausspars(data):
"""
calculates gaussian statistics for data
"""
N, mean, d = len(data), 0., 0.
if N < 1:
return "", ""
if N == 1:
return data[0], 0
for j in range(N):
mean += old_div(data[j], float(N))
for j in range(N):
d += (data[j] - mean)**2
s... | python | {
"resource": ""
} |
q11593 | weighted_mean | train | def weighted_mean(data):
"""
calculates weighted mean of data
"""
W, N, mean, d = 0, len(data), 0, 0
if N < 1:
return "", ""
if N == 1:
return data[0][0], 0
for x in data:
W += x[1] # sum of the weights
for x in data:
mean += old_div((float(x[1]) * float(... | python | {
"resource": ""
} |
q11594 | vclose | train | def vclose(L, V):
"""
gets the closest vector
"""
lam, X = 0, []
for k in range(3):
lam = lam + V[k] * L[k]
beta = np.sqrt(1. - lam**2)
for k in range(3):
X.append((old_div((V[k] - lam * L[k]), beta)))
return X | python | {
"resource": ""
} |
q11595 | calculate_best_fit_vectors | train | def calculate_best_fit_vectors(L, E, V, n_planes):
"""
Calculates the best fit vectors for a set of plane interpretations used in fisher mean calculations
@param: L - a list of the "EL, EM, EN" array of MM88 or the cartisian form of dec and inc of the plane interpretation
@param: E - the sum of the cart... | python | {
"resource": ""
} |
q11596 | process_data_for_mean | train | def process_data_for_mean(data, direction_type_key):
"""
takes list of dicts with dec and inc as well as direction_type if possible or method_codes and sorts the data into lines and planes and process it for fisher means
@param: data - list of dicts with dec inc and some manner of PCA type info
@param:... | python | {
"resource": ""
} |
q11597 | cdfout | train | def cdfout(data, file):
"""
spits out the cdf for data to file
"""
f = open(file, "w")
data.sort()
for j in range(len(data)):
y = old_div(float(j), float(len(data)))
out = str(data[j]) + ' ' + str(y) + '\n'
f.write(out)
f.close() | python | {
"resource": ""
} |
q11598 | dobingham | train | def dobingham(di_block):
"""
Calculates the Bingham mean and associated statistical parameters from
directions that are input as a di_block
Parameters
----------
di_block : a nested list of [dec,inc] or [dec,inc,intensity]
Returns
-------
bpars : dictionary containing the Bingham m... | python | {
"resource": ""
} |
q11599 | doflip | train | def doflip(dec, inc):
"""
flips lower hemisphere data to upper hemisphere
"""
if inc < 0:
inc = -inc
dec = (dec + 180.) % 360.
return dec, inc | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.