code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def add(self, num, price, aType, stuff_status, title, desc, location_state, location_city, cid, session, **kwargs):
'''taobao.item.add 添加一个商品
此接口用于新增一个商品 商品所属的卖家是当前会话的用户 商品的属性和sku的属性有包含的关系,商品的价格要位于sku的价格区间之中(例如,sku价格有5元、10元两种,那么商品的价格就需要大于等于5元,小于等于10元,否则新增商品会失败) 商品的类目和商品的价格、sku的价格都有一定的相关性(具体的关系要... | taobao.item.add 添加一个商品
此接口用于新增一个商品 商品所属的卖家是当前会话的用户 商品的属性和sku的属性有包含的关系,商品的价格要位于sku的价格区间之中(例如,sku价格有5元、10元两种,那么商品的价格就需要大于等于5元,小于等于10元,否则新增商品会失败) 商品的类目和商品的价格、sku的价格都有一定的相关性(具体的关系要通过类目属性查询接口获得) 商品的运费承担方式和邮费设置有相关性,卖家承担运费不用设置邮费,买家承担运费需要设置邮费 当关键属性值选择了“其他”的时候,需要输入input_pids和input_str商品才能添加成功。 |
def ReplaceAttachment(self, attachment_link, attachment, options=None):
"""Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:r... | Replaces an attachment and returns it.
:param str attachment_link:
The link to the attachment.
:param dict attachment:
:param dict options:
The request options for the request.
:return:
The replaced Attachment
:rtype:
dict |
def acknowledge_problem(self, notification_period, hosts, services, sticky, notify, author,
comment, end_time=0):
# pylint: disable=too-many-arguments
"""
Add an acknowledge
:param sticky: acknowledge will be always present is host return in UP state
... | Add an acknowledge
:param sticky: acknowledge will be always present is host return in UP state
:type sticky: integer
:param notify: if to 1, send a notification
:type notify: integer
:param author: name of the author or the acknowledge
:type author: str
:param c... |
def set_wallpaper(image):
'''Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper.
'''
desktop_env = system.get_name()
if desktop_env in ['gnome', 'unity', 'cinnamon', 'pantheon', 'mate']:
uri = 'file://%s' % image
SCHEMA = ... | Set the desktop wallpaper.
Sets the desktop wallpaper to an image.
Args:
image (str): The path to the image to be set as wallpaper. |
def on_deleted(self, event):
"""On deleted method"""
for delegate in self.delegates:
if hasattr(delegate, "on_deleted"):
delegate.on_deleted(event) | On deleted method |
def find_file(config_file=None, default_directories=None, default_bases=None):
'''Search for a config file in a list of files.'''
if config_file:
if path.exists(path.expanduser(config_file)):
return config_file
else:
raise FileNotFoundError('Config file not found: {}'.fo... | Search for a config file in a list of files. |
def _getSectionForDataDirectoryEntry(self, data_directory_entry, sections):
"""Returns the section which contains the data of DataDirectory"""
for section in sections:
if data_directory_entry.VirtualAddress >= section.header.VirtualAddress and \
data_directory_entry.VirtualAddres... | Returns the section which contains the data of DataDirectory |
def read_geo(fid, key):
"""Read geolocation and related datasets."""
dsid = GEO_NAMES[key.name]
add_epoch = False
if "time" in key.name:
days = fid["/L1C/" + dsid["day"]].value
msecs = fid["/L1C/" + dsid["msec"]].value
data = _form_datetimes(days, msecs)
add_epoch = True
... | Read geolocation and related datasets. |
def build_permuted_index(self):
"""
Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
... | Build PermutedIndex for all your binary hashings.
PermutedIndex would be used to find the neighbour bucket key
in terms of Hamming distance. Permute_configs is nested dict
in the following format:
permuted_config = {"<hash_name>":
{ "num_permutation":50,
... |
def method(self) -> str:
"""
获取请求方法
"""
if self._method is None:
self._method = decode_bytes(self._parser.get_method())
return self._method | 获取请求方法 |
def register_dde_task(self, *args, **kwargs):
"""Register a Dde task."""
kwargs["task_class"] = DdeTask
return self.register_task(*args, **kwargs) | Register a Dde task. |
def pad_to_multiple(obj, factor):
"""
Return a copy of the object with its piano-roll padded with zeros at the
end along the time axis with the minimal length that make the length of
the resulting piano-roll a multiple of `factor`.
Parameters
----------
factor : int
The value which ... | Return a copy of the object with its piano-roll padded with zeros at the
end along the time axis with the minimal length that make the length of
the resulting piano-roll a multiple of `factor`.
Parameters
----------
factor : int
The value which the length of the resulting piano-roll will be... |
def _get_xml(self, metric):
"""Returns the channel element of the RSS feed"""
self._opener = urllib2.build_opener()
self._opener.addheaders = [('User-agent', self.user_agent)]
if metric:
url = self.base_url + '?w={0}&u=c'.format(self.woeid)
else:
url = se... | Returns the channel element of the RSS feed |
def ahrs3_send(self, roll, pitch, yaw, altitude, lat, lng, v1, v2, v3, v4, force_mavlink1=False):
'''
Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
... | Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
yaw : Yaw angle (rad) (float)
... |
def get_health_color(score):
"""
Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal
"""
color = TERMINAL.green
if score <= 80:
color = TERMINAL.yellow
elif score <= 60:
color = TE... | Returns a color based on the health score
:param score: integer from 0 - 100 representing health
:return: string of color to apply in terminal |
def press_by_tooltip(step, tooltip):
"""
Press a button having a given tooltip.
"""
with AssertContextManager(step):
for button in world.browser.find_elements_by_xpath(str(
'//*[@title="%(tooltip)s" or @data-original-title="%(tooltip)s"]' %
dict(tooltip=tooltip))):
... | Press a button having a given tooltip. |
def has_no_error(
state,
incorrect_msg="Have a look at the console: your code contains an error. Fix it and try again!",
):
"""Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check wh... | Check whether the submission did not generate a runtime error.
If all SCTs for an exercise pass, before marking the submission as correct pythonwhat will automatically check whether
the student submission generated an error. This means it is not needed to use ``has_no_error()`` explicitly.
However, in som... |
def heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None,
scientific=False, style='triangular', colorbar=True,
permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None):
"""
Plots heatmap of given color values.
Parameters
----------
data: dictionary
... | Plots heatmap of given color values.
Parameters
----------
data: dictionary
A dictionary mapping the i, j polygon to the heatmap color, where
i + j + k = scale.
scale: Integer
The scale used to partition the simplex.
vmin: float, None
The minimum color value, used to... |
def print_stmt(self, print_loc, stmt):
"""
(2.6-2.7)
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] )
"""
stmt.keyword_loc = print_loc
if stmt.loc is None:
stmt.loc = print_loc
else:
... | (2.6-2.7)
print_stmt: 'print' ( [ test (',' test)* [','] ] |
'>>' test [ (',' test)+ [','] ] ) |
def load_window_settings(self, prefix, default=False, section='main'):
"""Load window layout settings from userconfig-based configuration
with *prefix*, under *section*
default: if True, do not restore inner layout"""
get_func = CONF.get_default if default else CONF.get
wind... | Load window layout settings from userconfig-based configuration
with *prefix*, under *section*
default: if True, do not restore inner layout |
def launch_app(app_path, params=[], time_before_kill_app=15):
"""
start an app
"""
import subprocess
try:
res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True)
print('res = ', res)
if res == 0:
return True
else:
re... | start an app |
async def jsk_retain(self, ctx: commands.Context, *, toggle: bool = None):
"""
Turn variable retention for REPL on or off.
Provide no argument for current status.
"""
if toggle is None:
if self.retain:
return await ctx.send("Variable retention is set... | Turn variable retention for REPL on or off.
Provide no argument for current status. |
def groupByWordIndex(self, transaction: 'TransTmpl', offset: int):
"""
Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
... | Group transaction parts splited on words to words
:param transaction: TransTmpl instance which parts
should be grupped into words
:return: generator of tuples (wordIndex, list of transaction parts
in this word) |
def cross(triangles):
"""
Returns the cross product of two edges from input triangles
Parameters
--------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
--------------
crosses : (n, 3) float
Cross product of two edge vectors
"""
vectors = np.diff(tri... | Returns the cross product of two edges from input triangles
Parameters
--------------
triangles: (n, 3, 3) float
Vertices of triangles
Returns
--------------
crosses : (n, 3) float
Cross product of two edge vectors |
def previous(self):
"""Return a copy of this object as was at its previous state in
history.
Returns None if this object is new (and therefore has no history).
The returned object is always "disconnected", i.e. does not receive
live updates.
"""
return self.mod... | Return a copy of this object as was at its previous state in
history.
Returns None if this object is new (and therefore has no history).
The returned object is always "disconnected", i.e. does not receive
live updates. |
def model_data(self):
"""str: The model location in S3. Only set if Estimator has been ``fit()``."""
if self.latest_training_job is not None:
model_uri = self.sagemaker_session.sagemaker_client.describe_training_job(
TrainingJobName=self.latest_training_job.name)['ModelArtifa... | str: The model location in S3. Only set if Estimator has been ``fit()``. |
def inner(tensor0: BKTensor, tensor1: BKTensor) -> BKTensor:
"""Return the inner product between two states"""
# Note: Relying on fact that vdot flattens arrays
N = rank(tensor0)
axes = list(range(N))
return tf.tensordot(tf.math.conj(tensor0), tensor1, axes=(axes, axes)) | Return the inner product between two states |
def get_path_effect(graph, path, relationship_dict):
"""Calculate the final effect of the root node to the sink node in the path.
:param pybel.BELGraph graph: A BEL graph
:param list path: Path from root to sink node
:param dict relationship_dict: dictionary with relationship effects
:rtype: Effect... | Calculate the final effect of the root node to the sink node in the path.
:param pybel.BELGraph graph: A BEL graph
:param list path: Path from root to sink node
:param dict relationship_dict: dictionary with relationship effects
:rtype: Effect |
def execute(self, request, target_route):
""" :meth:`.WWebServiceProto.execute` method implementation
"""
presenter = self.create_presenter(request, target_route)
presenter_name = target_route.presenter_name()
action_name = target_route.presenter_action()
presenter_args = target_route.presenter_args()
if... | :meth:`.WWebServiceProto.execute` method implementation |
def construct_json_event_logger(json_path):
'''Record a stream of event records to json'''
check.str_param(json_path, 'json_path')
return construct_single_handler_logger(
"json-event-record-logger",
DEBUG,
JsonEventLoggerHandler(
json_path,
lambda record: cons... | Record a stream of event records to json |
def get_func_argspec(func):
"""
wrapper around inspect.getargspec but takes into account utool decorators
"""
if hasattr(func, '_utinfo'):
argspec = func._utinfo['orig_argspec']
return argspec
if isinstance(func, property):
func = func.fget
try:
argspec = inspect.... | wrapper around inspect.getargspec but takes into account utool decorators |
def _get_string_match(self, key):
"""
Gets a MatchObject for the given key, assuming a string value.
Args:
key (str): Key of the property to look-up.
Return:
MatchObject: The discovered match.
"""
expression = r'(?:\s*)'.join([
'^',
... | Gets a MatchObject for the given key, assuming a string value.
Args:
key (str): Key of the property to look-up.
Return:
MatchObject: The discovered match. |
def count_cycle(iterable, n=None):
"""Cycle through the items from *iterable* up to *n* times, yielding
the number of completed cycles along with each item. If *n* is omitted the
process repeats indefinitely.
>>> list(count_cycle('AB', 3))
[(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')... | Cycle through the items from *iterable* up to *n* times, yielding
the number of completed cycles along with each item. If *n* is omitted the
process repeats indefinitely.
>>> list(count_cycle('AB', 3))
[(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')] |
def get_releases(self, url='', headers={}, repo_name=''):
"""
Retrieves the releases for the given repo in JSON.
"""
url_releases = (url + '/releases')
r = requests.get(url_releases, headers=headers)
self.releases_json[repo_name] = r.json() | Retrieves the releases for the given repo in JSON. |
def DeregisterBlockchain():
"""
Remove the default blockchain instance.
"""
Blockchain.SECONDS_PER_BLOCK = 15
Blockchain.DECREMENT_INTERVAL = 2000000
Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Blockchain._bloc... | Remove the default blockchain instance. |
def dict_merge(a, b):
"""
Recursively merge dicts.
recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
@see http://www.xormedia.com/rec... | Recursively merge dicts.
recursively merges dict's. not just simple a['key'] = b['key'], if
both a and bhave a key who's value is a dict then dict_merge is called
on both values and the result stored in the returned dictionary.
@see http://www.xormedia.com/recursively-merge-dictionaries-in-pyt... |
def updated_current_fields(
self,
update_fields):
"""updated_current_fields
:param update_fields: dict with values for
updating fields_to_add
"""
self.fields_to_add = {}
for k in self.org_fields:
self.fields_to_ad... | updated_current_fields
:param update_fields: dict with values for
updating fields_to_add |
def hilbertscan(size, distance):
"""Scan pixels in a Hilbert curve pattern in the first quadrant. Modified
algorithm from https://en.wikipedia.org/wiki/Hilbert_curve.
:param size: Size of enclosing square
:type size: int
:param distance: Distance along curve (Must be smaller than size**2 - 1)
... | Scan pixels in a Hilbert curve pattern in the first quadrant. Modified
algorithm from https://en.wikipedia.org/wiki/Hilbert_curve.
:param size: Size of enclosing square
:type size: int
:param distance: Distance along curve (Must be smaller than size**2 - 1)
:type distance: int
:returns: Coordi... |
def user_view_task(self, ):
"""View the task that is selected
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_user:
return
i = self.user_task_treev.currentIndex()
item = i.internalPointer()
if item:
task = ite... | View the task that is selected
:returns: None
:rtype: None
:raises: None |
def _perform_power_op(self, oper):
"""Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO.
"""
powe... | Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO. |
def quota(self):
"""Get the uploaded track count and allowance.
Returns:
tuple: Number of uploaded tracks, number of tracks allowed.
"""
response = self._call(
mm_calls.ClientState,
self.uploader_id
)
client_state = response.body.clientstate_response
return (client_state.total_track_count, cli... | Get the uploaded track count and allowance.
Returns:
tuple: Number of uploaded tracks, number of tracks allowed. |
def gatk_snp_cutoff(in_file, data):
"""Perform cutoff-based soft filtering on GATK SNPs using best-practice recommendations.
We have a more lenient mapping quality (MQ) filter compared to GATK defaults.
The recommended filter (MQ < 40) is too stringent, so we adjust to 30:
http://imgur.com/a/oHRVB
... | Perform cutoff-based soft filtering on GATK SNPs using best-practice recommendations.
We have a more lenient mapping quality (MQ) filter compared to GATK defaults.
The recommended filter (MQ < 40) is too stringent, so we adjust to 30:
http://imgur.com/a/oHRVB
QD and FS are not calculated when generati... |
def dump_declarations(declarations, file_path):
"""
Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file
"""
with open(file_pa... | Dump declarations tree rooted at each of the included nodes to the file
:param declarations: either a single :class:declaration_t object or a list
of :class:declaration_t objects
:param file_path: path to a file |
def get_name_cost(name, proxy=None, hostport=None):
"""
name_cost
Returns the name cost info on success
Returns {'amount': ..., 'units': ...} on success
Returns {'error': ...} on error
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostpo... | name_cost
Returns the name cost info on success
Returns {'amount': ..., 'units': ...} on success
Returns {'error': ...} on error |
def organization_memberships(self, state=None, number=-1, etag=None):
"""List organizations of which the user is a current or pending member.
:param str state: (option), state of the membership, i.e., active,
pending
:returns: iterator of :class:`Membership <github3.orgs.Membership>... | List organizations of which the user is a current or pending member.
:param str state: (option), state of the membership, i.e., active,
pending
:returns: iterator of :class:`Membership <github3.orgs.Membership>` |
def select_with_index(self, selector):
'''Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
... | Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
... |
def _make_expr_empty_dict(toplevel, stack_builders):
"""
This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead.
"""
if toplevel.arg:
raise DecompilationError(
"make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
)
... | This should only be hit for empty dicts. Anything else should hit the
STORE_MAP handler instead. |
def import_data(self, data_items):
""" import a bunch of dicts together """
# keep counts of all actions
record = {
'insert': 0, 'update': 0, 'noop': 0,
'start': utcnow(),
'records': {
'insert': [],
'update': [],
... | import a bunch of dicts together |
def stackplot(marray, seconds=None, start_time=None, ylabels=None):
"""
will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples
"""
tarray = np.transpose(marray)
stackplot_t(tarray, seconds=seconds, start_time=start_time, ylabels=ylabels)
plt.show() | will plot a stack of traces one above the other assuming
marray.shape = numRows, numSamples |
def _get_site_amplification_term(self, C, vs30):
"""
Returns the site amplification term for the case in which Vs30
is used directly
"""
return C["gamma"] * np.log10(vs30 / self.CONSTS["Vref"]) | Returns the site amplification term for the case in which Vs30
is used directly |
def send_work(self):
'''Sends the query to the actor for it to start executing the
work.
It is possible to execute once again a future that has finished
if necessary (overwriting the results), but only one execution
at a time.
'''
if self.__set_running():
... | Sends the query to the actor for it to start executing the
work.
It is possible to execute once again a future that has finished
if necessary (overwriting the results), but only one execution
at a time. |
def p_taskvardecls(self, p):
'taskvardecls : taskvardecls taskvardecl'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | taskvardecls : taskvardecls taskvardecl |
def mmPrettyPrintConnections(self):
"""
Pretty print the connections in the temporal memory.
TODO: Use PrettyTable.
@return (string) Pretty-printed text
"""
text = ""
text += ("Segments: (format => "
"(#) [(source cell=permanence ...), ...]\n")
text += "------------... | Pretty print the connections in the temporal memory.
TODO: Use PrettyTable.
@return (string) Pretty-printed text |
def delete_vhost(self, name):
"""
Delete a vhost.
:param name: The vhost name
:type name: str
"""
self._api_delete('/api/vhosts/{0}'.format(
urllib.parse.quote_plus(name)
)) | Delete a vhost.
:param name: The vhost name
:type name: str |
def tabSeparatedSummary(self, sortOn=None):
"""
Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
... | Summarize all the alignments for this title as multi-line string with
TAB-separated values on each line.
@param sortOn: A C{str} attribute to sort titles on. One of 'length',
'maxScore', 'medianScore', 'readCount', or 'title'.
@raise ValueError: If an unknown C{sortOn} value is give... |
def _set_timestamps_on_attach(self, record, exists=False):
"""
Set the creation an update timestamps on an attach record.
"""
fresh = self._parent.fresh_timestamp()
if not exists and self._has_pivot_column(self.created_at()):
record[self.created_at()] = fresh
... | Set the creation an update timestamps on an attach record. |
def pause(self):
"""Pause all VMs in this cluster and store data so that they
can be restarted later.
"""
log.info("Pausing cluster `%s` ...", self.name)
failed = self._pause_all_nodes()
if os.path.exists(self.known_hosts_file):
os.remove(self.known_hosts_file... | Pause all VMs in this cluster and store data so that they
can be restarted later. |
def load(cls, filename, **kwargs):
"""Load a Spectrum1D from a given filename.
:param filename:
The path of the filename to load. Can be either simple 1D FITS files
or an ASCII filename.
:type filename:
str
"""
if not os.path... | Load a Spectrum1D from a given filename.
:param filename:
The path of the filename to load. Can be either simple 1D FITS files
or an ASCII filename.
:type filename:
str |
def _map_intent_to_view_func(self, intent):
"""Provides appropiate parameters to the intent functions."""
if intent.name in self._intent_view_funcs:
view_func = self._intent_view_funcs[intent.name]
elif self._default_intent_view_func is not None:
view_func = self._default... | Provides appropiate parameters to the intent functions. |
def pin_type(self, pin):
"""Gets the `ahio.PortType` this pin was set to.
If you're developing a driver, implement _pin_type(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.PortType` the pin is set to
@throw KeyError if pin isn't mapped.
"""
... | Gets the `ahio.PortType` this pin was set to.
If you're developing a driver, implement _pin_type(self, pin)
@arg pin the pin you want to see the mode
@returns the `ahio.PortType` the pin is set to
@throw KeyError if pin isn't mapped. |
def gen_query(self):
"""
Generate an SQL query for the edge object.
"""
return (
SQL.forwards_relation(self.src, self.rel) if self.dst is None else
SQL.inverse_relation(self.dst, self.rel)
) | Generate an SQL query for the edge object. |
def merge(self, carts=None, new_cart_name=None):
"""
`carts` - A list of cart names
`new_cart_name` - Resultant cart name
Merge the contents of N carts into a new cart
TODO: Sanity check that each cart in `carts` exists. Try
'juicer pull'ing carts that can't be located ... | `carts` - A list of cart names
`new_cart_name` - Resultant cart name
Merge the contents of N carts into a new cart
TODO: Sanity check that each cart in `carts` exists. Try
'juicer pull'ing carts that can't be located locally. Then cry
like a baby and error out. |
def fresh(req_headers: HEADER_TYPE, res_headers: HEADER_TYPE) -> bool:
"""
根据 req_headers, res_headers 判断改消息是否为 304
"""
modified_since = cast(
Optional[str],
req_headers.get('if-modified-since'),
)
none_match = cast(
Optional[str],
req_headers.get('if-none-match')... | 根据 req_headers, res_headers 判断改消息是否为 304 |
def update_project(self, ID, data):
"""Update a project."""
# http://teampasswordmanager.com/docs/api-projects/#update_project
log.info('Update project %s with %s' % (ID, data))
self.put('projects/%s.json' % ID, data) | Update a project. |
def group_retrieve(self, device_group_id, **kwargs): # noqa: E501
"""Get a group. # noqa: E501
Get a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_retriev... | Get a group. # noqa: E501
Get a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_retrieve(device_group_id, asynchronous=True)
>>> result = thread.get()
... |
def _get_info(self, fullmodname):
"""
Internal helper for find_module() and load_module().
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
A tuple (submodname, is_package, relpath, fileobj) where:
submodname: The ... | Internal helper for find_module() and load_module().
Args:
fullmodname: The dot-separated full module name, e.g. 'django.core.mail'.
Returns:
A tuple (submodname, is_package, relpath, fileobj) where:
submodname: The final component of the module name, e.g. 'mail'.
... |
def _tokens_to_subtoken(self, tokens):
""" Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(
... | Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) |
def get_typecast_value(self, value, type):
""" Helper method to determine actual value based on type of feature variable.
Args:
value: Value in string form as it was parsed from datafile.
type: Type denoting the feature flag type.
Return:
Value type-casted based on type of feature variab... | Helper method to determine actual value based on type of feature variable.
Args:
value: Value in string form as it was parsed from datafile.
type: Type denoting the feature flag type.
Return:
Value type-casted based on type of feature variable. |
def check_post_role(self):
'''
check the user role for docs.
'''
priv_dic = {'ADD': False, 'EDIT': False, 'DELETE': False, 'ADMIN': False}
if self.userinfo:
if self.userinfo.role[1] > '0':
priv_dic['ADD'] = True
if self.userinfo.role[1] >= ... | check the user role for docs. |
def _init_spmatrix(self, data, index, columns, dtype=None,
fill_value=None):
"""
Init self from scipy.sparse matrix.
"""
index, columns = self._prep_index(data, index, columns)
data = data.tocoo()
N = len(index)
# Construct a dict of Sparse... | Init self from scipy.sparse matrix. |
def add_signature(self, key, alg=None, protected=None, header=None):
"""Adds a new signature to the object.
:param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for
the "alg" provided.
:param alg: An optional algorithm name. If already provided as an
element of the pro... | Adds a new signature to the object.
:param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for
the "alg" provided.
:param alg: An optional algorithm name. If already provided as an
element of the protected or unprotected header it can be safely
omitted.
:param p... |
def list_records(self, bucket_name, prefix='', delimiter='', max_results=1000, starting_key=''):
'''
a method for retrieving a list of the versions of records in a bucket
:param bucket_name: string with name of bucket
:param prefix: [optional] string with value limiting results to ... | a method for retrieving a list of the versions of records in a bucket
:param bucket_name: string with name of bucket
:param prefix: [optional] string with value limiting results to key prefix
:param delimiter: string with value which results must not contain (after prefix)
:param max_re... |
def object_id(self):
"""(:class:`numbers.Integral`) The identifier number of the image.
It uses the primary key if it's integer, but can be overridden,
and must be implemented when the primary key is not integer or
composite key.
.. versionchanged:: 1.1.0
Since 1.1.0,... | (:class:`numbers.Integral`) The identifier number of the image.
It uses the primary key if it's integer, but can be overridden,
and must be implemented when the primary key is not integer or
composite key.
.. versionchanged:: 1.1.0
Since 1.1.0, it provides a more default impl... |
def _labeled_uniform_sample(self, sample_size):
"""sample labeled entries uniformly"""
labeled_entries = self.dataset.get_labeled_entries()
samples = [labeled_entries[
self.random_state_.randint(0, len(labeled_entries))
]for _ in range(sample_size)]
return Dataset(*zi... | sample labeled entries uniformly |
def from_dict(d):
"""
load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object
"""
if isinstance(d, str):
return from_json(d)
if not isinstance(d, dict):
raise TypeError("argument must be of type dict")
if 'nparray' not in d.keys... | load an nparray object from a dictionary
@parameter str d: dictionary representing the nparray object |
def clean(cls, cpf):
u"""
Retorna apenas os dígitos do CPF.
>>> CPF.clean('581.194.436-59')
'58119443659'
"""
if isinstance(cpf, six.string_types):
cpf = int(re.sub('[^0-9]', '', cpf))
return '{0:011d}'.format(cpf) | u"""
Retorna apenas os dígitos do CPF.
>>> CPF.clean('581.194.436-59')
'58119443659' |
def call_heat(tstat):
"""
Adjusts the temperature setpoints in order to call for heating. Returns
a handler to call when you want to reset the thermostat
"""
current_hsp, current_csp = tstat.heating_setpoint, tstat.cooling_setpoint
current_temp = tstat.temperature
tstat.write({
'heat... | Adjusts the temperature setpoints in order to call for heating. Returns
a handler to call when you want to reset the thermostat |
def hit(self, event):
"""
Notify a breakpoint that it's been hit.
This triggers the corresponding state transition and sets the
C{breakpoint} property of the given L{Event} object.
@see: L{disable}, L{enable}, L{one_shot}, L{running}
@type event: L{Event}
@par... | Notify a breakpoint that it's been hit.
This triggers the corresponding state transition and sets the
C{breakpoint} property of the given L{Event} object.
@see: L{disable}, L{enable}, L{one_shot}, L{running}
@type event: L{Event}
@param event: Debug event to handle (depends o... |
def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. |
def download_quad(self, quad, callback=None):
'''Download the specified mosaic quad. If provided, the callback will
be invoked asynchronously. Otherwise it is up to the caller to handle
the response Body.
:param asset dict: A mosaic quad representation from the API
:param callb... | Download the specified mosaic quad. If provided, the callback will
be invoked asynchronously. Otherwise it is up to the caller to handle
the response Body.
:param asset dict: A mosaic quad representation from the API
:param callback: An optional function to aysnchronsously handle the
... |
def format_day(
self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True
) -> bool:
"""Formats the given date as a day of week.
Example: "Monday, January 22". You can remove the day of week with
``dow=False``.
"""
local_date = date - datetime.timedelta(mi... | Formats the given date as a day of week.
Example: "Monday, January 22". You can remove the day of week with
``dow=False``. |
def feature_selection(feat_select, X, y):
"""" Implements various kinds of feature selection """
# K-best
if re.match('.*-best', feat_select) is not None:
n = int(feat_select.split('-')[0])
selector = SelectKBest(k=n)
import warnings
with warnings.catch_warnings():
... | Implements various kinds of feature selection |
def prior_to_xarray(self):
"""Convert prior samples to xarray."""
return dict_to_dataset(
{k: np.expand_dims(v, 0) for k, v in self.prior.items()},
library=self.pymc3,
coords=self.coords,
dims=self.dims,
) | Convert prior samples to xarray. |
def _get_hash(f1, f2, dt):
"""
Calculate a 64-bit integral hash from <f1:f2:dt>, where f1 and f2 are
FFT frequency bins (based on frame width), and dt is propotional to the
time difference between f1 and f2 as the the difference in frame number
between the points.
"""
return ((long(f1) & 0xf... | Calculate a 64-bit integral hash from <f1:f2:dt>, where f1 and f2 are
FFT frequency bins (based on frame width), and dt is propotional to the
time difference between f1 and f2 as the the difference in frame number
between the points. |
def delete_collaborator(self, email):
"""Remove a collaborating user from the shared project.
:param email: The collaborator's email address.
:type email: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user... | Remove a collaborating user from the shared project.
:param email: The collaborator's email address.
:type email: str
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('PyTodoist')
>>> project.del... |
def index(self, value):
"""Return the 0-based position of integer `value` in
the sequence this range represents."""
try:
diff = value - self._start
except TypeError:
raise ValueError('%r is not in range' % value)
quotient, remainder = divmod(diff, self._st... | Return the 0-based position of integer `value` in
the sequence this range represents. |
def get_import_lines(self):
""" Take the stored imports and converts them to lines """
if self.imports:
return ["from %s import %s" % (value, key) for key, value in self.imports.items()]
else:
return [] | Take the stored imports and converts them to lines |
def validate_regex(regex, sub_service):
"""Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the reg... | Is the regex valid for StackInABox routing?
:param regex: Python regex object to match the URI
:param sub_service: boolean for whether or not the regex is for
a sub-service
:raises: InvalidRouteRegexError if the regex does not meet the
requirements. |
def admin_emails(doc):
"""View for admin email addresses (organisation and global)"""
if doc.get('type') == 'user' and doc.get('state') != 'deactivated':
if doc.get('role') == 'administrator':
yield None, doc['email']
for org_id, state in doc.get('organisations', {}).items():
... | View for admin email addresses (organisation and global) |
def list_keys(key_name,
max_suggestions,
cutoff,
jsonify,
locked,
key_type,
stash,
passphrase,
backend):
"""List all keys in the stash
If `KEY_NAME` is provided, will look for keys containing `KEY_NA... | List all keys in the stash
If `KEY_NAME` is provided, will look for keys containing `KEY_NAME`.
If `KEY_NAME` starts with `~`, close matches will be provided according
to `max_suggestions` and `cutoff`. |
def _setup_transport(self):
"""Setup to _write() directly to the socket, and
do our own buffered reads."""
self._write = self.sock.sendall
self._read_buffer = EMPTY_BUFFER
self._quick_recv = self.sock.recv | Setup to _write() directly to the socket, and
do our own buffered reads. |
def save(self):
""" Saves current patches list in the series file """
with open(self.series_file, "wb") as f:
for patchline in self.patchlines:
f.write(_encode_str(str(patchline)))
f.write(b"\n") | Saves current patches list in the series file |
def download(self, dest_pattern="{originalFilename}", override=True, parent=False):
"""
Download the original image.
Parameters
----------
dest_pattern : str, optional
Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute
... | Download the original image.
Parameters
----------
dest_pattern : str, optional
Destination path for the downloaded image. "{X}" patterns are replaced by the value of X attribute
if it exists.
override : bool, optional
True if a file with same name ca... |
def create_draft(self, layer_id):
"""
Creates a new draft version.
If anything in the data object has changed then an import will begin immediately.
Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`.
:rtype: La... | Creates a new draft version.
If anything in the data object has changed then an import will begin immediately.
Otherwise to force a re-import from the previous sources call :py:meth:`koordinates.layers.LayerManager.start_import`.
:rtype: Layer
:return: the new version
:raises C... |
def read_tile_header(codec, stream):
"""Reads a tile header.
Wraps the openjp2 library function opj_read_tile_header.
Parameters
----------
codec : codec_t
The JPEG2000 codec to read.
stream : STREAM_TYPE_P
The JPEG2000 stream.
Returns
-------
tile_index : int
... | Reads a tile header.
Wraps the openjp2 library function opj_read_tile_header.
Parameters
----------
codec : codec_t
The JPEG2000 codec to read.
stream : STREAM_TYPE_P
The JPEG2000 stream.
Returns
-------
tile_index : int
index of the tile being decoded
data... |
def _remap(object, name, value, safe=True):
"""Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
... | Prevent accidental assignment of existing members
Arguments:
object (object): Parent of new attribute
name (str): Name of new attribute
value (object): Value of new attribute
safe (bool): Whether or not to guarantee that
the new attribute was not overwritten.
... |
def _cmp_date(self):
"""Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase).
"""
dates = sorted(val for val in self.kw.values()
... | Returns Calendar date used for comparison.
Use the earliest date out of all CalendarDates in this instance,
or some date in the future if there are no CalendarDates (e.g.
when Date is a phrase). |
def case_highlight(seq, subseq):
"""
Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase.
"""
return re.subs(subseq.lower(), subseq.upper(), seq.lower()) | Highlights all instances of subseq in seq by making them uppercase and
everything else lowercase. |
def get_fastq_files(data):
"""Retrieve fastq files for the given lane, ready to process.
"""
assert "files" in data, "Did not find `files` in input; nothing to process"
ready_files = []
should_gzip = True
# Bowtie does not accept gzipped fastq
if 'bowtie' in data['reference'].keys():
... | Retrieve fastq files for the given lane, ready to process. |
def _get_value_from_config(self, section, name):
"""Loads the default from the config. Returns _no_value if it doesn't exist"""
conf = configuration.get_config()
try:
value = conf.get(section, name)
except (NoSectionError, NoOptionError, KeyError):
return _no_va... | Loads the default from the config. Returns _no_value if it doesn't exist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.