code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if len(nodes) > 0:
data = [node for node in self.get_clients() if node['name'] in nodes]
else:
data = self.get_clients()
channels = []
for client in data:
if 'subscriptions' in client:
if isinstance(client['subscriptions'], lis... | def get_subscriptions(self, nodes=[]) | Returns all the channels where (optionally specified) nodes are subscribed | 1.997096 | 1.863545 | 1.071665 |
data = self.get_clients()
clients = []
for client in data:
if 'subscriptions' in client:
if isinstance(client['subscriptions'], list):
if search_channel in client['subscriptions']:
clients.append(client['name'])
... | def get_subscriptions_channel(self, search_channel) | Return all the nodes that are subscribed to the specified channel | 2.281818 | 2.173156 | 1.050002 |
if sys.platform == "win32":
_clr_compiler = "C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\csc.exe"
else:
_clr_compiler = "mcs"
cmd = [
_clr_compiler,
"/target:library",
"clrmagic.cs"
]
check_call(" ".join... | def build_extension(self, ext) | build clrmagic.dll using csc or mcs | 4.18795 | 3.12145 | 1.341668 |
return self.__handler.wait_for_event(event, timeout=timeout) | def wait_for_event(self, event, timeout=10) | Block waiting for the given event. Returns the event params.
:param event: The event to handle.
:return: The event params.
:param timeout: The maximum time to wait before raising :exc:`.TimeoutError`. | 6.604632 | 9.668749 | 0.683091 |
first = 0
last = len(values)
while first < last:
middle = (first + last) // 2
if values[middle][0] < target:
first = middle + 1
else:
last = middle
return first | def search_greater(values, target) | Return the first index for which target is greater or equal to the first
item of the tuple found in values | 2.041888 | 2.120257 | 0.963038 |
if not isinstance(value, float):
value = float(value)
return self._do_add(value) | def add(self, value) | Add a value to the reservoir
The value will be casted to a floating-point, so a TypeError or a
ValueError may be raised. | 5.097489 | 4.07581 | 1.250669 |
return type(self) is type(other) and self._same_parameters(other) | def same_kind(self, other) | Return True if "other" is an object of the same type and it was
instantiated with the same parameters | 7.258825 | 5.524474 | 1.31394 |
idx = search_greater(self._values, timestamp)
if (idx < len(self._values)
and math.fabs(self._values[idx][0] - timestamp) < self.EPSILON):
return idx
return None | def _lookup(self, timestamp) | Return the index of the value associated with "timestamp" if any, else
None. Since the timestamps are floating-point values, they are
considered equal if their absolute difference is smaller than
self.EPSILON | 5.591712 | 3.92119 | 1.426024 |
idx = self._lookup(timestamp)
if idx is not None:
self._values[idx] = (timestamp, value)
else:
self._values.append((timestamp, value)) | def _put(self, timestamp, value) | Replace the value associated with "timestamp" or add the new value | 3.110175 | 2.889212 | 1.076479 |
values = self.reservoir.sorted_values
def safe(f, *args):
try:
return f(values, *args)
except exceptions.StatisticsError:
return 0.0
plevels = [50, 75, 90, 95, 99, 99.9]
percentiles = [safe(statistics.percentile, p) for ... | def get(self) | Return the computed statistics over the gathered data | 2.700298 | 2.56402 | 1.05315 |
glance = AppGlance(
version=1,
creation_time=time.time(),
slices=(slices or [])
)
SyncWrapper(self._blobdb.insert, BlobDatabaseID.AppGlance, target_app, glance.serialise()).wait() | def reload_glance(self, target_app, slices=None) | Reloads an app's glance. Blocks as long as necessary.
:param target_app: The UUID of the app for which to reload its glance.
:type target_app: ~uuid.UUID
:param slices: The slices with which to reload the app's glance.
:type slices: list[.AppGlanceSlice] | 12.823291 | 13.146665 | 0.975403 |
'''make an imshow of the intranetwork connectivity'''
im = ax.pcolor(params.C_YX, cmap='hot')
ax.axis(ax.axis('tight'))
ax.invert_yaxis()
ax.xaxis.set_ticks_position('top')
ax.set_xticks(np.arange(9)+0.5)
ax.set_yticks(np.arange(8)+0.5)
ax.set_xticklabels(params.X, rotation=270)
ax.s... | def plotConnectivity(ax) | make an imshow of the intranetwork connectivity | 2.939583 | 2.691648 | 1.092113 |
'''return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of nA.
'''
#convolution kernels
x = np.arange(100) * params.dt
kernel = np.exp(-x / params.model_para... | def getMeanInpCurrents(params, numunits=100,
filepattern=os.path.join('simulation_output_default',
'population_input_spikes*')) | return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of nA. | 6.74216 | 5.265046 | 1.280551 |
'''return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of nA.
'''
data = {}
#loop over network-populations
for i, Y in enumerate(params.Y):
... | def getMeanVoltages(params, numunits=100,
filepattern=os.path.join('simulation_output_default',
'voltages')) | return a dict with the per population mean and std synaptic current,
averaging over numcells recorded units from each population in the
network
Returned currents are in unit of nA. | 5.912891 | 4.198267 | 1.408412 |
'''
on colorplot and as background plot the summed CSD contributions
args:
::
ax : matplotlib.axes.AxesSubplot object
T : list, [tstart, tstop], which timeinterval
ylims : list, set range of yaxis to scale with other plots
fancy : bool,
N : integer, set to n... | def plot_signal_sum_colorplot(ax, params, fname='LFPsum.h5', unit='mV', N=1, ylabels = True,
T=[800, 1000], ylim=[-1500, 0], fancy=False, colorbar=True,
cmap='spectral_r', absmax=None, transient=200, rasterized=True) | on colorplot and as background plot the summed CSD contributions
args:
::
ax : matplotlib.axes.AxesSubplot object
T : list, [tstart, tstop], which timeinterval
ylims : list, set range of yaxis to scale with other plots
fancy : bool,
N : integer, set to number of LFP... | 4.269349 | 2.786163 | 1.53234 |
'''
calculates power spectrum of sum signal for all channels
'''
if type(fname) is str and os.path.isfile(fname):
#open file
f = h5py.File(fname)
data = f['data'].value
srate = f['srate'].value
tvec = np.arange(data.shape[1]) * 1000. / srate
f.close()
... | def calc_signal_power(params, fname, transient=200, Df=None, mlab=True, NFFT=1000,
noverlap=0, window=plt.mlab.window_hanning) | calculates power spectrum of sum signal for all channels | 3.866625 | 3.64263 | 1.061493 |
'''
on axes plot the LFP power spectral density
The whole signal duration is used.
args:
::
ax : matplotlib.axes.AxesSubplot object
fancy : bool,
'''
zvec = np.r_[params.electrodeParams['z']]
zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]]
#labels
ytic... | def plot_signal_power_colorplot(ax, params, fname, transient=200, Df=None,
mlab=True, NFFT=1000,
window=plt.mlab.window_hanning,
noverlap=0,
cmap = plt.cm.get_cmap('jet', 21),
... | on axes plot the LFP power spectral density
The whole signal duration is used.
args:
::
ax : matplotlib.axes.AxesSubplot object
fancy : bool, | 4.383095 | 3.318459 | 1.320822 |
'''plot power (variance) as function of depth for total and separate
contributors
Plot variance of sum signal
'''
colors = phlp.get_colors(len(popkeys))
depth = params.electrodeParams['z']
zpos = np.r_[params.layerBoundaries[:, 0],
params.layerBoundaries[-1, 1]]
... | def plotPowers(ax, params, popkeys, dataset, linestyles, linewidths, transient=200, SCALING_POSTFIX='', markerstyles=None) | plot power (variance) as function of depth for total and separate
contributors
Plot variance of sum signal | 3.69632 | 3.194467 | 1.1571 |
urld = {self.extract_site_url: 'extract_token_site.html',
self.success_site_url: 'success_site.html'}
site = urld.get(self.path)
if not site:
log.debug("Requesting false url on login server.")
self.send_error(404)
return
log.de... | def do_GET(self, ) | Handle GET requests
If the path is '/', a site which extracts the token will be generated.
This will redirect the user to the '/sucess' page, which shows
a success message.
:returns: None
:rtype: None
:raises: None | 6.874783 | 5.913122 | 1.162632 |
datapath = os.path.join('html', filename)
sitepath = pkg_resources.resource_filename('pytwitcherapi', datapath)
with open(sitepath, 'r') as f:
html = f.read()
self.wfile.write(html.encode('utf-8')) | def _write_html(self, filename) | Read the html site with the given filename
from the data directory and write it to :data:`RedirectHandler.wfile`.
:param filename: the filename to read
:type filename: :class:`str`
:returns: None
:rtype: None
:raises: None | 3.369091 | 3.330217 | 1.011673 |
log.debug('POST')
self._set_headers()
# convert the parameters back to the original fragment
# because we need to send the original uri to set_token
# url fragments will not show up in self.path though.
# thats why we make the hassle to send it as a post request.... | def do_POST(self, ) | Handle POST requests
When the user is redirected, this handler will respond with a website
which will send a post request with the url fragment as parameters.
This will get the parameters and store the original redirection
url and fragments in :data:`LoginServer.tokenurl`.
:ret... | 13.899447 | 12.233167 | 1.13621 |
log.debug('Setting the token on %s.' % self.session)
self.session.token_from_fragment(redirecturl) | def set_token(self, redirecturl) | Set the token on the session
:param redirecturl: the original full redirect url
:type redirecturl: :class:`str`
:returns: None
:rtype: None
:raises: None | 9.480412 | 9.83414 | 0.964031 |
s = super(TwitchOAuthClient, self)
uri, headers, body = s._add_bearer_token(*args, **kwargs)
authheader = headers.get('Authorization')
if authheader:
headers['Authorization'] = authheader.replace('Bearer', 'OAuth')
return uri, headers, body | def _add_bearer_token(self, *args, **kwargs) | Add a bearer token to the request uri, body or authorization header.
This is overwritten to change the headers slightly. | 3.090543 | 2.886636 | 1.070638 |
print("Installing template from " + username + "/" + repo)
dpath = os.path.join(cwd, "templates")
getunzipped(username, repo, dpath) | def install_template(username, repo) | Installs a Blended template from GitHub | 6.130121 | 6.124487 | 1.00092 |
print("\nBlended: Static Website Generator -\n")
checkConfig()
print("Importing from WordPress...")
wp = parseXML(filepath)
wname = wp.rss.channel.title.cdata
wdesc = wp.rss.channel.description.cdata
wlan = wp.rss.channel.language.cdata
wurl = wp.rss.channel.link.cdata
aname... | def import_wp(filepath) | Imports A WordPress export and converts it to a Blended site | 4.24146 | 3.981395 | 1.06532 |
print("\nBlended: Static Website Generator -\n")
checkConfig()
print("Importing from Blogger...")
blogger = parseXML(filepath)
wname = blogger.feed.title.cdata
aname = blogger.feed.author.name.cdata.strip()
createBlendedFolders()
# Populate the configuration file
createCon... | def import_blogger(filepath) | Imports A Blogger export and converts it to a Blended site | 5.393091 | 5.088368 | 1.059886 |
print("Installing plugin from " + username + "/" + repo)
pip.main(['install', '-U', "git+git://github.com/" +
username + "/" + repo + ".git"]) | def install_plugin(username, repo) | Installs a Blended plugin from GitHub | 4.085574 | 3.897805 | 1.048173 |
print("Blended: Static Website Generator -\n")
checkConfig()
if (sys.version_info > (3, 0)):
wname = input("Website Name: ")
wdesc = input("Website Description: ")
wlan = input("Website Language: ")
wlic = input("Website License: ")
aname = input("Author(s) Na... | def init() | Initiates a new website | 3.216109 | 3.145702 | 1.022382 |
for name in os.listdir(path):
if name != "config.py" and name != "config.pyc" and name != "templates" and name != "content":
localpath = os.path.join(path, name)
if os.path.isfile(localpath):
print("STOR", name, localpath)
ftp.storbinary('STOR ' +... | def placeFiles(ftp, path) | Upload the built files to FTP | 2.247853 | 2.172743 | 1.034569 |
print("Uploading the files in the " + outdir + "/ directory!\n")
# Make sure there is actually a configuration file
config_file_dir = os.path.join(cwd, "config.py")
if not os.path.exists(config_file_dir):
sys.exit(
"There dosen't seem to be a configuration file. Have you run th... | def send_ftp(outdir) | Upload the built website to FTP | 3.982336 | 3.936493 | 1.011645 |
print("Removing the built files!")
# Remove the build folder
build_dir = os.path.join(cwd, outdir)
if os.path.exists(build_dir):
shutil.rmtree(build_dir) | def clean_built(outdir) | Removes all built files | 3.766125 | 3.893611 | 0.967258 |
print("Zipping the built files!")
config_file_dir = os.path.join(cwd, "config.py")
if not os.path.exists(config_file_dir):
sys.exit(
"There dosen't seem to be a configuration file. Have you run the init command?")
else:
sys.path.insert(0, cwd)
try:
f... | def zip_built(outdir) | Packages the build folder into a zip | 3.929801 | 3.819136 | 1.028976 |
print("Purging the Blended files!")
# Remove the templates folder
templ_dir = os.path.join(cwd, "templates")
if os.path.exists(templ_dir):
shutil.rmtree(templ_dir)
# Remove the content folder
cont_dir = os.path.join(cwd, "content")
if os.path.exists(cont_dir):
shutil.r... | def purge() | Removes all files generated by Blended | 1.892786 | 1.801749 | 1.050527 |
text_content = open(filename, "r")
if ".md" in filename:
text_cont1 = "\n" + markdown.markdown(text_content.read()) + "\n"
elif ".docx" in filename:
with open(os.path.join(cwd, "content", filename), "rb") as docx_file:
result = mammoth.convert_to_html(docx_file)
... | def convert_text(filename) | Convert the post/page content using the converters | 2.445175 | 2.397049 | 1.020077 |
print("Building your Blended files into a website!")
reload(sys)
sys.setdefaultencoding('utf8')
build_files(outdir)
print("The files are built! You can find them in the " + outdir +
"/ directory. Run the view command to see what you have created in a web browser.") | def build(outdir) | Blends the generated files and outputs a HTML website | 10.803539 | 8.755145 | 1.233965 |
print("Building your Blended files into a website!")
global outdir_type
outdir_type = outdir
reload(sys)
sys.setdefaultencoding('utf8')
build_files(outdir)
print("Watching the content and templates directories for changes, press CTRL+C to stop...\n")
w = Watcher()
w.run() | def interactive(outdir) | Blends the generated files and outputs a HTML website on file change | 10.463599 | 8.307616 | 1.259519 |
index_path = os.path.realpath(os.path.join(cwd, outdir, "index.html"))
if os.path.exists(index_path):
webbrowser.open('file://' + index_path)
else:
print("The index.html file could not be found in the " + outdir +
"/ folder! Have you deleted it or have you built with home... | def view(outdir) | Opens the built index.html file in a web browser | 4.985383 | 4.460182 | 1.117753 |
event_handler = Handler()
threads = []
paths = [os.path.join(cwd, "content"), os.path.join(cwd, "templates")]
for i in paths:
targetPath = str(i)
self.observer.schedule(event_handler, targetPath, recursive=True)
threads.append(self.observer)
... | def run(self) | Run the builder on changes | 3.479869 | 3.412011 | 1.019888 |
cleaned_numbers = []
for x in uncleaned_numbers:
try:
cleaned_numbers.append(int(x))
except ValueError:
cleaned_numbers.append(x)
return cleaned_numbers | def _sanitize_numbers(uncleaned_numbers) | Convert strings to integers if possible | 1.951264 | 1.686403 | 1.157057 |
min_number = min(filter(lambda x : type(x)==int,numbers))
if min_number < 0:
return [x+abs(min_number) if type(x)==int else x for x in numbers]
else:
return numbers | def _handle_negatives(numbers) | Add the minimum negative number to all the numbers in the
such that all the elements become >= 0 | 3.214851 | 2.971263 | 1.081981 |
max_number = max(filter(lambda x : type(x)==int,numbers))
# If the maxium number is 0, then all the numbers should be 0
# coz we have called handle_negatives prior to this function
if max_number == 0 :
return upticks[0]*len(numbers)
else:
normalized_numbers = [ float(x)/max_numb... | def _draw_tickgram(numbers) | Takes a list of integers and generate the equivalent list
of ticks corresponding to each of the number | 4.349286 | 4.421904 | 0.983578 |
'''
Reads text file containing gids of neuron populations as created within the
NEST simulation. These gids are not continuous as in the simulation devices
get created in between.
'''
gidfile = open(os.path.join(model_params.raw_nest_output_path,
model_params.GID_... | def get_raw_gids(model_params) | Reads text file containing gids of neuron populations as created within the
NEST simulation. These gids are not continuous as in the simulation devices
get created in between. | 7.539754 | 2.799771 | 2.692989 |
if os.path.exists(path):
shutil.rmtree(path)
os.makedirs(path)
else:
os.makedirs(path) | def replace_folder(path) | If the specified folder exists, it is deleted and recreated | 1.990361 | 1.861497 | 1.069226 |
if ".html" in filename:
newFilename = filename
elif ".md" in filename:
newFilename = filename.replace(".md", ".html")
elif ".tile" in filename:
newFilename = filename.replace(".tile", ".html")
elif ".jade" in filename:
newFilename = filename.replace(".jade", ".html")... | def get_html_filename(filename) | Converts the filename to a .html extension | 1.877201 | 1.808008 | 1.03827 |
newFilename = filename.replace(".html", "")
newFilename = newFilename.replace(".md", "")
newFilename = newFilename.replace(".txt", "")
newFilename = newFilename.replace(".tile", "")
newFilename = newFilename.replace(".jade", "")
newFilename = newFilename.replace(".rst", "")
newFilename ... | def get_html_clear_filename(filename) | Clears the file extension from the filename and makes it nice looking | 2.106444 | 2.116177 | 0.995401 |
theurl = "https://github.com/" + username + "/" + repo + "/archive/master.zip"
name = os.path.join(thedir, 'temp.zip')
try:
name = urllib.urlretrieve(theurl, name)
name = os.path.join(thedir, 'temp.zip')
except IOError as e:
print("Can't retrieve %r to %r: %s" % (theurl, the... | def getunzipped(username, repo, thedir) | Downloads and unzips a zip file | 2.147536 | 2.168509 | 0.990328 |
config_file_dir = os.path.join(cwd, "config.py")
if os.path.exists(config_file_dir):
print("Making a backup of your config file!")
config_file_dir2 = os.path.join(cwd, "config.py.oldbak")
copyfile(config_file_dir, config_file_dir2) | def checkConfig() | If the config.py file exists, back it up | 3.093786 | 2.640264 | 1.171772 |
config_file_dir = os.path.join(cwd, "config.py")
config_file = open(config_file_dir, "w")
config_file.write('blended_version = ' + app_version + '\n')
config_file.write('\n')
config_file.write(
'# Configuration is automatically generated by Blended (http://jmroper.com/blended), feel fr... | def createConfig(app_version=5.0, wname="", wdesc="", wdescl="", wlic="", wlan="", wurl="", aname="", abio="") | Generates a config file from the information | 2.036175 | 2.038667 | 0.998778 |
# Create the templates folder
create_folder(os.path.join(cwd, "templates"))
# Create the templates/assets folder
create_folder(os.path.join(cwd, "templates", "assets"))
# Create the templates/assets/css folder
create_folder(os.path.join(cwd, "templates", "assets", "css"))
# Create th... | def createBlendedFolders() | Creates the standard folders for a Blended website | 1.558193 | 1.536416 | 1.014174 |
items = ((k, os.environ.get(k)) for k in keys)
subenv = dict((k, v) for (k, v) in items if v is not None)
needset = lambda k: k in keys and not subenv.get(k)
def setifnonempty(key, value):
if value:
subenv[key] = value
if needset('HOST'):
import platform
su... | def get_environ(keys) | Get environment variables from :data:`os.environ`.
:type keys: [str]
:rtype: dict
Some additional features.
* If 'HOST' is not in :data:`os.environ`, this function
automatically fetch it using :meth:`platform.node`.
* If 'TTY' is not in :data:`os.environ`, this function
automatically ... | 3.938778 | 2.989775 | 1.317416 |
host = data['environ']['HOST']
tty = data['environ'].get('TTY') or 'NO_TTY'
return ':'.join(map(str, [
host, tty, os.getppid(), data['start']])) | def generate_session_id(data) | Generate session ID based on HOST, TTY, PID [#]_ and start time.
:type data: dict
:rtype: str
.. [#] PID of the shell, i.e., PPID of this Python process. | 7.98385 | 5.354791 | 1.490973 |
if print_session_id and record_type != 'init':
raise RuntimeError(
'--print-session-id should be used with --record-type=init')
cfstore = ConfigStore()
# SOMEDAY: Pass a list of environment variables to shell by "rash
# init" and don't read configuration in "rash record" comman... | def record_run(record_type, print_session_id, **kwds) | Record shell history. | 4.751201 | 4.600098 | 1.032848 |
args_safe = map(conditional_escape, args)
kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
six.iteritems(kwargs)])
return mark_safe(format_string.format(*args_safe, **kwargs_safe)) | def format_html(format_string, *args, **kwargs) | Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments. | 2.8521 | 2.376809 | 1.19997 |
if path is None:
return None
if path.endswith(os.path.sep):
return path
else:
return path + os.path.sep | def normalize_directory(path) | Append "/" to `path` if needed. | 2.500148 | 2.27993 | 1.09659 |
args = command.split(' ')
for prog in args:
if '=' not in prog:
return prog
return args[0] | def sql_program_name_func(command) | Extract program name from `command`.
>>> sql_program_name_func('ls')
'ls'
>>> sql_program_name_func('git status')
'git'
>>> sql_program_name_func('EMACS=emacs make')
'make'
:type command: str | 5.618756 | 7.857169 | 0.715112 |
seq1 = path1.rstrip(sep).split(sep)
seq2 = path2.rstrip(sep).split(sep)
return sum(1 for (p1, p2) in zip_longest(seq1, seq2) if p1 != p2) | def sql_pathdist_func(path1, path2, sep=os.path.sep) | Return a distance between `path1` and `path2`.
>>> sql_pathdist_func('a/b/', 'a/b/', sep='/')
0
>>> sql_pathdist_func('a/', 'a/b/', sep='/')
1
>>> sql_pathdist_func('a', 'a/', sep='/')
0 | 2.382922 | 2.830312 | 0.841929 |
with self._get_db() as db:
with open(self.schemapath) as f:
db.cursor().executescript(f.read())
db.commit() | def _init_db(self) | Creates the database tables. | 3.724171 | 3.092646 | 1.204202 |
if commit:
self._need_commit = True
if self._db:
yield self._db
else:
try:
with self._get_db() as db:
self._db = db
db.create_function("REGEXP", 2, sql_regexp_func)
db.create_... | def connection(self, commit=False) | Context manager to keep around DB connection.
:rtype: sqlite3.Connection
SOMEDAY: Get rid of this function. Keeping connection around as
an argument to the method using this context manager is
probably better as it is more explicit.
Also, holding "global state" as instance att... | 3.095563 | 2.823534 | 1.096343 |
if self._db:
db = self._db
try:
if self._need_commit:
db.commit()
finally:
db.interrupt()
self._db = None
self._need_commit = False | def close_connection(self) | Close connection kept by :meth:`connection`.
If commit is needed, :meth:`sqlite3.Connection.commit`
is called first and then :meth:`sqlite3.Connection.interrupt`
is called.
A few methods/generators support :meth:`close_connection`:
- :meth:`search_command_record`
- :me... | 4.03304 | 4.149111 | 0.972025 |
with self.connection() as connection:
for row in connection.execute(sql, params):
yield row
if not self._db:
return | def _executing(self, sql, params=[]) | Execute and yield rows in a way to support :meth:`close_connection`. | 5.263426 | 4.664082 | 1.128502 |
keys = ['id', 'rash_version', 'schema_version', 'updated']
sql =
with self.connection() as connection:
for row in connection.execute(sql):
yield VersionRecord(**dict(zip(keys, row))) | def get_version_records(self) | Yield RASH version information stored in DB. Latest first.
:rtype: [VersionRecord] | 7.550654 | 5.063298 | 1.491252 |
from .__init__ import __version__ as version
with self.connection(commit=True) as connection:
for vrec in self.get_version_records():
if (vrec.rash_version == version and
vrec.schema_version == schema_version):
return # no nee... | def update_version_records(self) | Update rash_info table if necessary. | 4.628276 | 3.579151 | 1.293121 |
keys = ['command_history_id', 'command', 'session_history_id',
'cwd', 'terminal',
'start', 'stop', 'exit_code']
sql =
desired_row = [
crec.command, normalize_directory(crec.cwd), crec.terminal,
convert_ts(crec.start), convert_ts(c... | def select_by_command_record(self, crec) | Yield records that matches to `crec`.
All attributes of `crec` except for `environ` are concerned. | 5.613255 | 5.837826 | 0.961532 |
if after_context or before_context or context:
kwds['condition_as_column'] = True
limit = kwds['limit']
kwds['limit'] = -1
kwds['unique'] = False
kwds['sort_by'] = {
'session': ['session_start_time', 'start_time'],
... | def search_command_record(
self,
after_context, before_context, context, context_type,
**kwds) | Search command history.
:rtype: [CommandRecord] | 5.711075 | 5.693574 | 1.003074 |
with self.connection() as db:
crec = self._select_command_record(db, command_history_id)
crec.pipestatus = self._get_pipestatus(db, command_history_id)
# Set environment variables
cenv = self._select_environ(db, 'command', command_history_id)
... | def get_full_command_record(self, command_history_id,
merge_session_environ=True) | Get fully retrieved :class:`CommandRecord` instance by ID.
By "fully", it means that complex slots such as `environ` and
`pipestatus` are available.
:type command_history_id: int
:type merge_session_environ: bool | 2.857531 | 2.793509 | 1.022918 |
kwargs.setdefault('uptime', pytz.utc.localize(datetime.utcnow()))
kwargs.setdefault('priority', 0)
kwargs.setdefault('status', 'online')
kwargs.setdefault('status_text', '')
kwargs.setdefault('connection_type', CONNECTION_XMPP)
kwargs.setdefault('encrypted', Tru... | def start_user_session(self, username, domain, resource, **kwargs) | Method to add a user session for debugging.
Accepted parameters are the same as to the constructor of :py:class:`~xmpp_backends.base.UserSession`. | 2.78927 | 2.682617 | 1.039757 |
'''
NEST produces one file per virtual process containing recorder output.
This function gathers and combines them into one single file per
network population.
Parameters
----------
model_params : object
network parameters object
Returns
-------
None
... | def merge_gdf(model_params, raw_label='spikes_', file_type='gdf',
fileprefix='spikes') | NEST produces one file per virtual process containing recorder output.
This function gathers and combines them into one single file per
network population.
Parameters
----------
model_params : object
network parameters object
Returns
-------
None | 3.593971 | 2.964829 | 1.212202 |
'''
Convert dictionary containing numpy arrays to dictionary containing lists
Parameters
----------
d : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
d : dict
modified dictionary
'''
for key,value in d.iteritems... | def dict_of_numpyarray_to_dict_of_list(d) | Convert dictionary containing numpy arrays to dictionary containing lists
Parameters
----------
d : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
d : dict
modified dictionary | 3.918006 | 2.169636 | 1.805836 |
'''
Read parameters and send them to SLI
Parameters
----------
p : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
None
'''
for name in p.keys():
value = p[name]
if type(value) == np.ndarray:
value ... | def send_nest_params_to_sli(p) | Read parameters and send them to SLI
Parameters
----------
p : dict
sli parameter name and value as dictionary key and value pairs
Returns
-------
None | 3.640528 | 3.023103 | 1.204235 |
attr = None
try:
field = model._meta.get_field_by_name(name)[0]
if isinstance(field, RelatedObject):
label = field.opts.verbose_name
else:
label = field.verbose_name
except models.FieldDoesNotExist:
if name == "__unicode__":
label = fo... | def label_for_field(name, model, return_attr=False) | Returns a sensible label for a field name. The name can be a callable,
property (but not created with @property decorator) or the name of an
object's attribute, as well as a genuine fields. If return_attr is
True, the resolved attribute (which could be a callable) is also returned.
This will be None if ... | 2.055667 | 2.059121 | 0.998323 |
value = int(value)
with self.lock:
self.value += value | def update(self, value) | Update the current rate with the given value.
The value must be an integer. | 8.014771 | 6.513328 | 1.230519 |
instant_rate = float(self.value) / float(self.tick_interval)
with self.lock:
if self.initialized:
self.rate += (self.alpha * (instant_rate - self.rate))
else:
self.initialized = True
self.rate = instant_rate
... | def tick(self) | Decay the current rate according to the elapsed time | 4.428555 | 3.901139 | 1.135195 |
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of ticks depends on the actual time
# passed since the latest notification. Consider using
# a real timer to tick the EWMA.
self.tick()
fo... | def notify(self, value) | Add a new observation to the metric | 14.102375 | 13.883858 | 1.015739 |
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | def tick_all(self, times) | Tick all the EWMAs for the given number of times | 6.143014 | 5.001749 | 1.228173 |
now = time.time()
elapsed = now - self.latest_tick
if elapsed > self.tick_interval:
ticks = int(elapsed / self.tick_interval)
self.tick_all(ticks)
self.latest_tick = now | def tick(self) | Emulate a timer: in order to avoid a real timer we "tick" a number
of times depending on the actual time passed since the last tick | 3.741546 | 3.464142 | 1.080079 |
with self.lock:
self.tick()
data = dict(
kind="meter",
count=self.count,
mean=self.count / (time.time() - self.started_on),
one=self.m1.rate,
five=self.m5.rate,
fifteen=self.m15.rat... | def get(self) | Return the computed statistics over the gathered data | 4.763925 | 4.576121 | 1.04104 |
return Interval(Interval.OPEN, lower_value, upper_value, Interval.OPEN) | def open(lower_value, upper_value) | Helper function to construct an interval object with open lower and upper.
For example:
>>> open(100.2, 800.9)
(100.2, 800.9) | 5.971761 | 8.006178 | 0.745894 |
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.CLOSED) | def closed(lower_value, upper_value) | Helper function to construct an interval object with closed lower and upper.
For example:
>>> closed(100.2, 800.9)
[100.2, 800.9] | 5.599448 | 8.772508 | 0.638295 |
return Interval(Interval.OPEN, lower_value, upper_value, Interval.CLOSED) | def openclosed(lower_value, upper_value) | Helper function to construct an interval object with a open lower and closed upper.
For example:
>>> openclosed(100.2, 800.9)
(100.2, 800.9] | 5.342324 | 7.223641 | 0.739561 |
return Interval(Interval.CLOSED, lower_value, upper_value, Interval.OPEN) | def closedopen(lower_value, upper_value) | Helper function to construct an interval object with a closed lower and open upper.
For example:
>>> closedopen(100.2, 800.9)
[100.2, 800.9) | 5.579996 | 7.80481 | 0.714943 |
return Interval(self._lower, self._lower_value, self._upper_value, self._upper) | def copy(self) | Returns a new :class:`~pyinter.Interval` object with the same bounds and values. | 7.748505 | 4.753032 | 1.630224 |
g = operator.gt if self._lower is self.OPEN else operator.ge
l = operator.lt if self._upper is self.OPEN else operator.le
return g(value, self.lower_value) and l(value, self._upper_value) | def _contains_value(self, value) | Helper function for __contains__ to check a single value is contained within the interval | 3.967319 | 3.322472 | 1.194086 |
if self > other:
smaller, larger = other, self
else:
smaller, larger = self, other
if larger.empty():
return False
if smaller._upper_value == larger._lower_value:
return smaller._upper == smaller.CLOSED and larger._lower == smaller... | def overlaps(self, other) | If self and other have any overlapping values returns True, otherwise returns False | 4.659942 | 4.605962 | 1.011719 |
if self.overlaps(other):
newlower_value = max(self.lower_value, other.lower_value)
new_upper_value = min(self._upper_value, other._upper_value)
new_lower, new_upper = self._get_new_lower_upper(other, self.intersect)
return Interval(new_lower, newlower_val... | def intersect(self, other) | Returns a new :class:`~pyinter.Interval` representing the intersection of this :class:`~pyinter.Interval`
with the other :class:`~pyinter.Interval` | 3.037364 | 2.676616 | 1.134778 |
if other.empty():
return self
if self in other:
return open(self._lower_value, self._lower_value)
if self._lower == other._lower and self._lower_value == other._lower_value:
return Interval(self._opposite_boundary_type(other._upper), other._upper_valu... | def difference(self, other) | Returns a new Interval or an :class:`~pyinter.IntervalSet` representing the subtraction of this
:class:`~pyinter.Interval` with the other :class:`~pyinter.Interval`.
The result will contain everything that is contained by the left interval but not contained
by the second interval.
If t... | 1.989296 | 1.883902 | 1.055944 |
try:
iter(schedule)
except TypeError:
raise TypeError("{} is not iterable".format(schedule))
if not callable(callback):
raise TypeError("{} is not callable".format(callback))
thread = Timer(schedule, callback, tag)
id_ = str(uuid.uuid4())
with LOCK:
REGIS... | def register(callback, schedule, tag=None) | Register a callback which will be called at scheduled intervals with
the metrics that have the given tag (or all the metrics if None).
Return an identifier which can be used to access the registered callback later. | 3.263146 | 3.277076 | 0.995749 |
with LOCK:
thread = REGISTRY.pop(id_, None)
if thread is not None:
thread.cancel()
return thread | def remove(id_) | Remove the callback and its schedule | 6.891757 | 6.091672 | 1.131341 |
if tag is None:
return metrics.metrics_by_name_list(metrics.metrics())
else:
return metrics.metrics_by_tag(tag) | def get_metrics(tag) | Return the values for the metrics with the given tag or all the available metrics if None | 4.298176 | 4.089894 | 1.050926 |
start = time.time()
next_tick = start
while True:
next_tick += interval
yield next_tick | def fixed_interval_scheduler(interval) | A scheduler that ticks at fixed intervals of "interval" seconds | 4.019457 | 3.394941 | 1.183955 |
games = []
json = response.json()
gamejsons = json['games']
for j in gamejsons:
g = cls.wrap_json(j)
games.append(g)
return games | def wrap_search(cls, response) | Wrap the response from a game search into instances
and return them
:param response: The response from searching a game
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None | 4.032591 | 4.336884 | 0.929836 |
games = []
json = response.json()
topjsons = json['top']
for t in topjsons:
g = cls.wrap_json(json=t['game'],
viewers=t['viewers'],
channels=t['channels'])
games.append(g)
return games | def wrap_topgames(cls, response) | Wrap the response from quering the top games into instances
and return them
:param response: The response for quering the top games
:type response: :class:`requests.Response`
:returns: the new game instances
:rtype: :class:`list` of :class:`Game`
:raises: None | 4.588144 | 5.45092 | 0.841719 |
g = Game(name=json.get('name'),
box=json.get('box'),
logo=json.get('logo'),
twitchid=json.get('_id'),
viewers=viewers,
channels=channels)
return g | def wrap_json(cls, json, viewers=None, channels=None) | Create a Game instance for the given json
:param json: the dict with the information of the game
:type json: :class:`dict`
:param viewers: The viewer count
:type viewers: :class:`int`
:param channels: The viewer count
:type channels: :class:`int`
:returns: the ne... | 5.09814 | 4.881138 | 1.044457 |
channels = []
json = response.json()
channeljsons = json['channels']
for j in channeljsons:
c = cls.wrap_json(j)
channels.append(c)
return channels | def wrap_search(cls, response) | Wrap the response from a channel search into instances
and return them
:param response: The response from searching a channel
:type response: :class:`requests.Response`
:returns: the new channel instances
:rtype: :class:`list` of :class:`channel`
:raises: None | 4.263154 | 4.229062 | 1.008061 |
json = response.json()
c = cls.wrap_json(json)
return c | def wrap_get_channel(cls, response) | Wrap the response from getting a channel into an instance
and return it
:param response: The response from getting a channel
:type response: :class:`requests.Response`
:returns: the new channel instance
:rtype: :class:`list` of :class:`channel`
:raises: None | 6.957853 | 9.98347 | 0.696937 |
c = Channel(name=json.get('name'),
status=json.get('status'),
displayname=json.get('display_name'),
game=json.get('game'),
twitchid=json.get('_id'),
views=json.get('views'),
followers... | def wrap_json(cls, json) | Create a Channel instance for the given json
:param json: the dict with the information of the channel
:type json: :class:`dict`
:returns: the new channel instance
:rtype: :class:`Channel`
:raises: None | 2.358762 | 2.304335 | 1.023619 |
streams = []
json = response.json()
streamjsons = json['streams']
for j in streamjsons:
s = cls.wrap_json(j)
streams.append(s)
return streams | def wrap_search(cls, response) | Wrap the response from a stream search into instances
and return them
:param response: The response from searching a stream
:type response: :class:`requests.Response`
:returns: the new stream instances
:rtype: :class:`list` of :class:`stream`
:raises: None | 4.562905 | 4.412118 | 1.034176 |
json = response.json()
s = cls.wrap_json(json['stream'])
return s | def wrap_get_stream(cls, response) | Wrap the response from getting a stream into an instance
and return it
:param response: The response from getting a stream
:type response: :class:`requests.Response`
:returns: the new stream instance
:rtype: :class:`list` of :class:`stream`
:raises: None | 7.627106 | 9.89371 | 0.770905 |
if json is None:
return None
channel = Channel.wrap_json(json.get('channel'))
s = Stream(game=json.get('game'),
channel=channel,
twitchid=json.get('_id'),
viewers=json.get('viewers'),
preview=json.ge... | def wrap_json(cls, json) | Create a Stream instance for the given json
:param json: the dict with the information of the stream
:type json: :class:`dict` | None
:returns: the new stream instance
:rtype: :class:`Stream` | None
:raises: None | 4.070269 | 3.631145 | 1.120933 |
json = response.json()
u = cls.wrap_json(json)
return u | def wrap_get_user(cls, response) | Wrap the response from getting a user into an instance
and return it
:param response: The response from getting a user
:type response: :class:`requests.Response`
:returns: the new user instance
:rtype: :class:`list` of :class:`User`
:raises: None | 6.182529 | 8.608526 | 0.718187 |
u = User(usertype=json['type'],
name=json['name'],
logo=json['logo'],
twitchid=json['_id'],
displayname=json['display_name'],
bio=json['bio'])
return u | def wrap_json(cls, json) | Create a User instance for the given json
:param json: the dict with the information of the user
:type json: :class:`dict` | None
:returns: the new user instance
:rtype: :class:`User`
:raises: None | 6.159687 | 7.251833 | 0.849397 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.