Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
340,900 | def SETA(cpu, dest):
dest.write(Operators.ITEBV(dest.size, Operators.OR(cpu.CF, cpu.ZF) == False, 1, 0)) | Sets byte if above.
Sets the destination operand to 0 or 1 depending on the settings of the status flags (CF, SF, OF, ZF, and PF, 1, 0) in the
EFLAGS register. The destination operand points to a byte register or a byte in memory. The condition code suffix
(cc, 1, 0) indicates the condition bei... |
340,901 | def human_readable(self, decimal=False):
divisor = 1000 if decimal else 1024
number = int(self)
unit = ""
for unit in self.units:
if number < divisor:
break
number /= divisor
return number, unit.upper() | returns the size of size as a tuple of:
(number, single-letter-unit)
If the decimal flag is set to true, units 1000 is used as the
divisor, rather than 1024. |
340,902 | def init_defaults(self):
super(ModelTable, self).init_defaults()
self.model = self.table
self.name = self.model._meta.db_table | Sets a model instance variable to the table value and sets the name to the
table name as determined from the model class |
340,903 | def get_tunnel_info_output_next_page_cursor(self, **kwargs):
config = ET.Element("config")
get_tunnel_info = ET.Element("get_tunnel_info")
config = get_tunnel_info
output = ET.SubElement(get_tunnel_info, "output")
next_page_cursor = ET.SubElement(output, "next-page-curso... | Auto Generated Code |
340,904 | def FlagDictToArgs(flag_map):
for key, value in six.iteritems(flag_map):
if value is None:
yield % key
elif isinstance(value, bool):
if value:
yield % key
else:
yield % key
elif isinstance(value, (bytes, type(u))):
| Convert a dict of values into process call parameters.
This method is used to convert a dictionary into a sequence of parameters
for a binary that parses arguments using this module.
Args:
flag_map: a mapping where the keys are flag names (strings).
values are treated according to their type:
* ... |
340,905 | def dict_to_xml_schema(data):
for key, value in data.items():
root = _add_element_attrs(ET.Element(key), value.get("attrs", {}))
children = value.get("children", None)
if isinstance(children, dict):
_add_sub_elements_from_dict(root, children)
return root | Input a dictionary to be converted to xml. There should be only one key at
the top level. The value must be a dict with (required) `children` key and
(optional) `attrs` key. This will be called the `sub-element dictionary`.
The `attrs` value must be a dictionary; each value will be added to the
element's xml tag a... |
340,906 | def send_location(self, latitude: float, longitude: float, reply: Message=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
self.twx.send_location(peer=self, latitude=latitude, longitude=longitude,
reply_to_message_id=reply, o... | Send location to this peer.
:param latitude: Latitude of the location.
:param longitude: Longitude of the location.
:param reply: Message object.
:param on_success: Callback to call when call is complete.
:type reply: int or Message |
340,907 | def dlf(signal, points, out_pts, filt, pts_per_dec, kind=None, factAng=None,
ab=None, int_pts=None):
r
if isinstance(signal, tuple):
hankel = True
if factAng is None:
has_angle_factors = False
else:
one_angle = factAng.min() == fact... | r"""Digital Linear Filter method.
This is the kernel of the DLF method, used for the Hankel (``fht``) and the
Fourier (``ffht``) Transforms. See ``fht`` for an extensive description.
For the Hankel transform, `signal` contains 3 complex wavenumber-domain
signals: (PJ0, PJ1, PJ0b), as returned from `ke... |
340,908 | def opt_hyper(gpr,Ifilter=None,bounds=None,opts={},*args,**kw_args):
if in opts:
gradcheck = opts[]
else:
gradcheck = False
if in opts:
max_iter = opts[]
else:
max_iter = 5000
if in opts:
pgtol = opts[]
else:
pgtol = 1e-10
params0 = gp... | optimize params
Input:
gpr: GP regression class
params0: dictionary filled with starting hyperparameters
opts: options for optimizer |
340,909 | def _proc_accept_header(self, request, result):
if result:
return
try:
accept = request.headers[]
except KeyError:
return
ctype, params = best_match(accept, self.types.keys())
if ctype no... | Process the Accept header rules for the request. Both the
desired API version and content type can be determined from
those rules.
:param request: The Request object provided by WebOb.
:param result: The Result object to store the results in. |
340,910 | def _resolve_task_logging(job_metadata, job_resources, task_descriptors):
if not job_resources.logging:
return
for task_descriptor in task_descriptors:
logging_uri = provider_base.format_logging_uri(
job_resources.logging.uri, job_metadata, task_descriptor.task_metadata)
logging_path = job_m... | Resolve the logging path from job and task properties.
Args:
job_metadata: Job metadata, such as job-id, job-name, and user-id.
job_resources: Resources specified such as ram, cpu, and logging path.
task_descriptors: Task metadata, parameters, and resources.
Resolve the logging path, which may have su... |
340,911 | def find_course_and_crosslistings(self, partial):
course = self.find_course(partial)
crosslisted = self.crosslisted_with(course.crn)
return (course,) + tuple(map(self.find_course_by_crn, crosslisted)) | Returns the given course and all other courses it is
crosslisted with. |
340,912 | def download_content(self, dir_path=, filename=None,
force_download=False):
if filename is None:
filename = self.get_filename()
path = os.path.join(dir_path, filename)
data = self.client.get_document(self.url(), force_download)
with open(path... | Download the content for this document to a file
:type dir_path: String
:param dir_path: the path to which to write the data
:type filename: String
:param filename: filename to write to (if None, defaults to the document's
name, as specified by its metadata
:type for... |
340,913 | def logon(self, password=):
r = self._basic_post(url=, data=password)
return r.json() | Parameters
----------
password : str
default 'admin'
Returns
-------
dict |
340,914 | def delete(self, blocksize=100):
@host.comt be used on models on either side of a ``OneToMany``,
``ManyToOne``, or ``OneToOne`` relationship.
t delete entities of models with foreign key relationships")
de = []
i = 0
for result in self.iter_result(pagesize=blocksize)... | Will delete the entities that match at the time the query is executed.
Used like::
MyModel.query.filter(email=...).delete()
MyModel.query.endswith(email='@host.com').delete()
.. warning:: can't be used on models on either side of a ``OneToMany``,
``ManyToOne``, or ... |
340,915 | def display(self):
self.command(SSD1306_COLUMNADDR)
self.command(0)
self.command(self.width-1)
self.command(SSD1306_PAGEADDR)
self.command(0)
self.command(self._pages-1)
for i in range(0, len(self._buffer), 16):
... | Write display buffer to physical display. |
340,916 | def get_instance(self, payload):
return RecordingInstance(
self._version,
payload,
account_sid=self._solution[],
call_sid=self._solution[],
) | Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance |
340,917 | def clean_fields(fields, ignored_value_indices, transforms):
cleaned_fields = []
for i, field in enumerate(fields):
if field in ignored_value_indices:
ignored_index = ignored_value_indices[field]
if ignored_index == i:
continue
... | Sometimes, NetMHC* has fields that are only populated sometimes, which results
in different count/indexing of the fields when that happens.
We handle this by looking for particular strings at particular indices, and
deleting them.
Warning: this may result in unexpected behavior sometimes. For example,... |
340,918 | def get_cv_pattern(self, word, pprint=False):
subscripts = {
1: ,
2: ,
3: ,
4: ,
5: ,
6: ,
7: ,
8: ,
9: ,
0:
}
pattern = []
c_count = 1
v_count = 1
... | input = iparras
pattern = [('V', 1, 'i'), ('C', 1, 'p'), ('V', 2, 'a'), ('C', 2, 'r'),
('C', 2, 'r'), ('V', 2, 'a'), ('C', 3, 's')]
pprint = V₁C₁V₂C₂C₂V₂C₃ |
340,919 | def run():
args = parse_args()
if args.verbose:
log_level = logging.DEBUG
else:
log_level = logging.INFO
logging.basicConfig(
level=log_level,
format=)
if not args.verbose:
req_logger = logging.getLogger()
req_logger.setLevel(logging.WAR... | Command line entrypoint for the ``refresh-lsst-bib`` program. |
340,920 | def set_phases(self, literals=[]):
if self.maplesat:
pysolvers.maplecm_setphases(self.maplesat, literals) | Sets polarities of a given list of variables. |
340,921 | def log_function(self, stream_name, properties={},
log_function_stack_trace=False,
log_exception_stack_trace=False,
namespace=None):
namespace = namespace or self.namespace
def decorator(function):
@functools.wraps(function)
def wrapper(... | Logs each call to the function as an event in the stream with name
`stream_name`. If `log_stack_trace` is set, it will log the stack trace
under the `stack_trace` key. `properties` is an optional mapping fron key
name to some function which expects the same arguments as the function
`function` being dec... |
340,922 | def register_setting(name=None, label=None, editable=False, description=None,
default=None, choices=None, append=False,
translatable=False):
if name is None:
raise TypeError("yacms.conf.register_setting requires the "
" keyword argument.... | Registers a setting that can be edited via the admin. This mostly
equates to storing the given args as a dict in the ``registry``
dict by name. |
340,923 | def get_public_members(obj):
return {attr: getattr(obj, attr) for attr in dir(obj)
if not attr.startswith("_")
and not hasattr(getattr(obj, attr), )} | Retrieves a list of member-like objects (members or properties) that are
publically exposed.
:param obj: The object to probe.
:return: A list of strings. |
340,924 | def comparator_eval(comparator_params):
top1, top2, params1, params2, seq1, seq2, movements = comparator_params
xrot, yrot, zrot, xtrans, ytrans, ztrans = movements
obj1 = top1(*params1)
obj2 = top2(*params2)
obj2.rotate(xrot, [1, 0, 0])
obj2.rotate(yrot, [0, 1, 0])
obj2.rotate(zrot, [0... | Gets BUFF score for interaction between two AMPAL objects |
340,925 | def __check_properties(props):
mandatory = (
pelix.remote.PROP_ENDPOINT_ID,
pelix.remote.PROP_IMPORTED_CONFIGS,
pelix.constants.OBJECTCLASS,
)
for key in mandatory:
if key not in props:
raise ValueError("M... | Checks that the given dictionary doesn't have export keys and has
import keys
:param props: Properties to validate
:raise ValueError: Invalid properties |
340,926 | def get_stp_mst_detail_output_msti_port_configured_path_cost(self, **kwargs):
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
msti = ET.SubElement(output,... | Auto Generated Code |
340,927 | def validate_revocation_request(self, request):
self._raise_on_missing_token(request)
self._raise_on_invalid_client(request)
self._raise_on_unsupported_token(request) | Ensure the request is valid.
The client constructs the request by including the following parameters
using the "application/x-www-form-urlencoded" format in the HTTP
request entity-body:
token (REQUIRED). The token that the client wants to get revoked.
token_type_hint (OPTION... |
340,928 | def convert_to_int(value):
if not value:
return None
if isinstance(value, str):
value = value.strip()
try:
return int(value)
except (TypeError, ValueError):
return None | Attempts to convert a specified value to an integer
:param value: Content to be converted into an integer
:type value: string or int |
340,929 | def has_auth_params(self, scheme):
for k, v in iteritems(self.schemes[scheme][u]):
if not v: return False
return True | Check whether all information required for a given auth scheme have
been supplied.
Args:
scheme (str): Name of the authentication scheme to check. One of
Gem-Identify, Gem-Device, Gem-Application
Returns:
True if all required parameters for the specified scheme ... |
340,930 | def get_sun_rise_set_transit(self, times, method=, **kwargs):
if method == :
result = solarposition.sun_rise_set_transit_ephem(
times, self.latitude, self.longitude, **kwargs)
elif method == :
result = solarposition.sun_rise_set_transit_spa(
... | Calculate sunrise, sunset and transit times.
Parameters
----------
times : DatetimeIndex
Must be localized to the Location
method : str, default 'pyephem'
'pyephem', 'spa', or 'geometric'
kwargs are passed to the relevant functions. See
solarposi... |
340,931 | def save(self, fname=None, link_copy=False,raiseError=False):
if fname is None:
fname = self.filename
assert fname is not None
save(fname, self, link_copy=link_copy,raiseError=raiseError) | link_copy: only works in hfd5 format
save space by creating link when identical arrays are found,
it may slows down the saving (3 or 4 folds) but saves space
when saving different dataset together (since it does not duplicate
arrays) |
340,932 | def _log(self, level, message, context=None):
if self._logger:
self._logger.log(level, message, extra={: context or {}}) | Sends a message to the instance's logger, if configured. |
340,933 | def doplot(image0, image1, xs, crbs, errors, labels, diff_image_scale=0.1,
dolabels=True, multiple_crbs=True, xlim=None, ylim=None, highlight=None,
detailed_labels=False, xlabel="", title=""):
if len(crbs) != len(errors) or len(crbs) != len(labels):
raise IndexError, "lengths are not co... | Standardizing the plot format of the does_matter section. See any of the
accompaning files to see how to use this generalized plot.
image0 : ground true
image1 : difference image
xs : list of x values for the plots
crbs : list of lines of values of the crbs
errors : list of lines of errors
... |
340,934 | def list_floating_ip_actions(self, ip_addr):
if self.api_version == 2:
json = self.request( + ip_addr + )
return json[]
else:
raise DoError(v2_api_required_str) | Retrieve a list of all actions that have been executed on a Floating IP. |
340,935 | def breadth_first_search(G, seed):
G = asgraph(G)
N = G.shape[0]
order = np.empty(N, G.indptr.dtype)
level = np.empty(N, G.indptr.dtype)
level[:] = -1
BFS = amg_core.breadth_first_search
BFS(G.indptr, G.indices, int(seed), order, level)
return order, level | Breadth First search of a graph.
Parameters
----------
G : csr_matrix, csc_matrix
A sparse NxN matrix where each nonzero entry G[i,j] is the distance
between nodes i and j.
seed : int
Index of the seed location
Returns
-------
order : int array
Breadth first... |
340,936 | def read_cms(cms=None, domains=None):
assert_is_type(cms, [list])
return [ConfusionMatrix(cm, domains) for cm in cms] | Read confusion matrices from the list of sources (?). |
340,937 | def updateParams(self, newvalues, update_all=False):
assert all(map(lambda x: x in self.freeparams, newvalues.keys())),\
"Invalid entry in newvalues: {0}\nfreeparams: {1}".format(
.join(newvalues.keys()), .join(self.freeparams))
changed = set([])
for (na... | See docs for `Model` abstract base class. |
340,938 | def MUL(classical_reg, right):
left, right = unpack_reg_val_pair(classical_reg, right)
return ClassicalMul(left, right) | Produce a MUL instruction.
:param classical_reg: Left operand for the arithmetic operation. Also serves as the store target.
:param right: Right operand for the arithmetic operation.
:return: A ClassicalMul instance. |
340,939 | def ssh_sa_ssh_server_key_dsa(self, **kwargs):
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
server = ET.SubElement(ssh, "server")
key = ET.SubElement(server, "... | Auto Generated Code |
340,940 | def contraction_string(element):
if not in element:
return ""
cont_map = dict()
for sh in element[]:
nprim = len(sh[])
ngeneral = len(sh[])
is_spdf = len(sh[]) > 1
for am in sh[]:
ncont = ngeneral if not is_spdf else 1
... | Forms a string specifying the contractions for an element
ie, (16s,10p) -> [4s,3p] |
340,941 | def vertices(self):
if self._v_out is None:
output = qhalf(, self.halfspaces, self.interior_point)
pts = []
for l in output[2:]:
pt = []
for c in l.split():
c = float(c)
if c != 10.101 and c != -... | Returns the vertices of the halfspace intersection |
340,942 | def wa(client, event, channel, nick, rest):
client = wolframalpha.Client(pmxbot.config[])
res = client.query(rest)
return next(res.results).text | A free-text query resolver by Wolfram|Alpha. Returns the first
result, if available. |
340,943 | def update_ostree_summary(self, release):
self.log.info(, release[])
self.mock_chroot(release, release[])
return os.path.join(release[], ) | Update the ostree summary file and return a path to it |
340,944 | def stats_first(abf):
msg=""
for sweep in range(abf.sweeps):
for AP in abf.APs[sweep]:
for key in sorted(AP.keys()):
if key[-1] is "I" or key[-2:] in ["I1","I2"]:
continue
msg+="%s = %s\n"%(key,AP[key])
return msg | provide all stats on the first AP. |
340,945 | def set_riskfree_rate(self, rf):
self.rf = rf
self._update(self.prices) | Set annual risk-free rate property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only this instance of the PerformanceStats.
Args:
* rf (float): Annual `risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.a... |
340,946 | def has_no_fat_ends(neuron, multiple_of_mean=2.0, final_point_count=5):
bad_ids = []
for leaf in _nf.iter_sections(neuron.neurites, iterator_type=Tree.ileaf):
mean_radius = np.mean(leaf.points[1:][-final_point_count:, COLS.R])
if mean_radius * multiple_of_mean <= leaf.points[-1, COLS.R]:
... | Check if leaf points are too large
Arguments:
neuron(Neuron): The neuron object to test
multiple_of_mean(float): how many times larger the final radius
has to be compared to the mean of the final points
final_point_count(int): how many points to include in the mean
Returns:
... |
340,947 | def prev_next_group(project, group):
groups = sorted(x for x in project.groups if x.submissions)
try:
index = groups.index(group)
except ValueError:
return None, None
prev_group = groups[index - 1] if index > 0 else None
next_group = groups[index + 1] if index + 1 < len(gro... | Return adjacent group objects or None for the given project and group.
The previous and next group objects are relative to sort order of the
project's groups with respect to the passed in group. |
340,948 | def list(self, catid):
logger.info(.format(catid))
condition = self.gen_redis_kw()
sig = catid
bread_title =
bread_crumb_nav_str =
_catinfo = MCategory.get_by_uid(catid)
logger.info(.format(_catinfo))
if _catinfo.pid == :
pcatinfo =... | 页面打开后的渲染方法,不包含 list 的查询结果与分页导航 |
340,949 | def contains(self, index: Union[SchemaKey, int, str]) -> bool:
LOGGER.debug(, index)
rv = None
if isinstance(index, SchemaKey):
rv = (index in self._schema_key2schema)
elif isinstance(index, int) or (isinstance(index, str) and not in index):
rv = (int(... | Return whether the cache contains a schema for the input key, sequence number, or schema identifier.
:param index: schema key, sequence number, or sequence identifier
:return: whether the cache contains a schema for the input index |
340,950 | def Shift(self, value, copy=False):
numPoints = self.GetN()
if copy:
shiftGraph = self.Clone()
else:
shiftGraph = self
X = self.GetX()
EXlow = self.GetEXlow()
EXhigh = self.GetEXhigh()
Y = self.GetY()
EYlow = self.GetEYlow(... | Shift the graph left or right by value |
340,951 | def funTransSectY(theta, rho):
return np.matrix([[1, rho * theta], [0, 1]], dtype=np.double) | Sector matrix in Y
:param theta: bend angle, in [rad]
:param rho: bend radius, in [m]
:return: 2x2 numpy array |
340,952 | def deep_copy(self):
c = KalmanState(self.observation_matrix, self.translation_matrix)
c.state_vec = self.state_vec.copy()
c.state_cov = self.state_cov.copy()
c.noise_var = self.noise_var.copy()
c.state_noise = self.state_noise.copy()
c.state_noise_idx = self.sta... | Return a deep copy of the state |
340,953 | def environment_list(self, io_handler):
headers = ("Environment Variable", "Value")
lines = [item for item in os.environ.items()]
lines.sort()
io_handler.write(self._utils.make_table(headers, lines)) | Lists the framework process environment variables |
340,954 | def signal_handler(sig, frame):
print()
if board is not None:
board.send_reset()
board.shutdown()
sys.exit(0) | Helper method to shutdown the RedBot if Ctrl-c is pressed |
340,955 | def add_end_event_to_diagram(self, process_id, end_event_name="", end_event_definition=None, node_id=None):
end_event_id, end_event = self.add_flow_node_to_diagram(process_id, consts.Consts.end_event, end_event_name,
node_id)
end_e... | Adds an EndEvent element to BPMN diagram.
User-defined attributes:
- name
- event definition (creates a special type of end event). Supported event definitions
* `terminate`: 'terminateEventDefinition',
* `signal`: 'signalEventDefinition',
* `error`: 'error... |
340,956 | def _incorporate_delins(self):
seq, cds_start, cds_stop, start, end = self._setup_incorporate()
ref = self._var_c.posedit.edit.ref
alt = self._var_c.posedit.edit.alt
ref_length = end - start if ref is not None else 0
alt_length = len(
self._var_c.posedit... | Incorporate delins |
340,957 | def url(self):
endpoint = % self.id
return posixpath.join(self.connection.weburl, endpoint) | Return a kojiweb URL for this resource.
:returns: ``str``, kojiweb URL like
"http://cbs.centos.org/koji/taskinfo?taskID=381617" |
340,958 | def wait_for_next_completion(self, runtime_context):
if runtime_context.workflow_eval_lock is not None:
runtime_context.workflow_eval_lock.wait()
if self.exceptions:
raise self.exceptions[0] | Wait for jobs to finish. |
340,959 | def get_top(self):
tops, errors = self.get_tops()
try:
merged_tops = self.merge_tops(tops)
except TypeError as err:
merged_tops = OrderedDict()
errors.append()
return merged_tops, errors | Returns the high data derived from the top file |
340,960 | def rejected(self, value):
assert (isinstance(value, bool))
self._rejected = value
if value:
self._timeouted = False
self._acknowledged = False
self._cancelled = True | Marks this message as rejected.
:type value: Boolean
:param value: if rejected |
340,961 | def save(self, *args, **kwargs):
super(ModelDiffMixin, self).save(*args, **kwargs)
self.__initial = self._dict | Saves model and set initial state. |
340,962 | async def delete(self):
await r.table_name(self.table_name) \
.get(self.id) \
.delete() \
.run(await conn.get()) | Deletes the model from the database. |
340,963 | def _get_template_dict(template):
if isinstance(template, str):
return parse_template(template)
if isinstance(template, dict):
return copy.deepcopy(template)
raise ValueError() | Parse string template and or copy dictionary template.
:param template: Content of a packaged YAML or JSON SAM template
:type template: str_or_dict
:return: Template as a dictionary
:rtype: dict
:raises ValueError |
340,964 | def process_block(self, block_id, ops, backup=False, expected_snapshots=None):
log.debug("Process block {} ({} virtual transactions)".format(block_id, len(ops)))
if expected_snapshots is None:
expected_snapshots = self.expected_snapshots
if expected_snapshots is No... | Top-level block processing method.
Feed the block and its data transactions
through the implementation, to build up the
implementation's state. Cache the
resulting data to disk.
Return the (consensus hash, ops hash) for this block on success.
Exit on failure. |
340,965 | def tx_extend(partial_tx_hex, new_inputs, new_outputs, blockchain=, **blockchain_opts):
if blockchain == :
return btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts)
else:
raise ValueError(.format(blockchain)) | Add a set of inputs and outputs to a tx.
Return the new tx on success
Raise on error |
340,966 | def execute_template(self, template_name, variables, args=None):
js_text = self.build_js_from_template(template_name, variables)
try:
self.execute_script(js_text, args)
except WebDriverException:
return False
return True | Execute script from a template
@type template_name: str
@value template_name: Script template to implement
@type args: dict
@value args: Dictionary representing command line args
@rtype: bool
@rtype: Success or... |
340,967 | def _handle_repos(self, root):
ElementTree.SubElement(root, "key").text = "repos"
repos_array = ElementTree.SubElement(root, "array")
jss_server = JSS(url=self.url, user=self.user, password=self.password,
ssl_verify=self.verify, suppress_warnings=True)... | Handle repo configuration. |
340,968 | def geocode(
self,
query,
max_results=25,
set_back=0,
location_descriptor=,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
):
params = {: self.format_string % query}
if set_back != 0:
params[] = set... | Return a location point by address.
:param str query: The address or query you wish to geocode.
:param int max_results: The maximum number of resutls to request.
:param float set_back: The distance to move the accessPoint away
from the curb (in meters) and towards the interior of ... |
340,969 | def JSONEncoder_newdefault(kind=[, , , ]):
JSONEncoder_olddefault = json.JSONEncoder.default
def JSONEncoder_wrapped(self, o):
if ( in kind) and isinstance(o, UUID):
return str(o)
if ( in kind) and isinstance(o, datetime):
return str(o)
if ( in kind... | JSON Encoder newdfeault is a wrapper capable of encoding several kinds
Usage:
from codenerix.helpers import JSONEncoder_newdefault
JSONEncoder_newdefault() |
340,970 | def calculate_metrics(molecules, ensemble_lookup, filename, options):
metric_List = []
sort_order =
score_structure = classification.make_score_structure(molecules, ensemble_lookup[filename])
auc_structure = classification.make_auc_structure(score_structure)
auc = classificatio... | Determine the virtual screening performance of the ensemble
:param molecules: list [mol_object_1, mol_object_2, .... ]
:param ensemble: tuple (receptor_x, receptor_y, .... )
:param options: interface object that makes command line arguments available.
:return: |
340,971 | def quick_url(comment):
def to_id(fullname):
return fullname.split(, 1)[1]
return (
.format(comment.subreddit.display_name, to_id(comment.link_id),
comment.id)) | Return the URL for the comment without fetching its submission. |
340,972 | def serialize(self, value, **kwargs):
kwargs.update({: kwargs.get(, True)})
if self.serializer is not None:
return self.serializer(value, **kwargs)
if value is None:
return None
serial_list = [self.prop.serialize(val, **kwargs)
for ... | Return a serialized copy of the tuple |
340,973 | def get_fields_with_visibility(self, visibility, mode="add"):
ar = self.get_ar()
mv = api.get_view("ar_add_manage", context=ar)
mv.get_field_order()
out = []
for field in mv.get_fields_with_visibility(visibility, mode):
visible = self.is_field_v... | Return the AR fields with the current visibility |
340,974 | def ensure_private_dir_exists(app_name):
path = private_dir_path(app_name)
if not os.path.exists(path):
os.makedirs(path)
else:
if not os.path.isdir(path):
raise PrivateDirConflictError | Ensures that the private directory exists and is a directory.
:param str app_name: the name of the app |
340,975 | def open(self, name, attrs=None, *, close=False):
self._pad()
self._writer.startElement(_normalize_name(name), _normalize_attrs(attrs))
self._newline()
self._open_elements.append(name)
if close:
self.close() | Writes an opening element.
:name: the name of the element
:attrs: a dict of attributes
:close: if True, close will be called immediately after writing the element |
340,976 | def sct_report_string(report):
ret = []
namespaces = {"svrl": "http://purl.oclc.org/dsdl/svrl"}
for index, failed_assert_el in enumerate(
report.findall("svrl:failed-assert", namespaces=namespaces)
):
ret.append(
"{}. {}".format(
index + 1,
... | Return a human-readable string representation of the error report
returned by lxml's schematron validator. |
340,977 | def __tableStringParser(self, tableString):
error = []
header = []
decisions = []
if tableString.split() == []:
error.append()
else:
tableString = tableString.split()
newData = []
for element in tableString:
if element.strip():
newData.append(element)
for element in newData[0].sp... | Will parse and check tableString parameter for any invalid strings.
Args:
tableString (str): Standard table string with header and decisions.
Raises:
ValueError: tableString is empty.
ValueError: One of the header element is not unique.
ValueError: Missing data value.
ValueError: Missing parent dat... |
340,978 | def _blank_param_value(value):
sval = str(value)
if sval.isspace():
before, after = "", sval
else:
match = re.search(r"^(\s*).*?(\s*)$", sval, FLAGS)
before, after = match.group(1), match.group(2)
value.nodes = [Text(before), Text(after)] | Remove the content from *value* while keeping its whitespace.
Replace *value*\\ 's nodes with two text nodes, the first containing
whitespace from before its content and the second containing whitespace
from after its content. |
340,979 | def update(self, data):
for key, value in data.items():
setattr(self, key, value) | Update the current memory record with the given data dict.
Args:
data (dict): Data dictionary to update the record attributes with. |
340,980 | def dispatch(self, receiver):
super(ColumnsPatchedEvent, self).dispatch(receiver)
if hasattr(receiver, ):
receiver._columns_patched(self) | Dispatch handling of this event to a receiver.
This method will invoke ``receiver._columns_patched`` if it exists. |
340,981 | def _sanity_check(self):
if any(self.m1 < 0.0):
raise ValueError("Mass 1 is negative.")
if any(self.m2 < 0.0):
raise ValueError("Mass 2 is negative.")
if any(self.z <= 0.0):
raise ValueError("Redshift is zero or negative.")
if any(self.dist ... | Check if parameters are okay.
Sanity check makes sure each parameter is within an allowable range.
Raises:
ValueError: Problem with a specific parameter. |
340,982 | def modify_class(original_class, modifier_class, override=True):
modifier_methods = inspect.getmembers(modifier_class, inspect.ismethod)
for method_tuple in modifier_methods:
name = method_tuple[0]
method = method_tuple[1]
if isinstance(method, types.UnboundMethodType... | Adds class methods from modifier_class to original_class.
If override is True existing methods in original_class are overriden by those provided by modifier_class. |
340,983 | def get(self, request, *args, **kwargs):
self.widget = self.get_widget_or_404()
self.term = kwargs.get(, request.GET.get(, ))
self.object_list = self.get_queryset()
context = self.get_context_data()
return JsonResponse({
: [
{
... | Return a :class:`.django.http.JsonResponse`.
Example::
{
'results': [
{
'text': "foo",
'id': 123
}
],
'more': true
} |
340,984 | def _set_ether_stats_entry(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("ether_stats_index",ether_stats_entry.ether_stats_entry, yang_name="ether-stats-entry", rest_name="stats", parent=self, is_container=, user_ordered=False, path_hel... | Setter method for ether_stats_entry, mapped from YANG variable /interface/fortygigabitethernet/rmon/collection/ether_stats_entry (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ether_stats_entry is considered as a private
method. Backends looking to populate this vari... |
340,985 | def experiments_predictions_attachments_create(self, experiment_id, run_id, resource_id, filename, mime_type=None):
if self.experiments_get(experiment_id) is None:
return None
return self.predictions.create_data_file_attachment(
run_id,
resource_id,
... | Attach a given data file with a model run. The attached file is
identified by the resource identifier. If a resource with the given
identifier already exists it will be overwritten.
Parameters
----------
experiment_id : string
Unique experiment identifier
mod... |
340,986 | def encode(self):
encoder = LabelEncoder()
values = self.get_as_list()
encoded = encoder.fit_transform(values)
n_columns = len(self.matrix[0])
n_rows = len(self.matrix)
self.matrix = [
encoded[i: i + n_columns]
for i in range(0, n_row... | Encodes matrix
:return: Encoder used |
340,987 | def download_next_song(self, song):
dl_ydl_opts = dict(ydl_opts)
dl_ydl_opts["progress_hooks"] = [self.ytdl_progress_hook]
dl_ydl_opts["outtmpl"] = self.output_format
self.move_next_cache()
self.state =
self.play_empty()
with youtube... | Downloads the next song and starts playing it |
340,988 | def LabelValueTable(self, keys=None):
keys = keys or self.superkey
return super(CliTable, self).LabelValueTable(keys) | Return LabelValue with FSM derived keys. |
340,989 | def associate(self, model):
self._parent.set_attribute(self._foreign_key, model.get_key())
self._parent.set_attribute(self._morph_type, model.get_morph_name())
return self._parent.set_relation(
self._relation, Result(model, self, self._parent)
) | Associate the model instance to the given parent.
:type model: orator.Model
:rtype: orator.Model |
340,990 | async def sunionstore(self, dest, keys, *args):
res = await self.sunion(keys, *args)
await self.delete(dest)
return await self.sadd(dest, *res) | Store the union of sets specified by ``keys`` into a new
set named ``dest``. Returns the number of keys in the new set.
Cluster impl:
Use sunion() --> Dlete dest key --> store result in dest key
Operation is no longer atomic. |
340,991 | def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
count: int =None, min: float=None, max: float=None, std_dev: float=None,
properties: Dict[str, object]=None) -> NotImplemented:
self._client.track_metric(name, value, type, count... | Send information about a single metric data point that was captured for the application.
:param name: The name of the metric that was captured.
:param value: The value of the metric that was captured.
:param type: The type of the metric. (defaults to: TelemetryDataPointType.aggregation`)
... |
340,992 | def describe_features(self, traj):
feature_descs = []
for dihed_type in self.types:
feature_descs.extend(dict_maker(zippy))
return feature_descs | Return a list of dictionaries describing the dihderal features.
Parameters
----------
traj : mdtraj.Trajectory
The trajectory to describe
Returns
-------
feature_descs : list of dict
Dictionary describing each feature with the following informati... |
340,993 | def __request_except(self, requestId, exc, set_and_forget=True):
try:
with self.__requests:
if set_and_forget:
req = self.__requests.pop(requestId)
else:
req = self.__requests[requestId]
except KeyError:
... | Set exception (if not None) for the given request and (optionally) remove from internal cache & setting its
event |
340,994 | def _oversized_subqueries(
self,
coordinate,
radiusArcsec):
self.log.info()
import math
smallerRadiusArcsec = radiusArcsec / 2.
print "Calculating 7 sub-disks for coordinates %(coordinate)s, with smaller search radius of %(smallerRadiusArcse... | *subdivide oversized query*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _oversized_subqueries method
- @review: when complete add logging |
340,995 | def endpoint_absent(name, region=None, profile=None, interface=None, **connection_args):
t exist in Keystone catalog
name
The name of the service whose endpoints should not exist
region (optional)
The region of the endpoint. Defaults to ``RegionOne``.
interface
The interface ... | Ensure that the endpoint for a service doesn't exist in Keystone catalog
name
The name of the service whose endpoints should not exist
region (optional)
The region of the endpoint. Defaults to ``RegionOne``.
interface
The interface type, which describes the visibility
of ... |
340,996 | def determine_file_extension_based_on_format(format_specifier):
if format_specifier == FMT_INI:
return
if format_specifier == FMT_DELIMITED:
return
if format_specifier == FMT_XML:
return
if format_specifier == FMT_JSON:
return
if format_specifier == FMT_YAML:
return
raise ValueError(.format(forma... | returns file extension string |
340,997 | def get_temp_filename(suffix=None):
file = tempfile.mkstemp(suffix=suffix or "", prefix="temp_", dir=os.getcwd())
os.close(file[0])
return file[1] | return a string in the form of temp_X, where X is a large integer |
340,998 | def get_children(self):
key = self.CHILDREN_KEY % self.pk
children = super(Page, self).get_children()
return children | Cache superclass result |
340,999 | def get_appointment_group(self, appointment_group):
from canvasapi.appointment_group import AppointmentGroup
appointment_group_id = obj_or_id(
appointment_group, "appointment_group", (AppointmentGroup,)
)
response = self.__requester.request(
,
... | Return single Appointment Group by id
:calls: `GET /api/v1/appointment_groups/:id \
<https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_
:param appointment_group: The ID of the appointment group.
:type appointment_group: :class:`canvasapi.ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.