Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,400 | def define_header_values(self, http_method, route, values, update=False):
self.defined_header_values[(http_method.lower(), route)] = {
: update,
: values
} | Define header values for a given request.
By default, header values are determined from the class attribute
`headers`. But if you want to change the headers used in the
documentation for a specific route, this method lets you do that.
:param str http_method: An HTTP method, like "get".... |
340,401 | def _download_vswhere():
print(, _get_latest_release_url())
try:
from urllib.request import urlopen
with urlopen(_get_latest_release_url()) as response, open(DOWNLOAD_PATH, ) as outfile:
shutil.copyfileobj(response, outfile)
except ImportError:
import urllib... | Download vswhere to DOWNLOAD_PATH. |
340,402 | def _find_games(self, date, end_date):
if not end_date or date > end_date:
end_date = date
date_step = date
while date_step <= end_date:
url = self._create_url(date_step)
page = self._get_requested_page(url)
games = page(... | Retrieve all major games played on a given day.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that day. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the h... |
340,403 | def node_coord_in_direction(tile_id, direction):
tile_coord = tile_id_to_coord(tile_id)
for node_coord in nodes_touching_tile(tile_id):
if tile_node_offset_to_direction(node_coord - tile_coord) == direction:
return node_coord
raise ValueError(.format(
direction,
tile... | Returns the node coordinate in the given direction at the given tile identifier.
:param tile_id: tile identifier, int
:param direction: direction, str
:return: node coord, int |
340,404 | def get_unit_name(unit_id):
attribute =
response = LDAP_search(
pattern_search=.format(unit_id),
attribute=attribute
)
try:
unit_name = get_attribute(response, attribute)
except Exception:
raise EpflLdapException("The unit with id was not found".format(unit_id)... | Return the unit name to the unit 'unit_id' |
340,405 | def infer(pattern, base_path=None):
package = Package({}, base_path=base_path)
descriptor = package.infer(pattern)
return descriptor | https://github.com/frictionlessdata/datapackage-py#infer |
340,406 | def to_str(self, expandattrs=True, expandvals=True):
out = io.BytesIO()
node_display(self, expandattrs, expandvals, out)
return decode(out.getvalue()) | Convert the node into a string, intended for testing/debugging purposes
:param expandattrs:
print the values of the attributes if True, else print only the names
:param expandvals:
print the values if True, else print only the tag names |
340,407 | def _add_route(self, method, path, middleware=None):
if middleware is not None:
self.add(method, path, middleware)
return self
else:
return lambda func: (
self.add(method, path, func),
func
)[1] | The implementation of adding a route |
340,408 | def send_message(
self, request: str, response_expected: bool, **kwargs: Any
) -> Response:
response = self.session.post(self.endpoint, data=request.encode(), **kwargs)
return Response(response.text, raw=response) | Transport the message to the server and return the response.
Args:
request: The JSON-RPC request string.
response_expected: Whether the request expects a response.
Returns:
A Response object. |
340,409 | def get_monitor_physical_size(monitor):
width_value = ctypes.c_int(0)
width = ctypes.pointer(width_value)
height_value = ctypes.c_int(0)
height = ctypes.pointer(height_value)
_glfw.glfwGetMonitorPhysicalSize(monitor, width, height)
return width_value.value, height_value.value | Returns the physical size of the monitor.
Wrapper for:
void glfwGetMonitorPhysicalSize(GLFWmonitor* monitor, int* width, int* height); |
340,410 | def ask(self, answers=None):
if answers is None:
answers = {}
_answers = {}
if self.multiple:
print((bold( +
)))
_answers[self.value] = []
answer = self._ask(answers)
while answer is not None:
... | Ask the question, then ask any sub-questions.
This returns a dict with the {value: answer} pairs for the current
question plus all descendant questions. |
340,411 | def step_processing(self, warning=True):
if not self.__is_processing:
warning and LOGGER.warning(
"!> {0} | Engine is not processing, request has been ignored!".format(
self.__class__.__name__))
return False
LOGGER.debug("> Stepping... | Steps the processing operation progress indicator.
:param warning: Emit warning message.
:type warning: int
:return: Method success.
:rtype: bool |
340,412 | def check_installed_files(self):
mismatches = []
record_path = os.path.join(self.path, )
if os.path.exists(record_path):
for path, _, _ in self.list_installed_files():
if path == record_path:
continue
if not os.path.exists(... | Checks that the hashes and sizes of the files in ``RECORD`` are
matched by the files themselves. Returns a (possibly empty) list of
mismatches. Each entry in the mismatch list will be a tuple consisting
of the path, 'exists', 'size' or 'hash' according to what didn't match
(existence is ... |
340,413 | def doublec(self, j):
if j < 1 or self.b[j] != self.b[j-1]:
return False
return self.cons(j) | True iff j, j-1 contains double consonant |
340,414 | def filter_to_dmql(filter_dict):
if not isinstance(filter_dict, (dict, collections.OrderedDict)):
raise TypeError(.format(type(filter_dict)))
def is_date_time_type(val):
return isinstance(val, (datetime.datetime, datetime.date, datetime.time))
def... | Converts the filter dictionary into DMQL |
340,415 | def columnConfidences(self, cellConfidences=None):
if cellConfidences is None:
cellConfidences = self.confidence[]
colConfidences = cellConfidences.sum(axis=1)
return colConfidences | Compute the column confidences given the cell confidences. If
None is passed in for cellConfidences, it uses the stored cell confidences
from the last compute.
Parameters:
----------------------------
cellConfidencs : cell confidences to use, or None to use the
the cu... |
340,416 | def delete_custom_service_account(self, account, nickname, password):
return self.post(
url="https://api.weixin.qq.com/customservice/kfaccount/del",
data={
"kf_account": account,
"nickname": nickname,
"password": password
... | 删除客服帐号。
:param account: 客服账号的用户名
:param nickname: 客服账号的昵称
:param password: 客服账号的密码
:return: 返回的 JSON 数据包 |
340,417 | def get_30_date():
now = datetime.datetime.now()
end_date = now.date()
start_date = end_date - datetime.timedelta(days=30)
return start_date.strftime("%Y%m%d"), end_date.strftime("%Y%m%d") | 获得用于查询的默认日期, 今天的日期, 以及30天前的日期
用于查询的日期格式通常为 20160211
:return: |
340,418 | def remove_pool(self, auth, spec):
self._logger.debug("remove_pool called; spec: %s" % unicode(spec))
pools = self.list_pool(auth, spec)
where, params = self._expand_pool_spec(spec)
sql = "DELETE FROM ip_net_pool AS po WHERE %s" % where
self._execute(sql, par... | Remove a pool.
* `auth` [BaseAuth]
AAA options.
* `spec` [pool_spec]
Specifies what pool(s) to remove.
This is the documentation of the internal backend function. It's
exposed over XML-RPC, please also see the XML-RPC documentation for
... |
340,419 | def _set_hw_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=hw_state.hw_state, is_container=, presence=False, yang_name="hw-state", rest_name="hw-state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=Tru... | Setter method for hw_state, mapped from YANG variable /hw_state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_hw_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_hw_state() directly.
... |
340,420 | def get_families(data_dir=None):
data_dir = fix_data_dir(data_dir)
metadata = get_metadata(data_dir)
families = set()
for v in metadata.values():
families.add(v[])
return sorted(list(families)) | Return a list of all basis set families |
340,421 | def setup_for_bottle(
auth, app, send_email=None, render=None,
session=None, request=None, urloptions=None):
import bottle
auth.request = request or bottle.request
if session is not None:
auth.session = session
if send_email:
auth.send_email = send_email
auth.render... | Set the session **before** calling ``setup_for_bottle`` like this:
@hook('before_request')
def setup_request():
request.session = request.environ['beaker.session'] |
340,422 | def _create_counter_column_family(self, family, counter_columns=[],
key_validation_class=UTF8Type):
familyinbound
sm = SystemManager(random.choice(self.server_list))
sm.create_column_family(self.namespace, family, super=False,
key_validation... | Creates a column family of the name 'family' and sets any of
the names in the bytes_column list to have the BYTES_TYPE.
key_validation_class defaults to TIME_UUID_TYPE and could also
be ASCII_TYPE for md5 hash keys, like we use for 'inbound' |
340,423 | def set_domain_id(self, value=None, default=False, disable=False):
return self._configure_mlag(, value, default, disable) | Configures the mlag domain-id value
Args:
value (str): The value to configure the domain-id
default (bool): Configures the domain-id using the default keyword
disable (bool): Negates the domain-id using the no keyword
Returns:
bool: Returns True if the c... |
340,424 | def create(self, email, password, role="user", public=True, **kwargs):
kwargs["email"] = email
kwargs["password"] = password
kwargs["role"] = role
kwargs["public"] = public
self.metadata = self.db.create(
self.path, kwargs).json() | Creates the given user - using the passed in email and password.
You can also set other default properties by passing in the relevant information::
usr.create("my@email","mypass",description="I like trains.")
Furthermore, ConnectorDB permits immediate initialization of an entire user tree... |
340,425 | def relax_AX(self):
self.AXnr = self.cnst_A(self.X, self.Xf)
if self.rlx == 1.0:
self.AX = self.AXnr
else:
if not hasattr(self, ):
self._cnst_c = self.cnst_c()
alph... | Implement relaxation if option ``RelaxParam`` != 1.0. |
340,426 | def setState(self, state):
self._positionIdx = self.choices.index(state[])
self._bestPositionIdx = self.choices.index(state[])
self._bestResult = state[] | See comments in base class. |
340,427 | def _reinit_daq_daemons(sender, instance, **kwargs):
if type(instance) is ModbusDevice:
post_save.send_robust(sender=Device, instance=instance.modbus_device)
elif type(instance) is ModbusVariable:
post_save.send_robust(sender=Variable, instance=instance.modbus_variable)
elif type(instan... | update the daq daemon configuration when changes be applied in the models |
340,428 | def norm_squared(x, Mx=None, inner_product=ip_euclid):
assert(len(x.shape) == 2)
if Mx is None:
rho = inner_product(x, x)
else:
assert(len(Mx.shape) == 2)
rho = inner_product(x, Mx)
if rho.shape == (1, 1):
if abs(rho[0, 0].imag) > abs(rho[0, 0])*1e-10 or rho[0, 0].r... | Compute the norm^2 w.r.t. to a given scalar product. |
340,429 | def _get_included_file_path(self, user_specified_path: str, current_processed_file_path: Path) -> Path:
self.logger.debug(f)
included_file_path = (current_processed_file_path.parent / user_specified_path).resolve()
self.logger.debug(f)
if (
self.working_dir.resol... | Resolve user specified path to the local included file.
:param user_specified_path: User specified string that represents
the path to a local file
:param current_processed_file_path: Path to the currently processed Markdown file
that contains include statements
:return... |
340,430 | def set_spot_instance_settings(self, maximum_bid_price_percentage=None,
timeout_for_request=None,
maximum_spot_instance_percentage=None):
self.hadoop_settings[] = {
: maximum_bid_price_percentage,
: time... | Purchase options for spot instances. Valid only when
`slave_request_type` is hybrid or spot.
`maximum_bid_price_percentage`: Maximum value to bid for spot
instances, expressed as a percentage of the base price for the
slave node instance type.
`timeout_for_request`: Tim... |
340,431 | def _get_node_type(self):
if self.parent is None:
return self.NODE_ROOT
elif self.parent.node_type == self.NODE_ROOT:
return self.NODE_CONTROLLER_ROOT
elif b".slice" in self.name or b in self.name:
return self.NODE_SLICE
elif b".scope" in sel... | Returns the current node's type |
340,432 | def create_cluster(settings):
settings = copy.deepcopy(settings)
backend = settings.pop(, settings.pop(, None))
if isinstance(backend, basestring):
Conn = import_string(backend)
elif backend:
Conn = backend
else:
raise KeyError()
cluster = settings.pop(, N... | Creates a new Nydus cluster from the given settings.
:param settings: Dictionary of the cluster settings.
:returns: Configured instance of ``nydus.db.base.Cluster``.
>>> redis = create_cluster({
>>> 'backend': 'nydus.db.backends.redis.Redis',
>>> 'router': 'nydus.db.routers.redis.Partition... |
340,433 | def maybedotted(name):
if not name:
raise LookupError(
% name)
if not hasattr(name, ):
try:
mod = importlib.import_module(name)
except ImportError:
attr = None
if in name:
names = name.split()
attr = n... | Resolve dotted names:
.. code-block:: python
>>> maybedotted('irc3.config')
<module 'irc3.config' from '...'>
>>> maybedotted('irc3.utils.IrcString')
<class 'irc3.utils.IrcString'>
.. |
340,434 | def get_model_url_base():
url_base = get_model_url_base_from_env()
if url_base is not None:
logger.info(.format(url_base))
else:
url_base =
return url_base | Returns a root folder for models. |
340,435 | def create_blueprint(register_default_routes=True):
blueprint = Blueprint(
,
__name__,
template_folder=,
static_folder=,
)
if register_default_routes:
blueprint.add_url_rule(, view_func=set_lang, methods=[])
blueprint.add_url_rule(, view_func=set_lang,
... | Create Invenio-I18N blueprint. |
340,436 | def new(self):
if self._initialized:
raise pycdlibexception.PyCdlibInternalError()
tm = time.time()
local = time.localtime(tm)
self.years_since_1900 = local.tm_year - 1900
self.month = local.tm_mon
self.day_of_month = local.tm_mday
... | Create a new Directory Record date based on the current time.
Parameters:
tm - An optional argument that must be None
Returns:
Nothing. |
340,437 | def construct(self, data):
occurrences = {}
main_occurrences = {}
for pkg in data["data"]["dependencies"]:
package = pkg["package"]
for item in pkg["dependencies"]:
dep = item["name"]
if package != ".":
deps = map(lambda l: "%s/%s" % (package, l), item["location"])
else:
deps = ... | Construct info about a project from artefact
:param data: golang-project-packages artefact
:type data: json/dict |
340,438 | def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
... | Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
... |
340,439 | def register_states_of_state_machine(self, state_machine):
root = state_machine.root_state
root.add_observer(self, "state_execution_status",
notify_after_function=self.on_state_execution_status_changed_after)
self.recursively_register_child_states(root) | This functions registers all states of state machine.
:param state_machine: the state machine to register all states of
:return: |
340,440 | def create_file_node(self, doc_file):
file_node = URIRef(.format(
id=str(doc_file.spdx_id)))
type_triple = (file_node, RDF.type, self.spdx_namespace.File)
self.graph.add(type_triple)
name_triple = (file_node, self.spdx_namespace.fileName, Literal(doc_file.name))
... | Create a node for spdx.file. |
340,441 | def users(self):
existing_users = self.existing_users()
existing_user_ids = [x[] for x in existing_users]
sharing = getMultiAdapter((self.my_workspace(), self.request),
name=)
search_results = sharing.user_search_results()
user... | Get current users and add in any search results.
:returns: a list of dicts with keys
- id
- title
:rtype: list |
340,442 | def partial_fit(self, sequence, y=None):
s = super(MultiSequencePreprocessingMixin, self)
if hasattr(s, ):
return s.fit(sequence)
return self | Fit Preprocessing to X.
Parameters
----------
sequence : array-like, [sequence_length, n_features]
A multivariate timeseries.
y : None
Ignored
Returns
-------
self |
340,443 | def sine_wave(i, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE):
omega = 2.0 * pi * float(frequency)
sine = sin(omega * (float(i) / float(framerate)))
return float(amplitude) * sine | Returns value of a sine wave at a given frequency and framerate
for a given sample i |
340,444 | def set_scope(self, include=None, exclude=None):
context = {}
if exclude:
context["exclude"] = [[selector] for selector in exclude]
if include:
context["include"] = [[selector] for selector in include]
self.context = json.dumps(context) if context else... | Sets `scope` (refered to as `context` in ruleset documentation), which
defines the elements on a page to include or exclude in the audit. If
neither `include` nor `exclude` are passed, the entire document will
be included.
Args:
include (optional): a list of css selectors f... |
340,445 | def extract_references_from_string(source,
is_only_references=True,
recid=None,
reference_format="{title} {volume} ({year}) {page}",
linker_callback=None,
... | Extract references from a raw string.
The first parameter is the path to the file.
It returns a tuple (references, stats).
If the string does not only contain references, improve accuracy by
specifing ``is_only_references=False``.
The standard reference format is: {title} {volume} ({year}) {page}... |
340,446 | def operator_cross(self, graph, solution, op_diff_round_digits):
dm = graph._matrix
dn = graph._nodes | applies Cross inter-route operator to solution
Takes every node from every route and calculates savings when inserted
into all possible positions in other routes. Insertion is done at
position with max. saving and procedure starts over again with newly
created graph as input. Stops when... |
340,447 | def get_external_ip():
response = requests.get()
if not response.ok:
raise RuntimeError( % response.content)
return response.content.strip() | Returns the current external IP, based on http://icanhazip.com/. It will
probably fail if the network setup is too complicated or the service is
down. |
340,448 | def mlstreporter(self):
logging.info()
header_row = str()
combinedrow = str()
combined_header_row = str()
reportdirset = set()
mlst_dict = dict()
for sample in self.runmetadata.samples:
if sample.general.bestassembly... | Parse the results into a report |
340,449 | def serialize(self):
commands = []
for cmd in self.commands:
commands.append(cmd.serialize())
out = {: commands, : self.__device_url}
return out | Serialize action. |
340,450 | def get_unique_name(self, obj, name=, name_from_system=):
ns = self.namespace
newname = name
if not newname:
newname = name_from_system
if not newname:
newname = u"Nameless_" + obj.__class__.__name__
if not newname in ns:
return newn... | Give unique name for an Sensor/Program/Actuator object |
340,451 | def IterateAllClientsFullInfo(self, min_last_ping=None, batch_size=50000):
all_client_ids = self.ReadAllClientIDs(min_last_ping=min_last_ping)
for batch in collection.Batch(all_client_ids, batch_size):
res = self.MultiReadClientFullInfo(batch)
for full_info in itervalues(res):
yield fu... | Iterates over all available clients and yields full info protobufs.
Args:
min_last_ping: If not None, only the clients with last-ping timestamps
newer than (or equal to) min_last_ping will be returned.
batch_size: Always reads <batch_size> client full infos at a time.
Yields:
An rdfv... |
340,452 | def ParsePythonFlags(self, start_line=0):
modname = None
modlist = []
flag = None
for line_num in range(start_line, len(self.output)):
line = self.output[line_num].rstrip()
if not line:
continue
mobj = self.module_py_re.match(l... | Parse python/swig style flags. |
340,453 | def cut_tree(igraph, caps = None):
graph = digraph()
graph.add_graph(igraph)
if not caps:
caps = {}
for edge in graph.edges():
caps[edge] = igraph.edge_weight(edge)
f = {}
n = {}
N = 0
for node in graph.nodes():
n[N] = nod... | Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield.
@type igraph: graph
@param igraph: Graph
@type caps: dictionary
@param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge
will be used as its capacity. Otherwise, for each edge (a,... |
340,454 | def _detect_msgmerge(env):
if in env:
return env[]
msgmerge = env.Detect();
if msgmerge:
return msgmerge
raise SCons.Errors.StopError(MsgmergeNotFound, "Could not detect msgmerge")
return None | Detects *msgmerge(1)* program. |
340,455 | def update(self,records,**kw):
kw = dict([(k,v) for (k,v) in kw.iteritems() if k in self.fields])
if isinstance(records,dict):
records = [ records ]
for indx in set(self.indices.keys()) & set (kw.keys()):
for record in records:
... | Update one record of a list of records
with new keys and values and update indices |
340,456 | def blockgen1d(block, size):
def numblock(blk, x):
a, b = x
if b - a <= blk:
return [x]
else:
result = []
d = int(b - a) // 2
for i in imap(numblock, [blk, blk], [(a, a + d), (a + d, b)]):
result.extend(i)
... | Compute 1d block intervals to be used by combine.
blockgen1d computes the slices by recursively halving the initial
interval (0, size) by 2 until its size is lesser or equal than block
:param block: an integer maximum block size
:param size: original size of the interval, it corresponds to a 0:size sl... |
340,457 | def _add_tc_script(self):
context = dict(tc_options=self.config.get(, []))
contents = self._render_template(, context)
self.config.setdefault(, [])
self._add_unique_file({
"path": "/tc_script.sh",
"contents": contents,
... | generates tc_script.sh and adds it to included files |
340,458 | def vfunc(pars_1, pars_2):
cart_1 = dir2cart([pars_1["dec"], pars_1["inc"], pars_1["r"]])
cart_2 = dir2cart([pars_2[], pars_2[], pars_2["r"]])
Sw = pars_1[] * pars_1[] + pars_2[] * pars_2[]
xhat_1 = pars_1[] * cart_1[0] + pars_2[] * cart_2[0]
xhat_2 = pars_1[] * cart_1[1] + pars_2[] * cart_... | Calculate the Watson Vw test statistic. Calculated as 2*(Sw-Rw)
Parameters
----------
pars_1 : dictionary of Fisher statistics from population 1
pars_2 : dictionary of Fisher statistics from population 2
Returns
-------
Vw : Watson's Vw statistic |
340,459 | def edit_required_status_checks(self, strict=github.GithubObject.NotSet, contexts=github.GithubObject.NotSet):
assert strict is github.GithubObject.NotSet or isinstance(strict, bool), strict
assert contexts is github.GithubObject.NotSet or all(isinstance(element, (str, unicode)) or isinstance(e... | :calls: `PATCH /repos/:owner/:repo/branches/:branch/protection/required_status_checks <https://developer.github.com/v3/repos/branches>`_
:strict: bool
:contexts: list of strings |
340,460 | def __deserialize(self, data, klass):
if data is None:
return None
if type(klass) == str:
from tradenity.resources.paging import Page
if klass.startswith():
sub_kls = re.match(, klass).group(1)
return Page([self.__deserialize(... | Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object. |
340,461 | def get_version(self):
ptr = self._get_version_func(self.alpr_pointer)
version_number = ctypes.cast(ptr, ctypes.c_char_p).value
version_number = _convert_from_charp(version_number)
self._free_json_mem_func(ctypes.c_void_p(ptr))
return version_number | This gets the version of OpenALPR
:return: Version information |
340,462 | def help_text(self, name, text, text_kind=, trim_pfx=0):
if trim_pfx > 0:
text = toolbox.trim_prefix(text, trim_pfx)
if text_kind == :
try:
overrides = {: ,
: }
text_htm... | Provide help text for the user.
This method will convert the text as necessary with docutils and
display it in the WBrowser plugin, if available. If the plugin is
not available and the text is type 'rst' then the text will be
displayed in a plain text widget.
Parameters
... |
340,463 | def creation_time(self):
logs = self._query_logs()
time_string = logs[-1].find(, class_=).time[
]
return datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S") | :return: 问题创建时间
:rtype: datetime.datetime |
340,464 | def delete_selection(self):
selection = self.selection
if selection is None:
return
if isinstance(selection, ArrowWidget):
self.mainscreen.boardview.board.rm_arrow(
selection.origin.name,
selection.destination.name
)
... | Delete both the selected widget and whatever it represents. |
340,465 | def generateLatticeLine(self, latname=, line=None):
latticeline = []
for e in line:
if isinstance(e, list):
latticeline.extend(e)
else:
latticeline.append(e)
newblele = {latname.upper(): {: {: + .join(latticeline) + }}}
s... | construct a new lattice line
:param latname: name for generated new lattice |
340,466 | async def join(self, channel, password=None):
if self.in_channel(channel):
raise AlreadyInChannel(channel)
if password:
await self.rawmsg(, channel, password)
else:
await self.rawmsg(, channel) | Join channel, optionally with password. |
340,467 | def point_normals(self):
mesh = self.compute_normals(cell_normals=False, inplace=False)
return mesh.point_arrays[] | Point normals |
340,468 | def reporter(self):
logging.info(.format(self.analysistype))
make_path(self.reportpath)
header =
data =
with open(os.path.join(self.reportpath, .format(self.analysistype)), ) as report:
for sample in self.runmetadata.samples:
if sam... | Creates a report of the results |
340,469 | def authenticate(self, *args, **kwargs):
if not self.flags & BFD_FLAG_AUTH_PRESENT or \
not issubclass(self.auth_cls.__class__, BFDAuth):
return False
return self.auth_cls.authenticate(self, *args, **kwargs) | Authenticate this packet.
Returns a boolean indicates whether the packet can be authenticated
or not.
Returns ``False`` if the Authentication Present (A) is not set in the
flag of this packet.
Returns ``False`` if the Authentication Section for this packet is not
prese... |
340,470 | def _reset_internal(self):
self._load_model()
self.mjpy_model = self.model.get_model(mode="mujoco_py")
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
if self.has_renderer and self.viewer is None:
self.viewer = Muj... | Resets simulation internal configurations. |
340,471 | def synch(self, asset_manager_id, **params):
self.logger.info()
url = % (self.endpoint, asset_manager_id)
response = self.session.put(url, params=params)
if response.ok:
count = response.json().get(, 0)
self.logger.info(, count)
return count... | This method invokes a request to synch the assets in
dynamodb and/or elastic search with the SQL assets.
Args:
asset_manager_id (int): The id of the asset manager that owns the assets to be synched
cache (bool): Whether to synch the assets in DynamoDB
search (bool): ... |
340,472 | def run_build(self, config, bucket, names):
project = self._get_project()
bot.custom(, project, "CYAN")
bot.custom(, config[][0][], "CYAN")
response = self._build_service.projects().builds().create(body=config,
projectId=project).execute()
... | run a build, meaning creating a build. Retry if there is failure |
340,473 | def schedule_telegram_message(message, to, sender=None, priority=None):
schedule_messages(message, recipients(, to), sender=sender, priority=priority) | Schedules Telegram message for delivery.
:param str message: text to send.
:param list|str|unicode to: recipients addresses or Django User model heir instances with `telegram` attributes.
:param User sender: User model heir instance
:param int priority: number describing message priority. If set overri... |
340,474 | def to_string(self):
suffix = % (self.type, self.name)
if self.initial_value:
suffix += + self.initial_value
return suffix | Return a string that tries to reconstitute the variable decl. |
340,475 | def register(self, scope, *args, **kwargs):
self._assert_not_frozen()
self.get_parser(scope).register(*args, **kwargs)
deprecated_scope = self.known_scope_to_info[scope].deprecated_scope
if deprecated_scope:
self.get_parser(deprecated_scope).register(*args, **kwargs) | Register an option in the given scope. |
340,476 | def assignrepr(self, prefix):
caller =
blanks = * (len(prefix) + len(caller))
prefix = f
lines = [f]
if self.sim != self.init:
lines.append(f)
lines[-1] = lines[-1][:-1] +
return .join(lines) | Return a |repr| string with a prefixed assignment. |
340,477 | def _match_stmt(ctx, stmt, specs, canonical):
(spec, canspec) = specs
i = 0
while i < len(spec):
(keywd, occurance) = spec[i]
if keywd == :
return (spec, canspec)
if keywd == :
(keywd, occurance) = occurance
if (stmt.i_module.i_version == and... | Match stmt against the spec.
Return None | spec'
spec' is an updated spec with the matching spec consumed |
340,478 | def _iter_tokens(self):
reobj, actions, nextstates = self._rules[self.states[-1]]
mobj = reobj.match(self.string, self.pos)
while mobj is not None:
text = mobj.group(0)
idx = mobj.lastindex - 1
nextstate = nextstates[idx]
act... | Iterate through all tokens in the input string. |
340,479 | def parse(self):
start = time.time()
if self.cache:
self.load_cache()
if not self.cache_loaded:
super(ObjParser, self).parse()
logger.info("%s: Load time: %s", self.file_name, time.time() - start) | Trigger cache load or call superclass parse() |
340,480 | def get_timeseries(self, *args, **kwargs):
import predix.data.timeseries
ts = predix.data.timeseries.TimeSeries(*args, **kwargs)
return ts | Returns an instance of the Time Series Service. |
340,481 | def send(self, tids, session, **kwargs):
request = TOPRequest()
request[] = tids
for k, v in kwargs.iteritems():
if k not in (, , , , , , , , , ) and v==None: continue
request[k] = v
self.create(self.execute(request, session))
return self.task | taobao.topats.delivery.send 异步批量物流发货api
使用指南:http://open.taobao.com/dev/index.php/ATS%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97
- 1.提供异步批量物流发货功能
- 2.一次最多发货40个订单
- 3.提交任务会进行初步任务校验,如果成功会返回任务号和创建时间,如果失败就报错
- 4.可以接收淘宝发出的任务完成消息,也可以过一段时间来取结果。获取结果接口为taobao.topats.result.... |
340,482 | def fix_spelling(self, words, join=True, joinstring=):
fixed_words = []
for word in self.spellcheck(words, suggestions=True):
if word[]:
fixed_words.append(word[])
else:
suggestions = word[]
if len(suggestions) > 0:
... | Simple function for quickly correcting misspelled words.
Parameters
----------
words: list of str or str
Either a list of pretokenized words or a string. In case of a string, it will be splitted using
default behaviour of string.split() function.
join: boolean (d... |
340,483 | def _parse_scale(scale_exp):
m = re.search("(\w+?)\{(.*?)\}", scale_exp)
if m is None:
raise InvalidFormat()
scale = m.group(1)
range = m.group(2)
if scale not in SCALES:
raise InvalidFormat( % scale)
ranges = re.split("\s", range)
return scale, ranges | Parses a scale expression and returns the scale, and a list of ranges. |
340,484 | def upgrader(version=None):
def decorator(func):
func.__vers_upgrader__ = version
return func
if version is None:
return decorator
elif isinstance(version, six.integer_types):
if version < 1:
raise TypeError("In... | A decorator for marking a method as an upgrader from an older
version of a given object. Can be used in two different ways:
``@upgrader``
In this usage, the decorated method updates from the previous
schema version to this schema version.
``@upgrader(number)``
In this usage, the d... |
340,485 | def read_iso19115_metadata(layer_uri, keyword=None, version_35=False):
xml_uri = os.path.splitext(layer_uri)[0] +
file_prefix =
if xml_uri.startswith(file_prefix):
xml_uri = xml_uri[len(file_prefix):]
if not os.path.exists(xml_uri):
xml_uri = None
if not xml_uri and os.pa... | Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword: basestring
:returns: Dictionary of keywords or value of key as string.
... |
340,486 | def configure(log_file):
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
stderr_handler = logging.StreamHandler()
stderr_handler.setLevel(logging.INFO)
stderr_handler.setFormatter(logging.Formatter(, style=))
root_logger.addHandler(stderr_handler)
... | Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
log_file : ~pathlib.Path
File to log to.
Returns
... |
340,487 | def load_lynx(as_series=False):
rslt = np.array([269, 321, 585, 871, 1475, 2821, 3928, 5943, 4950,
2577, 523, 98, 184, 279, 409, 2285, 2685, 3409,
1824, 409, 151, 45, 68, 213, 546, 1033, 2129,
2536, 957, 361, 377, 225, 360, 731, 1638, 2725,
... | Annual numbers of lynx trappings for 1821–1934 in Canada.
This time-series records the number of skins of predators (lynx) that were
collected over several years by the Hudson's Bay Company. The dataset was
taken from Brockwell & Davis (1991) and appears to be the series
considered by Campbell & Walker... |
340,488 | def _create_for_element(cls, element_obj, conn, namespace, classname,
propname=None, methodname=None, parametername=None):
vm = ValueMapping()
vm._element_obj = element_obj
vm._conn = conn
vm._namespace = namespace
... | Return a new :class:`~pywbem.ValueMapping` instance for the specified
CIM element.
If a `Values` qualifier is defined but no `ValueMap` qualifier, a
default of 0-based consecutive numbers is applied (that is the default
defined in :term:`DSP0004`).
Parameters:
elemen... |
340,489 | def restart(self, key):
if key in self.queue:
if self.queue[key][] in [, ]:
new_entry = {: self.queue[key][],
: self.queue[key][]}
self.add_new(new_entry)
self.write()
return True
return Fal... | Restart a previously finished entry. |
340,490 | def write(self, writer, sheet_name=, startrow=0,
startcol=0, freeze_panes=None, engine=None):
from pandas.io.excel import ExcelWriter
from pandas.io.common import _stringify_path
if isinstance(writer, ExcelWriter):
need_save = False
else:
w... | writer : string or ExcelWriter object
File path or existing ExcelWriter
sheet_name : string, default 'Sheet1'
Name of sheet which will contain DataFrame
startrow :
upper left cell row to dump data frame
startcol :
upper left cell column to dump dat... |
340,491 | def _validate(self, val):
if callable(val):
return val
if self.allow_None and val is None:
return
if not _is_number(val):
raise ValueError("Parameter only takes numeric values"%(self.name))
if self.step is not None and not _is_number(self.... | Checks that the value is numeric and that it is within the hard
bounds; if not, an exception is raised. |
340,492 | def open(self, mode=, encoding=None):
access_type = self._get_access_type(mode)
if access_type == and encoding is not None and encoding != self.encoded_with:
warnings.warn(
% (self, encoding, self.encoded_with))
if encoding is None:
e... | Return file-like object
Args:
mode (str): access mode (only reading modes are supported)
encoding (str): text decoding method for text access (default: system default)
Returns:
io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters |
340,493 | def add_sc_attitude_vectors(inst):
import pysatMagVect
inst[], inst[], inst[] = \
pysatMagVect.normalize_vector(inst[], inst[], inst[])
inst[], inst[], inst[] = \
pysatMagVect.normalize_vector(-inst[], -inst[], -inst[])
ins... | Add attitude vectors for spacecraft assuming ram pointing.
Presumes spacecraft is pointed along the velocity vector (x), z is
generally nadir pointing (positive towards Earth), and y completes the
right handed system (generally southward).
Notes
-----
Expects velocity and positi... |
340,494 | def save(self, filename):
f = open(filename, mode=)
for p in self.points:
f.write("%f\t%f\n" % (p.lat, p.lng))
f.close() | save fence points to a file |
340,495 | def clean(self):
for prop in (, , , , ):
try:
delattr(self, prop)
except AttributeError:
pass
for prop in (, ):
try:
if getattr(self, prop, None) is not None and not getattr(self, prop):
dela... | Clean properties only needed for initialization and configuration
:return: None |
340,496 | def decode_entities(html):
def decode(m):
html = m.group(0)
if html[:2] == "&
try:
if html[:3] == "&
return chr(int(html[3:-1], 16))
else:
return chr(int(html[2:-1]))
except ValueError:
... | Remove HTML entities from a string.
Adapted from http://effbot.org/zone/re-sub.htm#unescape-html |
340,497 | def p_return(p):
if not FUNCTION_LEVEL:
p[0] = make_sentence()
return
if FUNCTION_LEVEL[-1].kind != KIND.sub:
syntax_error(p.lineno(1), )
p[0] = None
return
p[0] = make_sentence(, FUNCTION_LEVEL[-1]) | statement : RETURN |
340,498 | def unique_otuids(groups):
uniques = {key: set() for key in groups}
for i, group in enumerate(groups):
to_combine = groups.values()[:i]+groups.values()[i+1:]
combined = combine_sets(*to_combine)
uniques[group] = groups[group].difference(combined)
return uniques | Get unique OTUIDs of each category.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on category name and unique OTUIDs as values. |
340,499 | def list_user_messages_view(request, targetUsername):
targetUser = get_object_or_404(User, username=targetUsername)
targetProfile = get_object_or_404(UserProfile, user=targetUser)
user_messages = Message.objects.filter(owner=targetProfile)
thread_pks = list(set([i.thread.pk for i in user_messages])... | View of threads a user has posted in. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.