Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
376,500 | def validate_edge_direction(edge_direction):
if not isinstance(edge_direction, six.string_types):
raise TypeError(u.format(
type(edge_direction), edge_direction))
if edge_direction not in ALLOWED_EDGE_DIRECTIONS:
raise ValueError(u.format(edge_direction)) | Ensure the provided edge direction is either "in" or "out". |
376,501 | def django_include(context, template_name, **kwargs):
try:
djengine = engines[]
except KeyError as e:
raise TemplateDoesNotExist("Django template engine not configured in settings, so template cannot be found: {}".format(template_name)) from e
djtemplate = djengine.get_template(template... | Mako tag to include a Django template withing the current DMP (Mako) template.
Since this is a Django template, it is search for using the Django search
algorithm (instead of the DMP app-based concept).
See https://docs.djangoproject.com/en/2.1/topics/templates/.
The current context is sent to the incl... |
376,502 | def sync_main(async_main, config_path=None, default_config=None,
should_validate_task=True, loop_function=asyncio.get_event_loop):
context = _init_context(config_path, default_config)
_init_logging(context)
if should_validate_task:
validate_task_schema(context)
loop = loop_fun... | Entry point for scripts using scriptworker.
This function sets up the basic needs for a script to run. More specifically:
* it creates the scriptworker context and initializes it with the provided config
* the path to the config file is either taken from `config_path` or from `sys.argv[1]`.
... |
376,503 | def submit_url(self, url, params={}, _extra_params={}):
self._check_user_parameters(params)
params = copy.copy(params)
params[] = url
return self._submit(params, _extra_params=_extra_params) | Submit a website for analysis. |
376,504 | def proxy_global(name, no_expand_macro=False, fname=, args=()):
if no_expand_macro:
@property
def gSomething_no_func(self):
glob = self(getattr(ROOT, name))
def func():
return glob
glob.func = func
return gl... | Used to automatically asrootpy ROOT's thread local variables |
376,505 | def get_threads_where_participant_is_active(self, participant_id):
participations = Participation.objects.\
filter(participant__id=participant_id).\
exclude(date_left__lte=now()).\
distinct().\
select_related()
return Thread.objects.\
... | Gets all the threads in which the current participant is involved. The method excludes threads where the participant has left. |
376,506 | def decode_intervals(self, encoded, duration=None, multi=True, sparse=False,
transition=None, p_state=None, p_init=None):
if np.isrealobj(encoded):
if multi:
if transition is None:
encoded = encoded >= 0.5
else:
... | Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Frame-level annotation encodings as produced by
``encode_intervals``
duration : None or float > 0
The max duration of the annota... |
376,507 | def pre_execute(self, execution, context):
path = self._fspath
if path:
path = path.format(
benchmark=context.benchmark,
api=execution[],
**execution.get(, {})
)
if self.clean_path:
shutil.rmtree... | Make sure the named directory is created if possible |
376,508 | def standardize(self, x):
if self.preprocessing_function:
x = self.preprocessing_function(x)
if self.rescale:
x *= self.rescale
if self.samplewise_center:
x -= np.mean(x, keepdims=True)
if self.samplewise_std_normalization:
x /= np... | Apply the normalization configuration to a batch of inputs.
# Arguments
x: batch of inputs to be normalized.
# Returns
The inputs, normalized. |
376,509 | def series_index(self, series):
for idx, s in enumerate(self):
if series is s:
return idx
raise ValueError() | Return the integer index of *series* in this sequence. |
376,510 | def min(self):
results = [x.ufuncs.min() for x in self.elem]
return np.min(results) | Return the minimum of ``self``.
See Also
--------
numpy.amin
max |
376,511 | def loads(astring):
try:
return marshal.loads(zlib.decompress(astring))
except zlib.error as e:
raise SerializerError(
.format(str(e))
)
except Exception as e:
raise SerializerError(
.format(str... | Decompress and deserialize string into Python object via marshal. |
376,512 | def _update_tree_store(self):
self.list_store.clear()
if self.view_dict[] and isinstance(self.model, ContainerStateModel) and \
len(self.model.state.transitions) > 0:
for transition_id in self.combo[].keys():
t = self.model.state.tra... | Updates TreeStore of the Gtk.ListView according internal combo knowledge gained by
_update_internal_data_base function call. |
376,513 | def show_progress(self):
from pyemma import config
if not hasattr(self, "_show_progress"):
val = config.show_progress_bars
self._show_progress = val
elif not config.show_progress_bars:
return False
return self._show_progress | whether to show the progress of heavy calculations on this object. |
376,514 | def _Rforce(self,R,phi=0.,t=0.):
return self._A*math.exp(-(t-self._to)**2./2./self._sigma2)\
/R*math.sin(self._alpha*math.log(R)
-self._m*(phi-self._omegas*t-self._gamma)) | NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the radial force
HISTORY:
2010-11-24 - Written - Bovy (NYU) |
376,515 | def complete_server(self, text, line, begidx, endidx):
return [i for i in PsiturkShell.server_commands if i.startswith(text)] | Tab-complete server command |
376,516 | def query_pager_by_slug(slug, current_page_num=1, tag=, order=False):
cat_rec = MCategory.get_by_slug(slug)
if cat_rec:
cat_id = cat_rec.uid
else:
return None
if cat_id.endswith():
cat_con = TabPost2Tag.par_id == cat_id
... | Query pager via category slug. |
376,517 | def Beach(fm, linewidth=2, facecolor=, bgcolor=, edgecolor=,
alpha=1.0, xy=(0, 0), width=200, size=100, nofill=False,
zorder=100, axes=None):
try:
assert(len(width) == 2)
except TypeError:
width = (width, width)
mt = None
np1 = None
if isinstance(fm, Mom... | Return a beach ball as a collection which can be connected to an
current matplotlib axes instance (ax.add_collection).
S1, D1, and R1, the strike, dip and rake of one of the focal planes, can
be vectors of multiple focal mechanisms.
:param fm: Focal mechanism that is either number of mechanisms (NM) b... |
376,518 | def setColor( self, color ):
self.setBorderColor(color)
clr = QColor(color)
clr.setAlpha(150)
self.setHighlightColor(clr)
clr = QColor(color)
clr.setAlpha(80)
self.setFillColor(clr) | Convenience method to set the border, fill and highlight colors based
on the inputed color.
:param color | <QColor> |
376,519 | def _get_previous_open_tag(self, obj):
prev_instance = self.get_previous_instance(obj)
if prev_instance and prev_instance.plugin_type == self.__class__.__name__:
return prev_instance.glossary.get() | Return the open tag of the previous sibling |
376,520 | def derive_single_object_url_pattern(slug_url_kwarg, path, action):
if slug_url_kwarg:
return r % (path, action, slug_url_kwarg)
else:
return r % (path, action) | Utility function called by class methods for single object views |
376,521 | def to_dict(self):
return {
: self.asset,
: self.amount,
: self.cost_basis,
: self.last_sale_price
} | Creates a dictionary representing the state of this position.
Returns a dict object of the form: |
376,522 | def _sort_lows_and_highs(func):
"Decorator for extract_cycles"
@functools.wraps(func)
def wrapper(*args, **kwargs):
for low, high, mult in func(*args, **kwargs):
if low < high:
yield low, high, mult
else:
yield high, low, mult
return wrappe... | Decorator for extract_cycles |
376,523 | def _set_static_ag_ipv6_config(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=static_ag_ipv6_config.static_ag_ipv6_config, is_container=, presence=False, yang_name="static-ag-ipv6-config", rest_name="", parent=self, path_helper=self._path_helper, ext... | Setter method for static_ag_ipv6_config, mapped from YANG variable /rbridge_id/ipv6/static_ag_ipv6_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_static_ag_ipv6_config is considered as a private
method. Backends looking to populate this variable should
... |
376,524 | def configurar_interface_de_rede(self, configuracao):
resp = self._http_post(,
configuracao=configuracao.documento())
conteudo = resp.json()
return RespostaSAT.configurar_interface_de_rede(conteudo.get()) | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT |
376,525 | def set_prefs(prefs):
prefs[] = [, , ,
, , , , ]
prefs[] = True
prefs[] = False
prefs[] = True
prefs[] = 0
... | This function is called before opening the project |
376,526 | def age(self):
if not self.birthdate():
return -1
adjuster = 0
today = date.today()
birthday = self.birthdate()
if today.month == birthday.month:
if today.day < birthday.day:
adjuster -= 1
elif today.month < birthday.month:... | Returns the user's age, determined by their birthdate() |
376,527 | def tag_values(request):
data = defaultdict(lambda: {"values": {}})
for tag in Tag.objects.filter(lang=get_language(request)):
data[tag.type]["name"] = tag.type_name
data[tag.type]["values"][tag.value] = tag.value_name
return render_json(request, data, template=, help_text=tag_values.... | Get tags types and values with localized names
language:
language of tags |
376,528 | def send_keys(self, keys, wait=True):
self._process.stdin.write(bytearray(keys, self._encoding))
self._process.stdin.flush()
if wait:
self.wait() | Send a raw key sequence to *Vim*.
.. note:: *Vim* style key sequence notation (like ``<Esc>``)
is not recognized.
Use escaped characters (like ``'\033'``) instead.
Example:
>>> import headlessvim
>>> with headlessvim.open() as vim:
... v... |
376,529 | def _split_path(path, seps=PATH_SEPS):
if not path:
return []
for sep in seps:
if sep in path:
if path == sep:
return []
return [x for x in path.split(sep) if x]
return [path] | Parse path expression and return list of path items.
:param path: Path expression may contain separator chars.
:param seps: Separator char candidates.
:return: A list of keys to fetch object[s] later.
>>> assert _split_path('') == []
>>> assert _split_path('/') == [''] # JSON Pointer spec expects... |
376,530 | def loadUnStructuredGrid(filename):
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName(filename)
reader.Update()
gf = vtk.vtkUnstructuredGridGeometryFilter()
gf.SetInputConnection(reader.GetOutputPort())
gf.Update()
return Actor(gf.GetOutput()) | Load a ``vtkunStructuredGrid`` object from file and return a ``Actor(vtkActor)`` object. |
376,531 | def arrays2wcxf(C):
d = {}
for k, v in C.items():
if np.shape(v) == () or np.shape(v) == (1,):
d[k] = v
else:
ind = np.indices(v.shape).reshape(v.ndim, v.size).T
for i in ind:
name = k + + .join([str(int(j) + 1) for j in i])
... | Convert a dictionary with Wilson coefficient names as keys and
numbers or numpy arrays as values to a dictionary with a Wilson coefficient
name followed by underscore and numeric indices as keys and numbers as
values. This is needed for the output in WCxf format. |
376,532 | def iflat_nodes(self, status=None, op="==", nids=None):
nids = as_set(nids)
if status is None:
if not (nids and self.node_id not in nids):
yield self
for work in self:
if nids and work.node_id not in nids: continue
yield ... | Generators that produces a flat sequence of nodes.
if status is not None, only the tasks with the specified status are selected.
nids is an optional list of node identifiers used to filter the nodes. |
376,533 | def find_item_project(self, eitem):
ds_name = self.cfg_section_name if self.cfg_section_name else self.get_connector_name()
try:
if self.projects_json_repo:
project = self.prjs_map[ds_name][se... | Find the project for a enriched item
:param eitem: enriched item for which to find the project
:return: the project entry (a dictionary) |
376,534 | def minion_pub(self, load):
if not self.__verify_minion_publish(load):
return {}
pub_load = {
: load[],
: salt.utils.args.parse_input(
load[],
no_parse=load.get(, [])),
: load.get(, ),
: load[],... | Publish a command initiated from a minion, this method executes minion
restrictions so that the minion publication will only work if it is
enabled in the config.
The configuration on the master allows minions to be matched to
salt functions, so the minions can only publish allowed salt f... |
376,535 | def median1d(self, name, return_errors=False):
if return_errors:
mid = self.data[name][]
low, high = self.data[name][]
return (mid, low, high)
else:
return self.data[name][] | Return median 1d marginalized parameters
Parameters
----------
name: str
The name of the parameter requested
return_errors: Optional, {bool, False}
If true, return a second and third parameter that represents the
lower and upper 90% error on the param... |
376,536 | def html_single_plot(self,abfID,launch=False,overwrite=False):
if type(abfID) is str:
abfID=[abfID]
for thisABFid in cm.abfSort(abfID):
parentID=cm.parent(self.groups,thisABFid)
saveAs=os.path.abspath("%s/%s_plot.html"%(self.folder2,parentID))
if ... | create ID_plot.html of just intrinsic properties. |
376,537 | def blockstack_tx_filter( tx ):
if not in tx:
return False
if tx[] is None:
return False
payload = binascii.unhexlify( tx[] )
if payload.startswith(blockstack_magic_bytes()):
return True
else:
return False | Virtualchain tx filter function:
* only take txs whose OP_RETURN payload starts with 'id' |
376,538 | def check_version():
if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:
return
sys.exit(
ansi.error() +
+ os.linesep + os.linesep + BIN_PYTHON +
os.linesep
... | Sanity check version information for corrupt virtualenv symlinks |
376,539 | def _print_speed(self):
if self._bandwidth_meter.num_samples:
speed = self._bandwidth_meter.speed()
if self._human_format:
file_size_str = wpull.string.format_size(speed)
else:
file_size_str = .format(speed * 8)
speed_str... | Print the current speed. |
376,540 | def form_field(self):
"Returns appropriate form field."
label = unicode(self)
defaults = dict(required=False, label=label, widget=self.widget)
defaults.update(self.extra)
return self.field_class(**defaults) | Returns appropriate form field. |
376,541 | def create_namespace(self, namespace):
std_namespace = _ensure_unicode(namespace.strip())
ws_profiles = self.get_selected_profiles(, )
if ws_profiles:
ws_profiles_sorted = sorted(
ws_profiles, key=lambda prof: prof[])
ws_profile_i... | Create the specified CIM namespace in the WBEM server and
update this WBEMServer object to reflect the new namespace
there.
This method attempts the following approaches for creating the
namespace, in order, until an approach succeeds:
1. Namespace creation as described in the ... |
376,542 | def hicpro_mapping_chart (self):
keys = OrderedDict()
keys[] = { : , : }
keys[] = { : , : }
keys[] = { : , : }
data = [{},{}]
for s_name in self.hicpro_data:
for r in [1,2]:
data[r-1][... | Generate the HiC-Pro Aligned reads plot |
376,543 | def match_file(filename):
base_name = os.path.basename(filename)
if base_name.startswith():
return False
if not os.path.isdir(filename) and not filename.lower().endswith():
return False
return True | Return True if file is okay for modifying/recursing. |
376,544 | def show_instances(server, cim_class):
if cim_class == :
for inst in server.profiles:
print(inst.tomof())
return
for ns in server.namespaces:
try:
insts = server.conn.EnumerateInstances(cim_class, namespace=ns)
if len(insts):
prin... | Display the instances of the CIM_Class defined by cim_class. If the
namespace is None, use the interop namespace. Search all namespaces for
instances except for CIM_RegisteredProfile |
376,545 | def _FindLargestIdPostfixNumber(self, schedule):
postfix_number_re = re.compile()
def ExtractPostfixNumber(entity_id):
if entity_id is None:
return 0
match = postfix_number_re.search(entity_id)
if match is not None:
return int(match.group(1))
else:
re... | Finds the largest integer used as the ending of an id in the schedule.
Args:
schedule: The schedule to check.
Returns:
The maximum integer used as an ending for an id. |
376,546 | def image_uuid(pil_img):
print()
img_bytes_ = pil_img.tobytes()
uuid_ = hashable_to_uuid(img_bytes_)
return uuid_ | UNSAFE: DEPRICATE: JPEG IS NOT GAURENTEED TO PRODUCE CONSITENT VALUES ON
MULTIPLE MACHINES image global unique id
References:
http://stackoverflow.com/questions/23565889/jpeg-images-have-different-pixel-values-across-multiple-devices |
376,547 | def create_config(config_path="scriptworker.yaml"):
if not os.path.exists(config_path):
print("{} doesncredentials\ncredentialscredentials'])
config = get_frozen_copy(config)
return config, credentials | Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tuple: (config frozendict, credentials dict)
Raises:
SystemEx... |
376,548 | def add_pagination_meta(self, params, meta):
meta[] = params[]
meta[] = params[]
meta[] = "page={0}&page_size={1}".format(
params[] - 1, params[]
) if meta[] > 0 else None
meta[] = "page={0}&page_size={1}".format(
params[] + 1, params[]
... | Extend default meta dictionary value with pagination hints.
Note:
This method handler attaches values to ``meta`` dictionary without
changing it's reference. This means that you should never replace
``meta`` dictionary with any other dict instance but simply modify
... |
376,549 | def upload(self, fileobj, tileset, name=None, patch=False, callback=None, bypass=False):
tileset = self._validate_tileset(tileset)
url = self.stage(fileobj, callback=callback)
return self.create(url, tileset, name=name, patch=patch, bypass=bypass) | Upload data and create a Mapbox tileset
Effectively replicates the Studio upload feature. Returns a
Response object, the json() of which returns a dict with upload
metadata.
Parameters
----------
fileobj: file object or str
A filename or a Python file object... |
376,550 | def _get_ordering_field_lookup(self, field_name):
field = field_name
get_field = getattr(self, "get_%s_ordering_field" % field_name, None)
if get_field:
field = get_field()
return field | get real model field to order by |
376,551 | def _model_foreign(ins):
fks = []
for t in ins.tables:
fks.extend([
SaForeignkeyDoc(
key=fk.column.key,
target=fk.target_fullname,
onupdate=fk.onupdate,
ondelete=fk.ondelete
)
for fk in t.foreign_key... | Get foreign keys info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[SaForeignkeyDoc] |
376,552 | def _wrap_class(request_handler, validator):
METHODS = [, , , , , , ]
for name in METHODS:
method = getattr(request_handler, name)
setattr(request_handler, name, _auth_required(method, validator))
return request_handler | Decorate each HTTP verb method to check if the request is authenticated
:param request_handler: a tornado.web.RequestHandler instance |
376,553 | def clear(self, decorated_function=None):
if decorated_function is not None and decorated_function in self._storage:
self._storage.pop(decorated_function)
else:
self._storage.clear()
if self.__statistic is True:
self.__cache_missed = 0
self.__cache_hit = 0 | :meth:`WCacheStorage.clear` method implementation (Clears statistics also) |
376,554 | def _gti_dirint_lt_90(poa_global, aoi, aoi_lt_90, solar_zenith, solar_azimuth,
times, surface_tilt, surface_azimuth, pressure=101325.,
use_delta_kt_prime=True, temp_dew=None, albedo=.25,
model=, model_perez=,
max_iterations=30):
... | GTI-DIRINT model for AOI < 90 degrees. See Marion 2015 Section 2.1.
See gti_dirint signature for parameter details. |
376,555 | def is_course_run_enrollable(course_run):
now = datetime.datetime.now(pytz.UTC)
end = parse_datetime_handle_invalid(course_run.get())
enrollment_start = parse_datetime_handle_invalid(course_run.get())
enrollment_end = parse_datetime_handle_invalid(course_run.get())
return (not end or end > now)... | Return true if the course run is enrollable, false otherwise.
We look for the following criteria:
- end is greater than now OR null
- enrollment_start is less than now OR null
- enrollment_end is greater than now OR null |
376,556 | def findall(text):
results = TIMESTRING_RE.findall(text)
dates = []
for date in results:
if re.compile(, re.I).match(date[0]):
dates.append((date[0].strip(), Range(date[0])))
else:
dates.append((date[0].strip(), Date(date[0])))
return dates | Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),
('august 15th at 7:20 am', <timestring.Date 2014-08-15 0... |
376,557 | def save(self):
username, email, password = (self.cleaned_data[],
self.cleaned_data[],
self.cleaned_data[])
user = get_user_model().objects.create_user(username, email, password,
not defaults.ACCO... | Creates a new user and account. Returns the newly created user. |
376,558 | def unstack_annotations(annotations_sframe, num_rows=None):
_raise_error_if_not_sframe(annotations_sframe, variable_name="annotations_sframe")
cols = [, , ]
has_confidence = in annotations_sframe.column_names()
if has_confidence:
cols.append()
if num_rows is None:
if len(anno... | Converts object detection annotations (ground truth or predictions) to
unstacked format (an `SArray` where each element is a list of object
instances).
Parameters
----------
annotations_sframe: SFrame
An `SFrame` with stacked predictions, produced by the
`stack_annotations` function... |
376,559 | def events(cls, filters):
current = filters.pop(, False)
current_params = []
if current:
current_params = [(, )]
filter_url = uparse.urlencode(sorted(list(filters.items())) + current_params)
events = cls.json_get( % (cls.api_url, filter_url),
... | Retrieve events details from status.gandi.net. |
376,560 | async def async_poller(client, initial_response, deserialization_callback, polling_method):
try:
client = client if isinstance(client, ServiceClientAsync) else client._client
except AttributeError:
raise ValueError("Poller client parameter must be a low-level msrest Service Client or a SDK... | Async Poller for long running operations.
:param client: A msrest service client. Can be a SDK client and it will be casted to a ServiceClient.
:type client: msrest.service_client.ServiceClient
:param initial_response: The initial call response
:type initial_response: msrest.universal_http.ClientRespon... |
376,561 | def note_list(self, body_matches=None, post_id=None, post_tags_match=None,
creator_name=None, creator_id=None, is_active=None):
params = {
: body_matches,
: post_id,
: post_tags_match,
: creator_name,
: creator_id,
... | Return list of notes.
Parameters:
body_matches (str): The note's body matches the given terms.
post_id (int): A specific post.
post_tags_match (str): The note's post's tags match the given terms.
creator_name (str): The creator's name. Exact match.
cr... |
376,562 | def model_to_select_list(model_class, filter_dict=None, q_filter=None):
if filter_dict is None:
filter_dict = {}
if q_filter is not None:
filter_list = [q_filter]
else:
filter_list = []
objects = model_class.objects.filter(
*filter_list, **filter_dict).values(, )
... | 只选择 id 和 name,用来做列表选择
:param model_class:
:param filter_dict:
:param q_filter:
:return: |
376,563 | def determinize(m):
if not m.is_finite():
raise TypeError("machine must be a finite automaton")
transitions = collections.defaultdict(lambda: collections.defaultdict(set))
alphabet = set()
for transition in m.get_transitions():
[[lstate], read] = transition.lhs
[[rstate]] =... | Determinizes a finite automaton. |
376,564 | def hpforest(self, data: [, str] = None,
freq: str = None,
id: str = None,
input: [str, list, dict] = None,
save: str = None,
score: [str, bool, ] = True,
target: [str, list, dict] = None,
procopts: st... | Python method to call the HPFOREST procedure
Documentation link:
https://support.sas.com/documentation/solutions/miner/emhp/14.1/emhpprcref.pdf
:param data: SASdata object or string. This parameter is required.
:parm freq: The freq variable can only be a string type.
:parm id: ... |
376,565 | def _repr_html_row_(self, keys):
tr, th, c = , ,
r =
h =
for k in keys:
v = self.__dict__.get(k)
if k == :
k =
c = utils.text_colour_for_hex(v)
style = .format(c, v)
else:
st... | Jupyter Notebook magic repr function as a row – used by
``Legend._repr_html_()``. |
376,566 | def check_denovo_input(inputfile, params):
background = params["background"]
input_type = determine_file_type(inputfile)
if input_type == "fasta":
valid_bg = FA_VALID_BGS
elif input_type in ["bed", "narrowpeak"]:
genome = params["genome"]
valid_bg = BED_VALID_B... | Check if an input file is valid, which means BED, narrowPeak or FASTA |
376,567 | def re_evaluate(local_dict=None):
try:
compiled_ex = _numexpr_last[]
except KeyError:
raise RuntimeError("not a previous evaluate() execution found")
argnames = _numexpr_last[]
args = getArguments(argnames, local_dict)
kwargs = _numexpr_last[]
with evaluate_lock:
ret... | Re-evaluate the previous executed array expression without any check.
This is meant for accelerating loops that are re-evaluating the same
expression repeatedly without changing anything else than the operands.
If unsure, use evaluate() which is safer.
Parameters
----------
local_dict : dicti... |
376,568 | def write_by_templ(templ, target, sub_value, safe=False):
templ_txt = read_file(templ)
txt = None
if safe:
txt = Template(templ_txt).safe_substitute(sub_value)
else:
txt = Template(templ_txt).substitute(sub_value)
write_file(target, txt) | 根据模版写入文件。
:param str templ: 模版文件所在路径。
:param str target: 要写入的文件所在路径。
:param dict sub_value: 被替换的内容。 |
376,569 | def _imply_options(self):
self.no_upload = self.no_upload or self.to_stdout or self.offline
self.auto_update = self.auto_update and not self.offline
if (self.analyze_container or
self.analyze_file or
self.analyze_mountpoint or
self.analyze_image_id):
... | Some options enable others automatically |
376,570 | def process_flat_files(id_mappings_file, complexes_file=None, ptm_file=None,
ppi_file=None, seq_file=None, motif_window=7):
id_df = pd.read_csv(id_mappings_file, delimiter=, names=_hprd_id_cols,
dtype=)
id_df = id_df.set_index()
if complexes_file is None a... | Get INDRA Statements from HPRD data.
Of the arguments, `id_mappings_file` is required, and at least one of
`complexes_file`, `ptm_file`, and `ppi_file` must also be given. If
`ptm_file` is given, `seq_file` must also be given.
Note that many proteins (> 1,600) in the HPRD content are associated with
... |
376,571 | def get_n_excluded_patches(self):
base = self.get_patches_base()
if not base:
return 0
p = base.rfind()
if p == -1:
return 0
try:
n = int(base[p+1:])
return n
except TypeError:
return 0 | Gets number of excluded patches from patches_base:
#patches_base=1.0.0+THIS_NUMBER |
376,572 | def remove_info_file():
try:
os.unlink(_get_info_file_path())
except OSError as e:
if e.errno == errno.ENOENT:
pass
else:
raise | Remove the current process's TensorBoardInfo file, if it exists.
If the file does not exist, no action is taken and no error is raised. |
376,573 | def removeFile(file):
if "y" in speech.question("Are you sure you want to remove " + file + "? (Y/N): "):
speech.speak("Removing " + file + " with the command.")
subprocess.call(["rm", "-r", file])
else:
speech.speak("Okay, I won't remove " + file + ".") | remove a file |
376,574 | def topfnfile(self, fileobj):
for entry in self:
print >>fileobj, entry.path
fileobj.close() | write a cache object to filename as a plain text pfn file |
376,575 | def run_file(path_or_file, context=None):
if context is None:
context = EvalJs()
if not isinstance(context, EvalJs):
raise TypeError()
eval_value = context.eval(get_file_contents(path_or_file))
return eval_value, context | Context must be EvalJS object. Runs given path as a JS program. Returns (eval_value, context). |
376,576 | def get_books_for_schedule(self, schedule):
slns = self._get_slns(schedule)
books = {}
for sln in slns:
try:
section_books = self.get_books_by_quarter_sln(
schedule.term.quarter, sln
)
books[sln] = section... | Returns a dictionary of data. SLNs are the keys, an array of Book
objects are the values. |
376,577 | def handle_errors(
cls, message, *format_args,
re_raise=True, exception_class=Exception,
do_finally=None, do_except=None, do_else=None,
**format_kwds
):
try:
yield
except exception_class as err:
try:
fin... | provides a context manager that will intercept exceptions and repackage
them as Buzz instances with a message attached:
.. code-block:: python
with Buzz.handle_errors("It didn't work"):
some_code_that_might_raise_an_exception()
:param: message: The message to attach... |
376,578 | def recordAndPropagate(self, request: Request, clientName):
self.requests.add(request)
self.propagate(request, clientName)
self.tryForwarding(request) | Record the request in the list of requests and propagate.
:param request:
:param clientName: |
376,579 | def is_cf_trajectory(nc, variable):
dims = nc.variables[variable].dimensions
cmatrix = coordinate_dimension_matrix(nc)
for req in (, , ):
if req not in cmatrix:
return False
if len(cmatrix[]) != 2:
return False
if cmatrix[] != cmatrix[]:
return Fal... | Returns true if the variable is a CF trajectory feature type
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: name of the variable to check |
376,580 | def parse_pkcs12(data, password=None):
if not isinstance(data, byte_cls):
raise TypeError(pretty_message(
,
type_name(data)
))
if password is not None:
if not isinstance(password, byte_cls):
raise TypeError(pretty_message(
,
... | Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys
:param data:
A byte string of a DER-encoded PKCS#12 file
:param password:
A byte string of the password to any encrypted data
:raises:
ValueError - when any of the parameters are of the wrong type or value
... |
376,581 | def percent(self, value) -> :
raise_not_number(value)
self.gap = .format(value)
return self | Set the margin as a percentage. |
376,582 | def synchronize(self, graph_data=None):
profile = graph_data or self.graph.get()
self.facebook_username = profile.get()
self.first_name = profile.get()
self.middle_name = profile.get()
self.last_name = profile.get()
self.birthday = datetime.strptime(profile[], )... | Synchronize ``facebook_username``, ``first_name``, ``middle_name``,
``last_name`` and ``birthday`` with Facebook.
:param graph_data: Optional pre-fetched graph data |
376,583 | def dtype_contract(input_dtype=None, output_dtype=None):
def wrap(function):
@wraps(function)
def wrapped_function(*args, **kwargs):
if input_dtype is not None:
check_dtype(args[0], input_dtype)
array = function(*args, **kwargs)
if output_dtyp... | Function decorator for specifying input and/or output array dtypes. |
376,584 | def predecessors(self, node, exclude_compressed=True):
preds = super(Graph, self).predecessors(node)
if exclude_compressed:
return [n for n in preds if not self.node[n].get(, False)]
else:
return preds | Returns the list of predecessors of a given node
Parameters
----------
node : str
The target node
exclude_compressed : boolean
If true, compressed nodes are excluded from the predecessors list
Returns
-------
list
List of pre... |
376,585 | def enumeration(*values, **kwargs):
if not (values and all(isinstance(value, string_types) and value for value in values)):
raise ValueError("expected a non-empty sequence of strings, got %s" % values)
if len(values) != len(set(values)):
raise ValueError("enumeration items must be unique, ... | Create an |Enumeration| object from a sequence of values.
Call ``enumeration`` with a sequence of (unique) strings to create an
Enumeration object:
.. code-block:: python
#: Specify the horizontal alignment for rendering text
TextAlign = enumeration("left", "right", "center")
Args:
... |
376,586 | def print_all():
_, conf = read_latoolscfg()
default = conf[][]
pstr =
for s in conf.sections():
if s == default:
pstr += s +
elif s == :
pstr += s +
else:
pstr += s +
for k, v in conf[s].items():
if k != :
... | Prints all currently defined configurations. |
376,587 | def get_pr(pr_num, config=None, repo=DEFAULT_REPO, raw=False):
response = requests.get(PR_ENDPOINT.format(repo, pr_num), auth=get_auth_info(config))
if raw:
return response
else:
response.raise_for_status()
return response.json() | Get the payload for the given PR number. Let exceptions bubble up. |
376,588 | def nu_max(self, *args):
return 3120.* (self.mass(*args) /
(self.radius(*args)**2 * np.sqrt(self.Teff(*args)/5777.))) | Returns asteroseismic nu_max in uHz
reference: https://arxiv.org/pdf/1312.3853v1.pdf, Eq (3) |
376,589 | def _download_astorb(
self):
self.log.info()
url = self.settings["astorb"]["url"]
print "Downloading orbital elements from " % locals()
response = urllib2.urlopen(url)
data = response.read()
astorbgz = "/tmp/astorb.dat.gz"
file_ = o... | *download the astorb database file*
**Key Arguments:**
- ``astorbgz`` -- path to the downloaded astorb database file |
376,590 | def strain(self, ifo, duration=32, sample_rate=4096):
from astropy.utils.data import download_file
from pycbc.frame import read_frame
length = "{}sec".format(duration)
if sample_rate == 4096:
sampling = "4KHz"
el... | Return strain around the event
Currently this will return the strain around the event in the smallest
format available. Selection of other data is not yet available.
Parameters
----------
ifo: str
The name of the observatory you want strain for. Ex. H1, L1, V1
... |
376,591 | def _parse_materials(header, views):
try:
import PIL.Image
except ImportError:
log.warning("unable to load textures without pillow!")
return None
images = None
if "images" in header:
images = [None] * len(header["images"])
for i, img i... | Convert materials and images stored in a GLTF header
and buffer views to PBRMaterial objects.
Parameters
------------
header : dict
Contains layout of file
views : (n,) bytes
Raw data
Returns
------------
materials : list
List of trimesh.visual.texture.Material object... |
376,592 | def delete_all(self, filter, force=False, timeout=-1):
uri = "{}?filter={}&force={}".format(self._base_uri, quote(filter), force)
logger.debug("Delete all resources (uri = %s)" % uri)
return self.delete(uri) | Deletes all resources from the appliance that match the provided filter.
Args:
filter:
A general filter/query string to narrow the list of items deleted.
force:
If set to true, the operation completes despite any problems with network connectivity or erro... |
376,593 | def basic_params1():
return hparam.HParams(
batch_size=4096,
batch_shuffle_size=512,
use_fixed_batch_size=False,
num_hidden_layers=4,
kernel_height=3,
kernel_width=1,
hidden_size=64,
compress_steps=0,
drop... | A set of basic hyperparameters. |
376,594 | def _connect(self):
if self.connected:
return
self._connect_broker()
stack = self._build_stack()
self._connect_stack(stack) | Establish a connection to the master process's UNIX listener socket,
constructing a mitogen.master.Router to communicate with the master,
and a mitogen.parent.Context to represent it.
Depending on the original transport we should emulate, trigger one of
the _connect_*() service calls de... |
376,595 | def get_geocode(city, state, street_address="", zipcode=""):
try:
key = settings.GMAP_KEY
except AttributeError:
return "You need to put GMAP_KEY in settings"
location = ""
if street_address:
location += .format(street_address.replace(" ", "+"))
location += .format... | For given location or object, takes address data and returns
latitude and longitude coordinates from Google geocoding service
get_geocode(self, street_address="1709 Grand Ave.", state="MO", zip="64112")
Returns a tuple of (lat, long)
Most times you'll want to join the return. |
376,596 | def _file_where(user_id, api_path):
directory, name = split_api_filepath(api_path)
return and_(
files.c.name == name,
files.c.user_id == user_id,
files.c.parent_name == directory,
) | Return a WHERE clause matching the given API path and user_id. |
376,597 | def console_hline(
con: tcod.console.Console,
x: int,
y: int,
l: int,
flag: int = BKGND_DEFAULT,
) -> None:
lib.TCOD_console_hline(_console(con), x, y, l, flag) | Draw a horizontal line on the console.
This always uses the character 196, the horizontal line character.
.. deprecated:: 8.5
Use :any:`Console.hline` instead. |
376,598 | def random_forest_error(forest, X_train, X_test, inbag=None,
calibrate=True, memory_constrained=False,
memory_limit=None):
if inbag is None:
inbag = calc_inbag(X_train.shape[0], forest)
pred = np.array([tree.predict(X_test) for tree in forest]).T
... | Calculate error bars from scikit-learn RandomForest estimators.
RandomForest is a regressor or classifier object
this variance can be used to plot error bars for RandomForest objects
Parameters
----------
forest : RandomForest
Regressor or Classifier object.
X_train : ndarray
... |
376,599 | def _idx_table_by_num(tables):
logger_jsons.info("enter idx_table_by_num")
_tables = []
for name, table in tables.items():
try:
tmp = _idx_col_by_num(table)
_tables.append(tmp)
except Exception as e:
logger_jsons.error("idx_t... | Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.