Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
353,200 | def get_friends(self, limit=50, cacheable=False):
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getFriends", cacheable
):
seq.append(User(_extract(node, "name"), self.network))
return seq | Returns a list of the user's friends. |
353,201 | def log_gen() -> Iterator[int]:
y = 1
while True:
adder = max(1, math.pow(10, int(math.log10(y))))
yield int(y)
y = y + int(adder) | Logarithmic generator. |
353,202 | def get_asset_notification_session(self, asset_receiver):
if not self.supports_asset_notification():
raise errors.Unimplemented()
return sessions.AssetNotificationSession(runtime=self._runtime, receiver=asset_receiver) | Gets the notification session for notifications pertaining to asset changes.
arg: asset_receiver (osid.repository.AssetReceiver): the
notification callback
return: (osid.repository.AssetNotificationSession) - an
``AssetNotificationSession``
raise: NullArgumen... |
353,203 | def destroy_elb(app=, env=, region=, **_):
task_json = get_template(
template_file=,
app=app,
env=env,
region=region,
vpc=get_vpc_id(account=env, region=region))
wait_for_task(task_json)
return True | Destroy ELB Resources.
Args:
app (str): Spinnaker Application name.
env (str): Deployment environment.
region (str): AWS region.
Returns:
True upon successful completion. |
353,204 | def LHCb_label(side="L", status="final", text="", pad=None):
if pad is None:
pad = ROOT.gPad
with preserve_current_canvas():
pad.cd()
if side == "L":
l = ROOT.TPaveText(pad.GetLeftMargin() + 0.05,
0.87 - pad.GetTopMargin(),
... | Add an 'LHCb (Preliminary|Unofficial)' label to the current pad. |
353,205 | def fit_quantile(self, X, y, quantile, max_iter=20, tol=0.01, weights=None):
def _within_tol(a, b, tol):
return np.abs(a - b) <= tol
if quantile <= 0 or quantile >= 1:
raise ValueError(.format(quantile))
if tol <= 0:
raise ValueError(.forma... | fit ExpectileGAM to a desired quantile via binary search
Parameters
----------
X : array-like, shape (n_samples, m_features)
Training vectors, where n_samples is the number of samples
and m_features is the number of features.
y : array-like, shape (n_samples,)
... |
353,206 | 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 |
353,207 | def _okToExit(self):
return True | Test if it's OK to exit this worker. This is only called when we run
out of prospective new models to evaluate. This method sees if all models
have matured yet. If not, it will sleep for a bit and return False. This
will indicate to the hypersearch worker that we should keep running, and
check again lat... |
353,208 | def filter_threshold_percentile(self, analyte, percentiles, level=, filt=False,
samples=None, subset=None):
params = locals()
del(params[])
if samples is not None:
subset = self.make_subset(samples)
samples = self._get_samples(su... | Applies a threshold filter to the data.
Generates two filters above and below the threshold value for a
given analyte.
Parameters
----------
analyte : str
The analyte that the filter applies to.
percentiles : float or iterable of len=2
The percen... |
353,209 | def get_data_files():
if sys.platform.startswith():
if PY3:
data_files = [(,
[]),
(,
[])]
else:
data_files = [(,
[]),
(,
... | Return data_files in a platform dependent manner |
353,210 | def get_api_id(self, lambda_name):
try:
response = self.cf_client.describe_stack_resource(StackName=lambda_name,
LogicalResourceId=)
return response[].get(, None)
except:
try:
... | Given a lambda_name, return the API id. |
353,211 | def alternative_titles(self, **kwargs):
path = self._get_id_path()
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
return response | Get the alternative titles for a specific movie id.
Args:
country: (optional) ISO 3166-1 code.
append_to_response: (optional) Comma separated, any movie method.
Returns:
A dict representation of the JSON returned from the API. |
353,212 | def subscribe(self, *events: Union[Event, Pager]) -> Callable:
try:
first_event = events[0]
except IndexError:
raise IndexError()
if len(events) != len(set(events)):
raise ValueError(
)
if len(events) > 1:
... | Call a function in response to an event.
If more than one event is given, `func` will be given
as many arguments as there are events.
If the pager calls notify, the decorated function will be called.
Parameters
----------
*event : event or pager
Bowtie even... |
353,213 | def _ascii2(value):
if isinstance(value, Mapping):
items = [_ascii2(k) + ": " + _ascii2(v)
for k, v in six.iteritems(value)]
item_str = "{" + ", ".join(items) + "}"
if value.__class__.__name__ == :
return item_str
return "{0}({1})"... | A variant of the `ascii()` built-in function known from Python 3 that:
(1) ensures ASCII-only output, and
(2) produces a nicer formatting for use in exception and warning messages
and other human consumption.
This function calls `ascii()` and post-processes its output as follows:
* For unicod... |
353,214 | def from_dict(cls, cls_dict, fallback_xsi_type=None):
if not cls_dict:
return None
if isinstance(cls_dict, six.string_types):
if not getattr(cls, "_convert_strings", False):
return cls_dict
try:
typekey = cls.dictkey(cls_dict... | Parse the dictionary and return an Entity instance.
This will attempt to extract type information from the input
dictionary and pass it to entity_class to resolve the correct class
for the type.
Args:
cls_dict: A dictionary representation of an Entity object.
fa... |
353,215 | def get_holodeck_path():
if "HOLODECKPATH" in os.environ and os.environ["HOLODECKPATH"] != "":
return os.environ["HOLODECKPATH"]
if os.name == "posix":
return os.path.expanduser("~/.local/share/holodeck")
elif os.name == "nt":
return os.path.expanduser("~\\AppData\\Local\\holode... | Gets the path of the holodeck environment
Returns:
(str): path to the current holodeck environment |
353,216 | def submit_evaluation(self, variant_obj, user_obj, institute_obj, case_obj, link, criteria):
variant_specific = variant_obj[]
variant_id = variant_obj[]
user_id = user_obj[]
user_name = user_obj.get(, user_obj[])
institute_id = institute_obj[]
case_id = case_obj[... | Submit an evaluation to the database
Get all the relevant information, build a evaluation_obj
Args:
variant_obj(dict)
user_obj(dict)
institute_obj(dict)
case_obj(dict)
link(str): variant url
criteria(list(dict)):
... |
353,217 | def dropbox_fileupload(dropbox, request):
attachment = request.POST[]
attached = dropbox.add_attachment(attachment)
return dict(
files=[dict(
name=attached,
type=attachment.type,
)]
) | accepts a single file upload and adds it to the dropbox as attachment |
353,218 | def has_api_key(file_name):
f = open(file_name, )
text = f.read()
if re.search(real_api_regex, text) is not None and \
re.search(zero_api_regex, text) is None:
return True
return False | Detect whether the file contains an api key in the Token object that is not 40*'0'.
See issue #86.
:param file: path-to-file to check
:return: boolean |
353,219 | def normalize_subpath(self, subpath):
if subpath is None:
return None
subpath = posixpath.normpath(subpath)
filename = os.path.normpath(safe_join(self.root_directory, subpath))
if os.path.isdir(filename):
subpath +=
return su... | Normalizes the specified subpath, or None if subpath is None.
This allows Readme files to be inferred from directories while
still allowing relative paths to work properly.
Raises werkzeug.exceptions.NotFound if the resulting path
would fall out of the root directory. |
353,220 | def find(cls, api_key=None, fetch_all=True, endpoint=None, maximum=None,
**kwargs):
exclude = kwargs.pop(, None)
if isinstance(exclude, six.string_types):
exclude = [exclude, ]
query_params = cls.translate_query_params(**kwargs)
if e... | Find some entities from the API endpoint.
If no api_key is provided, the global api key will be used.
If fetch_all is True, page through all the data and find every record
that exists.
If add_headers is provided (as a dict) use it to add headers to the
HTTP request, eg.
... |
353,221 | def readGTF(infile):
df=pd.read_table(infile, sep=, comment="
df.columns=[,,,,,,,,]
return df | Reads a GTF file and labels the respective columns in agreement with GTF file standards:
'seqname','source','feature','start','end','score','strand','frame','attribute'.
:param infile: path/to/file.gtf
:returns: a Pandas dataframe of the respective GTF |
353,222 | def client_proof(user, password, salt, A, B, a, hash_algo):
N, g, k = get_prime()
K = client_session(user, password, salt, A, B, a)
n1 = bytes2long(hash_digest(hashlib.sha1, N))
n2 = bytes2long(hash_digest(hashlib.sha1, g))
if DEBUG_PRINT:
print(, binascii.b2a_hex(long2bytes(n1)), end=... | M = H(H(N) xor H(g), H(I), s, A, B, K) |
353,223 | def from_spec(spec, kwargs=None):
network = util.get_object(
obj=spec,
default_object=LayeredNetwork,
kwargs=kwargs
)
assert isinstance(network, Network)
return network | Creates a network from a specification dict. |
353,224 | def write_rec(table_name, objid, data, index_name_values):
with DatastoreTransaction() as tx:
entity = tx.get_upsert()
entity.key.CopyFrom(make_key(table_name, objid))
prop = entity.property.add()
prop.name =
prop.value.string_value = objid
prop = entity.prop... | Write (upsert) a record using a tran. |
353,225 | def password_entropy(length: int, chars: str) -> float:
if not isinstance(length, int):
raise TypeError()
if length < 0:
raise ValueError()
if not isinstance(chars, str):
raise TypeError()
if not chars:
raise ValueError("chars can't be null")
if length == 0:
... | Calculate the entropy of a password with given length and chars. |
353,226 | def to_image(self, filename=, band_width=1, length=60,
max_width=0, vertical=True, alpha_channel=False):
if max_width < 1:
pass
else:
band_width = int(max_width/len(self._colours))
image_width = band_width * len(self._colours)... | Creates an image from the palette.
Args:
filename(Optional[string]): filename of saved file. Defaults to
``palette.png`` in the current working directory.
band_width(optional[int]): how wide each colour band should be.
Defaults to 1 pixel.
len... |
353,227 | def index(self, key, default=UNSET):
self._find_lt(key)
node = self._path[0][2]
if node is self._tail or key < node[0]:
if default is self.UNSET:
raise KeyError(.format(key))
return default
return self._distance[0] | Find the first key-value pair with key *key* and return its position.
If the key is not found, return *default*. If default was not provided,
raise a ``KeyError`` |
353,228 | def clean_pid_file(pidfile):
if pidfile and os.path.exists(pidfile):
os.unlink(pidfile) | clean pid file. |
353,229 | def _aovhm_theta_worker(task):
times, mags, errs, frequency, nharmonics, magvariance = task
try:
theta = aovhm_theta(times, mags, errs, frequency,
nharmonics, magvariance)
return theta
except Exception as e:
return npnan | This is a parallel worker for the function below.
Parameters
----------
tasks : tuple
This is of the form below::
task[0] = times
task[1] = mags
task[2] = errs
task[3] = frequency
task[4] = nharmonics
task[5] = magvariance
... |
353,230 | def getnodefieldname(idfobject, endswith, fluid=None, startswith=None):
if startswith is None:
startswith =
if fluid is None:
fluid =
nodenames = getfieldnamesendswith(idfobject, endswith)
nodenames = [name for name in nodenames if name.startswith(startswith)]
fnodenames = [nd... | return the field name of the node
fluid is only needed if there are air and water nodes
fluid is Air or Water or ''.
if the fluid is Steam, use Water |
353,231 | def delete(self, *objs, condition=None, atomic=False):
objs = set(objs)
validate_not_abstract(*objs)
for obj in objs:
self.session.delete_item({
"TableName": self._compute_table_name(obj.__class__),
"Key": dump_key(self, obj),
... | Delete one or more objects.
:param objs: objects to delete.
:param condition: only perform each delete if this condition holds.
:param bool atomic: only perform each delete if the local and DynamoDB versions of the object match.
:raises bloop.exceptions.ConstraintViolation: if the condi... |
353,232 | def delete_storage(kwargs=None, conn=None, call=None):
if call != :
raise SaltCloudSystemExit(
)
if kwargs is None:
kwargs = {}
if not in kwargs:
raise SaltCloudSystemExit()
if not conn:
conn = get_conn()
try:
data = conn.delete_... | .. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage |
353,233 | def get_home_dir(require_writable=False):
if hasattr(sys, "frozen"):
if in IPython.__file__.lower():
root, rest = IPython.__file__.lower().split()
else:
root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
root=os.path.abspath(root).rstrip... | Return the 'home' directory, as a unicode string.
* First, check for frozen env in case of py2exe
* Otherwise, defer to os.path.expanduser('~')
See stdlib docs for how this is determined.
$HOME is first priority on *ALL* platforms.
Parameters
----------
require_writable : boo... |
353,234 | def send_to_graphite(self, metric, value, timestamp=None):
if not self.statsd_enabled or not self.carbon:
return
if timestamp is None:
timestamp = int(time.time())
self.my_metrics.append((.join([self.statsd_prefix, self.name, metric]),
... | Inner store a new metric and flush to Graphite if the flush threshold is reached.
If no timestamp is provided, get the current time for the metric timestam.
:param metric: metric name in dotted format
:type metric: str
:param value:
:type value: float
:param timestamp: ... |
353,235 | def get_version(self):
return Version.objects.get(
content_type=self.content_type,
object_id=self.object_id,
version_number=self.publish_version,
) | Get the version object for the related object. |
353,236 | def from_file(cls, path=None):
if path is None:
for path in cls.default_pathes():
try:
return cls.from_file(path)
except IOError as e:
logging.getLogger(__name__).debug(
_("Failed to rea... | Read YAML config file. Returns Config object.
:raises IOError: if the path does not exist |
353,237 | def check_path(path, otherwise):
if os.path.exists(path):
print("WARNING: Path already exists; skipping" % path)
else:
otherwise(path) | Checks if a path exists. If it does, print a warning message; if not,
execute the `otherwise` callback argument. |
353,238 | def get_temperatures(self, units):
sensor_value = self.get_temperature(self.DEGREES_C)
return [self._get_unit_factor(unit)(sensor_value) for unit in units] | Returns the temperatures in the specified units
:param list units: the units for the sensor temperature
:returns: the sensor temperature in the given units. The order of
the temperatures matches the order of the given units.
:rtype: list
:raises Unsupported... |
353,239 | def _cmp_by_aspath(path1, path2):
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert as_path1 and as_path2
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert l1 is not None and l2 is not None
if l1 > l2:
... | Calculated the best-paths by comparing as-path lengths.
Shortest as-path length is preferred. If both path have same lengths,
we return None. |
353,240 | async def enable(self, ctx, *, command: str):
command = command.lower()
guild_id = ctx.message.server.id
cmds = self.config.get(, {})
entries = cmds.get(guild_id, [])
try:
entries.remove(command)
except KeyError:
await self.bot.responses.... | Enables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command. |
353,241 | def getlist(self, key, delimiter=, **kwargs):
value = self.get(key, **kwargs)
if value is None: return value
if isinstance(value, str):
value = value.strip()
if value.startswith() and value.endswith():
return self.getserialized(key)
... | Gets the setting value as a :class:`list`; it splits the string using ``delimiter``.
:param str delimiter: split the value using this delimiter
:rtype: list |
353,242 | def get_hotttnesss(self, cache=True):
if not (cache and ( in self.cache)):
response = self.get_attribute()
self.cache[] = response[][]
return self.cache[] | Get our numerical description of how hottt an artist currently is
Args:
Kwargs:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
Returns:
float: the hotttnesss value
... |
353,243 | def index(self):
self._index = _C.SDfindattr(self._obj._id, self._name)
_checkErr(, self._index, )
return self._index | Retrieve the attribute index number.
Args::
no argument
Returns::
attribute index number (starting at 0)
C library equivalent : SDfindattr |
353,244 | def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())
try:
decoded_key = decoded_values[0]
except IndexError:
raise ValueError("Invalid public key encoding.")
return decoded_key["publicKey"].asOctets() | Convert a PKCS8-encoded RSA private key to PKCS1. |
353,245 | def _get_nr_bins(count):
if count <= 30:
k = np.ceil(np.sqrt(count))
else:
k = np.ceil(np.log2(count)) + 1
return int(k) | depending on the number of data points, compute a best guess for an
optimal number of bins
https://en.wikipedia.org/wiki/Histogram#Number_of_bins_and_width |
353,246 | def method(self, method):
if method is None:
raise ValueError("Invalid value for `method`, must not be `None`")
allowed_values = ["WEBHOOK", "EMAIL", "PAGERDUTY"]
if method not in allowed_values:
raise ValueError(
"Invalid value for `method` (... | Sets the method of this Notificant.
The notification method used for notification target. # noqa: E501
:param method: The method of this Notificant. # noqa: E501
:type: str |
353,247 | def total_ordering(cls):
convert = {
: [(, lambda self, other: not (self < other or self == other)),
(, lambda self, other: self < other or self == other),
(, lambda self, other: not self < other)],
: [(, lambda self, other: not self <= other or self == o... | Class decorator that fills in missing ordering methods |
353,248 | def upload_to_s3(self, source_path, bucket_name, disable_progress=False):
r
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError:
try:
self.s3_client.upload_file(
... | r"""
Given a file, upload it to S3.
Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows).
Returns True on success, false on failure. |
353,249 | def begin(script=, file_in=None, mlp_in=None):
script_file = open(script, )
script_file.write(.join([,
]))
script_file.close()
current_layer = -1
last_layer = -1
stl = False
if mlp_in is not None:
if not isinstance(file_in, list):
... | Create new mlx script and write opening tags.
Performs special processing on stl files.
If no input files are provided this will create a dummy
file and delete it as the first filter. This works around
the meshlab limitation that it must be provided an input
file, even if you will be creating a me... |
353,250 | def _uint2farray(ftype, num, length=None):
if num < 0:
raise ValueError("expected num >= 0")
else:
objs = _uint2objs(ftype, num, length)
return farray(objs) | Convert an unsigned integer to an farray. |
353,251 | def is_iterable(value):
return isinstance(value, np.ndarray) or isinstance(value, list) or isinstance(value, tuple), value | must be an iterable (list, array, tuple) |
353,252 | def decode(packet):
packet = bytes(packet).strip(END)
if not is_valid(packet):
raise ProtocolError(packet)
return packet.strip(END).replace(ESC + ESC_END, END).replace(ESC + ESC_ESC, ESC) | decode(packet) -> message from SLIP-encoded packet
Retrieves the message from the SLIP-encoded packet.
:param bytes packet: The SLIP-encoded message.
Note that this must be exactly one complete packet.
The :func:`decode` function does not provide any buffering
for incom... |
353,253 | def plot_markov_model(
P, pos=None, state_sizes=None, state_scale=1.0, state_colors=, state_labels=,
minflux=1e-6, arrow_scale=1.0, arrow_curvature=1.0, arrow_labels=,
arrow_label_format=, max_width=12, max_height=12, figpadding=0.2, show_frame=False,
ax=None, **textkwargs):
r
from msmtools impo... | r"""Network representation of MSM transition matrix
This visualization is not optimized for large matrices. It is meant to be
used for the visualization of small models with up to 10-20 states, e.g.
obtained by a HMM coarse-graining. If used with large network, the automatic
node positioning will be ve... |
353,254 | def _code_search(query, github_user=None):
github_client = temple.utils.GithubClient()
headers = {: }
resp = github_client.get(,
params={: query, : 100},
headers=headers)
if resp.status_code == requests.codes.unprocessable_entity and githu... | Performs a Github API code search
Args:
query (str): The query sent to Github's code search
github_user (str, optional): The Github user being searched in the query string
Returns:
dict: A dictionary of repository information keyed on the git SSH url
Raises:
`InvalidGithub... |
353,255 | def get_cached_document_ids(ids, doc_type):
for batch in _split_list(ids):
for id in _get_cached_document_ids(batch, doc_type):
yield id | Get the ids of documents that have been parsed with this doc_type |
353,256 | def place_center(window, width=None, height=None):
screenGeometry = QApplication.desktop().screenGeometry()
w, h = window.width(), window.height()
if width is not None or height is not None:
w = width if width is not None else w
h = height if height is not None else h
... | Places window in the center of the screen. |
353,257 | def follow_request_reject(self, id):
id = self.__unpack_id(id)
url = .format(str(id))
self.__api_request(, url) | Reject an incoming follow request. |
353,258 | def msearch(self, body, index=None, doc_type=None, **query_params):
self._es_parser.is_not_empty_params(body)
path = self._es_parser.make_path(index,
doc_type,
EsMethods.MULTIPLE_SEARCH)
result = yield se... | Execute several search requests within the same API.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html>`_
:arg body: The request definitions (metadata-search request definition
pairs), separated by newlines
:arg index: A comma-separated list of... |
353,259 | def on_install(self, editor):
super(FoldingPanel, self).on_install(editor)
self.context_menu = QtWidgets.QMenu(_(), self.editor)
action = self.action_collapse = QtWidgets.QAction(
_(), self.context_menu)
action.setShortcut()
action.triggered.connect(self._on_... | Add the folding menu to the editor, on install.
:param editor: editor instance on which the mode has been installed to. |
353,260 | def _add_graph_level(graph, level, parent_ids, names, scores, normalized_scores,
include_pad):
for i, parent_id in enumerate(parent_ids):
if not include_pad and names[i] == PAD_TOKEN:
continue
new_node = (level, i)
parent_node = (level - 1, parent_id)
... | Adds a level to the passed graph |
353,261 | def rate_tip_ride(self,
ride_id,
rating,
tip_amount=None,
tip_currency=None,
feedback=None
):
args = {
"rating": rating,
"tip.amount": tip_amount,
"tip.currency": tip_currency,
"feedback": feedback,
}
... | Provide a rating, tip or feedback for the specified ride.
Params
ride_id (str)
The unique ID of the Ride Request.
rating (int)
An integer between 1 and 5
tip_amount
Optional integer amount greater than 0 in minor currency units ... |
353,262 | def request(self, requests):
logging.info()
return self.driver.requestResources(map(encode, requests)) | Requests resources from Mesos.
(see mesos.proto for a description of Request and how, for example, to
request resources from specific slaves.)
Any resources available are offered to the framework via
Scheduler.resourceOffers callback, asynchronously. |
353,263 | def run_resume_status(self, entity, project_name, name):
query = gql()
response = self.gql(query, variable_values={
: entity, : project_name, : name,
})
if not in response or not in response[]:
return None
project = response[]
self.se... | Check if a run exists and get resume information.
Args:
entity (str, optional): The entity to scope this project to.
project_name (str): The project to download, (can include bucket)
run (str, optional): The run to download |
353,264 | def ParseRow(self, parser_mediator, row_offset, row):
timestamp = self._ParseTimestamp(parser_mediator, row)
if timestamp is None:
return
try:
action = int(row[], 10)
except (ValueError, TypeError):
action = None
try:
scan_type = int(row[], 10)
except (ValueError, ... | Parses a line of the log file and produces events.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row_offset (int): line number of the row.
row (dict[str, str]): fields of a single row, as specified in COLUM... |
353,265 | def delete(self):
for field_name in self._fields:
field = self.get_field(field_name)
if not isinstance(field, PKField):
field.delete()
self.connection.srem(self.get_field().collection_key, self._pk)
dela... | Delete the instance from redis storage. |
353,266 | def find_requirements(path):
requirements = []
setup_py = os.path.join(path, )
if os.path.exists(setup_py) and os.path.isfile(setup_py):
try:
requirements = from_setup_py(setup_py)
requirements.sort()
return requirements
except CouldNotParseRequireme... | This method tries to determine the requirements of a particular project
by inspecting the possible places that they could be defined.
It will attempt, in order:
1) to parse setup.py in the root for an install_requires value
2) to read a requirements.txt file or a requirements.pip in the root
3) to... |
353,267 | def _get_stub(self, table, create):
if table is None:
return BLANK_STUB
else:
if create:
stub = CREATE_STUB
else:
stub = UPDATE_STUB
return stub | Get the migration stub template
:param table: The table name
:type table: str
:param create: Whether it's a create migration or not
:type create: bool
:rtype: str |
353,268 | def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id):
shutit_global.shutit_global_object.yield_to_draw()
for key in self.shutit_pexpect_sessions:
if self.shutit_pexpect_sessions[key].pexpect_session_id == shutit_pexpect_id:
return self.shutit_pexpect_sessions[key]
return self.fail(,throw_exce... | Get the pexpect session from the given identifier. |
353,269 | def _read_species_and_inital_geometry(self):
header_pattern = r"Standard Nuclear Orientation \(Angstroms\)\s+I\s+Atom\s+X\s+Y\s+Z\s+-+"
table_pattern = r"\s*\d+\s+([a-zA-Z]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*([\d\-\.]+)\s*"
footer_pattern = r"\s*-+"
temp_geom = read_table_pattern(s... | Parses species and initial geometry. |
353,270 | def result(self, root = None):
root = root or self._result
if isinstance(root, Aggregator):
return root.result()
else:
result = {}
for key, value in six.iteritems(root):
if value:
result[key] = self.result(value)
return result | Formats the result. |
353,271 | def from_dict(cls, d):
ce = cls()
for cg in d[].keys():
if d[][cg][] is None:
l2p_map = None
else:
l2p_map = {int(key): int(val) for key, val in d[][cg][].items()}
if d[][cg][] is None:
p2l_map = None
... | Reconstructs the ChemicalEnvironments object from a dict representation of the ChemicalEnvironments created
using the as_dict method.
:param d: dict representation of the ChemicalEnvironments object
:return: ChemicalEnvironments object |
353,272 | def update(self):
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_climate_params(self._id)
if data:
if time.time() - self.__manual_update_time > 60:
self.__is_auto_conditioning_on = (data
... | Update the HVAC state. |
353,273 | def refresh_table(self):
if self.is_visible and self.isVisible():
self.shellwidget.refresh_namespacebrowser()
try:
self.editor.resizeRowToContents()
except TypeError:
pass | Refresh variable table |
353,274 | def _get_app_libs_volume_mounts(app_name, assembled_specs):
volumes = []
for lib_name in assembled_specs[][app_name][][]:
lib_spec = assembled_specs[][lib_name]
volumes.append("{}:{}".format(Repo(lib_spec[]).vm_path, container_code_path(lib_spec)))
return volumes | Returns a list of the formatted volume mounts for all libs that an app uses |
353,275 | def tx_context_for_idx(self, tx_in_idx):
tx_in = self.tx.txs_in[tx_in_idx]
tx_context = TxContext()
tx_context.lock_time = self.tx.lock_time
tx_context.version = self.tx.version
tx_context.puzzle_script = b if self.tx.missing_unspent(tx_in_idx) else self.tx.unspents[tx_... | solution_script: alleged solution to the puzzle_script
puzzle_script: the script protecting the coins |
353,276 | def are_equivalent_xml(a_xml, b_xml):
return are_equivalent_pyxb(
d1_common.xml.deserialize(a_xml), d1_common.xml.deserialize(b_xml)
) | Check if two ReplicationPolicy XML docs are semantically equivalent.
The ReplicationPolicy XML docs are normalized before comparison.
Args:
a_xml, b_xml: ReplicationPolicy XML docs to compare
Returns:
bool: ``True`` if the resulting policies for the two objects are semantically
equivale... |
353,277 | def listify(fn=None, wrapper=list):
def listify_return(fn):
@wraps(fn)
def listify_helper(*args, **kw):
return wrapper(fn(*args, **kw))
return listify_helper
if fn is None:
return listify_return
return listify_return(fn) | A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
... for i in iterable:
... yi... |
353,278 | def remove_builtin(self, key, orig):
if orig is BuiltinUndefined:
del __builtin__.__dict__[key]
else:
__builtin__.__dict__[key] = orig | Remove an added builtin and re-set the original. |
353,279 | def abivalidate_inputs(self):
if not self.allocated:
self.allocate()
isok, tuples = True, []
for task in self.iflat_tasks():
t = task.input.abivalidate()
if t.retcode != 0: isok = False
tuples.append(t)
return isok, tuples | Run ABINIT in dry mode to validate all the inputs of the flow.
Return:
(isok, tuples)
isok is True if all inputs are ok.
tuples is List of `namedtuple` objects, one for each task in the flow.
Each namedtuple has the following attributes:
retcode... |
353,280 | def _load_repodata(filepaths, extra_data=None, metadata=None):
extra_data = extra_data if extra_data else {}
metadata = metadata if metadata else {}
repodata = []
for filepath in filepaths:
compressed = filepath.endswith()
mode = if filepath.endswith() e... | Load all the available pacakges information.
For downloaded repodata files (repo.continuum.io), additional
data provided (anaconda cloud), and additional metadata and merge into
a single set of packages and apps. |
353,281 | def stop(self):
if not self._running or self._device is None:
logging.warning( %(self._device_num))
return False
self._device.stop()
self._device.close()
self._device = None
self._running = False
return True | Stops the Kinect2 sensor stream.
Returns
-------
bool
True if the stream was stopped, False if the device was already
stopped or was not otherwise available. |
353,282 | def _get_environ(environ):
keys = ["SERVER_NAME", "SERVER_PORT"]
if _should_send_default_pii():
keys += ["REMOTE_ADDR", "HTTP_X_FORWARDED_FOR", "HTTP_X_REAL_IP"]
for key in keys:
if key in environ:
yield key, environ[key] | Returns our whitelisted environment variables. |
353,283 | def tilt(poly):
num = len(poly) - 1
vec = unit_normal(poly[0], poly[1], poly[num])
vec_alt = np.array([vec[0], vec[1], vec[2]])
vec_z = np.array([0, 0, 1])
return angle2vecs(vec_alt, vec_z) | Tilt of a polygon poly |
353,284 | def attach(domain, filename):
log.info(, domain)
result = actions.attach(domain, filename)
log.info(, result.success, domain) | Attach existing datasets to their harvest remote id
Mapping between identifiers should be in FILENAME CSV file. |
353,285 | def serve(request, path, document_root=None, show_indexes=False, default=):
path = posixpath.normpath(unquote(path))
path = path.lstrip()
newpath =
for part in path.split():
if not part:
continue
drive, part = os.path.splitdrive(part)
head, pa... | Serve static files below a given point in the directory structure.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root' : '/path/to/my/files/'})
in your URLconf. You must provide the ``document_root`` param. You may
also set ``show_inde... |
353,286 | def rename(self, key, newkey):
if key == newkey:
raise ValueError("key and newkey are the same")
fut = self.execute(b, key, newkey)
return wait_ok(fut) | Renames key to newkey.
:raises ValueError: if key == newkey |
353,287 | def wait_for_ready(self, timeout=None, times=None, delay=None, delay_between=None, abort=None):
if delay:
try:
sleep(delay)
except IOError:
pass
if timeout is not None:
if timeout < 0:
raise ValueError("timeou... | Determine the ready state of the device and wait until device is ready.
Parameters
----------
timeout : int, float
The maximum amount of time to wait in seconds. Reaching the timeout will raise a RuntimeError.
times : int
Maximum number of times reading the ready... |
353,288 | def setCustomField(mambuentity, customfield="", *args, **kwargs):
from . import mambuuser
from . import mambuclient
try:
customFieldValue = mambuentity[customfield]
datatype = [ l[][] for l in mambuentity[mambuentity.customFieldName] if (l[] == customfield or l[] == customfield... | Modifies the customField field for the given object with
something related to the value of the given field.
If the dataType == "USER_LINK" then instead of using the value
of the CF, it will be a MambuUser object.
Same if dataType == "CLIENT_LINK", but with a MambuClient.
Default case: just uses t... |
353,289 | def project(self, term_doc_mat, x_dim=0, y_dim=1):
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat),
x_dim, y_dim) | Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection |
353,290 | def _format_pair_no_equals(explode, separator, escape, key, value):
if not value:
return key
return _format_pair(explode, separator, escape, key, value) | Format a key, value pair but don't include the equals sign
when there is no value |
353,291 | def send_line(self, line, ending=None):
if ending is None:
ending = self.LINE_ENDING
return self.send(line + ending) | Write the string to the wire, followed by a newline. The newline string
can be changed by changing ``nc.LINE_ENDING``.
Aliases: sendline, writeline, write_line, writeln, sendln |
353,292 | def index(self):
c.pynipap_version = pynipap.__version__
try:
c.nipapd_version = pynipap.nipapd_version()
except:
c.nipapd_version =
c.nipap_db_version = pynipap.nipap_db_version()
return render() | Display NIPAP version info |
353,293 | def _sentinel_parse_scene_id(sceneid):
if not re.match("^S2[AB]_tile_[0-9]{8}_[0-9]{2}[A-Z]{3}_[0-9]$", sceneid):
raise InvalidSentinelSceneId("Could not match {}".format(sceneid))
sentinel_pattern = (
r"^S"
r"(?P<sensor>\w{1})"
r"(?P<satellite>[AB]{1})"
r"_tile_"
... | Parse Sentinel-2 scene id.
Attributes
----------
sceneid : str
Sentinel-2 sceneid.
Returns
-------
out : dict
dictionary with metadata constructed from the sceneid.
e.g:
_sentinel_parse_scene_id('S2A_tile_20170323_07SNC_0')
{
"acquisitionDay... |
353,294 | async def set_version(self, tp, params, version=None, elem=None):
self.registry.set_tr(None)
tw = TypeWrapper(tp, params)
if not tw.is_versioned():
return TypeWrapper.ELEMENTARY_RES
if not self.version_db.is_versioned(tw):
if version is None:
... | Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return: |
353,295 | def deauthorize_application(request):
if request.facebook:
user = User.objects.get(
facebook_id = request.facebook.signed_request.user.id
)
user.authorized = False
user.save()
return HttpResponse()
else:
return HttpResponse(status=400) | When a user deauthorizes an application, Facebook sends a HTTP POST request to the application's
"deauthorization callback" URL. This view picks up on requests of this sort and marks the corresponding
users as unauthorized. |
353,296 | def get_view_definition(self, connection, view_name, schema=None, **kw):
view = self._get_redshift_relation(connection, view_name, schema, **kw)
return sa.text(view.view_definition) | Return view definition.
Given a :class:`.Connection`, a string `view_name`,
and an optional string `schema`, return the view definition.
Overrides interface
:meth:`~sqlalchemy.engine.interfaces.Dialect.get_view_definition`. |
353,297 | def get_version(*file_paths):
filename = os.path.join(os.path.dirname(__file__), *file_paths)
print("Looking for version in: {}".format(filename))
version_file = open(filename).read()
version_match = re.search(r"^__version__ = [\"]*)[Unable to find version string.') | Retrieves the version from path |
353,298 | def getidfkeyswithnodes():
idf = IDF(StringIO(""))
keys = idfobjectkeys(idf)
keysfieldnames = ((key, idf.newidfobject(key.upper()).fieldnames)
for key in keys)
keysnodefdnames = ((key, (name for name in fdnames
if (name.endswith())))
... | return a list of keys of idfobjects that hve 'None Name' fields |
353,299 | def delete_cluster_custom_object(self, group, version, plural, name, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.delete_cluster_custom_object_with_http_info(group, version, plural, name, body, **kwargs)
else:
(data) = self.delete_cluster_cus... | delete_cluster_custom_object # noqa: E501
Deletes the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_cluster_custom_object(group, vers... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.