code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
#create a cell instance cell = self.cellsim(cellindex, return_just_cell=True) #local containers synidx = {} #get synaptic placements and cells from the network, #then set spike times, for i, X in enumerate(self.X): synidx[X] = self.fetchSyn...
def get_synidx(self, cellindex)
Local function, draw and return synapse locations corresponding to a single cell, using a random seed set as `POPULATIONSEED` + `cellindex`. Parameters ---------- cellindex : int Index of cell object. Returns ------- synidx : dict ...
13.798888
12.10971
1.13949
#segment indices in each layer is stored here, list of np.array syn_idx = [] #loop over layer bounds, find synapse locations for i, zz in enumerate(self.layerBoundaries): if nidx[i] == 0: syn_idx.append(np.array([], dtype=int)) else: ...
def fetchSynIdxCell(self, cell, nidx, synParams)
Find possible synaptic placements for each cell As synapses are placed within layers with bounds determined by self.layerBoundaries, it will check this matrix accordingly, and use the probabilities from `self.connProbLayer to distribute. For each layer, the synapses are placed with prob...
6.160531
5.54074
1.111861
tic = time() cell = LFPy.Cell(**self.cellParams) cell.set_pos(**self.pop_soma_pos[cellindex]) cell.set_rotation(**self.rotations[cellindex]) if return_just_cell: #with several cells, NEURON can only hold one cell at the time allsecnames ...
def cellsim(self, cellindex, return_just_cell = False)
Do the actual simulations of LFP, using synaptic spike times from network simulation. Parameters ---------- cellindex : int cell index between 0 and population size-1. return_just_cell : bool If True, return only the `LFPy.Cell` object if Fal...
5.253289
4.925683
1.06651
for i, X in enumerate(self.X): #range(self.k_yXL.shape[1]): synParams = self.synParams synParams.update({ 'weight' : self.J_yX[i], 'tau' : self.tau_yX[i], }) for j in range(len(self.synIdx[cellindex][X])): ...
def insert_all_synapses(self, cellindex, cell)
Insert all synaptic events from all presynaptic layers on cell object with index `cellindex`. Parameters ---------- cellindex : int cell index in the population. cell : `LFPy.Cell` instance Postsynaptic target cell. Returns ------- ...
3.939897
4.224962
0.932529
#Insert synapses in an iterative fashion try: spikes = self.networkSim.dbs[X].select(SpCell[:idx.size]) except AttributeError as ae: raise ae, 'could not open CachedNetwork database objects' #apply synaptic delays if synDelays is not None and id...
def insert_synapses(self, cell, cellindex, synParams, idx = np.array([]), X='EX', SpCell = np.array([]), synDelays = None)
Insert synapse with `parameters`=`synparams` on cell=cell, with segment indexes given by `idx`. `SpCell` and `SpTimes` picked from Brunel network simulation Parameters ---------- cell : `LFPy.Cell` instance Postsynaptic target cell. cellindex : int ...
7.120036
7.085253
1.004909
SpCell = [] for size in numSyn: SpCell.append(np.random.randint(nodes.min(), nodes.max(), size=size).astype('int32')) return SpCell
def fetchSpCells(self, nodes, numSyn)
For N (nodes count) nestSim-cells draw POPULATION_SIZE x NTIMES random cell indexes in the population in nodes and broadcast these as `SpCell`. The returned argument is a list with len = numSyn.size of np.arrays, assumes `numSyn` is a list Parameters ---------- ...
5.369401
5.770365
0.930513
if max_procs is None: max_procs = cpu_count() kw_arr = saturate_kwargs(keys=keys, **kwargs) if len(kw_arr) == 0: return if isinstance(affinity, int): win32process.SetProcessAffinityMask(win32api.GetCurrentProcess(), affinity) task_queue = queue.Queue() while len(kw_arr) > 0: ...
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs)
Provide interface for multiprocessing Args: func: callable functions keys: keys in kwargs that want to use process max_procs: max number of processes show_proc: whether to show process affinity: CPU affinity **kwargs: kwargs for func
2.466973
2.49405
0.989143
# Validate if keys are in kwargs and if they are iterable if isinstance(keys, str): keys = [keys] keys = [k for k in keys if k in kwargs and hasattr(kwargs.get(k, None), '__iter__')] if len(keys) == 0: return [] # Saturate coordinates of kwargs kw_corr = list(product(*(range(len(kwargs[k])...
def saturate_kwargs(keys, **kwargs)
Saturate all combinations of kwargs Args: keys: keys in kwargs that want to use process **kwargs: kwargs for func
3.960814
3.949572
1.002846
return SmoothIdw(input_geojson_points, variable_name, power, nb_pts, resolution, variable_name2, mask, **kwargs ).render(nb_class=nb_class, ...
def quick_idw(input_geojson_points, variable_name, power, nb_class, nb_pts=10000, resolution=None, disc_func=None, mask=None, user_defined_breaks=None, variable_name2=None, output='GeoJSON', **kwargs)
Function acting as a one-shot wrapper around SmoothIdw object. Read a file of point values and optionnaly a mask file, return the smoothed representation as GeoJSON or GeoDataFrame. Parameters ---------- input_geojson_points : str Path to file to use as input (Points/Polygons) or GeoDataFra...
2.620145
3.046934
0.859928
return SmoothStewart( input_geojson_points, variable_name, span, beta, typefct, nb_pts, resolution, variable_name2, mask, **kwargs ).render( nb_class=nb_class, ...
def quick_stewart(input_geojson_points, variable_name, span, beta=2, typefct='exponential',nb_class=None, nb_pts=10000, resolution=None, mask=None, user_defined_breaks=None, variable_name2=None, output="GeoJSON", **kwargs)
Function acting as a one-shot wrapper around SmoothStewart object. Read a file of point values and optionnaly a mask file, return the smoothed representation as GeoJSON or GeoDataFrame. Parameters ---------- input_geojson_points : str Path to file to use as input (Points/Polygons) or GeoDat...
2.443706
3.069389
0.796154
minlon, minlat, maxlon, maxlat = bounds minlon, minlat, maxlon, maxlat = bounds offset_lon = (maxlon - minlon) / 8 offset_lat = (maxlat - minlat) / 8 minlon -= offset_lon maxlon += offset_lon minlat -= offset_lat maxlat += offset_lat nb_x = int(nb_points**0.5) nb_y = int(nb...
def make_regular_points_with_no_res(bounds, nb_points=10000)
Return a regular grid of points within `bounds` with the specified number of points (or a close approximate value). Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. nb_points : int, optionnal The desired number of points (default: 10000)...
2.042879
2.053275
0.994937
# xmin, ymin, xmax, ymax = bounds minlon, minlat, maxlon, maxlat = bounds offset_lon = (maxlon - minlon) / 8 offset_lat = (maxlat - minlat) / 8 minlon -= offset_lon maxlon += offset_lon minlat -= offset_lat maxlat += offset_lat if longlat: height = hav_dist( ...
def make_regular_points(bounds, resolution, longlat=True)
Return a regular grid of points within `bounds` with the specified resolution. Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. resolution : int The resolution to use, in the same unit as `bounds` Returns ------- points : nu...
1.747926
1.774682
0.984924
if longlat: return hav_dist(xy1[:, None], xy2) else: d0 = np.subtract.outer(xy1[:, 0], xy2[:, 0]) d1 = np.subtract.outer(xy1[:, 1], xy2[:, 1]) return np.hypot(d0, d1)
def make_dist_mat(xy1, xy2, longlat=True)
Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- xy1 : numpy.array The first set of coordinates as [(x, y), (x, y), (x, y)]. xy2 : numpy.array The second set of coordinates as [(x...
2.312845
2.61444
0.884643
# locs1 = np.radians(locs1) # locs2 = np.radians(locs2) cos_lat1 = np.cos(locs1[..., 0]) cos_lat2 = np.cos(locs2[..., 0]) cos_lat_d = np.cos(locs1[..., 0] - locs2[..., 0]) cos_lon_d = np.cos(locs1[..., 1] - locs2[..., 1]) return 6367000 * np.arccos( cos_lat_d - cos_lat1 * cos_lat2...
def hav_dist(locs1, locs2)
Return a distance matrix between two set of coordinates. Use geometric distance (default) or haversine distance (if longlat=True). Parameters ---------- locs1 : numpy.array The first set of coordinates as [(long, lat), (long, lat)]. locs2 : numpy.array The second set of coordinates ...
1.764913
1.791289
0.985276
polygons, data = [], [] for i, polygon in enumerate(collec_poly.collections): mpoly = [] for path in polygon.get_paths(): path.should_simplify = False poly = path.to_polygons() exterior, holes = [], [] if len(poly) > 0 and len(poly[0]) > 3: ...
def isopoly_to_gdf(collec_poly, levels, field_name="levels")
Convert a collection of matplotlib.contour.QuadContourSet to a GeoDataFrame Set an attribute `field_name` on each feature, according to `levels` values (`levels` must have the same number of features as the collection of contours) Parameters ---------- collection_polygons : matplotlib.contour.QuadC...
2.192192
2.416321
0.907244
chinese = _get_hanzi(s) if not chinese: return UNKNOWN if chinese.issubset(_SHARED_CHARACTERS): return BOTH if chinese.issubset(_TRADITIONAL_CHARACTERS): return TRADITIONAL if chinese.issubset(_SIMPLIFIED_CHARACTERS): return SIMPLIFIED return MIXED
def identify(s)
Identify what kind of Chinese characters a string contains. *s* is a string to examine. The string's Chinese characters are tested to see if they are compatible with the Traditional or Simplified characters systems, compatible with both, or contain a mixture of Traditional and Simplified characters. Th...
3.695765
2.901109
1.273915
chinese = _get_hanzi(s) if not chinese: return False elif chinese.issubset(_SHARED_CHARACTERS): return True elif chinese.issubset(_TRADITIONAL_CHARACTERS): return True return False
def is_traditional(s)
Check if a string's Chinese characters are Traditional. This is equivalent to: >>> identify('foo') in (TRADITIONAL, BOTH)
4.191882
4.382872
0.956424
chinese = _get_hanzi(s) if not chinese: return False elif chinese.issubset(_SHARED_CHARACTERS): return True elif chinese.issubset(_SIMPLIFIED_CHARACTERS): return True return False
def is_simplified(s)
Check if a string's Chinese characters are Simplified. This is equivalent to: >>> identify('foo') in (SIMPLIFIED, BOTH)
4.469214
4.403224
1.014987
if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.GetAction, operation_timeout, max_envelope_size, locale) self.service.invoke.set_options(tsoapheaders=headers) return self.service.invoke
def get(self, resource, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
6.414755
5.583664
1.148843
headers = None return self.service.invoke(headers, obj)
def put(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
24.089975
20.58954
1.17001
if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.DeleteAction, operation_timeout, max_envelope_size, locale) return self.service.invoke(headers, None)
def delete(self, resource, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
5.124918
4.497344
1.139543
if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.CreateAction, operation_timeout, max_envelope_size, locale) return self.service.invoke(headers, obj)
def create(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
5.065469
4.52764
1.118788
if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.CommandAction, operation_timeout, max_envelope_size, locale) return self.service.invoke(headers, obj)
def command(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
4.9117
4.518206
1.087091
if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource, Session.ReceiveAction, operation_timeout, max_envelope_size, locale) return self.service.invoke(headers, obj)
def recieve(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None)
resource can be a URL or a ResourceLocator
5.0078
4.698138
1.065912
'''default figure size''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm, self.frontierswidth/self.inchpercm], })
def set_default_fig_style(self)
default figure size
8.318691
8.287811
1.003726
'''twice width figure size''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*2, self.frontierswidth/self.inchpercm], })
def set_large_fig_style(self)
twice width figure size
12.143198
8.072189
1.504325
'''4 times width, 1.5 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*4, self.frontierswidth/self.inchpercm*1.5], })
def set_broad_fig_style(self)
4 times width, 1.5 times height
8.776773
6.137344
1.43006
'''2 times width, 2 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*2, self.frontierswidth/self.inchpercm*2], })
def set_enormous_fig_style(self)
2 times width, 2 times height
9.065235
6.983856
1.298027
'''figure size corresponding to Plos 1 column''' plt.rcParams.update({ 'figure.figsize' : [self.PLOSwidth1Col,self.PLOSwidth1Col*ratio], })
def set_PLOS_1column_fig_style(self, ratio=1)
figure size corresponding to Plos 1 column
7.38593
5.166504
1.42958
'''figure size corresponding to Plos 2 columns''' plt.rcParams.update({ 'figure.figsize' : [self.PLOSwidth2Col, self.PLOSwidth2Col*ratio], })
def set_PLOS_2column_fig_style(self, ratio=1)
figure size corresponding to Plos 2 columns
7.567133
5.070257
1.492456
if RANK == 0: if 'LFP' in self.savelist: #get the per population LFPs and total LFP from all populations: self.LFPdict, self.LFPsum = self.calc_lfp() self.LFPdictLayer = self.calc_lfp_layer() #save global LFP sum, and from...
def run(self)
Perform the postprocessing steps, computing compound signals from cell-specific output files.
2.341127
2.271512
1.030647
if not os.path.isdir(self.cells_path): os.mkdir(self.cells_path) if not os.path.isdir(self.figures_path): os.mkdir(self.figures_path) if not os.path.isdir(self.populations_path): os.mkdir(self.populations_path)
def _set_up_savefolder(self)
Create catalogs for different file output to clean up savefolder.
1.990685
1.913835
1.040154
LFParray = np.array([]) LFPdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'LFP.h5')) f = h5py.File(fil) if i == 0: LFParray = np.zeros((l...
def calc_lfp(self)
Sum all the LFP contributions from every cell type.
3.603059
3.395076
1.06126
CSDarray = np.array([]) CSDdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'CSD.h5')) f = h5py.File(fil) if i == 0: CSDarray = np.zeros((l...
def calc_csd(self)
Sum all the CSD contributions from every layer.
3.656303
3.450104
1.059766
LFPdict = {} lastY = None for Y, y in self.mapping_Yy: if lastY != Y: try: LFPdict.update({Y : self.LFPdict[y]}) except KeyError: pass else: try: LFPdict[...
def calc_lfp_layer(self)
Calculate the LFP from concatenated subpopulations residing in a certain layer, e.g all L4E pops are summed, according to the `mapping_Yy` attribute of the `hybridLFPy.Population` objects.
4.263563
3.13924
1.358152
CSDdict = {} lastY = None for Y, y in self.mapping_Yy: if lastY != Y: try: CSDdict.update({Y : self.CSDdict[y]}) except KeyError: pass else: try: CSDdict[...
def calc_csd_layer(self)
Calculate the CSD from concatenated subpopulations residing in a certain layer, e.g all L4E pops are summed, according to the `mapping_Yy` attribute of the `hybridLFPy.Population` objects.
4.306645
3.239501
1.329416
#file filter EXCLUDE_FILES = glob.glob(os.path.join(self.savefolder, 'cells')) EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder, 'populations', 'subsamples')) EXCLUDE_FILES += glob.glob(os.path.join(self.savefolder, ...
def create_tar_archive(self)
Create a tar archive of the main simulation outputs.
3.226648
3.139189
1.027861
sort_by = request.GET.get('sort_by') if sort_by: if sort_by in [el.name for el in queryset.model._meta.fields]: queryset = queryset.order_by(sort_by) else: if sort_by in request.session: sort_by = request.session[sort_by] try: ...
def sort_queryset(queryset, request, context=None)
Returns a sorted queryset The context argument is only used in the template tag
3.192385
3.201529
0.997144
(it0, it1) = itertools.tee(iterative) ps = _backward_shifted_predicate(predicate, num, it1) return (e for (e, p) in zip(it0, ps) if p)
def include_before(predicate, num, iterative)
Return elements in `iterative` including `num`-before elements. >>> list(include_before(lambda x: x == 'd', 2, 'abcded')) ['b', 'c', 'd', 'e', 'd']
5.186059
7.688352
0.674535
(it0, it1) = itertools.tee(iterative) ps = _forward_shifted_predicate(predicate, num, it1) return (e for (e, p) in zip(it0, ps) if p)
def include_after(predicate, num, iterative)
Return elements in `iterative` including `num`-after elements. >>> list(include_after(lambda x: x == 'b', 2, 'abcbcde')) ['b', 'c', 'b', 'c', 'd']
5.066581
7.029679
0.720741
(it0, it1, it2) = itertools.tee(iterative, 3) psf = _forward_shifted_predicate(predicate, num, it1) psb = _backward_shifted_predicate(predicate, num, it2) return (e for (e, pf, pb) in zip(it0, psf, psb) if pf or pb)
def include_context(predicate, num, iterative)
Return elements in `iterative` including `num` before and after elements. >>> ''.join(include_context(lambda x: x == '!', 2, 'bb!aa__bb!aa')) 'bb!aabb!aa'
3.831304
4.346447
0.881479
''' calculates power spectrum of sum signal for all channels ''' for i, data_type in enumerate(['CSD','LFP','CSD_10_0', 'LFP_10_0']): if i % SIZE == RANK: # Load data if data_type in ['CSD','LFP']: fname=os.path.join(params.savefolder, data_type+'sum.h...
def calc_signal_power(params)
calculates power spectrum of sum signal for all channels
3.947126
3.795708
1.039892
'''This function calculates the depth-resolved power spectrum of signals without taking into account any cross-correlation.''' for i, data_type in enumerate(['LFP','CSD']): if i % SIZE == RANK: # Determine size of PSD matrix f = h5py.File(os.path.join(params....
def calc_uncorrelated_signal_power(params)
This function calculates the depth-resolved power spectrum of signals without taking into account any cross-correlation.
3.922417
3.696882
1.061007
''' This function calculates the variance of the sum signal and all population-resolved signals ''' depth = params.electrodeParams['z'] ############################ ### CSD ### ############################ for i, data_type in enumerate(['CSD','LFP']): if i % ...
def calc_variances(params)
This function calculates the variance of the sum signal and all population-resolved signals
5.496962
4.672287
1.176503
target = event.source self.privmsg(target, 'Hello %s!' % target)
def on_join(self, connection, event)
Handles the join event and greets everone :param connection: the connection with the event :type connection: :class:`irc.client.ServerConnection` :param event: the event to handle :type event: :class:`irc.client.Event` :returns: None
8.092523
9.754203
0.829645
# Probably it makes sense to use this daemon to provide search # API, so that this daemon is going to be the only process that # is connected to the DB? from .config import ConfigStore from .indexer import Indexer from .log import setup_daemon_log_file, LogForTheFuture from .watchrecord...
def daemon_run(no_error, restart, record_path, keep_json, check_duplicate, use_polling, log_level)
Run RASH index daemon. This daemon watches the directory ``~/.config/rash/data/record`` and translate the JSON files dumped by ``record`` command into sqlite3 DB at ``~/.config/rash/data/db.sqlite``. ``rash init`` will start RASH automatically by default. But there are alternative ways to start da...
3.970293
4.029472
0.985314
import subprocess import sys from .utils.py3compat import nested from .utils.pathutils import mkdirp if outpath != os.devnull: mkdirp(os.path.dirname(outpath)) with nested(open(os.devnull), open(outpath, 'w')) as (stdin, stdout): subprocess.Popen( ...
def start_daemon_in_subprocess(options, outpath=os.devnull)
Run `rash daemon --no-error` in background. :type options: list of str :arg options: options for "rash daemon" command :type outpath: str :arg outpath: path to redirect daemon output
3.704626
3.063451
1.209298
from pprint import pprint from .config import ConfigStore from .database import DataBase db = DataBase(ConfigStore().db_path) with db.connection(): for ch_id in command_history_id: crec = db.get_full_command_record(ch_id) pprint(crec.__dict__) print("...
def show_run(command_history_id)
Show detailed command history by its ID.
5.278893
5.13945
1.027132
token = self._get_token() self._enqueue(self._PendingItem(token, BlobCommand(token=token, database=database, content=InsertCommand(key=key.bytes, value=value)), callback))
def insert(self, database, key, value, callback=None)
Insert an item into the given database. :param database: The database into which to insert the value. :type database: .BlobDatabaseID :param key: The key to insert. :type key: uuid.UUID :param value: The value to insert. :type value: bytes :param callback: A call...
13.941129
11.28864
1.23497
token = self._get_token() self._enqueue(self._PendingItem(token, BlobCommand(token=token, database=database, content=DeleteCommand(key=key.bytes)), callback))
def delete(self, database, key, callback=None)
Delete an item from the given database. :param database: The database from which to delete the value. :type database: .BlobDatabaseID :param key: The key to delete. :type key: uuid.UUID :param callback: A callback to be called on success or failure.
18.03113
14.179764
1.27161
token = self._get_token() self._enqueue(self._PendingItem(token, BlobCommand(token=token, database=database, content=ClearCommand()), callback))
def clear(self, database, callback=None)
Wipe the given database. This only affects items inserted remotely; items inserted on the watch (e.g. alarm clock timeline pins) are not removed. :param database: The database to wipe. :type database: .BlobDatabaseID :param callback: A callback to be called on success or failure.
20.862904
20.956072
0.995554
xml = Service._create_request(headers, body) try: response = self.session.post(self.endpoint, verify=False, data=xml) logging.debug(response.content) except Exception as e: traceback.print_exc() raise WSManException(e) if respons...
def invoke(self, headers, body)
Invokes the soap service
3.0257
2.961906
1.021538
if re.match('(.*)@(.+)', username) is not None: if delegation is True: raise Exception('Kerberos is not yet supported, specify the username in <domain>\<username> form for NTLM') else: raise Exception('Kerberos is not yet supported, specify the us...
def _determine_auth_mechanism(username, password, delegation)
if the username contains at '@' sign we will use kerberos if the username contains a '/ we will use ntlm either NTLM or Kerberos. In fact its basically always Negotiate.
5.537426
5.206016
1.063659
envelope = OrderedDict() for (namespace, alias) in Service.Namespaces.items(): envelope['@xmlns:' + alias] = namespace envelope['soap:Header'] = headers envelope['soap:Body'] = body return xmltodict.unparse({'soap:Envelope': envelope}, encoding='utf-8')
def _create_request(headers, body)
Create the SOAP 1.2 Envelope An ordered dictionary is required to ensure the same order is reflected in the XML, otherwise the SOAP Body element would appear before the Header element.
5.0774
3.769595
1.346935
try: soap_response = xmltodict.parse(xml, process_namespaces=True, namespaces=Service.Namespaces) except Exception: logging.debug('unable to parse the xml response: %s', xml) raise WSManException("the remote host returned an invalid soap response") #...
def _parse_response(xml)
Attempt to parse the SOAP response and return a python object Raise a WSManException if a Fault is found
4.597083
4.099346
1.121418
try: # python 2 from urllib2 import urlopen, HTTPError, URLError except ImportError: # python 3 from urllib.request import urlopen, HTTPError, URLError if os.path.isdir(FIJI_ROOT) and not force: return elif not os.path.isdir(FIJI_ROOT): print('Fiji m...
def fetch(force=False)
Fetch and extract latest Life-Line version of Fiji is just ImageJ to *~/.bin*. Parameters ---------- force : bool Force overwrite of existing Fiji in *~/.bin*.
2.96218
2.956619
1.001881
if isinstance(value, six.string_types): string = value else: string = json.dumps(value, cls=DjangoJSONEncoder) return mark_safe(escapejson(string))
def escapejson_filter(value)
Escape `value` to prevent </script> and unicode whitespace attacks. If `value` is not a string, JSON-encode it first.
2.890796
3.429672
0.842878
try: if self.host: if self.port: client = MongoClient(self.host, self.port) else: client = MongoClient( self.host, MongoCollection.DEFAULT_PORT) else: client = MongoC...
def get_mongo_cursor(self, bulk=False)
Returns Mongo cursor using the class variables :param bulk: bulk writer option :type bulk: boolean :return: mongo collection for which cursor will be created :rtype: mongo colection object
2.338096
2.345057
0.997032
try: result = bulk_cursor.execute() except BulkWriteError as bwe: msg = "bulk_cursor_execute: Exception in executing Bulk cursor to mongo with {error}".format( error=str(bwe)) raise Exception(msg) except Exception as e: msg...
def bulk_cursor_execute(self, bulk_cursor)
Executes the bulk_cursor :param bulk_cursor: Cursor to perform bulk operations :type bulk_cursor: pymongo bulk cursor object :returns: pymongo bulk cursor object (for bulk operations)
3.81581
4.010879
0.951365
if _environ.get('TMUX'): return 'tmux' elif subdict_by_key_prefix(_environ, 'BYOBU'): return 'byobu' elif _environ.get('TERM').startswith('screen'): return _environ['TERM'] elif _environ.get('COLORTERM'): return _environ['COLORTERM'] else: return _environ...
def detect_terminal(_environ=os.environ)
Detect "terminal" you are using. First, this function checks if you are in tmux, byobu, or screen. If not it uses $COLORTERM [#]_ if defined and fallbacks to $TERM. .. [#] So, if you are in Gnome Terminal you have "gnome-terminal" instead of "xterm-color"".
3.804736
3.28247
1.159108
now = time.time() self.sentmessages.appendleft(now) if len(self.sentmessages) == self.sentmessages.maxlen: # check if the oldes message is older than # limited by self.limitinterval oldest = self.sentmessages[-1] waittime = self.limitinter...
def get_waittime(self)
Return the appropriate time to wait, if we sent too many messages :returns: the time to wait in seconds :rtype: :class:`float` :raises: None
5.542225
5.173996
1.071169
waittime = self.get_waittime() if waittime: log.debug('Sent too many messages. Waiting %s seconds', waittime) time.sleep(waittime) return super(ServerConnection3, self).send_raw(string)
def send_raw(self, string)
Send raw string to the server. The string will be padded with appropriate CR LF. If too many messages are sent, this will call :func:`time.sleep` until it is allowed to send messages again. :param string: the raw string to send :type string: :class:`str` :returns: None ...
5.412184
4.946679
1.094105
m = self._rfc_1459_command_regexp.match(line) prefix = m.group('prefix') tags = self._process_tags(m.group('tags')) source = self._process_prefix(prefix) command = self._process_command(m.group('command')) arguments = self._process_arguments(m.group('argument')) ...
def _process_line(self, line)
Process the given line and handle the events :param line: the raw message :type line: :class:`str` :returns: None :rtype: None :raises: None
4.837385
4.673741
1.035014
if command == "privmsg": if irc.client.is_channel(target): command = "pubmsg" else: if irc.client.is_channel(target): command = "pubnotice" else: command = "privnotice" return command
def _resolve_command(self, command, target)
Get the correct event for the command Only for 'privmsg' and 'notice' commands. :param command: The command string :type command: :class:`str` :param target: either a user or a channel :type target: :class:`str` :returns: the correct event type :rtype: :class:`s...
3.089376
2.844181
1.08621
if isinstance(msg, tuple): if command in ["privmsg", "pubmsg"]: command = "ctcp" else: command = "ctcpreply" msg = list(msg) log.debug("tags: %s, command: %s, source: %s, target: %s, " "arguments: %s"...
def _handle_message(self, tags, source, command, target, msg)
Construct the correct events and handle them :param tags: the tags of the message :type tags: :class:`list` of :class:`message.Tag` :param source: the sender of the message :type source: :class:`str` :param command: the event type :type command: :class:`str` :par...
2.078718
2.15778
0.963359
if not tags: return [] return [message.Tag.from_str(x) for x in tags.split(';')]
def _process_tags(self, tags)
Process the tags of the message :param tags: the tags string of a message :type tags: :class:`str` | None :returns: list of tags :rtype: :class:`list` of :class:`message.Tag` :raises: None
6.649899
4.465139
1.489292
if not arguments: return None a = arguments.split(" :", 1) arglist = a[0].split() if len(a) == 2: arglist.append(a[1]) return arglist
def _process_arguments(self, arguments)
Process the arguments :param arguments: arguments string of a message :type arguments: :class:`str` | None :returns: A list of arguments :rtype: :class:`list` of :class:`str` | None :raises: None
3.888431
3.878082
1.002669
mongo_doc = {} if isinstance(key_list, list) and key_list: for key in key_list: mongo_doc[key] = "$" + str(key) return mongo_doc
def build_mongo_doc(self, key_list)
Creates the components of aggregation pipeline :param key_list: list of key which will be used to create the components of aggregation pipeline :type key_list: list :returns mongo_doc: dict
3.219997
3.40637
0.945287
pipeline = [] if isinstance(collection.where_dict, dict) and collection.where_dict: match_dict = { "$match": collection.where_dict } pipeline.append(match_dict) group_keys_dict = self.build_mongo_doc(self.join_keys) push_dict...
def build_pipeline(self, collection)
Creates aggregation pipeline for aggregation :param collection: Mongo collection for aggregation :type collection: MongoCollection :return pipeline: list of dicts
3.210357
3.284057
0.977558
collection_cursor = collection.get_mongo_cursor() grouped_docs = list(collection_cursor.aggregate(pipeline)) grouped_docs_dict = {} while grouped_docs: doc = grouped_docs.pop() keys_list = [] for group_by_key in self.join_keys: ...
def fetch_and_process_data(self, collection, pipeline)
Fetches and Processess data from the input collection by aggregating using the pipeline :param collection: The collection object for which mongo connection has to be made :type collection: MongoCollection :param pipeline: The pipeline using which aggregation will be performed ...
3.446902
3.334865
1.033596
collections = { 'left': self.left_collection, 'right': self.right_collection } for collection_type, collection in collections.iteritems(): pipeline = self.build_pipeline(collection) self.collections_data[collection_type] = self.fetch_and_...
def get_collections_data(self)
Driver function to fetch the data from the two collections
3.952595
3.625683
1.090166
if string.isdigit(): return int(string) try: return float(string) except ValueError: pass string = string.rstrip() for (suf, mult) in DURATION_SUFFIX_MAP.items(): if string.lower().endswith(suf): try: return parse_duration(string[:-len...
def parse_duration(string)
Parse human readable duration. >>> parse_duration('1m') 60 >>> parse_duration('7 days') == 7 * 24 * 60 * 60 True
3.015587
3.27108
0.921893
shell = CommandShell('http://192.168.137.238:5985/wsman', 'Administrator', 'Pa55w0rd') shell.open() command_id = shell.run('ipconfig', ['/all']) (stdout, stderr, exit_code) = shell.receive(command_id) sys.stdout.write(stdout.strip() + '\r\n') shell.close() ...
def create_session()
shell = CommandShell('http://192.168.145.132:5985/wsman', 'Administrator', 'Pa55w0rd')
4.846301
3.018076
1.605759
return self.djipsum_fields().randomCharField( self.model_class(), field_name=field_name )
def fake_chars_or_choice(self, field_name)
Return fake chars or choice it if the `field_name` has choices. Then, returning random value from it. This specially for `CharField`. Usage: faker.fake_chars_or_choice('field_name') Example for field: TYPE_CHOICES = ( ('project', 'I wanna to talk a...
18.568129
20.771749
0.893913
return self.djipsum_fields().randomDecimalField( self.model_class(), field_name=field_name )
def fake_decimal(self, field_name)
Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number. Usage: faker.fake_decimal('field_name') Example: 10.7, 13041.00, 200.000.000
15.032312
20.869417
0.720303
return self.djipsum_fields().getOrCreateForeignKey( model_class=self.model_class(), field_name=field_name )
def fake_fk(self, field_name)
Return related random object to set as ForeignKey. Example Output: <User: username>
11.350813
13.035952
0.870731
instance_m2m = getattr(obj, field_name) objects_m2m = instance_m2m.model.objects.all() if objects_m2m.exists(): ids_m2m = [i.pk for i in objects_m2m] random_decission = random.sample( range(min(ids_m2m), max(ids_m2m)), max(ids_m2m) - 1 ...
def fake_m2m(self, obj, field_name)
Return the random objects from m2m relationship. The ManyToManyField need specific object, so i handle it after created the object.
3.332985
3.216388
1.036251
try: # Cleaning the fields, and check if has `ForeignKey` type. cleaned_fields = {} for key, value in fields.items(): if type(value) is dict: try: if value['type'] == 'fk': fake_f...
def create(self, fields)
Create the object only once. So, you need loop to usage. :param `fields` is dictionary fields.
3.058797
2.98588
1.024421
kw = dict(start=pd.Timestamp(start, tz='UTC').date(), end=pd.Timestamp(end, tz='UTC').date()) us_cal = getattr(sys.modules[__name__], f'{calendar}TradingCalendar')() return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))
def trading_dates(start, end, calendar='US')
Trading dates for given exchange Args: start: start date end: end date calendar: exchange as string Returns: pd.DatetimeIndex: datetime index Examples: >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27'] >>> trd_dates = trading_dates(start='2018-12-2...
3.669919
5.024704
0.730375
if isinstance(level, str): level = getattr(logging, level.upper()) log_name = name_or_func if isinstance(name_or_func, str) else utils.func_scope(name_or_func) logger = logging.getLogger(name=log_name) logger.setLevel(level=level) if not len(logger.handlers): formatter = logging.Format...
def get_logger( name_or_func, log_file='', level=logging.INFO, types='stream', **kwargs )
Generate logger Args: name_or_func: logger name or current running function log_file: logger file level: level of logs - debug, info, error types: file or stream, or both Returns: logger Examples: >>> get_logger(name_or_func='download_data', level='debug', ...
1.826186
2.00695
0.909931
if raw_password is None: self.set_unusable_password() else: xmpp_backend.set_password(self.node, self.domain, raw_password)
def set_password(self, raw_password)
Calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_password` for the user. If password is ``None``, calls :py:func:`~xmpp_backends.base.XmppBackendBase.set_unusable_password`.
4.677664
3.283081
1.424779
return xmpp_backend.check_password(self.node, self.domain, raw_password)
def check_password(self, raw_password)
Calls :py:func:`~xmpp_backends.base.XmppBackendBase.check_password` for the user.
9.582454
4.993373
1.919034
data = {} if limit: data['limit'] = limit if offset: data['offset'] = offset result = self._request('GET', '/clients', data=json.dumps(data)) return result.json()
def get_clients(self, limit=None, offset=None)
Returns a list of clients.
2.615846
2.448667
1.068274
data = self._request('GET', '/clients/{}'.format(client)) return data.json()
def get_client_data(self, client)
Returns a client.
6.418293
5.11897
1.253825
data = self._request('GET', '/clients/{}/history'.format(client)) return data.json()
def get_client_history(self, client)
Returns the history for a client.
5.85574
4.428399
1.322315
data = self._request('GET', '/events/{}'.format(client)) return data.json()
def get_all_client_events(self, client)
Returns the list of current events for a given client.
6.957533
5.291198
1.314926
data = self._request('GET', '/events/{}/{}'.format(client, check)) return data.json()
def get_event(self, client, check)
Returns an event for a given client & check name.
5.908376
4.435277
1.332132
self._request('DELETE', '/events/{}/{}'.format(client, check)) return True
def delete_event(self, client, check)
Resolves an event for a given check on a given client. (delayed action)
7.618624
5.511122
1.382409
self._request('POST', '/resolve', data=json.dumps({'client': client, 'check': check})) return True
def post_event(self, client, check)
Resolves an event. (delayed action)
7.607171
5.851633
1.300008
data = self._request('GET', '/checks/{}'.format(check)) return data.json()
def get_check(self, check)
Returns a check.
5.987484
5.308366
1.127933
data = { 'check': check, 'subscribers': [subscribers] } self._request('POST', '/request', data=json.dumps(data)) return True
def post_check_request(self, check, subscribers)
Issues a check execution request.
4.754748
4.070218
1.16818
self._request('POST', '/silenced', data=json.dumps(kwargs)) return True
def post_silence_request(self, kwargs)
Create a silence entry.
7.458628
6.664973
1.119078
self._request('POST', '/silenced/clear', data=json.dumps(kwargs)) return True
def clear_silence(self, kwargs)
Clear a silence entry.
8.654382
6.773422
1.277697
data = {} if age: data['max_age'] = age result = self._request('GET', '/aggregates/{}'.format(check), data=json.dumps(data)) return result.json()
def get_aggregate_check(self, check, age=None)
Returns the list of aggregates for a given check
4.070437
3.797176
1.071964
data = {'consumers': consumers, 'messages': messages} try: self._request('GET', '/health', data=json.dumps(data)) return True except SensuAPIException: return False
def get_health(self, consumers=2, messages=100)
Returns health information on transport & Redis connections.
4.141165
4.015817
1.031214
data = self._request('GET', '/results/{}'.format(client)) return data.json()
def get_results(self, client)
Returns a result.
8.904492
6.73607
1.321912
data = self._request('GET', '/results/{}/{}'.format(client, check)) return data.json()
def get_result(self, client, check)
Returns an event for a given client & result name.
6.737268
4.819676
1.397867
self._request('DELETE', '/results/{}/{}'.format(client, check)) return True
def delete_result(self, client, check)
Deletes an check result data for a given check on a given client.
7.728853
6.394804
1.208615
data = { 'source': client, 'name': check, 'output': output, 'status': status, } self._request('POST', '/results', data=json.dumps(data)) return True
def post_result_data(self, client, check, output, status)
Posts check result data.
3.34399
3.182236
1.05083
if path: self._request('POST', '/stashes/{}'.format(path), json=payload) else: self._request('POST', '/stashes', json=payload) return True
def create_stash(self, payload, path=None)
Create a stash. (JSON document)
3.086036
2.719916
1.134607