Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
341,100 | def strip_errors(obj):
rtn_obj = copy.deepcopy(obj)
try:
del rtn_obj["__error_keys__"]
except KeyError:
pass
for key in obj.get(, []):
rtn_obj[key] = rtn_obj[key][]
return rtn_obj | Reads through and error object and replaces the error dict with the
value
args:
obj: the error object/dictionary |
341,101 | def load_requirements(*requirements_paths):
requirements = set()
for path in requirements_paths:
requirements.update(
line.split()[0].strip() for line in open(path).readlines()
if is_requirement(line.strip())
)
return list(requirements) | Load all requirements from the specified requirements files.
Returns a list of requirement strings. |
341,102 | def create_content_item(access_token, payload):
headers = {
: ,
: + str(access_token)
}
request = requests.post(enrichment_url, json=payload, headers=headers)
if request.status_code == 201:
content_item = request.json()
return content_item
return {: request.status_code, "message": request.text} | Name: create_content_item
Parameters: access_token, payload (dict)
Return: dictionary |
341,103 | def toy_classification(return_X_y=True, n=5000):
X = np.random.rand(n,5) * 10 - 5
cat = np.random.randint(0,4, n)
X = np.c_[X, cat]
log_odds = (-0.5*X[:,0]**2) + 5 +(-0.5*X[:,1]**2) + np.mod(X[:,-1], 2)*-30
p = 1/(1+np.exp(-log_odds)).squeeze()
y = (np.random.rand(n) < p).astype(... | toy classification dataset with irrelevant features
fitting a logistic model on this data and performing a model summary
should reveal that features 2,3,4 are not significant.
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, re... |
341,104 | def validate_stringlist(s):
if isinstance(s, six.string_types):
return [six.text_type(v.strip()) for v in s.split() if v.strip()]
else:
try:
return list(map(validate_str, s))
except TypeError as e:
raise ValueError(e.message) | Validate a list of strings
Parameters
----------
val: iterable of strings
Returns
-------
list
list of str
Raises
------
ValueError |
341,105 | def _get_sync_query_processor(self, pack_func, unpack_func, is_create_socket=True):
def sync_query_processor(**kargs):
while True:
with self._lock:
if self._status == ContextStatus.Ready:
net_mgr = self._net_mgr
... | synchronize the query processor
:param pack_func: back
:param unpack_func: unpack
:return: sync_query_processor |
341,106 | def _prepare_data(self):
self._extract_genes()
self._extract_total_number_of_chars()
self._extract_number_of_taxa()
self._extract_reading_frames()
Data = namedtuple(, [, , ,
, ,
])
self.data =... | Creates named tuple with info needed to create a dataset.
:return: named tuple |
341,107 | def validate_object(brain_or_object, data):
obj = get_object(brain_or_object)
if is_at_content(obj):
return obj.validate(data=data)
return {} | Validate the entire object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:param data: The sharing dictionary as returned from the API
:type data: dict
:returns: invalidity status
:rtype: dict |
341,108 | def _get_expanded_active_specs(specs):
_filter_active(constants.CONFIG_BUNDLES_KEY, specs)
_filter_active(, specs)
_expand_libs_in_apps(specs)
_filter_active(, specs)
_filter_active(, specs)
_add_active_assets(specs) | This function removes any unnecessary bundles, apps, libs, and services that aren't needed by
the activated_bundles. It also expands inside specs.apps.depends.libs all libs that are needed
indirectly by each app |
341,109 | def large_size(self, as_string=True):
size = getattr(settings, , (150, 150))
if as_string:
return u.format(size[0], size[1])
return size | Returns a thumbnail's large size. |
341,110 | def build_parser(self):
parser = argparse.ArgumentParser(
description=)
subparsers = parser.add_subparsers(title="subcommands", metavar="", dest=)
parser.add_argument(, , action=, version=__version__)
parser.add_argument(, action=,
help=... | ! @brief Construct the command line parser with all subcommands and options. |
341,111 | def system_requirements():
command_exists("systemd-nspawn",
["systemd-nspawn", "--version"],
"Command systemd-nspawn does not seems to be present on your system"
"Do you have system with systemd")
command_exists(
"machinectl",
["machin... | Check if all necessary packages are installed on system
:return: None or raise exception if some tooling is missing |
341,112 | def _fit_RSA_marginalized(self, X, Y, X_base,
scan_onsets=None):
rank = self.rank
n_subj = len(Y)
n_V = [np.size(y, axis=1) for y in Y]
n_T = [np.size(y, axis=0) for y in Y]
n_C = np.size(X[0], axis=1)
l_idx, rank = self._chol_idx(n_... | The major utility of fitting Bayesian RSA
(marginalized version).
Note that there is a naming change of variable. X in fit()
is changed to Y here, and design in fit() is changed to X here.
This is because we follow the tradition that X expresses the
variable d... |
341,113 | def generate_permutations(elements, n):
c = [0] * n
yield elements
i = 0
while i < n:
if c[i] < i:
if i % 2 == 0:
elements[0], elements[i] = elements[i], elements[0]
else:
elements[c[i]], elements[i] = elements[i], elements[c[i]]
... | Heap's algorithm for generating all n! permutations in a list
https://en.wikipedia.org/wiki/Heap%27s_algorithm |
341,114 | def dict_top(d, k, n, reverse=False):
h = list()
for i in range(len(d)):
heappush(h, (-d[i][k] if reverse else d[i][k], i))
r = list()
while len(r) < n and len(h) > 0:
_, i = heappop(h)
r.append(d[i].copy())
return r | Return top n of a dictionary list sorted by key
:param d: dictionary list
:param k: key
:param n: top n
:param reverse: whether the value should be reversed
:return: top n of the sorted dictionary list |
341,115 | def start_map(name,
handler_spec,
reader_spec,
mapper_parameters,
shard_count=None,
output_writer_spec=None,
mapreduce_parameters=None,
base_path=None,
queue_name=None,
eta=None,
c... | Start a new, mapper-only mapreduce.
Deprecated! Use map_job.start instead.
If a value can be specified both from an explicit argument and from
a dictionary, the value from the explicit argument wins.
Args:
name: mapreduce name. Used only for display purposes.
handler_spec: fully qualified name of map... |
341,116 | def get_gradebook_admin_session(self, proxy):
if not self.supports_gradebook_admin():
raise errors.Unimplemented()
return sessions.GradebookAdminSession(proxy=proxy, runtime=self._runtime) | Gets the OsidSession associated with the gradebook administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookAdminSession) - a
``GradebookAdminSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable t... |
341,117 | def _validate_buckets(categorical, k, scheme):
if categorical and (k != 5 or scheme):
raise ValueError("Invalid input: categorical cannot be specified as True simultaneously with scheme or k "
"parameters")
if k > 10:
warnings.warn("Generating a choropleth using a c... | This method validates that the hue parameter is correctly specified. Valid inputs are:
1. Both k and scheme are specified. In that case the user wants us to handle binning the data into k buckets
ourselves, using the stated algorithm. We issue a warning if the specified k is greater than 10.
... |
341,118 | def end(self):
self.send_headers()
self.write()
self.write_eof()
self.has_ended = True | Ends the response. Useful for quickly ending connection with no data
sent |
341,119 | def invoke(self, request_envelope, context):
if (self.skill_id is not None and
request_envelope.context.system.application.application_id !=
self.skill_id):
raise AskSdkException("Skill ID Verification failed!!")
if self.api_client is not No... | Invokes the dispatcher, to handle the request envelope and
return a response envelope.
:param request_envelope: Request Envelope instance containing
request information
:type request_envelope: RequestEnvelope
:param context: Context passed during invocation
:type con... |
341,120 | def _find_mocker(symbol: str, context: ) -> Callable[[], bool]:
components = []
method = None
for component in symbol.split():
components.append(component.lower())
name = .join([ ] + components)
if hasattr(context, name):
method = getattr(context, name)
... | Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowercased and periods replaced with underscores.
If no match is found, a dummy function (only returns... |
341,121 | def delete(self, url, params=None, **kwargs):
return self.call_api(
"DELETE",
url,
params=params,
**kwargs
) | Call the API with a DELETE request.
Args:
url (str): Resource location relative to the base URL.
params (dict or None): Query-string parameters.
Returns:
ResultParser or ErrorParser. |
341,122 | def summary(self, *statistics):
if len(statistics) == 1 and isinstance(statistics[0], list):
statistics = statistics[0]
jdf = self._jdf.summary(self._jseq(statistics))
return DataFrame(jdf, self.sql_ctx) | Computes specified statistics for numeric and string columns. Available statistics are:
- count
- mean
- stddev
- min
- max
- arbitrary approximate percentiles specified as a percentage (eg, 75%)
If no statistics are given, this function computes count, mean, std... |
341,123 | def get_followers(self):
return github.PaginatedList.PaginatedList(
NamedUser,
self._requester,
self.url + "/followers",
None
) | :calls: `GET /users/:user/followers <http://developer.github.com/v3/users/followers>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` |
341,124 | def run_once():
if _debug: run_once._debug("run_once")
global taskManager, deferredFns
taskManager = TaskManager()
try:
delta = 0.0
while delta == 0.0:
task, delta = taskManager.get_next_task()
if _debug: run_once._debug(" - task, delta... | Make a pass through the scheduled tasks and deferred functions just
like the run() function but without the asyncore call (so there is no
socket IO actviity) and the timers. |
341,125 | def a_not_committed(ctx):
ctx.ctrl.sendline()
ctx.msg = "Some active software packages are not yet committed. Reload may cause software rollback."
ctx.device.chain.connection.emit_message(ctx.msg, log_level=logging.ERROR)
ctx.failed = True
return False | Provide the message that current software is not committed and reload is not possible. |
341,126 | def versions_from_trove(trove):
versions = set()
for classifier in trove:
if in classifier:
ver = classifier.split()[-1]
major = ver.split()[0].strip()
if major:
versions.add(major)
return sorted(
set([v for v in versions if v.replace... | Finds out python version from list of trove classifiers.
Args:
trove: list of trove classifiers
Returns:
python version string |
341,127 | def get_maxdays(name):
*
policies = _get_account_policy(name)
if in policies:
max_minutes = policies[]
return int(max_minutes) / 24 / 60
return 0 | Get the maximum age of the password
:param str name: The username of the account
:return: The maximum age of the password in days
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-block:: bash
salt '*' shadow.get_maxdays ad... |
341,128 | def get_relay_ip_list(server=_DEFAULT_SERVER):
Only the list belowAll except the list below*
ret = list()
setting =
lines = _get_wmi_setting(, setting, server)
if not lines:
_LOG.debug(, setting, lines)
if lines is None:
lines = [None]
return list(lines)
... | Get the RelayIpList list for the SMTP virtual server.
:param str server: The SMTP server name.
:return: A list of the relay IPs.
:rtype: list
.. note::
A return value of None corresponds to the restrictive 'Only the list below' GUI parameter
with an empty access list, and setting an ... |
341,129 | def list_workspace_configs(namespace, workspace, allRepos=False):
uri = "workspaces/{0}/{1}/methodconfigs".format(namespace, workspace)
return __get(uri, params={: allRepos}) | List method configurations in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
Swagger:
https://api.firecloud.org/#!/Method_Configurations/listWorkspaceMethodConfigs
DUPLICATE: https://api.firecloud.org/#!/Workspaces/listWorks... |
341,130 | def repr_setup(self, name=None, col_names=None, col_types=None):
self._name = name or self._name | This wasn't safe to pass into init because of the inheritance
:param name: name of the api return type (ex. CAMERA_DATA_LIST)
:param col_names:
:param col_types:
:return None: |
341,131 | def _process_value_fetcher_call_args(args):
if not args:
return _undefined, ()
if isinstance(args[0], JSONValueMapper):
default = _undefined
mappers = args
else:
default = args[0]
mappers = args[1:]
for mapper in mappers:
if not isinstance(mapper, J... | This function processes the incoming varargs of ValueNotFoundNode.__call__() and
_ConfigNode.__call__().
:param args: A list or tuple containing positional function call arguments. The optional
arguments we expect are the following: An optional default value followed by zero or more
JSONValueMapper inst... |
341,132 | def flatten_params(self, data, base_key=None):
result = {}
if data is None:
return result
map_data = None
if not isinstance(data, collections.Mapping):
map_data = []
for idx, val in enumerate(data):
map_data.append([str(idx),... | Flatten out nested arrays and dicts in query params into correct format |
341,133 | def _handle_packet(self, packet):
events = packet_events(packet)
for event in events:
if self.ignore_event(event[]):
log.debug(, event)
continue
log.debug(, event)
if self.event_callback:
self.event_callback(ev... | Event specific packet handling logic.
Break packet into events and fires configured event callback or
nicely prints events for console. |
341,134 | def check_for_nans_in_columns(df, columns=None):
if columns is None:
columns = df.columns
if pd.isnull(df.loc[:, columns]).any().any():
if not isinstance(columns, list):
columns = list(columns)
raise ValueError("Columns {} of DataFrame must not contain NaN values".forma... | Helper function to check for ``NaN`` in the data frame and raise a ``ValueError`` if there is one.
:param df: the pandas DataFrame to test for NaNs
:type df: pandas.DataFrame
:param columns: a list of columns to test for NaNs. If left empty, all columns of the DataFrame will be tested.
:type columns: l... |
341,135 | def send_text_message(self, recipient_id, message, notification_type=NotificationType.regular):
return self.send_message(recipient_id, {
: message
}, notification_type) | Send text messages to the specified recipient.
https://developers.facebook.com/docs/messenger-platform/send-api-reference/text-message
Input:
recipient_id: recipient id to send to
message: message to send
Output:
Response from API as <dict> |
341,136 | def to_dataframe(self, drop_weights_below=0, whitelist=None):
network_df_cols = ["pw0", "pw1", "weight"]
if self.features:
network_df_cols.append("features")
network_df = pd.DataFrame(columns=network_df_cols)
idx = 0
edge_pathways = set()
for (v0, v1)... | Conversion of the network to a pandas.DataFrame.
Parameters
-----------
drop_weights_below : int (default=0)
specify an edge weight threshold - remove all edges with weight
below this value
whitelist : [set|list](tup(int, int))|None (default=None)
option to... |
341,137 | def read_xyz(cls, buf, start_index=0, get_bonds=True,
nrows=None, engine=None):
frame = pd.read_table(buf, skiprows=2, comment=,
nrows=nrows,
delim_whitespace=True,
names=[, , , ], engine=engine)
... | Read a file of coordinate information.
Reads xyz-files.
Args:
inputfile (str):
start_index (int):
get_bonds (bool):
nrows (int): Number of rows of file to read.
Note that the first two rows are implicitly excluded.
engine (str... |
341,138 | def get_fragment_generator(self, on_load=None, on_seeds=None, on_plink=None, on_link=None, on_type=None,
on_type_validation=None, on_tree=None, workers=None, stop_event=None, queue_wait=None,
queue_size=100, provider=None, lazy=True):
if wo... | Create a fragment generator that executes the search plan.
:param on_load: Function to be called just after a new URI is dereferenced
:param on_seeds: Function to be called just after a seed of a tree is identified
:param on_plink: Function to be called when a pattern link is reached
:pa... |
341,139 | def create_binary_security_token(key_file):
node = etree.Element(
ns_id(, ns.wssens),
nsmap={ns.wssens[0]: ns.wssens[1]})
node.set(ns_id(, ns.wsuns), get_unique_id())
node.set(, ns.wssns[1] + )
node.set(, BINARY_TOKEN_TYPE)
with open(key_file) as fh:
cert = crypto.load_... | Create the BinarySecurityToken node containing the x509 certificate. |
341,140 | def tokenize(self, s):
javabridge.call(self.jobject, "tokenize", "(Ljava/lang/String;)V", s)
return TokenIterator(self) | Tokenizes the string.
:param s: the string to tokenize
:type s: str
:return: the iterator
:rtype: TokenIterator |
341,141 | def get_one_required(self, locator):
components = self.find(locator, True)
return components[0] if len(components) > 0 else None | Gets a required component reference that matches specified locator.
:param locator: the locator to find a reference by.
:return: a matching component reference.
:raises: a [[ReferenceException]] when no references found. |
341,142 | def rename_feature(spec, current_name, new_name, rename_inputs=True,
rename_outputs=True):
from coremltools.models import MLModel
if not rename_inputs and not rename_outputs:
return
changed_input = False
changed_output = False
if rename_inputs:
for input in... | Rename a feature in the specification.
Parameters
----------
spec: Model_pb
The specification containing the feature to rename.
current_name: str
Current name of the feature. If this feature doesn't exist, the rename
is a no-op.
new_name: str
New name of the featur... |
341,143 | def _configure_niceness(kwargs):
niceness = kwargs[]
if niceness is not None:
try:
try:
current = os.nice(0)
if niceness - current > 0:
os.nice(niceness-current)
except AttributeError:
... | Sets niceness of a process |
341,144 | def ProduceEventTag(self, event_tag):
self._storage_writer.AddEventTag(event_tag)
self.number_of_produced_event_tags += 1
self.last_activity_timestamp = time.time() | Produces an event tag.
Args:
event_tag (EventTag): event tag. |
341,145 | def clean_storage(block_device):
for mp, d in mounts():
if d == block_device:
juju_log( %
(d, mp), level=INFO)
umount(mp, persist=True)
if is_lvm_physical_volume(block_device):
deactivate_lvm_volume_group(block_device)
remove_lvm_physica... | Ensures a block device is clean. That is:
- unmounted
- any lvm volume groups are deactivated
- any lvm physical device signatures removed
- partition table wiped
:param block_device: str: Full path to block device to clean. |
341,146 | def coordination_geometry_symmetry_measures_separation_plane_optim(self,
coordination_geometry,
separation_plane_algo,
... | Returns the symmetry measures of the given coordination geometry "coordination_geometry" using separation
facets to reduce the complexity of the system. Caller to the refined 2POINTS, 3POINTS and other ...
:param coordination_geometry: The coordination geometry to be investigated
:return: The sy... |
341,147 | def set_time(time):
"17:46"*"17:34"
time_format = _get_date_time_format(time)
dt_obj = datetime.strptime(time, time_format)
cmd = .format(dt_obj.strftime())
return salt.utils.mac_utils.execute_return_success(cmd) | Sets the current time. Must be in 24 hour format.
:param str time: The time to set in 24 hour format. The value must be
double quoted. ie: '"17:46"'
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Time format
:raises: CommandExecutionError o... |
341,148 | def gelman_rubin(mcmc):
if mcmc.n_chains < 2:
raise ValueError(
)
Vhat, W = _vhat_w(mcmc)
Rhat = np.sqrt(Vhat / W)
return pd.DataFrame({: Rhat}, index=mcmc.levels) | Args:
mcmc (MCMCResults): Pre-sliced MCMC samples to compute diagnostics for. |
341,149 | def subject_area(soup):
subject_area = []
tags = raw_parser.subject_area(soup)
for tag in tags:
subject_area.append(node_text(tag))
return subject_area | Find the subject areas from article-categories subject tags |
341,150 | def _init_map(self):
super(EdXDragAndDropQuestionFormRecord, self)._init_map()
QuestionTextFormRecord._init_map(self)
QuestionFilesFormRecord._init_map(self)
self.my_osid_object_form._my_map[][] = | stub |
341,151 | def should_remove(self, point, node):
if not self.data == point:
return False
return (node is None) or (node is self) | checks if self's point (and maybe identity) matches |
341,152 | def to_child(self, append_message="", node_name="", **kwargs):
base_kwargs = {
attr: getattr(self, attr)
for attr in self.params
if attr not in ["highlight"]
}
if not isinstance(append_message, dict):
append_message = {"msg": append_messa... | Dive into nested tree.
Set the current state as a state with a subtree of this syntax tree as
student tree and solution tree. This is necessary when testing if statements or
for loops for example. |
341,153 | def conv2d(self, x_in: Connection, w_in: Connection, receptive_field_size, filters_number, stride=1, padding=1,
name=""):
x_cols = self.tensor_3d_to_cols(x_in, receptive_field_size, stride=stride, padding=padding)
mul = self.transpose(self.matrix_multiply(x_cols, w_in), 0, 2, 1)
... | Computes a 2-D convolution given 4-D input and filter tensors. |
341,154 | def ctmc(data, numstates, transintv=1.0, toltime=1e-8, debug=False):
if debug:
datacheck(data, numstates, toltime)
transcount, statetime = aggregateevents(data, numstates)
if debug:
errorcheck(transcount, statetime, toltime)
genmat = generatormatrix(transcount... | Continous Time Markov Chain
Parameters
----------
data : list of lists
A python list of N examples (e.g. rating histories of N companies,
the event data of N basketball games, etc.). The i-th example
consist of one list with M_i encoded state labels and M_i the
durations or ... |
341,155 | def make_emoji_dict(self):
emoji_dict = {}
for line in self.emoji_full_filepath.split():
(emoji, description) = line.strip().split()[0:2]
emoji_dict[emoji] = description
return emoji_dict | Convert emoji lexicon file to a dictionary |
341,156 | def get_dictkey(In, k, dtype):
Out = []
for d in In:
if dtype == :
Out.append(d[k])
if dtype == :
if d[k] == "":
Out.append(0)
elif d[k] == None:
Out.append(0)
else:
Out.append(float(d[k]))
... | returns list of given key (k) from input list of dictionaries (In) in data type dtype. uses command:
get_dictkey(In,k,dtype). If dtype =="", data are strings; if "int", data are integers; if "f", data are floats. |
341,157 | def write_json_to_file(self, net_type, filename, indent=):
export_data.write_json_to_file(self, net_type, filename, indent) | Save dat or viz as a JSON to file. |
341,158 | def getinnerframes(tb, context=1):
framelist = []
while tb:
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
tb = tb.tb_next
return framelist | Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context. |
341,159 | def get_all_clients(self, params=None):
return self._iterate_through_pages(
get_function=self.get_clients_per_page,
resource=CLIENTS,
**{: params}
) | Get all clients
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list |
341,160 | def encode(self, encoding=None):
r
try:
fc = self.func.value
except AttributeError:
fc = self.func
mhash = bytes([fc, len(self.digest)]) + self.digest
if encoding:
mhash = CodecReg.get_encoder(encoding)(mhash)
return mhash | r"""Encode into a multihash-encoded digest.
If `encoding` is `None`, a binary digest is produced:
>>> mh = Multihash(0x01, b'TEST')
>>> mh.encode()
b'\x01\x04TEST'
If the name of an `encoding` is specified, it is used to encode the
binary digest before returning it (se... |
341,161 | def _disk_setter(self, variable, value):
value = self.manager.get_abs_image_path(value)
if not self.linked_clone:
for node in self.manager.nodes:
if node != self and getattr(node, variable) == value:
raise QemuError("Sorry a node without the linke... | Use by disk image setter for checking and apply modifications
:param variable: Variable name in the class
:param value: New disk value |
341,162 | def format_symbol(self, symbol, link_resolver):
if not symbol:
return
if isinstance(symbol, FieldSymbol):
return
out = self._format_symbol(symbol)
template = self.get_template()
return template.render(
{: symbol,
... | Format a symbols.Symbol |
341,163 | def references(self):
t technically cited anywhere.
_referenceshttphttp:*propextlinksellimitmax'
})
]
return self._references | List of URLs of external links on a page.
May include external links within page that aren't technically cited anywhere. |
341,164 | def for_format(filename, format=None, writable=False, prefix_dir=None):
ext = op.splitext(filename)[1].lower()
try:
_format = supported_formats[ext]
except KeyError:
_format = None
format = get_default(format, _format)
if format is None:
io = MeshIO.any_from_filename(f... | Create a MeshIO instance for file `filename` with forced `format`.
Parameters
----------
filename : str
The name of the mesh file.
format : str
One of supported formats. If None,
:func:`MeshIO.any_from_filename()` is called instead.
writable : bool
If True, verify th... |
341,165 | def cache_nodes(gir_root, all_girs):
ns_node = gir_root.find( % NS_MAP[])
id_prefixes = ns_node.attrib[ % NS_MAP[]]
sym_prefixes = ns_node.attrib[ % NS_MAP[]]
id_key = % NS_MAP[]
for node in gir_root.xpath(
,
namespaces=NS_MAP):
make_translations (node.attrib[i... | Identify and store all the gir symbols the symbols we will document
may link to, or be typed with |
341,166 | def nhanesi(display=False):
X = pd.read_csv(cache(github_data_url + "NHANESI_subset_X.csv"))
y = pd.read_csv(cache(github_data_url + "NHANESI_subset_y.csv"))["y"]
if display:
X_display = X.copy()
X_display["Sex"] = ["Male" if v == 1 else "Female" for v in X["Sex"]]
return X_disp... | A nicely packaged version of NHANES I data with surivival times as labels. |
341,167 | def dest(self):
if hasattr(self, "parent") and self.parent is None:
raise ValueError("orphaned object: parent is None")
if self.parent.parent.isClosed or self.parent.parent.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
doc = self.p... | Create link destination details. |
341,168 | def _expanded_sql(self, sampling=None):
expanded_sql += sampling(self._sql) if sampling else self._sql
return expanded_sql | Get the expanded SQL of this object, including all subqueries, UDFs, and external datasources
Returns:
The expanded SQL string of this object |
341,169 | def create_repo(self, name, description=github.GithubObject.NotSet, homepage=github.GithubObject.NotSet,
private=github.GithubObject.NotSet, has_issues=github.GithubObject.NotSet,
has_wiki=github.GithubObject.NotSet, has_downloads=github.GithubObject.NotSet,
h... | :calls: `POST /user/repos <http://developer.github.com/v3/repos>`_
:param name: string
:param description: string
:param homepage: string
:param private: bool
:param has_issues: bool
:param has_wiki: bool
:param has_downloads: bool
:param has_projects: boo... |
341,170 | def get_parameter_values(self, parameters, from_cache=True, timeout=10):
params = {
: from_cache,
: int(timeout * 1000),
}
req = rest_pb2.BulkGetParameterValueRequest()
req.id.extend(_build_named_object_ids(parameters))
url = .format(
... | Retrieve the current value of the specified parameter.
:param str[] parameters: List of parameter names. These may be
fully-qualified XTCE name or an alias
in the format ``NAMESPACE/NAME``.
:param bool from_cache: If ``False`` this call ... |
341,171 | def get_valid_users(request):
users = [get_user(request)]
if settings.LOCKDOWN and hasattr(request, ):
if request.user.is_authenticated:
groups = request.user.groups.all()
if groups:
users = list(User.objects.filter(groups__in=groups)
... | Returns a list of `users` based on groups membership.
Returns a list made of a single user when it is not member of any group. |
341,172 | def monoclinic(a: float, b: float, c: float, beta: float):
return Lattice.from_parameters(a, b, c, 90, beta, 90) | Convenience constructor for a monoclinic lattice.
Args:
a (float): *a* lattice parameter of the monoclinc cell.
b (float): *b* lattice parameter of the monoclinc cell.
c (float): *c* lattice parameter of the monoclinc cell.
beta (float): *beta* angle between latt... |
341,173 | def labeled_uniform_sample(self, sample_size, replace=True):
if replace:
samples = [
random.choice(self.get_labeled_entries())
for _ in range(sample_size)
]
else:
samples = random.sample(self.get_labeled_entries(), sample_size)... | Returns a Dataset object with labeled data only, which is
resampled uniformly with given sample size.
Parameter `replace` decides whether sampling with replacement or not.
Parameters
----------
sample_size |
341,174 | def get_pipeline_field(self, pipeline_key, field_key = None):
uri = .join([
self.api_uri,
self.pipelines_suffix,
pipeline_key,
self.fields_suffix
])
if field_key:
uri = .join([uri, field_key])
return self._req(, uri) | Gets one/all field in a pipeline
Args:
pipeline_key key for pipeline
field_key key for field (default: None i.e. ALL)
returns status code, field dict or list thereof |
341,175 | def update_confirmation(self, confirmation_id, confirmation_dict):
return self._create_put_request(
resource=CONFIRMATIONS,
billomat_id=confirmation_id,
send_data=confirmation_dict
) | Updates a confirmation
:param confirmation_id: the confirmation id
:param confirmation_dict: dict
:return: dict |
341,176 | def signed_session(self, session=None):
session = super(ApiKeyCredentials, self).signed_session(session)
session.headers.update(self.in_headers)
try:
session.params.update(self.in_query)
except AttributeError:
raise ValueError("se... | Create requests session with ApiKey.
If a session object is provided, configure it directly. Otherwise,
create a new session and return it.
:param session: The session to configure for authentication
:type session: requests.Session
:rtype: requests.Session |
341,177 | def initialise_by_names(self, plugins=None):
if plugins is None:
plugins = []
self._log.debug("Plugins Initialisation started")
if not isinstance(plugins, list):
raise AttributeError("plugins must be a list, not %s" % type(plugins))
self._log.debug("Pl... | Initialises given plugins, but does not activate them.
This is needed to import and configure libraries, which are imported by used patterns, like GwFlask.
After this action, all needed python modules are imported and configured.
Also the groundwork application object is ready and contains fun... |
341,178 | def to_front(intersection, intersections, unused):
if intersection.s == 1.0:
next_index = (intersection.index_first + 1) % 3
return _intersection_helpers.Intersection(
next_index, 0.0, None, None, interior_curve=CLASSIFICATION_T.FIRST
)
elif intersecti... | Rotates a node to the "front".
.. note::
This is a helper used only by :func:`basic_interior_combine`, which in
turn is only used by :func:`combine_intersections`.
If a node is at the end of a segment, moves it to the beginning
of the next segment (at the exact same point). We assume that
... |
341,179 | def count_relations(graph) -> Counter:
return Counter(
data[RELATION]
for _, _, data in graph.edges(data=True)
) | Return a histogram over all relationships in a graph.
:param pybel.BELGraph graph: A BEL graph
:return: A Counter from {relation type: frequency} |
341,180 | def get_time(time_to_convert=None):
if time_to_convert is None:
time_to_convert = time.time()
return time.strftime(TIMESTAMP_FORMAT, time.localtime(time_to_convert)) | Create blink-compatible timestamp. |
341,181 | def set_range(self, bounds, keep_aspect=False):
bounds = np.asarray(bounds, dtype=np.float64)
v0 = bounds[:2]
v1 = bounds[2:]
pan = -.5 * (v0 + v1)
zoom = 2. / (v1 - v0)
if keep_aspect:
zoom = zoom.min() * np.ones(2... | Zoom to fit a box. |
341,182 | def from_path_except(dir_path,
ignore=list(), ignore_ext=list(), ignore_pattern=list()):
ignore = [i.lower() for i in ignore]
ignore_ext = [i.lower() for i in ignore_ext]
ignore_pattern = [i.lower() for i in ignore_pattern]
def filter(winfile):
relpath =... | Create a new FileCollection, and select all files except file
matching ignore-rule::
dir_path = "your/path"
fc = FileCollection.from_path_except(
dir_path, ignore=["test"], ignore_ext=[".log", ".tmp"]
ignore_pattern=["some_pattern"])
... |
341,183 | def calc_K_xx_wo_variance(self,X):
K_xx = np.ones([X.shape[0],X.shape[0]])
for i,x in enumerate(X):
for j,x2 in enumerate(X):
for il,l in enumerate(self.lengthscale):
idx = il*2
K_xx[i,j] *= self.k_xx(x[idx],x2[idx],x[idx+1],... | Calculates K_xx without the variance term |
341,184 | def match_sequence(self, tokens, item):
tail = None
if len(tokens) == 2:
series_type, matches = tokens
else:
series_type, matches, tail = tokens
self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")
if tail is None:
... | Matches a sequence. |
341,185 | def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(, , required=True,
action=, help=)
arg_parser.add_argument(, , required=True, action=,
help=)
arg_parser.add_argument(, , action=, help=)
arg_parser.add_argum... | Main routine. |
341,186 | async def connect(self):
self.reader = SMTPStreamReader(loop=self.loop)
protocol = asyncio.StreamReaderProtocol(self.reader, loop=self.loop)
conn = {
"protocol_factory": lambda: protocol,
"host": self.hostname,
"p... | Connects to the server.
.. note:: This method is automatically invoked by
:meth:`SMTP.__aenter__`. The code is mostly borrowed from the
:func:`asyncio.streams.open_connection` source code.
Raises:
ConnectionError subclass: If the connection between client and
... |
341,187 | def get_result(self):
result = get_json_from_remote_server(self.call)
referrers = list(result)
for referrer in referrers:
referrer[] = stringify_seconds(referrer[])
return sorted(referrers, key=itemgetter(), reverse=True)[0:10] | Perform the call and return a list of referrers |
341,188 | def delete(customer, card):
if isinstance(customer, resources.Customer):
customer = customer.id
if isinstance(card, resources.Card):
card = card.id
http_client = HttpClient()
http_client.delete(routes.url(routes.CARD_RESOURCE, resource_id=card, customer_... | Delete a card from its id.
:param customer: The customer id or object
:type customer: string|Customer
:param card: The card id or object
:type card: string|Card |
341,189 | def get_comment(self, item):
key = item.upper()
if key not in self._record_map:
raise KeyError("unknown record: %s" % key)
if not in self._record_map[key]:
return None
else:
return self._record_map[key][] | Get the comment for the requested entry |
341,190 | def AddNoiseToLatLng(lat, lng):
m_per_tenth_lat = Distance(lat, lng, lat + 0.1, lng)
m_per_tenth_lng = Distance(lat, lng, lat, lng + 0.1)
lat_per_100m = 1 / m_per_tenth_lat * 10
lng_per_100m = 1 / m_per_tenth_lng * 10
return (lat + (lat_per_100m * 5 * (random.random() * 2 - 1)),
lng + (lng_per_10... | Add up to 500m of error to each coordinate of lat, lng. |
341,191 | def list_keys(user=None, gnupghome=None):
s keychain to access, defaults to user Salt is running as.
Passing the user as ``salt`` will set the GnuPG home directory to the
``/etc/salt/gpgkeys``.
gnupghome
Specify the location where GPG keyring and related files are stored.
CLI Examp... | List keys in GPG keychain
user
Which user's keychain to access, defaults to user Salt is running as.
Passing the user as ``salt`` will set the GnuPG home directory to the
``/etc/salt/gpgkeys``.
gnupghome
Specify the location where GPG keyring and related files are stored.
... |
341,192 | def how_similar_dicts(dict1, dict2):
values = []
for k in dict1:
if k in dict2 and dict1[k] and dict2[k]:
values.append(
how_similar_are(str(dict1[k]), str(dict2[k]))
)
return np.mean(values) | Calculates similarity
:param dict1: Dictionary
:param dict2: Dictionary
:return: measure of how much similar values of dictionaries are |
341,193 | def get_mysql_password_on_disk(self, username=None, password=None):
if username:
template = self.user_passwd_file_template
passwd_file = template.format(username)
else:
passwd_file = self.root_passwd_file_template
_password = None
if os.path.... | Retrieve, generate or store a mysql password for the provided
username on disk. |
341,194 | def neutron_process(body, message):
event_type = body[]
process = neutron_customer_process.get(event_type)
if process is not None:
process(body, message)
else:
matched = False
process_wildcard = None
for pattern in neutron_customer_process_wildcard.keys():
... | This function deal with the neutron notification.
First, find process from customer_process that not include wildcard.
if not find from customer_process, then find process from customer_process_wildcard.
if not find from customer_process_wildcard, then use ternya default process.
:param body: dict of o... |
341,195 | def confd_state_internal_callpoints_authorization_callbacks_registration_type_file_file(self, **kwargs):
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
internal = ET.SubElement(confd_state, "internal")
... | Auto Generated Code |
341,196 | def save_graph(graphdef):
if graphdef.filename is None:
if in os.environ:
dname = os.path.join(os.environ[], )
if os.path.exists(dname):
mp_util.mkdir_p(dname)
graphdef.filename = os.path.join(dname, )
elif in os.environ:
dna... | save a graph as XML |
341,197 | def decode_bucket_props(self, msg):
props = {}
for prop in NORMAL_PROPS:
if msg.HasField(prop):
props[prop] = getattr(msg, prop)
if isinstance(props[prop], bytes):
props[prop] = bytes_to_str(props[prop])
for prop in COMMIT_... | Decodes the protobuf bucket properties message into a dict.
:param msg: the protobuf message to decode
:type msg: riak.pb.riak_pb2.RpbBucketProps
:rtype dict |
341,198 | def remove_distributed_artifact(self, id, artifact_id, **kwargs):
kwargs[] = True
if kwargs.get():
return self.remove_distributed_artifact_with_http_info(id, artifact_id, **kwargs)
else:
(data) = self.remove_distributed_artifact_with_http_info(id, artifact_id, **... | Removes an artifact from the specified product milestone
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>>... |
341,199 | def relaxNGValidatePushCData(self, data, len):
ret = libxml2mod.xmlRelaxNGValidatePushCData(self._o, data, len)
return ret | check the CData parsed for validation in the current stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.