code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.session = self._session_start() result = yield gen.Task(self.session.fetch) self._set_session_cookie() if not self.session.get('ip_address'): self.session.ip_address = self.request.remote_ip self._last_values() raise gen.Return(result)
def start_session(self)
Start the session. Invoke in your @gen.coroutine wrapped prepare method like:: result = yield gen.Task(self.start_session) :rtype: bool
5.089466
4.844887
1.050482
super(SessionRequestHandler, self).prepare() result = yield gen.Task(self.start_session) LOGGER.debug('Exiting SessionRequestHandler.prepare: %r', result)
def prepare(self)
Prepare the session, setting up the session object and loading in the values, assigning the IP address to the session if it's an new one.
8.922583
7.046637
1.266219
value = (datetime.datetime.utcnow() + datetime.timedelta(seconds=self._session_duration)) LOGGER.debug('Cookie expires: %s', value.isoformat()) return value
def _cookie_expiration(self)
Return the expiration timestamp for the session cookie. :rtype: datetime
4.834077
5.925754
0.815774
if not self.session.get('last_request_uri'): self.session.last_request_uri = None self.session.last_request_at = self.session.get('last_request_at', 0)
def _last_values(self)
Always carry last_request_uri and last_request_at even if the last_* values are null.
4.475416
2.571207
1.740589
return self._session_class(self._session_id, self._session_duration, self._session_settings)
def _session_start(self)
Return an instance of the proper session object. :rtype: Session
6.845414
7.264185
0.942351
LOGGER.debug('Setting session cookie for %s', self.session.id) self.set_secure_cookie(name=self._session_cookie_name, value=self.session.id, expires=self._cookie_expiration)
def _set_session_cookie(self)
Set the session data cookie.
3.741939
3.537446
1.057808
# is for an authenticated Splunk TCP Port log_msg = None if self.token: if IS_PY2: log_msg = ('token={}, body={}').format( self.token, body) else: log_msg = ('token={}, body={}').format( ...
def build_into_splunk_tcp_message( self, body)
build_into_splunk_tcp_message Format a message for a Splunk JSON sourcetype :param body: splunk JSON dictionary msg body
4.829493
4.862858
0.993139
use_vals = self.custom if not use_vals: use_vals = {} for i in self.included_vals: if i not in use_vals: use_vals[i] = self.included_vals[i] # for now leave as None use_vals['asctime'] = None use_vals['systime'] = datetim...
def makePickle( self, record)
makePickle Convert a log record into a JSON dictionary packaged into a socket-ready message for a Splunk TCP Port configured that is set up with a JSON sourcetype :param record: log record to format as a socket-ready message
4.178499
3.949527
1.057975
try: self.df = self.df.rename(columns={source_col: dest_col}) except Exception as e: self.err(e, self.rename, "Can not rename column") return self.ok("Column", source_col, "renamed")
def rename(self, source_col: str, dest_col: str)
Renames a column in the main dataframe :param source_col: name of the column to rename :type source_col: str :param dest_col: new name of the column :type dest_col: str :example: ``ds.rename("Col 1", "New col")``
4.37633
4.700035
0.931127
try: self.df[col] = value except Exception as e: self.err(e, self.add, "Can not add column")
def add(self, col: str, value)
Add a column with default values :param col: column name :type col: str :param value: column value :type value: any :example: ``ds.add("Col 4", 0)``
6.08615
6.550758
0.929076
try: ds2 = self._duplicate_(self.df[list(cols)]) except Exception as e: self.err(e, "Can not remove colums") return self.ok("Columns", " ,".join(cols), "kept") return ds2
def keep_(self, *cols) -> "Ds"
Returns a dataswim instance with a dataframe limited to some columns :param cols: names of the columns :type cols: str :return: a dataswim instance :rtype: Ds :example: ``ds2 = ds.keep_("Col 1", "Col 2")``
8.382045
9.617184
0.87157
try: self.df = self.df[list(cols)] except Exception as e: self.err(e, "Can not remove colums") return self.ok("Setting dataframe to columns", " ".join(cols))
def keep(self, *cols)
Limit the dataframe to some columns :param cols: names of the columns :type cols: str :example: ``ds.keep("Col 1", "Col 2")``
6.956836
7.803169
0.89154
try: index = self.df.columns.values for col in cols: if col not in index: self.warning("Column", col, "not found. Aborting") return self.df = self.df.drop(col, axis=1) except Exception as e: ...
def drop(self, *cols)
Drops columns from the main dataframe :param cols: names of the columns :type cols: str :example: ``ds.drop("Col 1", "Col 2")``
3.557414
3.889992
0.914504
try: self.df = self.df[self.df[col] != val] except Exception as e: self.err(e, "Can not exclude rows based on value " + str(val))
def exclude(self, col: str, val)
Delete rows based on value :param col: column name :type col: str :param val: value to delete :type val: any :example: ``ds.exclude("Col 1", "value")``
4.214181
4.273263
0.986174
try: self.df[dest_col] = self.df[[origin_col]] except Exception as e: self.err(e, self.copy_col, "Can not copy column")
def copycol(self, origin_col: str, dest_col: str)
Copy a columns values in another column :param origin_col: name of the column to copy :type origin_col: str :param dest_col: name of the new column :type dest_col: str :example: ``ds.copy("col 1", "New col")``
5.672724
5.266526
1.077128
try: self.df[col] = self.df.index.values except Exception as e: self.err(e) return self.ok("Column", col, "added from the index")
def indexcol(self, col: str)
Add a column from the index :param col: name of the new column :type col: str :example: ``ds.index_col("New col")``
6.605699
5.346995
1.235404
placeholders_search_list = getattr(settings, 'CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST', {}) included = placeholders_search_list.get('include', []) excluded = placeholders_search_list.get('exclude', []) diff = set(included) - set(excluded) if diff: return artic...
def get_article_placeholders(self, article)
In the project settings set up the variable CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = { 'include': [ 'slot1', 'slot2', etc. ], 'exclude': [ 'slot3', 'slot4', etc. ], } or leave it empty CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {}
2.925447
2.003087
1.460469
ds2 = Ds(df, db, nbload_libs) if quiet is False: self.ok("A new instance was created") return ds2
def new_(self, df=pd.DataFrame(), db=None, quiet=False, nbload_libs=True)
Returns a new DataSwim instance from a dataframe
9.239715
7.991944
1.156129
if self._check_db() is False: return try: table = self.db[table] except Exception as e: self.err(e, "Can not find table " + table) t = type(records) if t == dict: func = table.insert elif t == list: func...
def insert(self, table, records, create_cols=False, dtypes=None)
Insert one or many records in the database from a dictionary or a list of dictionaries
3.307451
3.175545
1.041538
try: self.db[table].upsert(record, pks, create_cols, dtypes) except Exception as e: self.err(e, "Can not upsert data") return names = "" for el in namefields: names += " " + record[el] self.ok("Upserted record"+names)
def upsert(self, table: str, record: dict, create_cols: bool=False, dtypes: list=None, pks=["id"], namefields=["id"])
Upsert a record in a table
4.699071
4.622328
1.016603
if self._check_db() is False: return try: table = self.db[table] except Exception as e: self.err(e, "Can not find table " + table) if self.db is None: msg = "Please connect a database before or provide a database url" s...
def update_table(self, table, pks=['id'])
Update records in a database table from the main dataframe
5.957372
5.592945
1.065158
if self._check_db() is False: return if table not in self.db.tables: self.db.create_table(table) self.info("Created table ", table) self.start("Saving data to database table " + table + " ...") recs = self.to_records_() self.insert(tab...
def to_db(self, table, dtypes=None)
Save the main dataframe to the database
4.84997
4.534307
1.069617
color, _ = self._get_color_size(style) try: fig = sns.residplot(self.df[self.x], self.df[self.y], lowess=True, color=color) fig = self._set_with_height(fig, opts) return fig except Exception as e: self.err(e...
def residual_(self, label=None, style=None, opts=None)
Returns a Seaborn models residuals chart
5.766886
4.612948
1.250152
try: fig = sns.kdeplot(self.df[self.x], self.df[self.y]) fig = self._set_with_height(fig, opts) return fig except Exception as e: self.err(e, self.density_, "Can not draw density chart")
def _density_seaborn_(self, label=None, style=None, opts=None)
Returns a Seaborn density chart
5.622922
5.574715
1.008647
try: kde = False rug = True if "kde" in opts: kde = opts["kde"] rug = opts["rug"] fig = sns.distplot(self.df[self.x], kde=kde, rug=rug) fig = self._set_with_height(fig, opts) return fig excep...
def _distrib_seaborn_(self, label=None, style=None, opts=None)
Returns a Seaborn distribution chart
4.565631
4.502642
1.013989
xticks, yticks = self._get_ticks(opts) try: fig = sns.lmplot(self.x, self.y, data=self.df) fig = self._set_with_height(fig, opts) return fig except Exception as e: self.err(e, self.linear_, "Can not draw linear regress...
def _linear_seaborn_(self, label=None, style=None, opts=None)
Returns a Seaborn linear regression plot
6.433117
6.117848
1.051533
color, size = self._get_color_size(style) try: fig = sns.jointplot(self.x, self.y, color=color, size=size, data=self.df, kind="reg") fig = self._set_with_height(fig, opts) return fig except Exception as e: s...
def _dlinear_seaborn_(self, label=None, style=None, opts=None)
Returns a Seaborn linear regression plot with marginal distribution
5.568039
5.477571
1.016516
try: fig = sns.barplot(self.x, self.y, palette="BuGn_d") return fig except Exception as e: self.err(e, self.seaborn_bar_, "Can not get Seaborn bar chart object")
def seaborn_bar_(self, label=None, style=None, opts=None)
Get a Seaborn bar chart
5.53692
5.066877
1.092768
if opts is None: if self.chart_opts is None: opts = {} else: opts = self.chart_opts if style is None: if self.chart_style is None: style = self.chart_style else: style = {} re...
def _get_opts_seaborn(self, opts, style)
Initialialize for chart rendering
2.339184
2.11691
1.104999
plt.figure() try: opts, style = self._get_opts_seaborn(_opts, _style) except Exception as e: self.err(e, "Can not get chart options") return # params # opts["xfield"] = xfield # opts["yfield"] = yfield # opts["dataobj"]...
def _get_seaborn_chart(self, xfield, yfield, chart_type, label, _opts=None, _style=None, **kwargs)
Get an Seaborn chart object
2.658895
2.604593
1.020848
opts, _ = self._get_opts(opts, None) if "xticks" not in opts: if "xticks" not in self.chart_opts: self.err(self.dlinear_, "Please set the xticks option for this chart to work") return else: xticks =...
def _get_ticks(self, opts)
Check if xticks and yticks are set
2.585085
2.376418
1.087807
color = "b" if "color" in style: color = style["color"] size = 7 if "size" in style: size = style["size"] return color, size
def _get_color_size(self, style)
Get color and size from a style dict
2.71433
2.370889
1.144858
h = 5 if "height" in opts: h = opts["height"] w = 12 if "width" in opts: w = opts["width"] try: fig.figure.set_size_inches((w, h)) return fig except Exception: try: fig.fig.set_size_inche...
def _set_with_height(self, fig, opts)
Set the width and height of a Matplotlib figure
3.102176
2.98612
1.038865
if folderpath is None: if self.imgs_path is None: self.err(self._save_seaborn_chart, "Please set a path where to save images: ds.imgs_path" " = '/my/path'") return path = self.imgs_path els...
def _save_seaborn_chart(self, report, folderpath)
Saves a png image of the seaborn chart
3.640108
3.573632
1.018602
return np.sum([hcu.array_bytes(a) for a in self.arrays(reify=True).itervalues()])
def bytes_required(self)
Returns ------- int Estimated number of bytes required by arrays registered on the cube, taking their extents into account.
24.734741
20.772732
1.190731
if name in self._dims: raise AttributeError(( "Attempted to register dimension '{n}'' " "as an attribute of the cube, but " "it already exists. Please choose " "a different name!").format(n=name)) # Create the dimensi...
def register_dimension(self, name, dim_data, **kwargs)
Registers a dimension on this cube. .. code-block:: python cube.register_dimension('ntime', 10000, decription="Number of Timesteps", lower_extent=100, upper_extent=200) Parameters ---------- dim_data : int or :class:`~hypercu...
5.305367
5.949996
0.891659
if isinstance(dims, collections.Mapping): dims = dims.itervalues() for dim in dims: self.register_dimension(dim.name, dim)
def register_dimensions(self, dims)
Register multiple dimensions on the cube. .. code-block:: python cube.register_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_size' : 3, 'lower_extent' : 2, 'upper...
3.941277
5.883886
0.669843
if isinstance(dims, collections.Mapping): dims = dims.itervalues() for dim in dims: # Defer to update dimension for dictionaries if isinstance(dim, dict): self.update_dimension(**dim) # Replace if given a Dimension object ...
def update_dimensions(self, dims)
Update multiple dimension on the cube. .. code-block:: python cube.update_dimensions([ {'name' : 'ntime', 'global_size' : 10, 'lower_extent' : 2, 'upper_extent' : 7 }, {'name' : 'na', 'global_size' : 3, 'lower_extent' : 2, 'upper_exte...
4.542317
4.799266
0.946461
if not name: raise AttributeError("A dimension name is required to update " "a dimension. Update dictionary {u}." .format(u=update_dict)) dim = self._dims.get(name, None) # Sanity check dimension existence if not dim: ...
def update_dimension(self, name, **update_dict)
Update the dimension size and extents. Parameters ---------- **update_dict : : dict: dict A dictionary containing keywords passed through to :meth:`~hypercube.dims.Dimension.update` name : str Name of the dimension to update
4.892576
4.920027
0.994421
import re # If we got a single string argument, try splitting it by separators if len(args) == 1 and isinstance(args[0], str): args = (s.strip() for s in re.split(',|:|;| ', args[0])) # Now get the specific attribute for each string dimension # Integers ar...
def _dim_attribute(self, attr, *args, **kwargs)
Returns a list of dimension attribute attr, for the dimensions specified as strings in args. .. code-block:: python ntime, nbl, nchan = cube._dim_attribute('global_size', 'ntime', 'nbl', 'nchan') or .. code-block:: python ntime, nbl, nchan, nsrc = cube._dim_a...
5.327086
5.408417
0.984962
return { d.name: d.global_size for d in self._dims.itervalues()}
def dim_global_size_dict(self)
Returns a mapping of dimension name to global size
7.480464
5.616267
1.331928
return { d.name: d.lower_extent for d in self._dims.itervalues()}
def dim_lower_extent_dict(self)
Returns a mapping of dimension name to lower_extent
7.690116
5.469967
1.40588
return { d.name: d.upper_extent for d in self._dims.itervalues()}
def dim_upper_extent_dict(self)
Returns a mapping of dimension name to upper_extent
7.598888
5.421477
1.401627
# The lower extent of any integral dimension is 0 by default args = tuple(0 if isinstance(a, (int, np.integer)) else a for a in args) return self._dim_attribute('lower_extent', *args, **kwargs)
def dim_lower_extent(self, *args, **kwargs)
Returns the lower extent of the dimensions in args. .. code-block:: python t_ex, bl_ex, ch_ex = cube.dim_lower_extent('ntime', 'nbl', 'nchan') or .. code-block:: python t_ex, bl_ex, ch_ex, src_ex = cube.dim_lower_extent('ntime,nbl:nchan nsrc')
6.104711
7.121347
0.857241
l = self.dim_lower_extent(*args, **kwargs) u = self.dim_upper_extent(*args, **kwargs) # Handle sequence and singles differently if isinstance(l, collections.Sequence): return zip(l, u) else: return (l, u)
def dim_extents(self, *args, **kwargs)
Returns extent tuples of the dimensions in args. .. code-block:: python (tl, tu), (bl, bu) = cube.dim_extents('ntime', 'nbl') or .. code-block:: python (tl, tu), (bl, bu) = cube.dim_upper_extent('ntime,nbl')
4.720564
4.646809
1.015872
extents = self.dim_extents(*args, **kwargs) # Handle tuples and sequences differently if isinstance(extents, tuple): return extents[1] - extents[0] else: # isinstance(extents, collections.Sequence): return (u-l for l, u in extents)
def dim_extent_size(self, *args, **kwargs)
Returns extent sizes of the dimensions in args. .. code-block:: python ts, bs, cs = cube.dim_extent_size('ntime', 'nbl', 'nchan') or .. code-block:: python ts, bs, cs, ss = cube.dim_extent_size('ntime,nbl:nchan nsrc')
4.893879
4.969594
0.984765
# Complain if array exists if name in self._arrays: raise ValueError(('Array %s is already registered ' 'on this cube object.') % name) # OK, create a record for this array A = self._arrays[name] = AttrDict(name=name, dtype=dtype, shape=...
def register_array(self, name, shape, dtype, **kwargs)
Register an array with this cube. .. code-block:: python cube.register_array("model_vis", ("ntime", "nbl", "nchan", 4), np.complex128) Parameters ---------- name : str Array name shape : A tuple containing either Dimension names or ints Arra...
5.53178
5.579584
0.991432
if isinstance(arrays, collections.Mapping): arrays = arrays.itervalues() for ary in arrays: self.register_array(**ary)
def register_arrays(self, arrays)
Register arrays using a list of dictionaries defining the arrays. The list should itself contain dictionaries. i.e. .. code-block:: python D = [{ 'name':'uvw', 'shape':(3,'ntime','nbl'),'dtype':np.float32 }, { 'name':'lm', 'shape':(2,'nsrc'),'dtype':np.float32 }] ...
5.508723
7.322906
0.752259
if name in self._properties: raise ValueError(('Property %s is already registered ' 'on this cube object.') % name) P = self._properties[name] = AttrDict(name=name, dtype=dtype, default=default) #if not hasattr(HyperCube, name): if not H...
def register_property(self, name, dtype, default, **kwargs)
Registers a property with this Solver object .. code-block:: python cube.register_property("reference_frequency", np.float64, 1.4e9) Parameters ---------- name : str The name of this property. dtype : Numpy data type Numpy data type ...
4.482784
4.754169
0.942916
if isinstance(properties, collections.Mapping): properties = properties.itervalues() for prop in properties: self.register_property(**prop)
def register_properties(self, properties)
Register properties using a list defining the properties. The dictionary should itself contain dictionaries. i.e. .. code-block:: python D = [ { 'name':'ref_wave','dtype':np.float32, 'default':1.41e6 }, ] Parameters --------...
4.486839
7.564214
0.593167
return self._dims.copy() if copy else self._dims
def dimensions(self, copy=True)
Return a dictionary of :class:`~hypercube.dims.Dimension` objects. Parameters ---------- copy : boolean: Returns a copy of the dimension dictionary if True (Default value = True) Returns ------- dict Dictionary of :class:`~hypercube.dims.Dimensio...
7.920934
10.938334
0.724144
try: return create_dimension(name, self._dims[name]) if copy else self._dims[name] except KeyError: raise KeyError("Dimension '{n}' is not registered " "on this cube".format(n=name)), None, sys.exc_info()[2]
def dimension(self, name, copy=True)
Returns the requested :class:`~hypercube.dims.Dimension` object Parameters ---------- name : str Name of the :class:`~hypercube.dims.Dimension` object copy : boolean Returns a copy of the :class:`~hypercube.dims.Dimension` object if True (Default value = True) ...
5.035763
4.822832
1.044151
return HyperCube( dimensions=self.dimensions(copy=False), arrays=self.arrays(), properties=self.properties())
def copy(self)
:rtype: Return a copy of the hypercube
11.679888
8.096906
1.442513
headers = ['Dimension Name', 'Description', 'Global Size', 'Extents'] table = [] for dimval in sorted(self.dimensions(copy=False).itervalues(), key=lambda dval: dval.name.upper()): table.append([dimval.name, dimval.d...
def _gen_dimension_table(self)
2D array describing each registered dimension together with headers - for use in __str__
4.76683
4.404903
1.082165
headers = ['Array Name', 'Size', 'Type', 'Shape'] # Reify arrays to work out their actual size reified_arrays = self.arrays(reify=True) table = [] for array in sorted(self.arrays().itervalues(), key=lambda aval: aval.name.upper()): ...
def _gen_array_table(self)
2D array describing each registered array together with headers - for use in __str__
5.440517
5.248423
1.0366
headers = ['Property Name', 'Type', 'Value', 'Default Value'] table = [] for propval in sorted(self._properties.itervalues(), key=lambda pval: pval.name.upper()): table.append([propval.name, np.dtype(propval.dtype).name, ...
def _gen_property_table(self)
2D array describing each registered property together with headers - for use in __str__
3.668489
3.486294
1.05226
def _dim_endpoints(size, stride): r = xrange(0, size, stride) if stride > 0 else xrange(0, size) return ((i, min(i+stride, size)) for i in r) dims = self.dimensions(copy=False) gens = (_dim_endpoints(dims[d].global_size, s) for d, s in dim_strides) retu...
def endpoint_iter(self, *dim_strides, **kwargs)
Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning the start and end indices for each chunk. For example, the following call effectively produces 2 loops over the 'ntime' and 'nchan' dimensions in chunks of 10 and 4 respectively. ...
4.471714
4.22457
1.058502
def _create_slices(*args): return tuple(slice(s,e,1) for (s, e) in args) return (_create_slices(*s) for s in self.endpoint_iter( *dim_strides, **kwargs))
def slice_iter(self, *dim_strides, **kwargs)
Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning the chunk start offsets for each specified dimensions. For example, the following call effectively produces 2 loops over the 'ntime' and 'nchan' dimensions in chunks of 10 and 4 respectiv...
5.635343
4.987751
1.129836
# Extract dimension names dims = [ds[0] for ds in dim_strides] def _create_dim_dicts(*args): return tuple({ 'name': d, 'lower_extent': s, 'upper_extent': e } for (d, (s, e)) in args) # Return a tuple-dict-cre...
def dim_iter(self, *dim_strides, **kwargs)
Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning a tuple of dictionaries describing a dimension update. For example, the following call effectively produces 2 loops over the 'ntime' and 'nchan' dimensions in chunks of 10 and 4 respectiv...
7.177498
7.230105
0.992724
def _make_cube(dims, arrays, *args): # Create new hypercube, registering everything in dims cube = HyperCube() cube.register_dimensions(dims) cube.register_arrays(arrays) # Now update dimensions given slice information ...
def cube_iter(self, *dim_strides, **kwargs)
Recursively iterate over the (dimension, stride) tuples specified in dim_strides, returning cloned hypercubes with each of the specified dimensions modified accordingly. For example, the following call effectively produces 2 loops over the 'ntime' and 'nchan' dimensions in chunk...
6.964962
6.623986
1.051476
A = self.array(array_name, reify=False) return self.dim_extents(*A.shape, single=False)
def array_extents(self, array_name, **kwargs)
Return a list of lower and upper extents for the given array_name. .. code-block:: python cube.register("uvw", ("ntime", "na", 3), np.float64) (lt, ut), (la, ua), (_, _) = cube.array_extents("uvw") Parameters ---------- array_name : string ...
11.86495
13.231763
0.896702
A = self.array(array_name, reify=False) return self.slice_index(*A.shape, single=False)
def array_slice_index(self, array_name, **kwargs)
Returns a tuple of slices, each slice equal to the slice(lower_extent, upper_extent, 1) of the dimensions of array_name. .. code-block:: python cube.register("uvw", ("ntime", "na", 3), np.float64) idx = cube.array_slice_index("uvw") uvw[idx].sum() ...
10.612547
10.41147
1.019313
return tuple(slice(l, u, 1) for l, u in zip( self.dim_lower_extent(*slice_dims, single=False), self.dim_upper_extent(*slice_dims, single=False)))
def slice_index(self, *slice_dims, **kwargs)
Returns a tuple of slices, each slice equal to the slice(lower_extent, upper_extent, 1) of the dimensions supplied in slice_dims. If the dimension is integer d, slice(0, d, 1) will be used instead of the lower and upper extents .. code-block:: python A = np.ones(ntime, na) ...
4.43278
4.177914
1.061003
for key in adict: if key.lower() == akey.lower(): return True return False
def contains_case_insensitive(adict, akey)
Check if key is in adict. The search is case insensitive.
2.471076
2.234536
1.105857
with open(json_file, 'wb') as f: json.dump(res, f, sort_keys=True)
def save_result(res, json_file)
Save result to file.
2.631275
2.805487
0.937903
name = unescape(text) name = asciify(name.replace(u'&', u'And').replace(u'@', u'At')) name = capfirst(name) return name
def format_name(text)
Format a comic name.
5.161973
4.892698
1.055036
from ..models import Title titles = Title.objects.select_related('article').filter(article__tree=tree) published_only = (not draft and not preview) if draft: titles = titles.filter(publisher_is_draft=True) elif preview: titles = titles.filter(publisher_is_draft=False) else...
def get_article_from_slug(tree, slug, preview=False, draft=False)
Resolves a slug to a single article object. Returns None if article does not exist
2.788495
3.040537
0.917106
# Needs to re-implement the method but contains all the things the parent does. if not action_map: # actions must not be empty raise TypeError("action_map is a required argument.") def view(request): self = cls(**initkwargs) self.request = request ...
def as_view(cls, action_map=None, **initkwargs)
Allows custom request to method routing based on given ``action_map`` kwarg.
3.717636
3.525353
1.054543
self.session.username = 'gmr' session = self.session.as_dict() if session['last_request_at']: session['last_request_at'] = str(date.fromtimestamp( session['last_request_at'])) # Send a JSON string for our test se...
def get(self, *args, **kwargs)
Example HTTP Get response method. :param args: positional args :param kwargs: keyword args
4.238049
4.2841
0.989251
for key in data: if isinstance(data[key], dict): if data[key].get('type') == 'datetime': data[key] = \ datetime.datetime.fromtimestamp(data[key]['value']) return data
def _deserialize_datetime(self, data)
Take any values coming in as a datetime and deserialize them
2.856528
2.546218
1.121871
if not data: return dict() return self._deserialize_datetime(pickle.loads(data))
def deserialize(self, data)
Return the deserialized data. :param str data: The data to deserialize :rtype: dict
9.104713
10.709119
0.850183
return json.dumps(self._serialize_datetime(data), ensure_ascii=False)
def serialize(self, data)
Return the data as serialized string. :param dict data: The data to serialize :rtype: str
6.69902
8.805279
0.760796
# Check all values for None for attr in self.__dict__: if self.__dict__[attr] is None: raise ValueError(attr + " is not set") # Validate name invalid_chars = GPTaskSpec.invalid_chars() if any(char in invalid_chars for char in self.name): ...
def validate(self)
Perform some basic checks to help ensure that the specification is valid. Throws an exception if an invalid value is found. Returns true if all checks were passed. :return: boolean
3.033624
3.005204
1.009457
# First validate the attributes self.validate() # Check to see if an existing interferes with module creation if os.path.exists(MANIFEST_FILE_NAME): raise OSError("existing manifest blocks manifest file creation") # Write the manifest self.write_man...
def create_zip(self, clean=True, increment_version=True, register=True)
Creates a GenePattern module zip file for upload and installation on a GenePattern server :param clean: boolean :return:
5.115724
5.327786
0.960197
# Create the zip file zip = zipfile.ZipFile(self.name + '.zip', 'w', zipfile.ZIP_DEFLATED) # Add the manifest file to the zip zip.write(MANIFEST_FILE_NAME) # Add the support files to the zip for file in self.support_files: zip.write(file) #...
def _zip_files(self)
Adds the manifest and all support files to the zip file :return:
2.542006
2.194339
1.158438
# First validate the spec self.validate() # Open the manifest file for writing manifest_file = open(os.path.join(module_directory, "manifest"), "w") # Write the header manifest_file.write("# " + self.name + "\n") manifest_file.write("# " + str(datetime....
def write_manifest(self, module_directory="")
Write a GenePattern manifest file for the module :param module_directory: optionally write to subdirectory :return:
2.461321
2.418197
1.017833
if self.author and self.institution: return self.author + ";" + self.institution elif self.author: return self.author else: return self.institution
def _author_line(self)
Helper method to concatenate author and institution values, if necessary :return: string
3.40536
2.668911
1.275936
if not isinstance([], list): raise TypeError("non-list value found where list is expected") return all(isinstance(x, str) for x in arr)
def all_strings(arr)
Ensures that the argument is a list that either is empty or contains only strings :param arr: list :return:
7.139086
7.075222
1.009026
if not isinstance([], list): raise TypeError("non-list value found for parameters") return all(isinstance(x, GPParamSpec) for x in arr)
def _all_params(arr)
Ensures that the argument is a list that either is empty or contains only GPParamSpec's :param arr: list :return:
11.695271
7.753943
1.5083
if not isinstance(self.lsid, str): raise TypeError("lsid is not a string, string expected: " + str(self.lsid)) if self.lsid.count(':') != 4: raise ValueError("lsid contains incorrect number of colons, 4 expected: " + str(self.lsid)) if self.lsid.split(':')[0].l...
def _valid_lsid(self)
Performs some basic (non-comprehensive) LSID validation :return:
2.953256
2.906137
1.016214
# Build the parameter prefix prefix = "p" + str(p_num) + "_" # Generate the manifest string manifest = prefix + "MODE=" + ("IN" if self.type == Type.FILE else "") + "\n" manifest += prefix + "TYPE=" + str(self.type.value) + "\n" if self.type == Type.FILE and len...
def manifest_repr(self, p_num)
Builds a manifest string representation of the parameters and returns it :param p_num: int :return: string
2.76183
2.706643
1.020389
# Generate key/value strings pairs = [] for key, value in self.choices.items(): pairs.append(str(value) + "=" + str(key)) # Assemble into overall string and escape return GPTaskSpec.manifest_escape(";".join(pairs))
def _choices(self)
Generate a string of choices as key/value pairs :return: string
12.111353
10.957487
1.105304
# Add min_values to string num_values = str(self.min_values) if self.min_values else "0" # Handle infinite max_values or finite max_values if self.max_values is None or self.max_values == float("inf"): num_values += "+" else: num_values += ".." +...
def _num_values(self)
Generate a valid num_values string based off min_values and max_values :return: string
3.551211
2.98242
1.190715
raw_namespace = None # Get the Jupyter user, if available try: raw_namespace = os.environ['JPY_USER'] except KeyError: pass # Otherwise get the current user if raw_namespace is None or raw_namespace == '': raw_namespace = get...
def _generate_namespace()
Generate an LSID namespace based off Jupyter user or system user :return: string
3.990494
3.45172
1.156088
# Check for LSID domain setting file try: user_dir = str(pathlib.Path.home()) jupyter_dir = os.path.join(user_dir, '.jupyter') domain_path = os.path.join(jupyter_dir, 'lsid_domain') with open(domain_path, 'r') as domain_file: doma...
def _generate_domain()
Generate an LSID domain based off a setting file or the hostname :return: string
3.945378
3.20831
1.229737
domain = self._generate_domain() namespace = self._generate_namespace() # Return the base LSID return "urn:lsid:" + domain + ":" + namespace
def _generate_base_lsid(self)
Generates and returns a base LSID :return:
5.988072
5.846751
1.024171
parent_dir = os.path.dirname(os.path.realpath(file_path)) # Create the parent directory if it does not exist if not os.path.exists(parent_dir): os.makedirs(parent_dir) # Create blank LSID authority structure blank = self._create_blank_authority() #...
def _create_authority_file(self, file_path)
Create a new LSID authority file at the indicated location :param file_path: location of LSID authority file
2.750469
2.478803
1.109595
authority_file = open(self.authority, 'r') authority_json = json.load(authority_file) authority_file.close() self.base_lsid = authority_json['base_lsid'] self.module_count = int(authority_json['module_count']) self.registered_modules = authority_json['registered_...
def _load_lsid_authority(self)
Load (or reload) the LSID authority file and set class attributes
2.732344
2.509843
1.088651
if self.base_lsid is None: raise Exception("Base LSID in LSID authority not initialized") return self.base_lsid + ":" + str(module_number)
def _assemble_lsid(self, module_number)
Return an assembled LSID based off the provided module number and the authority's base LSID. Note: Never includes the module's version number. :param module_number: :return: string
6.239165
5.092247
1.225228
if self.validate(task_spec.lsid): # Add the module name to the map self.registered_modules[task_spec.lsid] = task_spec.name # Increment module count self.module_count += 1 # Write the updated LSID authority file and reload with o...
def register(self, task_spec)
Registers a module specification with the LSID authority. Validates that it possesses an LSID assigned by the authority. Raises an exception if registration wasn't successful. :param task_spec: :return: boolean - True if registration was successful
3.48612
2.913142
1.196688
# Base LSID matches if not lsid.startswith(self.base_lsid): return False # Module number isn't already taken if check_existing and lsid in self.registered_modules: return False # Everything checks out, return True return True
def validate(self, lsid, check_existing=True)
Validates an LSID with the LSID authority. :param lsid: :return: boolean - is the LSID valid with this authority?
6.107407
6.342541
0.962927
if self.registered_modules is None or lsid not in self.registered_modules: return None else: return self.registered_modules[lsid]
def lookup(self, lsid)
Look up the name of a module by LSID assigned by the authority. Returns None if the LSID is not found. :param lsid: :return: string or none
3.356404
2.854358
1.175888
hostname = get_hostname(url) return host_locks.setdefault(hostname, threading.Lock())
def get_host_lock(url)
Get lock object for given URL host.
4.185407
4.177638
1.00186
if options.handler: for name in set(options.handler): events.addHandler(name, options.basepath, options.baseurl, options.allowdownscale) events.getHandler().start() errors = 0 try: for scraperobj in getScrapers(options.comic, options.basepath, options.adult, options.mult...
def getComics(options)
Retrieve comics.
5.145379
5.148643
0.999366
out.warn("Interrupted!") for t in threads: t.stop() jobs.clear() out.warn("Waiting for download threads to finish.")
def finish()
Print warning about interrupt and empty the job queue.
11.091494
9.231853
1.201437
if '@' in comics: # only scrapers whose directory already exists if len(comics) > 1: out.warn(u"using '@' as comic name ignores all other specified comics.") for scraperclass in scraper.get_scraperclasses(): dirname = getDirname(scraperclass.getName()) ...
def getScrapers(comics, basepath=None, adult=True, multiple_allowed=False, listing=False)
Get scraper objects for the given comics.
3.386438
3.372363
1.004174
out.warn(u"Skipping comic %s: %s" % (scraperclass.getName(), ' '.join(reasons.values())))
def warn_disabled(scraperclass, reasons)
Print warning about disabled comic modules.
9.146851
7.315783
1.25029
self.all_tasks_done.acquire() try: while self.unfinished_tasks: self.all_tasks_done.wait(timeout) finally: self.all_tasks_done.release()
def join(self, timeout=None)
Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete. When the...
2.628773
2.151244
1.221978
self.mutex.acquire() self.queue.clear() self.mutex.release()
def clear(self)
Remove all queue entries.
4.584775
2.91596
1.572304
try: while not self.stopped: scraperobj = jobs.get(False) self.setName(scraperobj.getName()) try: self.getStrips(scraperobj) finally: jobs.task_done() self.setName(sel...
def run(self)
Process from queue until it is empty.
5.983803
5.344682
1.119581