code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def config_list(ctx):
ingest_config_obj(ctx, silent=False)
click.echo(json.dumps(ctx.obj['config'].to_dict(), indent=4)) | List the current configuration. |
def isBlockComment(self, block, column):
dataObject = block.userData()
data = dataObject.data if dataObject is not None else None
return self._syntax.isBlockComment(data, column) | Check if character at column is a block comment |
def Expandkey(key, clen):
import sha
from string import join
from array import array
blocks = (clen + 19) / 20
xkey = []
seed = key
for i in xrange(blocks):
seed = sha.new(key + seed).digest()
xkey.append(seed)
j = join(xkey, '')
return array('L', j) | Internal method supporting encryption and decryption functionality. |
def username(anon, obj, field, val):
return anon.faker.user_name(field=field) | Generates a random username |
def _handle_watch_metadata(self, node, scope, ctxt, stream):
keyvals = node.metadata.keyvals
if "watch" not in keyvals:
raise errors.PfpError("Packed fields require a packer function set")
if "update" not in keyvals:
raise errors.PfpError("Packed fields require a packer function set")
watch_field_name = keyvals["watch"]
update_func_name = keyvals["update"]
watch_fields = list(map(lambda x: self.eval(x.strip()), watch_field_name.split(";")))
update_func = scope.get_id(update_func_name)
return {
"type": "watch",
"watch_fields": watch_fields,
"update_func": update_func,
"func_call_info": (ctxt, scope, stream, self, self._coord)
} | Handle watch vars for fields |
def endpointlist_post_save(instance, *args, **kwargs):
with open(instance.upload.file.name, mode='rb') as f:
lines = f.readlines()
for url in lines:
if len(url) > 255:
LOGGER.debug('Skipping this endpoint, as it is more than 255 characters: %s' % url)
else:
if Endpoint.objects.filter(url=url, catalog=instance.catalog).count() == 0:
endpoint = Endpoint(url=url, endpoint_list=instance)
endpoint.catalog = instance.catalog
endpoint.save()
if not settings.REGISTRY_SKIP_CELERY:
update_endpoints.delay(instance.id)
else:
update_endpoints(instance.id) | Used to process the lines of the endpoint list. |
def add_jinja2_ext(pelican):
if 'JINJA_ENVIRONMENT' in pelican.settings:
pelican.settings['JINJA_ENVIRONMENT']['extensions'].append(AssetsExtension)
else:
pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension) | Add Webassets to Jinja2 extensions in Pelican settings. |
def update_cache_for_instance(
model_name, instance_pk, instance=None, version=None):
cache = SampleCache()
invalid = cache.update_instance(model_name, instance_pk, instance, version)
for invalid_name, invalid_pk, invalid_version in invalid:
update_cache_for_instance.delay(
invalid_name, invalid_pk, version=invalid_version) | Update the cache for an instance, with cascading updates. |
def _handleCallInitiated(self, regexMatch, callId=None, callType=1):
if self._dialEvent:
if regexMatch:
groups = regexMatch.groups()
if len(groups) >= 2:
self._dialResponse = (int(groups[0]) , int(groups[1]))
else:
self._dialResponse = (int(groups[0]), 1)
else:
self._dialResponse = callId, callType
self._dialEvent.set() | Handler for "outgoing call initiated" event notification line |
def _roundSlist(slist):
slist[-1] = 60 if slist[-1] >= 30 else 0
for i in range(len(slist)-1, 1, -1):
if slist[i] == 60:
slist[i] = 0
slist[i-1] += 1
return slist[:-1] | Rounds a signed list over the last element and removes it. |
async def _recv_reply(self):
raw_reply, = await self._async_socket.recv_multipart()
reply = from_msgpack(raw_reply)
_log.debug("Received reply: %s", reply)
self._replies[reply.id] = reply
self._events.pop(reply.id).set() | Helper task to recieve a reply store the result and trigger the associated event. |
def extract_common_fields(self, data):
return dict(
dc=data.get('dc'),
role=data.get('role'),
account_name=data.get('accountname'),
user_id=data.get('user_id'),
login=data.get('login'),
login_url=data.get('login_url'),
api_endpoint=data.get('api_endpoint'),
) | Extract fields from a metadata query. |
def del_action_role(ctx):
objects = ctx.obj['objects']
action = ctx.obj['action']
role = ctx.obj['role']
if action is None or role is None:
log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
return
for item in objects:
if role in item.perms[action]:
item.perms[action].remove(role)
item.save()
log("Done") | Deletes a role from an action on objects |
def validate_nonce(nonce, secret):
nonce_components = nonce.split(':', 2)
if not len(nonce_components) == 3:
return False
timestamp = nonce_components[0]
salt = nonce_components[1]
nonce_signature = nonce_components[2]
calculated_nonce = calculate_nonce(timestamp, secret, salt)
if not nonce == calculated_nonce:
return False
return True | Is the nonce one that was generated by this library using the provided secret? |
def __load_settings(self):
file_path = self.file_path
try:
self.data = json.load(open(file_path))
except FileNotFoundError:
print("Could not load", file_path) | Load settings from .json file |
def removeFilter(self, filter_index):
f = self._filter[filter_index]
self._filter.remove(f) | removes a layer filter based on position in filter list |
def description(self):
if self._meta and self._meta.get_payload():
return utils.TrueCallableProxy(self._description)
return utils.CallableProxy(None) | Get the textual description of the category |
def im_set_topic(self, room_id, topic, **kwargs):
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) | Sets the topic for the direct message |
def find_global(self, name):
defglobal = lib.EnvFindDefglobal(self._env, name.encode())
if defglobal == ffi.NULL:
raise LookupError("Global '%s' not found" % name)
return Global(self._env, defglobal) | Find the Global by its name. |
def decode_netloc(self):
rv = _decode_idna(self.host or '')
if ':' in rv:
rv = '[%s]' % rv
port = self.port
if port is not None:
rv = '%s:%d' % (rv, port)
auth = ':'.join(filter(None, [
_url_unquote_legacy(self.raw_username or '', '/:%@'),
_url_unquote_legacy(self.raw_password or '', '/:%@'),
]))
if auth:
rv = '%s@%s' % (auth, rv)
return rv | Decodes the netloc part into a string. |
def trigger(self, *args, **kwargs):
for h in self.handlers:
h(*args, **kwargs) | Execute the handlers with a message, if any. |
def special_get_field(self, value, args, kwargs, format_spec=None):
if value in self.chain:
raise BadOptionFormat("Recursive option", chain=self.chain + [value]) | Also take the spec into account |
def handle_left_double_click(self, info):
if (self.double_click_focus == False):
print(self.pre, "handle_left_double_click: focus on")
self.cb_focus()
else:
print(self.pre, "handle_left_double_click: focus off")
self.cb_unfocus()
self.double_click_focus = not(
self.double_click_focus) | Whatever we want to do, when the VideoWidget has been double-clicked with the left button |
def enable_vt_mode(filehandle=None):
if filehandle is None:
filehandle = msvcrt.get_osfhandle(sys.__stdout__.fileno())
current_mode = wintypes.DWORD()
KERNEL32.GetConsoleMode(filehandle, ctypes.byref(current_mode))
new_mode = 0x0004 | current_mode.value
KERNEL32.SetConsoleMode(filehandle, new_mode) | Enables virtual terminal processing mode for the given console or stdout |
def _check_missing_manifests(self, segids):
manifest_paths = [ self._manifest_path(segid) for segid in segids ]
with Storage(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:
exists = stor.files_exist(manifest_paths)
dne = []
for path, there in exists.items():
if not there:
(segid,) = re.search(r'(\d+):0$', path).groups()
dne.append(segid)
return dne | Check if there are any missing mesh manifests prior to downloading. |
def sort(self):
super(JSSObjectList, self).sort(key=lambda k: k.id) | Sort list elements by ID. |
def add_matplotlib_cmaps(fail_on_import_error=True):
try:
from matplotlib import cm as _cm
from matplotlib.cbook import mplDeprecation
except ImportError:
if fail_on_import_error:
raise
return
for name in _cm.cmap_d:
if not isinstance(name, str):
continue
try:
with warnings.catch_warnings():
warnings.simplefilter('error', mplDeprecation)
cm = _cm.get_cmap(name)
add_matplotlib_cmap(cm, name=name)
except Exception as e:
if fail_on_import_error:
print("Error adding colormap '%s': %s" % (name, str(e))) | Add all matplotlib colormaps. |
def _create_element(name, element_type, data, server=None):
if 'properties' in data:
data['property'] = ''
for key, value in data['properties'].items():
if not data['property']:
data['property'] += '{0}={1}'.format(key, value.replace(':', '\\:'))
else:
data['property'] += ':{0}={1}'.format(key, value.replace(':', '\\:'))
del data['properties']
_api_post(element_type, _clean_data(data), server)
return unquote(name) | Create a new element |
def _compute_register_list(self, operand):
ret = []
for reg_range in operand.reg_list:
if len(reg_range) == 1:
ret.append(ReilRegisterOperand(reg_range[0].name, reg_range[0].size))
else:
reg_num = int(reg_range[0].name[1:])
reg_end = int(reg_range[1].name[1:])
if reg_num > reg_end:
raise NotImplementedError("Instruction Not Implemented: Invalid register range.")
while reg_num <= reg_end:
ret.append(ReilRegisterOperand(reg_range[0].name[0] + str(reg_num), reg_range[0].size))
reg_num = reg_num + 1
return ret | Return operand register list. |
def print_update(self, stream=sys.stdout, job_stats=None):
if job_stats is None:
job_stats = JobStatusVector()
job_det_list = []
job_det_list += self._scatter_link.jobs.values()
for job_dets in job_det_list:
if job_dets.status == JobStatus.no_job:
continue
job_stats[job_dets.status] += 1
stream.write("Status :\n Total : %i\n Unknown: %i\n" %
(job_stats.n_total, job_stats[JobStatus.unknown]))
stream.write(" Not Ready: %i\n Ready: %i\n" %
(job_stats[JobStatus.not_ready], job_stats[JobStatus.ready]))
stream.write(" Pending: %i\n Running: %i\n" %
(job_stats[JobStatus.pending], job_stats[JobStatus.running]))
stream.write(" Done: %i\n Failed: %i\n" %
(job_stats[JobStatus.done], job_stats[JobStatus.failed])) | Print an update about the current number of jobs running |
def valarray(shape, value=np.NaN, typecode=None):
if typecode is None:
typecode = bool
out = np.ones(shape, dtype=typecode) * value
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out | Return an array of all value. |
def info(request):
if check_key(request):
api = get_api(request)
user = api.users(id='self')
print dir(user)
return render_to_response('djfoursquare/info.html', {'user': user})
else:
return HttpResponseRedirect(reverse('main')) | display some user info to show we have authenticated successfully |
def save_matpower(self, fd):
from pylon.io import MATPOWERWriter
MATPOWERWriter(self).write(fd) | Serialize the case as a MATPOWER data file. |
def _make_request(self, conf, post_params={}):
endpoint, requires_auth = conf
url = '%s%s.php' % (self.api_url, endpoint)
log.debug('Setting url to %s' % url)
request = urllib2.Request(url)
log.debug('Post params: %s' % post_params)
if requires_auth:
post_params.update({
'user': self.username,
'pass': self.password
})
data = urlencode(post_params).encode('utf-8')
try:
log.debug('Requesting data from %s' % url)
response = urllib2.urlopen(request, data)
return json.loads(response.read())
except urllib2.URLError as e:
log.debug('Full error: %s' % e)
if hasattr(e, 'reason'):
self.log.error('Could not reach host. Reason: %s' % e.reason)
elif hasattr(e, 'code'):
self.log.error('Could not fulfill request. Error Code: %s' % e.code)
return None | Make a request to the API and return data in a pythonic object |
def gaussian_video(video, shrink_multiple):
vid_data = None
for x in range(0, video.shape[0]):
frame = video[x]
gauss_copy = np.ndarray(shape=frame.shape, dtype="float")
gauss_copy[:] = frame
for i in range(shrink_multiple):
gauss_copy = cv2.pyrDown(gauss_copy)
if x == 0:
vid_data = np.zeros((video.shape[0], gauss_copy.shape[0], gauss_copy.shape[1], 3))
vid_data[x] = gauss_copy
return vid_data | Create a gaussian representation of a video |
def pad(attrs, inputs, proto_obj):
new_attrs = translation_utils._fix_attribute_names(attrs, {'pads' : 'pad_width',
'value' : 'constant_value'
})
new_attrs['pad_width'] = translation_utils._pad_sequence_fix(new_attrs.get('pad_width'))
return 'pad', new_attrs, inputs | Add padding to input tensor |
def decrypt(source, dest=None, passphrase=None):
if not os.path.exists(source):
raise CryptoritoError("Encrypted file %s not found" % source)
cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(),
passphrase_file(passphrase)]
if dest:
cmd.append(["--output", dest])
cmd.append([source])
stderr_output(flatten(cmd))
return True | Attempts to decrypt a file |
def allow_event_stream(self, **kwargs):
scope = ScopeURI('stream', 'subscribe', {'path': '/2010-04-01/Events'})
if kwargs:
scope.add_param('params', urlencode(kwargs, doseq=True))
self.capabilities["events"] = scope | Allow the user of this token to access their event stream. |
def do_not_disturb(self, enabled):
self._set_setting(
{
CONST.SETTINGS_DO_NOT_DISTURB: str(enabled).lower()
}) | Set do not disturb. |
def format(self, record):
if hasattr(record, 'data'):
return "%s. DEBUG DATA=%s" % (
logging.Formatter.format(self, record),
record.__dict__['data'])
return logging.Formatter.format(self, record) | Print out any 'extra' data provided in logs. |
def log_train(batch_id, batch_num, metric, step_loss, log_interval, epoch_id, learning_rate):
metric_nm, metric_val = metric.get()
if not isinstance(metric_nm, list):
metric_nm = [metric_nm]
metric_val = [metric_val]
train_str = '[Epoch %d Batch %d/%d] loss=%.4f, lr=%.7f, metrics:' + \
','.join([i + ':%.4f' for i in metric_nm])
logging.info(train_str, epoch_id + 1, batch_id + 1, batch_num, \
step_loss / log_interval, \
learning_rate, \
*metric_val) | Generate and print out the log message for training. |
def cross_variance(self, x, z, sigmas_f, sigmas_h):
Pxz = zeros((sigmas_f.shape[1], sigmas_h.shape[1]))
N = sigmas_f.shape[0]
for i in range(N):
dx = self.residual_x(sigmas_f[i], x)
dz = self.residual_z(sigmas_h[i], z)
Pxz += self.Wc[i] * outer(dx, dz)
return Pxz | Compute cross variance of the state `x` and measurement `z`. |
def _load_config(self):
"Load and parse config file, pass options to livestreamer"
config = SafeConfigParser()
config_file = os.path.join(self.config_path, 'settings.ini')
config.read(config_file)
for option, type in list(AVAILABLE_OPTIONS.items()):
if config.has_option('DEFAULT', option):
if type == 'int':
value = config.getint('DEFAULT', option)
if type == 'float':
value = config.getfloat('DEFAULT', option)
if type == 'bool':
value = config.getboolean('DEFAULT', option)
if type == 'str':
value = config.get('DEFAULT', option)
self.livestreamer.set_option(option, value) | Load and parse config file, pass options to livestreamer |
def create_feature_layer(ds, sql, name="layer"):
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
result = arcpy.MakeFeatureLayer_management(in_features=ds,
out_layer=name,
where_clause=sql)
return result[0] | creates a feature layer object |
def run_checks(number_samples, k_choices):
assert isinstance(k_choices, int), \
"Number of optimal trajectories should be an integer"
if k_choices < 2:
raise ValueError(
"The number of optimal trajectories must be set to 2 or more.")
if k_choices >= number_samples:
msg = "The number of optimal trajectories should be less than the \
number of samples"
raise ValueError(msg) | Runs checks on `k_choices` |
def _get_status_timestamp(row):
try:
divs = row.find('div', {'id': 'coltextR3'}).find_all('div')
if len(divs) < 2:
return None
timestamp_string = divs[1].string
except AttributeError:
return None
try:
return parse(timestamp_string)
except ValueError:
return None | Get latest package timestamp. |
async def schemes(dev: Device):
schemes = await dev.get_schemes()
for scheme in schemes:
click.echo(scheme) | Print supported uri schemes. |
def validate_db(sqlalchemy_bind, is_enabled=ENABLE_DB):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
def is_db_responsive():
try:
sqlalchemy_bind.session.query('1').first_or_404()
except:
return False
else:
return True
if is_enabled and is_db_responsive():
return func(*args, **kwargs)
else:
abort(HTTP_CODES.UNAUTHORIZED)
return wrapper
return decorator | Checks if a DB is authorized and responding before executing the function |
def _from_dict(cls, _dict):
args = {}
if 'type' in _dict:
args['type'] = _dict.get('type')
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'relevance' in _dict:
args['relevance'] = _dict.get('relevance')
if 'mentions' in _dict:
args['mentions'] = [
EntityMention._from_dict(x) for x in (_dict.get('mentions'))
]
if 'count' in _dict:
args['count'] = _dict.get('count')
if 'emotion' in _dict:
args['emotion'] = EmotionScores._from_dict(_dict.get('emotion'))
if 'sentiment' in _dict:
args['sentiment'] = FeatureSentimentResults._from_dict(
_dict.get('sentiment'))
if 'disambiguation' in _dict:
args['disambiguation'] = DisambiguationResult._from_dict(
_dict.get('disambiguation'))
return cls(**args) | Initialize a EntitiesResult object from a json dictionary. |
def canonicalize_spec(spec, parent_context):
test_specs = {k:v for (k,v) in spec.items() if k.startswith("Test")}
local_context = {k:v for (k,v) in spec.items() if not k.startswith("Test")}
context = reduce_contexts(parent_context, local_context)
if test_specs:
return {k: canonicalize_spec(v, context) for (k,v) in test_specs.items()}
else:
program_chunks = sum([resolve_module(m,context['Definitions']) for m in context['Modules']],[]) + [context['Program']]
test_spec = {
'Arguments': context['Arguments'],
'Program': "\n".join(program_chunks),
'Expect': context['Expect'],
}
return test_spec | Push all context declarations to the leaves of a nested test specification. |
def last_values(self):
last_dict = {
'date': self.last_session_date,
'score': self.last_sleep_score,
'breakdown': self.last_sleep_breakdown,
'tnt': self.last_tnt,
'bed_temp': self.last_bed_temp,
'room_temp': self.last_room_temp,
'resp_rate': self.last_resp_rate,
'heart_rate': self.last_heart_rate,
'processing': self.last_session_processing,
}
return last_dict | Return a dict of all the 'last' parameters. |
def add(self, new_hw_map):
new_route = new_hw_map.route
if new_route in self.raw_maps:
raise KeyError("HW Map already exists: {0:s}".format(new_hw_map.route))
common_addresses = set(self).intersection(new_hw_map)
if common_addresses:
raise ValueError("An address in {0:s} already exists in the manager".format(new_route))
self.raw_maps[new_route] = new_hw_map
self.update(new_hw_map) | Add the HW map only if it doesn't exist for a given key, and no address collisions |
def filter_queryset(self, request, queryset, view):
applicable_filters, applicable_exclusions = self.build_filters(view, filters=self.get_request_filters(request))
return self.apply_filters(
queryset=queryset,
applicable_filters=self.process_filters(applicable_filters, queryset, view),
applicable_exclusions=self.process_filters(applicable_exclusions, queryset, view)
) | Return the filtered queryset. |
def _rev(repo):
try:
repo_info = dict(six.iteritems(CLIENT.info(repo['repo'])))
except (pysvn._pysvn.ClientError, TypeError,
KeyError, AttributeError) as exc:
log.error(
'Error retrieving revision ID for svnfs remote %s '
'(cachedir: %s): %s',
repo['url'], repo['repo'], exc
)
else:
return repo_info['revision'].number
return None | Returns revision ID of repo |
def to_file(self, filename):
xml = self.to_xml()
f = gzip.open(filename, 'wb')
try:
f.write(xml.encode('utf-8'))
finally:
f.close() | Save the store to disk |
def normalize_missing(xs):
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, six.string_types):
if xs.lower() in ["none", "null"]:
xs = None
elif xs.lower() == "true":
xs = True
elif xs.lower() == "false":
xs = False
return xs | Normalize missing values to avoid string 'None' inputs. |
def update_lang(self,
lang: Optional[Text],
data: List[Tuple[Text, Text]],
flags: Flags):
sd = SortingDict()
for item in (self.parse_item(x[0], x[1], flags) for x in data):
if item:
sd.append(item)
if lang not in self.dict:
self.dict[lang] = {}
d = self.dict[lang]
for k, v in sd.extract().items():
if k not in d:
d[k] = SentenceGroup()
d[k].update(v, flags) | Update translations for one specific lang |
def destroy(self, request, project, pk=None):
try:
note = JobNote.objects.get(id=pk)
note.delete()
return Response({"message": "Note deleted"})
except JobNote.DoesNotExist:
return Response("No note with id: {0}".format(pk),
status=HTTP_404_NOT_FOUND) | Delete a note entry |
def unlink(self, definition, doc1, doc2) :
"deletes all links between doc1 and doc2"
links = self.database[definition].fetchByExample( {"_from": doc1._id,"_to" : doc2._id}, batchSize = 100)
for l in links :
self.deleteEdge(l) | deletes all links between doc1 and doc2 |
def _izip(*iterables):
iterators = map(iter, iterables)
while iterators:
yield tuple(map(next, iterators)) | Iterate through multiple lists or arrays of equal size |
def __flush_eventqueue(self):
while self.eventqueue:
past_event = self.eventqueue.pop(0)
self.postprocess_keyevent(past_event) | Flush keyboard event queue |
def peek(self, default=None):
try:
result = self.pointer.next()
self.pointer = itertools.chain([result], self.pointer)
return result
except StopIteration:
return default | Returns `default` is there is no subsequent item |
def as_dict(self) -> Dict[str, str]:
items: Dict[str, str] = {}
for k, v in self.items():
if type(v) is str:
items.update({k: v})
return items | Export color register as dict. |
def delete_security_group(self, sec_grp):
sec_grp_id = self._find_security_group_id(sec_grp)
ret = self.network_conn.delete_security_group(sec_grp_id)
return ret if ret else True | Deletes the specified security group |
def extend(self, iterable):
with self.lock:
for item in iterable:
self.append(item) | Add each item from iterable to the end of the list |
def query_versions_pypi(self, package_name):
if not package_name in self.pkg_list:
self.logger.debug("Package %s not in cache, querying PyPI..." \
% package_name)
self.fetch_pkg_list()
versions = []
for pypi_pkg in self.pkg_list:
if pypi_pkg.lower() == package_name.lower():
if self.debug:
self.logger.debug("DEBUG: %s" % package_name)
versions = self.package_releases(pypi_pkg)
package_name = pypi_pkg
break
return (package_name, versions) | Fetch list of available versions for a package from The CheeseShop |
def use_comparative_item_view(self):
self._object_views['item'] = COMPARATIVE
for session in self._get_provider_sessions():
try:
session.use_comparative_item_view()
except AttributeError:
pass | Pass through to provider ItemLookupSession.use_comparative_item_view |
def _find_zone_by_id(self, zone_id):
if not self.zones:
return None
zone = list(filter(
lambda zone: zone.id == zone_id, self.zones))
return zone[0] if zone else None | Return zone by id. |
def _assign(self, assignment):
self._assignments.append(assignment)
self._register(assignment) | Adds an Assignment to _assignments and _positive or _negative. |
def _setup_argparse(self):
parser = argparse.ArgumentParser(
prog='catalog', description='Parent Catalog class for astrocats.')
subparsers = parser.add_subparsers(
description='valid subcommands', dest='subcommand')
self._add_parser_arguments_import(subparsers)
self._add_parser_arguments_git(subparsers)
self._add_parser_arguments_analyze(subparsers)
return parser | Create `argparse` instance, and setup with appropriate parameters. |
def user_agents(self):
return (self.get_query()
.select(
PageView.headers['User-Agent'],
fn.Count(PageView.id))
.group_by(PageView.headers['User-Agent'])
.order_by(fn.Count(PageView.id).desc())
.tuples()) | Retrieve user-agents, sorted by most common to least common. |
def recommend(self, userid, user_items,
N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False):
if userid >= user_items.shape[0]:
raise ValueError("userid is out of bounds of the user_items matrix")
items = N
if filter_items:
items += len(filter_items)
indices, data = self.scorer.recommend(userid, user_items.indptr, user_items.indices,
user_items.data, K=items,
remove_own_likes=filter_already_liked_items)
best = sorted(zip(indices, data), key=lambda x: -x[1])
if not filter_items:
return best
liked = set(filter_items)
return list(itertools.islice((rec for rec in best if rec[0] not in liked), N)) | returns the best N recommendations for a user given its id |
def sleeping_func(arg, secs=10, result_queue=None):
import time
time.sleep(secs)
if result_queue is not None:
result_queue.put(arg)
else:
return arg | This methods illustrates how the workers can be used. |
def _wait_for_finishing(self):
self.state_machine_running = True
self.__running_state_machine.join()
self.__set_execution_mode_to_finished()
self.state_machine_manager.active_state_machine_id = None
plugins.run_on_state_machine_execution_finished()
self.state_machine_running = False | Observe running state machine and stop engine if execution has finished |
def respond_for(self, view_function, args, kwargs):
request = args[0]
form = self.get_requested_form(request)
if form.is_valid():
result = self.handle_form_valid(request, form)
if result:
return result
self.update_request(request, form)
return view_function(*args, **kwargs) | Returns a response for the given view & args. |
def all_settings(self, uppercase_keys=False):
d = {}
for k in self.all_keys(uppercase_keys):
d[k] = self.get(k)
return d | Return all settings as a `dict`. |
def _setup_subpix(self,nside=2**16):
if hasattr(self,'subpix'): return
self.roi_radius = self.config['coords']['roi_radius']
logger.info("Setup subpixels...")
self.nside_pixel = self.config['coords']['nside_pixel']
self.nside_subpixel = self.nside_pixel * 2**4
epsilon = np.degrees(hp.max_pixrad(self.nside_pixel))
subpix = ugali.utils.healpix.query_disc(self.nside_subpixel,self.roi.vec,self.roi_radius+epsilon)
superpix = ugali.utils.healpix.superpixel(subpix,self.nside_subpixel,self.nside_pixel)
self.subpix = subpix[np.in1d(superpix,self.roi.pixels)] | Subpixels for random position generation. |
def _handle_heading_end(self):
reset = self._head
self._head += 1
best = 1
while self._read() == "=":
best += 1
self._head += 1
current = int(log(self._context / contexts.HEADING_LEVEL_1, 2)) + 1
level = min(current, min(best, 6))
try:
after, after_level = self._parse(self._context)
except BadRoute:
if level < best:
self._emit_text("=" * (best - level))
self._head = reset + best - 1
return self._pop(), level
else:
self._emit_text("=" * best)
self._emit_all(after)
return self._pop(), after_level | Handle the end of a section heading at the head of the string. |
def create_option_from_value(tag, value):
dhcp_option.parser()
fake_opt = dhcp_option(tag = tag)
for c in dhcp_option.subclasses:
if c.criteria(fake_opt):
if hasattr(c, '_parse_from_value'):
return c(tag = tag, value = c._parse_from_value(value))
else:
raise ValueError('Invalid DHCP option ' + str(tag) + ": " + repr(value))
else:
fake_opt._setextra(_tobytes(value))
return fake_opt | Set DHCP option with human friendly value |
def completion(ctx):
header(completion.__doc__)
with ctx.cd(ROOT):
ctx.run('_bumpr_COMPLETE=source bumpr > bumpr-complete.sh', pty=True)
success('Completion generated in bumpr-complete.sh') | Generate bash completion script |
def getRawReportDescriptor(self):
descriptor = _hidraw_report_descriptor()
size = ctypes.c_uint()
self._ioctl(_HIDIOCGRDESCSIZE, size, True)
descriptor.size = size
self._ioctl(_HIDIOCGRDESC, descriptor, True)
return ''.join(chr(x) for x in descriptor.value[:size.value]) | Return a binary string containing the raw HID report descriptor. |
def move(self, state):
if state == tuple([ BEGIN ] * self.state_size):
choices = self.begin_choices
cumdist = self.begin_cumdist
else:
choices, weights = zip(*self.model[state].items())
cumdist = list(accumulate(weights))
r = random.random() * cumdist[-1]
selection = choices[bisect.bisect(cumdist, r)]
return selection | Given a state, choose the next item at random. |
def getForegroundWindow(self):
active_app = NSWorkspace.sharedWorkspace().frontmostApplication().localizedName()
for w in self._get_window_list():
if "kCGWindowOwnerName" in w and w["kCGWindowOwnerName"] == active_app:
return w["kCGWindowNumber"] | Returns a handle to the window in the foreground |
def getDatetimeAxis():
dataSet = 'nyc_taxi'
filePath = './data/' + dataSet + '.csv'
data = pd.read_csv(filePath, header=0, skiprows=[1, 2],
names=['datetime', 'value', 'timeofday', 'dayofweek'])
xaxisDate = pd.to_datetime(data['datetime'])
return xaxisDate | use datetime as x-axis |
def stage_pywbem_result(self, ret, exc):
self._pywbem_result_ret = ret
self._pywbem_result_exc = exc | Set Result return info or exception info |
def execute_cmd(cmd, **kwargs):
yield '$ {}\n'.format(' '.join(cmd))
kwargs['stdout'] = subprocess.PIPE
kwargs['stderr'] = subprocess.STDOUT
proc = subprocess.Popen(cmd, **kwargs)
buf = []
def flush():
line = b''.join(buf).decode('utf8', 'replace')
buf[:] = []
return line
c_last = ''
try:
for c in iter(partial(proc.stdout.read, 1), b''):
if c_last == b'\r' and buf and c != b'\n':
yield flush()
buf.append(c)
if c == b'\n':
yield flush()
c_last = c
finally:
ret = proc.wait()
if ret != 0:
raise subprocess.CalledProcessError(ret, cmd) | Call given command, yielding output line by line |
def deserialize(self, data):
ct_in_map = {
'application/x-www-form-urlencoded': self._form_loader,
'application/json': salt.utils.json.loads,
'application/x-yaml': salt.utils.yaml.safe_load,
'text/yaml': salt.utils.yaml.safe_load,
'text/plain': salt.utils.json.loads
}
try:
value, parameters = cgi.parse_header(self.request.headers['Content-Type'])
return ct_in_map[value](tornado.escape.native_str(data))
except KeyError:
self.send_error(406)
except ValueError:
self.send_error(400) | Deserialize the data based on request content type headers |
def auto_thaw(vault_client, opt):
icefile = opt.thaw_from
if not os.path.exists(icefile):
raise aomi.exceptions.IceFile("%s missing" % icefile)
thaw(vault_client, icefile, opt)
return opt | Will thaw into a temporary location |
def kick(self, channel, nick, comment=""):
self.send_items('KICK', channel, nick, comment and ':' + comment) | Send a KICK command. |
def tokenize_string(cls, string, separator):
results = []
token = ""
found_escape = False
for c in string:
if found_escape:
if c == separator:
token += separator
else:
token += "\\" + c
found_escape = False
continue
if c == "\\":
found_escape = True
elif c == separator:
results.append(token)
token = ""
else:
token += c
results.append(token)
return results | Split string with given separator unless the separator is escaped with backslash |
def clear_list_value(self, value):
if not value:
return self.empty_value
if self.clean_empty:
value = [v for v in value if v]
return value or self.empty_value | Clean the argument value to eliminate None or Falsy values if needed. |
def generate_sample_cfn_module(env_root, module_dir=None):
if module_dir is None:
module_dir = os.path.join(env_root, 'sampleapp.cfn')
generate_sample_module(module_dir)
for i in ['stacks.yaml', 'dev-us-east-1.env']:
shutil.copyfile(
os.path.join(ROOT,
'templates',
'cfn',
i),
os.path.join(module_dir, i)
)
os.mkdir(os.path.join(module_dir, 'templates'))
with open(os.path.join(module_dir,
'templates',
'tf_state.yml'), 'w') as stream:
stream.write(
cfn_flip.flip(
check_output(
[sys.executable,
os.path.join(ROOT,
'templates',
'stacker',
'tfstate_blueprints',
'tf_state.py')]
)
)
)
LOGGER.info("Sample CloudFormation module created at %s",
module_dir) | Generate skeleton CloudFormation sample module. |
def gen_add(src1, src2, dst):
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.ADD, src1, src2, dst) | Return an ADD instruction. |
def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0):
x = x / axis_scale
x = min(max(x, min_v), max_v)
return x | Normalize raw HID readings to target range. |
def _unsubscribe_myself(self):
url = UNSUBSCRIBE_ENDPOINT
return self._session.query(url, method='GET', raw=True, stream=False) | Unsubscribe this base station for all events. |
def notifyBlock(self, queue, blocked):
if blocked:
if self.prioritySet[-1] == queue.priority:
self.prioritySet.pop()
else:
pindex = bisect_left(self.prioritySet, queue.priority)
if pindex < len(self.prioritySet) and self.prioritySet[pindex] == queue.priority:
del self.prioritySet[pindex]
else:
if queue.canPop():
pindex = bisect_left(self.prioritySet, queue.priority)
if pindex >= len(self.prioritySet) or self.prioritySet[pindex] != queue.priority:
self.prioritySet.insert(pindex, queue.priority)
newblocked = not self.canPop()
if newblocked != self.blocked:
self.blocked = newblocked
if self.parent is not None:
self.parent.notifyBlock(self, newblocked) | Internal notify for sub-queues been blocked |
def _adjust_inserted_indices(inserted_indices_list, prune_indices_list):
updated_inserted = [[i for i in dim_inds] for dim_inds in inserted_indices_list]
pruned_and_inserted = zip(prune_indices_list, updated_inserted)
for prune_inds, inserted_inds in pruned_and_inserted:
prune_inds = prune_inds[~np.in1d(prune_inds, inserted_inds)]
for i, ind in enumerate(inserted_inds):
ind -= np.sum(prune_inds < ind)
inserted_inds[i] = ind
return updated_inserted | Adjust inserted indices, if there are pruned elements. |
def axes(self, offset = False):
reg, self._scale = self.SCALES[self._gauss]
x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA)
if x == -4096: x = OVERFLOW
y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA)
if y == -4096: y = OVERFLOW
z = self.bus.read_int16_data(self.address, self.HMC5883L_DZRA)
if z == -4096: z = OVERFLOW
x*=self._scale
y*=self._scale
z*=self._scale
if offset: (x, y, z) = self.__offset((x,y,z))
return (x, y, z) | returns measured value in miligauss |
def block_all(self):
self.block()
for em in self._emitters.values():
em.block() | Block all emitters in this group. |
def response_as_single(self, copy=0):
arr = []
for sid, frame in self.response.iteritems():
if copy:
frame = frame.copy()
'security' not in frame and frame.insert(0, 'security', sid)
arr.append(frame.reset_index().set_index(['date', 'security']))
return concat(arr).unstack() | convert the response map to a single data frame with Multi-Index columns |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.