Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
379,000 | def is_square_matrix(mat):
mat = np.array(mat)
if mat.ndim != 2:
return False
shape = mat.shape
return shape[0] == shape[1] | Test if an array is a square matrix. |
379,001 | def _login(session):
resp = session.get(LOGIN_URL, params=_get_params(session.auth.locale))
parsed = BeautifulSoup(resp.text, HTML_PARSER)
csrf = parsed.find(CSRF_FIND_TAG, CSRF_FIND_ATTR).get(VALUE_ATTR)
resp = session.post(LOGIN_URL, {
: session.auth.username,
: session.auth.passw... | Login to UPS. |
379,002 | def view_sbo(self):
sbo_url = self.sbo_url.replace("/slackbuilds/", "/repository/")
br1, br2, fix_sp = "", "", " "
if self.meta.use_colors in ["off", "OFF"]:
br1 = "("
br2 = ")"
fix_sp = ""
print("")
self.msg.template(78)
pr... | View slackbuild.org |
379,003 | def match(self, path):
match = self._re.search(path)
if match is None:
return None
kwargs_indexes = match.re.groupindex.values()
args_indexes = [i for i in range(1, match.re.groups + 1)
if i not in kwargs_indexes]
args = [match.group... | Return route handler with arguments if path matches this route.
Arguments:
path (str): Request path
Returns:
tuple or None: A tuple of three items:
1. Route handler (callable)
2. Positional arguments (list)
3. Keyword arguments (dict)
... |
379,004 | def del_application(self, application, sync=True):
LOGGER.debug("Team.del_application")
if not sync:
self.app_2_rm.append(application)
else:
if application.id is None:
application.sync()
if self.id is not None and application.id is not... | delete application from this team
:param application: the application to be deleted from this team
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the application object on list to be removed on next save().
:return: |
379,005 | def dataframe(self):
fields_to_include = {
: self.abbreviation,
: self.assist_percentage,
: self.assists,
: self.away_losses,
: self.away_wins,
: self.block_percentage,
: self.blocks,
: self.conference,
... | Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string abbreviation of the
team, such as 'PURDUE'. |
379,006 | def DictReader(file_obj, columns=None):
footer = _read_footer(file_obj)
keys = columns if columns else [s.name for s in
footer.schema if s.type]
for row in reader(file_obj, columns):
yield OrderedDict(zip(keys, row)) | Reader for a parquet file object.
This function is a generator returning an OrderedDict for each row
of data in the parquet file. Nested values will be flattend into the
top-level dict and can be referenced with '.' notation (e.g. 'foo' -> 'bar'
is referenced as 'foo.bar')
:param file_obj: the fil... |
379,007 | def restore_event(self, requestId):
with self.__requests:
if requestId not in self.__requests:
self.__requests[requestId] = RequestEvent(requestId)
return True
return False | restore an event based on the requestId.
For example if the user app had to shutdown with pending requests.
The user can rebuild the Events they were waiting for based on the requestId(s). |
379,008 | def on_persist_completed(self, block):
if len(self._events_to_write):
addr_db = self.db.prefixed_db(NotificationPrefix.PREFIX_ADDR)
block_db = self.db.prefixed_db(NotificationPrefix.PREFIX_BLOCK)
contract_db = self.db.prefixed_db(NotificationPrefix.PREFIX_CONTRACT)
... | Called when a block has been persisted to disk. Used as a hook to persist notification data.
Args:
block (neo.Core.Block): the currently persisting block |
379,009 | def create_json_archive(self):
archive_data = {"packets": self.recv_msgs,
"dataset": self.dataset_name,
"num_packets": len(self.recv_msgs),
"created": rnow()}
self.write_to_file(archive_data,
sel... | create_json_archive |
379,010 | def smart_convert(original, colorkey, pixelalpha):
tile_size = original.get_size()
threshold = 127
try:
px = pygame.mask.from_surface(original, threshold).count()
except:
return original.convert_alpha()
if px == tile_size[0] * tile_size[1]:
... | this method does several tests on a surface to determine the optimal
flags and pixel format for each tile surface.
this is done for the best rendering speeds and removes the need to
convert() the images on your own |
379,011 | def run(self, executable: Executable,
memory_map: Dict[str, List[Union[int, float]]] = None) -> np.ndarray:
self.qam.load(executable)
if memory_map:
for region_name, values_list in memory_map.items():
for offset, value in enumerate(values_list):
... | Run a quil executable. If the executable contains declared parameters, then a memory
map must be provided, which defines the runtime values of these parameters.
:param executable: The program to run. You are responsible for compiling this first.
:param memory_map: The mapping of declared parame... |
379,012 | def edit( cls, record, parent = None, uifile = , commit = True ):
dlg = QDialog(parent)
dlg.setWindowTitle( % record.schema().name())
cls = record.schema().property(, cls)
widget = cls(dlg)
if ( uifile ):
... | Prompts the user to edit the inputed record.
:param record | <orb.Table>
parent | <QWidget>
:return <bool> | accepted |
379,013 | def __set_rouge_dir(self, home_dir=None):
if not home_dir:
self._home_dir = self.__get_rouge_home_dir_from_settings()
else:
self._home_dir = home_dir
self.save_home_dir()
self._bin_path = os.path.join(self._home_dir, )
self.data_dir = os.path.... | Verfify presence of ROUGE-1.5.5.pl and data folder, and set
those paths. |
379,014 | def thumbnail(self, size):
if size in self.thumbnail_sizes:
return self.thumbnails.get(str(size))
else:
raise ValueError(.format(size)) | Get the thumbnail filename for a given size |
379,015 | def getContactItems(self, person):
return person.store.query(
EmailAddress,
EmailAddress.person == person) | Return all L{EmailAddress} instances associated with the given person.
@type person: L{Person} |
379,016 | def setColor(self, typeID, color):
self._connection._beginMessage(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_COLOR, typeID, 1 + 1 + 1 + 1 + 1)
self._connection._string += struct.pack("!BBBBB", tc.TYPE_COLOR, int(
color[0]), int(color[1]), int(color[2]), int(color[3]))
... | setColor(string, (integer, integer, integer, integer)) -> None
Sets the color of this type. |
379,017 | def create_db_user(username, password=None, flags=None):
flags = flags or u
sudo(u % (flags, username), user=u)
if password:
change_db_user_password(username, password) | Create a databse user. |
379,018 | def search(
self, query, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, answer_count=None, country_code=None, count=None, freshness=None, market="en-us", offset=None, promote=None, response_filter=None, safe_search=None, set_lang=None, text_decorations=Non... | The Web Search API lets you send a search query to Bing and get back
search results that include links to webpages, images, and more.
:param query: The user's search query term. The term may not be empty.
The term may contain Bing Advanced Operators. For example, to limit
results to a... |
379,019 | def _encrypt_message(self, msg, nonce, timestamp=None):
xml =
nonce = to_binary(nonce)
timestamp = to_binary(timestamp) or to_binary(int(time.time()))
encrypt = self.__pc.encrypt(to_text(msg), self.__id)
signature = get_sha1_signature(self.__token, timestamp, n... | 将公众号回复用户的消息加密打包
:param msg: 待回复用户的消息,xml格式的字符串
:param nonce: 随机串,可以自己生成,也可以用URL参数的nonce
:param timestamp: 时间戳,可以自己生成,也可以用URL参数的timestamp,如为None则自动用当前时间
:return: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串 |
379,020 | def getBurstingColumnsStats(self):
traceData = self.tm.mmGetTraceUnpredictedActiveColumns().data
resetData = self.tm.mmGetTraceResets().data
countTrace = []
for x in xrange(len(traceData)):
if not resetData[x]:
countTrace.append(len(traceData[x]))
mean = numpy.mean(countTrace)
... | Gets statistics on the Temporal Memory's bursting columns. Used as a metric
of Temporal Memory's learning performance.
:return: mean, standard deviation, and max of Temporal Memory's bursting
columns over time |
379,021 | def _method_response_handler(self, response: Dict[str, Any]):
code = response.get("CODE")
if code in (200, 300):
self._result_handler(response)
else:
asyncio.ensure_future(self._gen_result_handler(response)) | 处理200~399段状态码,为对应的响应设置结果.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True |
379,022 | def _brute_force_install_pip(self):
if os.path.exists(self.pip_installer_fname):
logger.debug("Using pip installer from %r", self.pip_installer_fname)
else:
logger.debug(
"Installer for pip not found in %r, downloading it", self.pip_installer_fname)
... | A brute force install of pip itself. |
379,023 | def find_one(self, cls, id):
one = self._find(cls, {"_id": id})
if not one:
return None
return one[0] | Required functionality. |
379,024 | def from_packed(cls, packed):
packed = np.asarray(packed)
check_ndim(packed, 2)
check_dtype(packed, )
packed = memoryview_safe(packed)
data = genotype_array_unpack_diploid(packed)
return cls(data) | Unpack diploid genotypes that have been bit-packed into single
bytes.
Parameters
----------
packed : ndarray, uint8, shape (n_variants, n_samples)
Bit-packed diploid genotype array.
Returns
-------
g : GenotypeArray, shape (n_variants, n_samples, 2)
... |
379,025 | def radio_status_encode(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed):
return MAVLink_radio_status_message(rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed) | Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi : Remote signal strength (uint8_t)
txbuf : Remaining free buffer space in percent. (uint8_t)
... |
379,026 | def wait_until_visible(self, timeout=None):
try:
self.utils.wait_until_element_visible(self, timeout)
except TimeoutException as exception:
parent_msg = " and parent locator ".format(self.parent) if self.parent else
msg = "Page element of type with locator ... | Search element and wait until it is visible
:param timeout: max time to wait
:returns: page element instance |
379,027 | def process_rdfgraph(self, rg, ont=None):
if ont is None:
ont = Ontology()
subjs = list(rg.subjects(RDF.type, SKOS.ConceptScheme))
if len(subjs) == 0:
logging.warning("No ConceptScheme")
else:
ont.id = self._uri2id... | Transform a skos terminology expressed in an rdf graph into an Ontology object
Arguments
---------
rg: rdflib.Graph
graph object
Returns
-------
Ontology |
379,028 | def plot_macadam(
ellipse_scaling=10,
plot_filter_positions=False,
plot_standard_deviations=False,
plot_rgb_triangle=True,
plot_mesh=True,
n=1,
xy_to_2d=lambda xy: xy,
axes_labels=("x", "y"),
):
dir_path = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(di... | See <https://en.wikipedia.org/wiki/MacAdam_ellipse>,
<https://doi.org/10.1364%2FJOSA.32.000247>. |
379,029 | def _handle_tag_definetext2(self):
obj = _make_object("DefineText2")
self._generic_definetext_parser(obj, self._get_struct_rgba)
return obj | Handle the DefineText2 tag. |
379,030 | def exit_config_mode(self, exit_config="return", pattern=r">"):
return super(HuaweiBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | Exit configuration mode. |
379,031 | def classmethod(self, encoding):
encoding = ensure_bytes(encoding)
typecodes = parse_type_encoding(encoding)
typecodes.insert(1, b)
encoding = b.join(typecodes)
def decorator(f):
def objc_class_method(objc_cls, objc_cmd, *args):
py_c... | Function decorator for class methods. |
379,032 | def column_signs_(self):
if self._always_positive():
return np.ones(self.n_features)
self.unhasher.recalculate_attributes()
return self.unhasher.column_signs_ | Return a numpy array with expected signs of features.
Values are
* +1 when all known terms which map to the column have positive sign;
* -1 when all known terms which map to the column have negative sign;
* ``nan`` when there are both positive and negative known terms
for this... |
379,033 | def get_distance_metres(aLocation1, aLocation2):
dlat = aLocation2.lat - aLocation1.lat
dlong = aLocation2.lon - aLocation1.lon
return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5 | Returns the ground distance in metres between two LocationGlobal objects.
This method is an approximation, and will not be accurate over large distances and close to the
earth's poles. It comes from the ArduPilot test code:
https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py |
379,034 | def download(self):
mp3_directory = self._pre_download()
self.data.swifter.apply(func=lambda arg: self._download(*arg, mp3_directory), axis=1, raw=True)
return mp3_directory | Downloads the data associated with this instance
Return:
mp3_directory (os.path): The directory into which the associated mp3's were downloaded |
379,035 | def download_task(url, headers, destination, download_type=):
bot.verbose("Downloading %s from %s" % (download_type, url))
file_name = "%s.%s" % (destination,
next(tempfile._get_candidate_names()))
tar_download = download(url, file_name, headers=headers)
try:... | download an image layer (.tar.gz) to a specified download folder.
This task is done by using local versions of the same download functions
that are used for the client.
core stream/download functions of the parent client.
Parameters
==========
image_id: the shasum id of the la... |
379,036 | def function(self, x, y, sigma0, Rs, center_x=0, center_y=0):
x_ = x - center_x
y_ = y - center_y
r = np.sqrt(x_**2 + y_**2)
if isinstance(r, int) or isinstance(r, float):
r = max(self._s, r)
else:
r[r < self._s] = self._s
X = r / Rs
... | lensing potential
:param x:
:param y:
:param sigma0: sigma0/sigma_crit
:param a:
:param s:
:param center_x:
:param center_y:
:return: |
379,037 | def add(self, *args, **kwargs):
for cookie in args:
self.all_cookies.append(cookie)
if cookie.name in self:
continue
self[cookie.name] = cookie
for key, value in kwargs.items():
cookie = self.cookie_class(key, val... | Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as the cookie name and the
value as the ... |
379,038 | def get_ranks(self):
if self._use_non_text_features:
return self._term_doc_matrix.get_metadata_freq_df()
else:
return self._term_doc_matrix.get_term_freq_df() | Returns
-------
pd.DataFrame |
379,039 | def _fix_example_namespace(self):
example_prefix =
idgen_prefix = idgen.get_id_namespace_prefix()
if example_prefix not in self._input_namespaces:
return
self._input_namespaces[example_prefix] = idgen.EXAMPLE_NAMESPACE.name | Attempts to resolve issues where our samples use
'http://example.com/' for our example namespace but python-stix uses
'http://example.com' by removing the former. |
379,040 | def process_warn_strings(arguments):
def _capitalize(s):
if s[:5] == "scons":
return "SCons" + s[5:]
else:
return s.capitalize()
for arg in arguments:
elems = arg.lower().split()
enable = 1
if elems[0] == :
enable = 0
... | Process string specifications of enabling/disabling warnings,
as passed to the --warn option or the SetOption('warn') function.
An argument to this option should be of the form <warning-class>
or no-<warning-class>. The warning class is munged in order
to get an actual class name from the classes... |
379,041 | def add(self, component: Union[Component, Sequence[Component]]) -> None:
try:
self[Span(*self._available_cell())] = component
except NoUnusedCellsError:
span = list(self._spans.keys())[-1]
self._spans[span] += component | Add a widget to the grid in the next available cell.
Searches over columns then rows for available cells.
Parameters
----------
components : bowtie._Component
A Bowtie widget instance. |
379,042 | def flatatt(self, **attr):
cs =
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = .join(classes)
attr[] = cs
if css:
attr[] = .join(... | Return a string with attributes to add to the tag |
379,043 | def _process_thread(self, client):
system_type = client.data.os_info.system
print(.format(system_type))
artifact_list = []
if self.artifacts:
print(.format(self.artifacts))
artifact_list = self.artifacts
else:
default_artifacts = self.artifact_registry.get(system_type, N... | Process a single GRR client.
Args:
client: a GRR client object. |
379,044 | def serialize(self, queryset, **options):
self.options = options
self.stream = options.get("stream", StringIO())
self.primary_key = options.get("primary_key", None)
self.properties = options.get("properties")
self.geometry_field = options.get("geometry_field", "geom")
... | Serialize a queryset. |
379,045 | def in_file(self, filename: str) -> Iterator[FunctionDesc]:
yield from self.__filename_to_functions.get(filename, []) | Returns an iterator over all of the functions definitions that are
contained within a given file. |
379,046 | def _write_response(self, response):
status = .format(response[],
response[],
responses[response[]])
self.logger.debug("Responding status: ", status.strip())
self._write_transport(status)
if in respo... | Write the response back to the client
Arguments:
response -- the dictionary containing the response. |
379,047 | def set_python(self, value):
if not self.multiselect:
if value and not isinstance(value, list):
value = [value]
value = value or []
records = SortedDict()
for record in value:
self.validate_value(record)
records[record.id] =... | Expect list of record instances, convert to a SortedDict for internal representation |
379,048 | def qteRemoveMode(self, mode: str):
for idx, item in enumerate(self._qteModeList):
if item[0] == mode:
self._qteModeList.remove(item)
item[2].hide()
item[2].deleteLater()
self._qteUpdateLabelWidths()
... | Remove ``mode`` and associated label.
If ``mode`` does not exist then nothing happens and the method
returns **False**, otherwise **True**.
|Args|
* ``pos`` (**QRect**): size and position of new window.
* ``windowID`` (**str**): unique window ID.
|Returns|
* ... |
379,049 | def send_emission(self):
if self._emit_queue.empty():
return
emit = self._emit_queue.get()
emit() | emit and remove the first emission in the queue |
379,050 | def check_tx_with_confirmations(self, tx_hash: str, confirmations: int) -> bool:
tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash)
if not tx_receipt or tx_receipt[] is None:
return False
else:
return (self.w3.eth.blockNumber - tx_receipt[]) >= ... | Check tx hash and make sure it has the confirmations required
:param w3: Web3 instance
:param tx_hash: Hash of the tx
:param confirmations: Minimum number of confirmations required
:return: True if tx was mined with the number of confirmations required, False otherwise |
379,051 | def pad_length(s):
padding_chars = [
u,
u,
u,
u,
u,
u,
u,
u,
u,
u,
u,
u,
]
padding_generator = itertools.cycle(padding_chars)
target_lengths = {
six.moves.range(1, 11)... | Appends characters to the end of the string to increase the string length per
IBM Globalization Design Guideline A3: UI Expansion.
https://www-01.ibm.com/software/globalization/guidelines/a3.html
:param s: String to pad.
:returns: Padded string. |
379,052 | def entries(self):
timer = Timer()
passwords = []
logger.info("Scanning %s ..", format_path(self.directory))
listing = self.context.capture("find", "-type", "f", "-name", "*.gpg", "-print0")
for filename in split(listing, "\0"):
basename, extension = os.path.... | A list of :class:`PasswordEntry` objects. |
379,053 | def get_fun(fun):
with _get_serv(ret=None, commit=True) as cur:
sql =
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = salt.utils.json.loads(full_ret)
return ret | Return a dict of the last function called for all minions |
379,054 | def set(self, key, value, *, section=DataStoreDocumentSection.Data):
key_notation = .join([section, key])
try:
self._delete_gridfs_data(self._data_from_dotnotation(key_notation,
default=None))
except KeyError:... | Store a value under the specified key in the given section of the document.
This method stores a value into the specified section of the workflow data store
document. Any existing value is overridden. Before storing a value, any linked
GridFS document under the specified key is deleted.
... |
379,055 | def has_column(self, table, column):
column = column.lower()
return column in list(map(lambda x: x.lower(), self.get_column_listing(table))) | Determine if the given table has a given column.
:param table: The table
:type table: str
:type column: str
:rtype: bool |
379,056 | def encode_ulid(value: hints.Buffer) -> str:
length = len(value)
if length != 16:
raise ValueError(.format(length))
encoding = ENCODING
return \
encoding[(value[0] & 224) >> 5] + \
encoding[value[0] & 31] + \
encoding[(value[1] & 248) >> 3] + \
encoding[((v... | Encode the given buffer to a :class:`~str` using Base32 encoding.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is not meant for arbitrary encoding.
:param value: Bytes to encode
:type value: :class:`~bytes`, :class:`~bytearray`, or :cl... |
379,057 | def addRnaQuantificationSet(self):
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
if self._args.name is None:
name = getNameFromPath(self._args.filePath)
else:
name = self._args.name
rnaQuantificationSet = rna_quant... | Adds an rnaQuantificationSet into this repo |
379,058 | def EXTRA_LOGGING(self):
input_text = get(, )
modules = input_text.split()
if input_text:
modules = input_text.split()
modules = [x.split() for x in modules]
else:
modules = []
return modules | lista modulos con los distintos niveles a logear y su
nivel de debug
Por ejemplo:
[Logs]
EXTRA_LOGGING = oscar.paypal:DEBUG, django.db:INFO |
379,059 | def update(self, allow_partial=True, force=False, **kwargs):
if kwargs:
self.__init__(partial=allow_partial, force=force, **kwargs)
return not self._partial
if not force and CACHE.get(hash(self)):
cached = CACHE[hash(self)]
for field in self._SIM... | Updates record and returns True if record is complete after update, else False. |
379,060 | def order(self, *args):
if not args:
return self
orders = []
o = self.orders
if o:
orders.append(o)
for arg in args:
if isinstance(arg, model.Property):
orders.append(datastore_query.PropertyOrder(arg._name, _ASC))
elif isinstance(arg, datastore_query.Order)... | Return a new Query with additional sort order(s) applied. |
379,061 | def signature(self, value):
h = HMAC(self.key, self.digest, backend=settings.CRYPTOGRAPHY_BACKEND)
h.update(force_bytes(value))
return h | :type value: any
:rtype: HMAC |
379,062 | def find_packages_parents_requirements_dists(pkg_names, working_set=None):
dists = []
targets = set(pkg_names)
for dist in find_packages_requirements_dists(pkg_names, working_set):
if dist.project_name in targets:
continue
dists.append(dist)
return dists | Leverages the `find_packages_requirements_dists` but strip out the
distributions that matches pkg_names. |
379,063 | def split_token(output):
output = ensure_tuple(output)
flags, i, len_output, data_allowed = set(), 0, len(output), True
while i < len_output and isflag(output[i]):
if output[i].must_be_first and i:
raise ValueError("{} flag must be first.".format(output[i]))
if i and outpu... | Split an output into token tuple, real output tuple.
:param output:
:return: tuple, tuple |
379,064 | def failure_count(self):
return len([i for i, result in enumerate(self.data) if result.failure]) | Amount of failed test cases in this list.
:return: integer |
379,065 | def save_neighbour_info(self, cache_dir, mask=None, **kwargs):
if cache_dir:
mask_name = getattr(mask, , None)
filename = self._create_cache_filename(
cache_dir, mask=mask_name, **kwargs)
LOG.info(, filename)
cache = self._read_resampler_a... | Cache resampler's index arrays if there is a cache dir. |
379,066 | def list_user_access(self, user):
user = utils.get_name(user)
uri = "/%s/%s/databases" % (self.uri_base, user)
try:
resp, resp_body = self.api.method_get(uri)
except exc.NotFound as e:
raise exc.NoSuchDatabaseUser("User does not exist." % user)
d... | Returns a list of all database names for which the specified user
has access rights. |
379,067 | def _align_header(header, alignment, width, visible_width, is_multiline=False,
width_fn=None):
"Pad string header to width chars given known visible_width of the header."
if is_multiline:
header_lines = re.split(_multiline_codes, header)
padded_lines = [_align_header(h, alignme... | Pad string header to width chars given known visible_width of the header. |
379,068 | def save(self, path="speech"):
if self._data is None:
raise Exception("There's nothing to save")
extension = "." + self.__params["format"]
if os.path.splitext(path)[1] != extension:
path += extension
with open(path, "wb") as f:
for d in self... | Save data in file.
Args:
path (optional): A path to save file. Defaults to "speech".
File extension is optional. Absolute path is allowed.
Returns:
The path to the saved file. |
379,069 | def _collect_masters_map(self, response):
while True:
try:
data, addr = self._socket.recvfrom(0x400)
if data:
if addr not in response:
response[addr] = []
response[addr].append(data)
... | Collect masters map from the network.
:return: |
379,070 | def makeParameterTable(filename, params):
macro_panel = "\multicolumn{3}{c}{\\textbf{Macroeconomic Parameters} } \n"
macro_panel += "\\\\ $\\kapShare$ & " + "{:.2f}".format(params.CapShare) + " & Capital.texw_1.texw_2.texw') as f:
f.write(slides2_output)
f.close() | Makes the parameter table for the paper, saving it to a tex file in the tables folder.
Also makes two partial parameter tables for the slides.
Parameters
----------
filename : str
Name of the file in which to save output (in the tables directory).
Suffix .tex is automatically added.
... |
379,071 | def do_bash_complete(cli, prog_name):
comp_words = os.environ[]
try:
cwords = shlex.split(comp_words)
quoted = False
except ValueError:
cwords = split_args(comp_words)
quoted = True
cword = int(os.environ[])
args = cwords[1:cword]
try:
incomplete = ... | Do the completion for bash
Parameters
----------
cli : click.Command
The main click Command of the program
prog_name : str
The program name on the command line
Returns
-------
bool
True if the completion was successful, False otherwise |
379,072 | def set(self, stype, sid, fields):
if stype not in [, , ]:
raise SyntaxError("{} is not a valid type for set. Should be one of: votelist, vnlist or wishlist.".format(stype))
command = "{} {} {}".format(stype, id, ujson.dumps(fields))
data = self.connection.send_command(, co... | Send a request to the API to modify something in the database if logged in.
:param str stype: What are we modifying? One of: votelist, vnlist, wishlist
:param int sid: The ID that we're modifying.
:param dict fields: A dictionary of the fields and their values
:raises ServerError: Raise... |
379,073 | def to_prettytable(df):
pt = PrettyTable()
pt.field_names = df.columns
for tp in zip(*(l for col, l in df.iteritems())):
pt.add_row(tp)
return pt | Convert DataFrame into ``PrettyTable``. |
379,074 | def swap(tokens, maxdist=2):
assert maxdist >= 2
tokens = list(tokens)
if maxdist > len(tokens):
maxdist = len(tokens)
l = len(tokens)
for i in range(0,l - 1):
for permutation in permutations(tokens[i:i+maxdist]):
if permutation != tuple(tokens[i:i+maxdist]):
... | Perform a swap operation on a sequence of tokens, exhaustively swapping all tokens up to the maximum specified distance. This is a subset of all permutations. |
379,075 | def implied_local_space(*, arg_index=None, keys=None):
from qnet.algebra.core.hilbert_space_algebra import (
HilbertSpace, LocalSpace)
def args_to_local_space(cls, args, kwargs):
if isinstance(args[arg_index], LocalSpace):
new_args = args
else:
if i... | Return a simplification that converts the positional argument
`arg_index` from (str, int) to a subclass of :class:`.LocalSpace`, as well
as any keyword argument with one of the given keys.
The exact type of the resulting Hilbert space is determined by
the `default_hs_cls` argument of :func:`init_algebr... |
379,076 | def cancel(self, consumer_tag):
if not self.channel.connection:
return
self.channel.basic_cancel(consumer_tag) | Cancel a channel by consumer tag. |
379,077 | def update_dependency(self, tile, depinfo, destdir=None):
if destdir is None:
destdir = os.path.join(tile.folder, , , depinfo[])
has_version = False
had_version = False
if os.path.exists(destdir):
has_version = True
had_version = True
... | Attempt to install or update a dependency to the latest version.
Args:
tile (IOTile): An IOTile object describing the tile that has the dependency
depinfo (dict): a dictionary from tile.dependencies specifying the dependency
destdir (string): An optional folder into which to... |
379,078 | def set_parameter(name, parameter, value, path=None):
*
if not exists(name, path=path):
return None
cmd =
if path:
cmd += .format(pipes.quote(path))
cmd += .format(name, parameter, value)
ret = __salt__[](cmd, python_shell=False)
if ret[] != 0:
return False
else... | Set the value of a cgroup parameter for a container.
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.set_parameter name parameter value |
379,079 | def get_group_category(self, category):
category_id = obj_or_id(category, "category", (GroupCategory,))
response = self.__requester.request(
,
.format(category_id)
)
return GroupCategory(self.__requester, response.json()) | Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
:type category: :class:`canvasapi.group.GroupCategory... |
379,080 | def sharedInterfaces():
def get(self):
if not self.sharedInterfaceNames:
return ()
if self.sharedInterfaceNames == ALL_IMPLEMENTED_DB:
I = implementedBy(self.sharedItem.__class__)
L = list(I)
T = tuple(L)
... | This attribute is the public interface for code which wishes to discover
the list of interfaces allowed by this Share. It is a list of
Interface objects. |
379,081 | def lower(self):
if self._reaction in self._view._flipped:
return -super(FlipableFluxBounds, self).upper
return super(FlipableFluxBounds, self).lower | Lower bound |
379,082 | def match_tracks(self, set_a, set_b, closest_matches=False):
costs = self.track_cost_matrix(set_a, set_b) * 100
min_row_costs = costs.min(axis=1)
min_col_costs = costs.min(axis=0)
good_rows = np.where(min_row_costs < 100)[0]
good_cols = np.where(min_col_costs < 100)[0]
... | Find the optimal set of matching assignments between set a and set b. This function supports optimal 1:1
matching using the Munkres method and matching from every object in set a to the closest object in set b.
In this situation set b accepts multiple matches from set a.
Args:
set_a... |
379,083 | def build_polygons(self, polygons):
if not polygons:
return
if not isinstance(polygons, (list, tuple)):
raise AttributeError()
for points in polygons:
if isinstance(points, dict):
self.add_polygon(**points)
elif isinstance... | Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tup... |
379,084 | def untrigger(queue, trigger=_c.FSQ_TRIGGER):
trigger_path = fsq_path.trigger(queue, trigger=trigger)
_queue_ok(os.path.dirname(trigger_path))
try:
os.unlink(trigger_path)
except (OSError, IOError, ), e:
if e.errno != errno.ENOENT:
raise FSQConfigError(e.errno, wrap_io_o... | Uninstalls the trigger for the specified queue -- if a queue has no
trigger, this function is a no-op. |
379,085 | def assert_200(response, max_len=500):
if response.status_code == 200:
return
raise ValueError(
"Response was {}, not 200:\n{}\n{}".format(
response.status_code,
json.dumps(dict(response.headers), indent=2),
response.content[:max_len])) | Check that a HTTP response returned 200. |
379,086 | def read_pure_water_absorption_from_file(self, file_name):
lg.info()
try:
self.a_water = self._read_iop_from_file(file_name)
except:
lg.exception( + file_name) | Read the pure water absorption from a csv formatted file
:param file_name: filename and path of the csv file |
379,087 | def encoded_to_array(encoded):
if not isinstance(encoded, dict):
if is_sequence(encoded):
as_array = np.asanyarray(encoded)
return as_array
else:
raise ValueError()
encoded = decode_keys(encoded)
dtype = np.dtype(encoded[])
if in encoded:
... | Turn a dictionary with base64 encoded strings back into a numpy array.
Parameters
------------
encoded : dict
Has keys:
dtype: string of dtype
shape: int tuple of shape
base64: base64 encoded string of flat array
binary: decode result coming from numpy.tostring
R... |
379,088 | def toy_heaviside(seed=default_seed, max_iters=100, optimize=True, plot=True):
try:import pods
except ImportError:print()
data = pods.datasets.toy_linear_1d_classification(seed=seed)
Y = data[][:, 0:1]
Y[Y.flatten() == -1] = 0
kernel = GPy.kern.RBF(1)
likelihood = GPy.likelihoods... | Simple 1D classification example using a heavy side gp transformation
:param seed: seed value for data generation (default is 4).
:type seed: int |
379,089 | def RABC(self):
A = self.raw_data[-3]*2 - self.raw_data[-6]
B = self.raw_data[-2]*2 - self.raw_data[-5]
C = self.raw_data[-1]*2 - self.raw_data[-4]
return % (A,B,C) | Return ABC
轉折點 ABC |
379,090 | def complete(self, uio, dropped=False):
if self.dropped and not dropped:
return
for end in [, ]:
if getattr(self, end):
continue
uio.show( + end + )
uio.show()
uio.show(self.summary())
try:
... | Query for all missing information in the transaction |
379,091 | def get_finder(import_path):
finder_class = import_string(import_path)
if not issubclass(finder_class, BaseProcessesFinder):
raise ImproperlyConfigured(
.format(finder_class, BaseProcessesFinder))
return finder_class() | Get a process finder. |
379,092 | def as_dict(self):
d = {"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"structure": self.structure.as_dict(),
"frequencies": list(self.frequencies),
"densities": list(self.densities),
"pdos": []}
if len(s... | Json-serializable dict representation of CompletePhononDos. |
379,093 | def to_fmt(self) -> str:
infos = fmt.end(";\n", [])
s = fmt.sep(, [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block(, , [s]))
infos.lsdata.append("events:" + repr(self.events))
infos.lsdata.append(
... | Provide a useful representation of the register. |
379,094 | def create_simple_tear_sheet(returns,
positions=None,
transactions=None,
benchmark_rets=None,
slippage=None,
estimate_intraday=,
live_start_date=N... | Simpler version of create_full_tear_sheet; generates summary performance
statistics and important plots as a single image.
- Plots: cumulative returns, rolling beta, rolling Sharpe, underwater,
exposure, top 10 holdings, total holdings, long/short holdings,
daily turnover, transaction time dist... |
379,095 | def check_support_user_port(cls, hw_info_ex):
return ((hw_info_ex.m_dwProductCode & PRODCODE_MASK_PID) != ProductCode.PRODCODE_PID_BASIC) \
and ((hw_info_ex.m_dwProductCode & PRODCODE_MASK_PID) != ProductCode.PRODCODE_PID_RESERVED1) \
and cls.check_version_is_equal_or_high... | Checks whether the module supports a user I/O port.
:param HardwareInfoEx hw_info_ex:
Extended hardware information structure (see method :meth:`get_hardware_info`).
:return: True when the module supports a user I/O port, otherwise False.
:rtype: bool |
379,096 | async def send_photo(self, path, entity):
await self.send_file(
entity, path,
progress_callback=self.upload_progress_callback
)
print() | Sends the file located at path to the desired entity as a photo |
379,097 | def solve_limited(self, assumptions=[]):
if self.maplesat:
if self.use_timer:
start_time = time.clock()
def_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_DFL)
self.status = pysolvers.maplechrono_solve_lim(self.maplesat, ass... | Solve internal formula using given budgets for conflicts and
propagations. |
379,098 | def remove_properties(self):
if self.features_layer is not None:
self.features_layer.remove_properties()
if self.header is not None:
self.header.remove_lp() | Removes the property layer (if exists) of the object (in memory) |
379,099 | def quaternion_from_axis_rotation(angle, axis):
out = np.zeros(4, dtype=float)
if axis == :
out[1] = 1
elif axis == :
out[2] = 1
elif axis == :
out[3] = 1
else:
raise ValueError()
out *= math.sin(angle/2.0)
out[0] = math.cos(angle/2.0)
return Quaterni... | Return quaternion for rotation about given axis.
Args:
angle (float): Angle in radians.
axis (str): Axis for rotation
Returns:
Quaternion: Quaternion for axis rotation.
Raises:
ValueError: Invalid input axis. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.