Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
372,100 | def main(argv=None):
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
args = default_parser().parse_args(argv)
arg... | Entry point for the `simpl` command. |
372,101 | def _patch_prebuild(cls):
orig_run = cls.run
def new_run(self):
self.run_command("prebuild")
orig_run(self)
cls.run = new_run | Patch a setuptools command to depend on `prebuild` |
372,102 | def _dcm_to_q(self, dcm):
assert(dcm.shape == (3, 3))
q = np.zeros(4)
tr = np.trace(dcm)
if tr > 0:
s = np.sqrt(tr + 1.0)
q[0] = s * 0.5
s = 0.5 / s
q[1] = (dcm[2][1] - dcm[1][2]) * s
q[2] = (dcm[0][2] - dcm[2][0]) * s... | Create q from dcm
Reference:
- Shoemake, Quaternions,
http://www.cs.ucr.edu/~vbz/resources/quatut.pdf
:param dcm: 3x3 dcm array
returns: quaternion array |
372,103 | def error(message, *args, **kwargs):
if in kwargs:
end = kwargs[]
else:
end =
if len(args) == 0:
sys.stderr.write(message)
else:
sys.stderr.write(message % args)
sys.stderr.write(end)
sys.stderr.flush() | write a message to stderr |
372,104 | def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
super(LongInteger, self).read(istream, kmip_version=kmip_version)
if self.length is not LongInteger.LENGTH:
raise exceptions.InvalidPrimitiveLength(
"invalid long integer length read; "
... | Read the encoding of the LongInteger from the input stream.
Args:
istream (stream): A buffer containing the encoded bytes of a
LongInteger. Usually a BytearrayStream object. Required.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version wi... |
372,105 | def do_repl(self):
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter
self.options.quiet = False
proxy = self... | REPL for rTorrent XMLRPC commands. |
372,106 | def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec",
name_prefix="__proper_motion_gal2eq",
right_ascension_galactic_pole=192.85,
... | Transform/rotate proper motions from galactic to equatorial coordinates.
Inverse of :py:`add_virtual_columns_proper_motion_eq2gal` |
372,107 | def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
workspace = _get_workspace(workspace, resolver, me... | Create a workspace for mets_url and run MP CLI through it |
372,108 | def transformByDistance(wV, subModel, alphabetSize=4):
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | transform wV by given substitution matrix |
372,109 | def array_to_image(
arr, mask=None, img_format="png", color_map=None, **creation_options
):
img_format = img_format.lower()
if len(arr.shape) < 3:
arr = np.expand_dims(arr, axis=0)
if color_map is not None and isinstance(color_map, dict):
arr = _apply_discrete_colormap(arr, color_... | Translate numpy ndarray to image buffer using GDAL.
Usage
-----
tile, mask = rio_tiler.utils.tile_read(......)
with open('test.jpg', 'wb') as f:
f.write(array_to_image(tile, mask, img_format="jpeg"))
Attributes
----------
arr : numpy ndarray
Image array to encode.
mask:... |
372,110 | def _Import(self, t):
self._fill("import ")
for i, (name,asname) in enumerate(t.names):
if i != 0:
self._write(", ")
self._write(name)
if asname is not None:
self._write(" as "+asname) | Handle "import xyz.foo". |
372,111 | def stop_apppool(name):
*MyTestPool
ps_cmd = [, r"".format(name)]
cmd_ret = _srvmgr(ps_cmd)
return cmd_ret[] == 0 | Stop an IIS application pool.
.. versionadded:: 2017.7.0
Args:
name (str): The name of the App Pool to stop.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_iis.stop_apppool name='MyTestPool' |
372,112 | def register(cls, associations, backend, style_aliases={}):
if backend not in cls.registry:
cls.registry[backend] = {}
cls.registry[backend].update(associations)
groups = Options._option_groups
if backend not in cls._options:
cls._options[backend] = Opti... | Register the supplied dictionary of associations between
elements and plotting classes to the specified backend. |
372,113 | def spev(t_int, C, deg, x, cov_C=None, M_spline=False, I_spline=False, n=0):
C = scipy.asarray(C, dtype=float)
t_int = scipy.asarray(t_int, dtype=float)
if (t_int != scipy.sort(t_int)).any():
raise ValueError("Knots must be in increasing order!")
if n > deg:
return scipy.z... | Evaluate a B-, M- or I-spline with the specified internal knots, order and coefficients.
`deg` boundary knots are appended at both sides of the domain.
The zeroth order basis functions are modified to ensure continuity at the
right-hand boundary.
Note that the I-splines include the :math:... |
372,114 | def _find_lib_path():
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
amalgamation_lib_path = os.path.join(curr_path, )
if os.path.exists(amalgamation_lib_path) and os.path.isfile(amalgamation_lib_path):
lib_path = [amalgamation_lib_path]
return lib_path
e... | Find mxnet library. |
372,115 | def _fromiter(it, dtype, count, progress, log):
if progress > 0:
it = _iter_withprogress(it, progress, log)
if count is not None:
a = np.fromiter(it, dtype=dtype, count=count)
else:
a = np.fromiter(it, dtype=dtype)
return a | Utility function to load an array from an iterator. |
372,116 | def enrich_sentences_with_NLP(self, all_sentences):
if not self.has_NLP_support():
raise NotImplementedError(
f"Language {self.lang} not available in spacy beyond tokenization"
)
if len(all_sentences) == 0:
return
if self.model.has... | Enrich a list of fonduer Sentence objects with NLP features. We merge
and process the text of all Sentences for higher efficiency.
:param all_sentences: List of fonduer Sentence objects for one document
:return: |
372,117 | def emit(
self,
record):
self.debug_log()
try:
record = self.format_record(
record)
except Exception as e:
self.write_log(
% str(e))
self.write_log(
traceback.format_exc())
... | emit
Emit handler for queue-ing message for
the helper thread to send to Splunk on the ``self.sleep_interval``
:param record: LogRecord to send to Splunk
https://docs.python.org/3/library/logging.html |
372,118 | def preprocessFastqs(fastqFNs, seqFNPrefix, offsetFN, abtFN, areUniform, logger):
<DIR>/seqs.npy<DIR>/offsets.npy<DIR>/about.npy
seqArray = []
tempFileId = 0
seqsPerFile = 1000000
maxSeqLen = -1
numSeqs = 0
subSortFNs = []
for fnID, fn in enumerate(fastqFNs):
... | This function does the grunt work behind string extraction for fastq files
@param fastqFNs - a list of .fq filenames for parsing
@param seqFNPrefix - this is always of the form '<DIR>/seqs.npy'
@param offsetFN - this is always of the form '<DIR>/offsets.npy'
@param abtFN - this is always of the form '<D... |
372,119 | def parse_url(url):
scheme, dest = url.split()
host = None
ssl_context = None
if scheme == :
host, port = dest.split() if in dest else (dest, 2101)
elif scheme == :
host, port = dest.split() if in dest else (dest, 2601)
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
... | Parse a Elk connection string |
372,120 | def site_url(self, url):
regex = re.compile(
r
r
r
r
r
r
r, re.IGNORECASE)
if re.match(, url):
if re.search(regex, url):
self.__site_url = url
... | URL setter and validator for site_url property.
Parameters:
url (str): URL of on Moebooru/Danbooru based sites.
Raises:
PybooruError: When URL scheme or URL are invalid. |
372,121 | def get_version(extension, workflow_file):
if extension == and two_seven_compatible(workflow_file):
return
elif extension == :
return yaml.load(open(workflow_file))[]
else:
try:
return [l.lstrip() for l in workflow_file.splitlines() if in l.split()][0]
... | Determines the version of a .py, .wdl, or .cwl file. |
372,122 | def main():
config = context.config
config.set_main_option("sqlalchemy.url", config.get_main_option())
run_migrations_online(config) | main. |
372,123 | def fetch_ticker(self) -> Ticker:
return self._fetch(, self.market.code)(self._ticker)() | Fetch the market ticker. |
372,124 | def expand_to_one_hot(data,expand = True,use_alternative=False):
header_dict = {:0,:1,:2,:3,:4,:5,:6,:7,:8,:9,:10}
new_data = []
for entry in data:
temp = {}
if expand == True:
if entry[header_dict["SEX1"]] == "FEMALE":
temp[] = 1
else:
temp[] = 0
if entry[header_dict["ALCABUS"]] == :... | with open("brandon_testing/test_"+str(time.clock())+".csv","w") as f:
writer = csv.writer(f,delimiter=",")
for row in fin:
writer.writerow(row) |
372,125 | def create_game(
self,
map_name,
bot_difficulty=sc_pb.VeryEasy,
bot_race=sc_common.Random,
bot_first=False):
self._controller.ping()
map_inst = maps.get(map_name)
map_data = map_inst.data(self._run_config)
if map_name not in self._saved_maps:
self._controll... | Create a game, one remote agent vs the specified bot.
Args:
map_name: The map to use.
bot_difficulty: The difficulty of the bot to play against.
bot_race: The race for the bot.
bot_first: Whether the bot should be player 1 (else is player 2). |
372,126 | def dict_copy(func):
"copy dict args, to avoid modifying caller's copy"
def proxy(*args, **kwargs):
new_args = []
new_kwargs = {}
for var in kwargs:
if isinstance(kwargs[var], dict):
new_kwargs[var] = dict(kwargs[var])
else:
new_kwa... | copy dict args, to avoid modifying caller's copy |
372,127 | def get_json_result(results, n=10):
s = []
last = -1
for res in results[:min(len(results), n)]:
if res[] < last*0.5 and res[] < 0.05:
break
if res[] < 0.01:
break
s.append(res)
last = res[]
return json.dumps(s) | Return the top `n` results as a JSON list.
>>> results = [{'probability': 0.65,
... 'whatever': 'bar'},
... {'probability': 0.21,
... 'whatever': 'bar'},
... {'probability': 0.05,
... 'whatever': 'bar'},]
>>> get_json_result(results, ... |
372,128 | async def readline(self) -> bytes:
while True:
line = self._serial_instance.readline()
if not line:
await asyncio.sleep(self._asyncio_sleep_time)
else:
return line | Reads one line
>>> # Keeps waiting for a linefeed incase there is none in the buffer
>>> await test.readline()
:returns: bytes forming a line |
372,129 | def _normalize_tabular_data(tabular_data, headers):
if hasattr(tabular_data, "keys") and hasattr(tabular_data, "values"):
if hasattr(tabular_data.values, "__call__"):
keys = tabular_data.keys()
rows = list(izip_longest(*tabular_data.values()))
el... | Transform a supported data type to a list of lists, and a list of headers.
Supported tabular data types:
* list-of-lists or another iterable of iterables
* list of named tuples (usually used with headers="keys")
* 2D NumPy arrays
* NumPy record arrays (usually used with headers="keys")
* d... |
372,130 | def set_frequency(self, host, sem=None, interval=None):
sem = sem or self.sem
interval = self.interval if interval is None else interval
frequency = Frequency(sem, interval, host)
frequencies = {host: frequency}
self.update_frequency(frequencies)
return ... | Set frequency for host with sem and interval. |
372,131 | def unblock_pin(ctx, puk, new_pin):
controller = ctx.obj[]
if not puk:
puk = click.prompt(
, default=, show_default=False,
hide_input=True, err=True)
if not new_pin:
new_pin = click.prompt(
, default=,
show_default=False, hide_input=True, ... | Unblock the PIN.
Reset the PIN using the PUK code. |
372,132 | def __get_html(self, body=None):
output = []
output.append("<html>")
output.append("<head>")
for javascript in (self.__jquery_javascript,
self.__crittercism_javascript,
self.__reporter_javascript):
output.append(... | Returns the html content with given body tag content.
:param body: Body tag content.
:type body: unicode
:return: Html.
:rtype: unicode |
372,133 | def commitAndCloseEditor(self):
editor = self.sender()
try:
self.commitData.emit(editor)
except AttributeError:
pass
self.closeEditor.emit(editor, QAbstractItemDelegate.NoHint) | Commit and close editor |
372,134 | def _dictlist_to_lists(dl, *keys):
atestbazazbawowbtestzazwow
lists = []
for k in keys:
lists.append([])
for item in dl:
for i, key in enumerate(keys):
x = item[key]
if isinstance(x, unicode):
x = str(x)
lists[i].append(x)
return li... | convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300]) |
372,135 | def union_overlapping(intervals):
disjoint_intervals = []
for interval in intervals:
if disjoint_intervals and disjoint_intervals[-1].overlaps(interval):
disjoint_intervals[-1] = disjoint_intervals[-1].union(interval)
else:
disjoint_intervals.append(interval)
r... | Union any overlapping intervals in the given set. |
372,136 | def tqdm(self, desc, total, leave, initial=0):
return tqdm_notebook(desc=desc, total=total, leave=leave, initial=initial) | Extension point. Override to provide custom options to tqdm_notebook initializer.
:param desc: Description string
:param total: Total number of updates
:param leave: Leave progress bar when done
:return: new progress bar
:param initial: Initial counter state |
372,137 | def _variable_inputs(self, op):
if op.name not in self._vinputs:
self._vinputs[op.name] = np.array([t.op in self.between_ops or t in self.model_inputs for t in op.inputs])
return self._vinputs[op.name] | Return which inputs of this operation are variable (i.e. depend on the model inputs). |
372,138 | def move(self, x, y):
self._x = int(round(x * 2, 0))
self._y = int(round(y * 2, 0)) | Move the drawing cursor to the specified position.
:param x: The column (x coord) for the location to check.
:param y: The line (y coord) for the location to check. |
372,139 | def prepare_inventory(self):
if self.inventory is None:
self.inventory = os.path.join(self.private_data_dir, "inventory") | Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. |
372,140 | def _get_game_number(cls, gid_path):
game_number = str(gid_path[len(gid_path)-2:len(gid_path)-1])
if game_number.isdigit():
return int(game_number)
else:
for char in reversed(gid_path):
if char.isdigit():
return int(char)
... | Game Number
:param gid_path: game logs directory path
:return: game number(int) |
372,141 | def get_context(request, context=None):
if context is None:
context = {}
network_config = getattr(settings, , {})
context[] = policy.check(
(("compute", "os_compute_api:servers:create"),), request)
context[] = _quota_exceeded(request, )
context[] = policy.check(
(("net... | Returns common context data for network topology views. |
372,142 | def shutdown(self):
if self.sock:
self.sock.close()
self.sock = None
self.connected = False | close socket, immediately. |
372,143 | def get_writer_factory_for(self, name, *, format=None):
return self.get_factory_for(WRITER, name, format=format) | Returns a callable to build a writer for the provided filename, eventually forcing a format.
:param name: filename
:param format: format
:return: type |
372,144 | def pvpc_procesa_datos_dia(_, response, verbose=True):
try:
d_data = response[]
df = _process_json_pvpc_hourly_data(pd.DataFrame(d_data))
return df, 0
except Exception as e:
if verbose:
print(.format(e))
return None, -2 | Procesa la información JSON descargada y forma el dataframe de los datos de un día. |
372,145 | def dumpLines(self):
for i, line in enumerate(self.lines):
logger.debug("Line %d:", i)
logger.debug(line.dumpFragments()) | For debugging dump all line and their content |
372,146 | def check_exists(self):
response = self.repo.api.http_request(, self.uri)
self.status_code = response.status_code
if self.status_code == 200:
self.exists = True
elif self.status_code == 410:
self.exists = False
elif self.status_code == 404:
self.exists = False
return self.exists | Check if resource exists, update self.exists, returns
Returns:
None: sets self.exists |
372,147 | def acknowledge_time(self):
if (self.is_acknowledged and
self._proto.acknowledgeInfo.HasField()):
return parse_isostring(self._proto.acknowledgeInfo.acknowledgeTime)
return None | Processor time when the alarm was acknowledged.
:type: :class:`~datetime.datetime` |
372,148 | def long_click(self, duration=2.0):
try:
duration = float(duration)
except ValueError:
raise ValueError(.format(repr(duration)))
pos_in_percentage = self.get_position(self._focus or )
self.poco.pre_action(, self, pos_in_percentage)
ret = self.po... | Perform the long click action on the UI element(s) represented by the UI proxy. If this UI proxy represents a
set of UI elements, the first one in the set is clicked and the anchor point of the UI element is used as the
default one. Similar to click but press the screen for the given time interval and... |
372,149 | def quantize_weights(full_precision_model,
nbits,
quantization_mode="linear",
sample_data=None,
**kwargs):
qmode_mapping = {
"linear": _QUANTIZATION_MODE_LINEAR_QUANTIZATION,
"kmeans": _QUANTIZATION_MODE_LOOKUP_... | Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param full_precision_model: MLModel
Model which will be converted to half precision. Currently conversion
for only neural network models is supported. If a pipeline model is
passed in th... |
372,150 | def exclude_matches(self, matches):
for match in matches:
for exclude_pattern in self.exclude_patterns:
if re.match(exclude_pattern, match) is not None:
break
else:
yield match | Filter any matches that match an exclude pattern.
:param matches: a list of possible completions |
372,151 | def max(self):
if "max" not in self.attrs.keys():
def f(dataset, s):
return np.nanmax(dataset[s])
self.attrs["max"] = np.nanmax(list(self.chunkwise(f).values()))
return self.attrs["max"] | Maximum, ignorning nans. |
372,152 | def sample(self, size=1):
samples = []
for i in range(size):
xi = self._r_xi_rv.rvs(size=1)
S_xi = skew(xi)
R_sample = scipy.linalg.expm(S_xi)
t_sample = self._t_rv.rvs(size=1)
samples.append(RigidTransform(rotation=R_samp... | Sample rigid transform random variables.
Parameters
----------
size : int
number of sample to take
Returns
-------
:obj:`list` of :obj:`RigidTransform`
sampled rigid transformations |
372,153 | def subalignment(alnfle, subtype, alntype="fasta"):
aln = AlignIO.read(alnfle, alntype)
alnlen = aln.get_alignment_length()
nseq = len(aln)
subaln = None
subalnfile = alnfle.rsplit(".", 1)[0] + "_{0}.{1}".format(subtype, alntype)
if subtype == "synonymous":
for j in range( 0, alnle... | Subset synonymous or fourfold degenerate sites from an alignment
input should be a codon alignment |
372,154 | def _get_unit_factor(cls, unit):
try:
if isinstance(unit, str):
unit = cls.UNIT_FACTOR_NAMES[unit]
return cls.UNIT_FACTORS[unit]
except KeyError:
raise UnsupportedUnitError() | Returns the unit factor depending on the unit constant
:param int unit: the unit of the factor requested
:returns: a function to convert the raw sensor value to the given unit
:rtype: lambda function
:raises UnsupportedUnitError: if the unit is not supported |
372,155 | def certificate_issuer_id(self, certificate_issuer_id):
if certificate_issuer_id is None:
raise ValueError("Invalid value for `certificate_issuer_id`, must not be `None`")
if certificate_issuer_id is not None and len(certificate_issuer_id) > 32:
raise ValueError("Invalid... | Sets the certificate_issuer_id of this CreateCertificateIssuerConfig.
The ID of the certificate issuer.
:param certificate_issuer_id: The certificate_issuer_id of this CreateCertificateIssuerConfig.
:type: str |
372,156 | def count_replica(self, partition):
return sum(1 for b in partition.replicas if b in self.brokers) | Return count of replicas of given partition. |
372,157 | def frac_vol_floc_initial(ConcAluminum, ConcClay, coag, material):
return ((conc_precipitate(ConcAluminum, coag).magnitude/coag.PrecipDensity)
+ (ConcClay / material.Density)) | Return the volume fraction of flocs initially present, accounting for both suspended particles and coagulant precipitates.
:param ConcAluminum: Concentration of aluminum in solution
:type ConcAluminum: float
:param ConcClay: Concentration of particle in suspension
:type ConcClay: float
:param coag:... |
372,158 | def _wrap_result(self, func):
def wrapper(*args):
result = func(*args)
if hasattr(result, ) and not isinstance(result, etree._Element):
return [self._wrap_element(element) for element in result]
else:
return self._wrap_element(result)
... | Wrap result in Parser instance |
372,159 | def has_length(self, value, q, strict=False):
value = stringify(value)
if value is not None:
if len(value) == q:
return
self.shout(, strict, value, q) | if value has a length of q |
372,160 | def _parse_keys(row, line_num):
link =
none_keys = [key for key in row.keys() if key is None]
if none_keys:
fail(
.format(line_num), link)
elif not row.get():
fail(
.format(line_num), link) | Perform some sanity checks on they keys
Each key in the row should not be named None cause
(that's an overrun). A key named `type` MUST be
present on the row & have a string value.
:param row: dict
:param line_num: int |
372,161 | def add_post_process(self, name, post_process, description=""):
self._pprocesses.append(PostProcess(name=name,
function=post_process,
description=description))
self._pprocesses[-1].function(self) | add a post-process
Parameters
----------
name : str
name of the post-traitment
post_process : callback (function of a class with a __call__ method
or a streamz.Stream).
this callback have to accept the simulation state as paramete... |
372,162 | def group_get(auth=None, **kwargs):
***
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_group(**kwargs) | Get a single group
CLI Example:
.. code-block:: bash
salt '*' keystoneng.group_get name=group1
salt '*' keystoneng.group_get name=group2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.group_get name=0e4febc2a5ab4f2c8f374b054162506d |
372,163 | def __add_flag (rule_or_module, variable_name, condition, values):
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, property_set.PropertySet)
assert is_iterable(values) and all(
isinstance(v, (basestring, type(Non... | Adds a new flag setting with the specified values.
Does no checking. |
372,164 | def do_down(self, arg):
if self.curindex + 1 == len(self.stack):
self.error()
return
try:
count = int(arg or 1)
except ValueError:
self.error( % arg)
return
if count < 0:
newframe = len(self.stack) - 1
... | d(own) [count]
Move the current frame count (default one) levels down in the
stack trace (to a newer frame). |
372,165 | def FromBinary(cls, record_data, record_count=1):
if len(record_data) < ReflashTileRecord.RecordHeaderLength:
raise ArgumentError("Record was too short to contain a full reflash record header",
length=len(record_data), header_length=ReflashTileRecord.RecordH... | Create an UpdateRecord subclass from binary record data.
This should be called with a binary record blob (NOT including the
record type header) and it will decode it into a ReflashTileRecord.
Args:
record_data (bytearray): The raw record data that we wish to parse
i... |
372,166 | def check_bearer_validity(self, token: dict, connect_mtd) -> dict:
warnings.warn(
"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.",
DeprecationWarning,
)
if datetime.now() < token.get("expires_at"):
... | Check API Bearer token validity.
Isogeo ID delivers authentication bearers which are valid during
a certain time. So this method checks the validity of the token
with a 30 mn anticipation limit, and renews it if necessary.
See: http://tools.ietf.org/html/rfc6750#section-2
FI: 2... |
372,167 | def new_comment(self, string, start, end, line):
prefix = line[:start[1]]
if prefix.strip():
self.current_block.add(string, start, end, line)
else:
block = Comment(start[0], end[0], string)
self.blocks.append(block)
... | Possibly add a new comment.
Only adds a new comment if this comment is the only thing on the line.
Otherwise, it extends the noncomment block. |
372,168 | def is_usable(host, port, timeout=3):
try:
proxies = {
: % (host, port),
: % (host, port)
}
requests.get(, proxies=proxies, timeout=timeout)
except HTTPError:
print(, host, port)
return False
else:
print(, host, port)
ret... | 测试代理是否可用
params
----------
host ip地址
port 端口号
timeout 默认值为3,通过设置这个参数可以过滤掉一些速度慢的代理
example
----------
is_usable('222.180.24.13', '808', timeout=3) |
372,169 | def dollars_to_cents(s, allow_negative=False):
if not s:
return
if isinstance(s, string_types):
s = .join(RE_NUMBER.findall(s))
dollars = int(round(float(s) * 100))
if not allow_negative and dollars < 0:
raise ValueError()
return dollars | Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_cents('$1')
100
>>> dollars_to_cents('1')
... |
372,170 | def get_credits_by_section_and_regid(section, regid):
deprecation("Use get_credits_by_reg_url")
except InvalidOperation:
pass | Returns a uw_sws.models.Registration object
for the section and regid passed in. |
372,171 | def access_func(self, id_, lineno, scope=None, default_type=None):
assert default_type is None or isinstance(default_type, symbols.TYPEREF)
result = self.get_entry(id_, scope)
if result is None:
if default_type is None:
if global_.DEFAULT_IMPLICIT_TYPE == TY... | Since ZX BASIC allows access to undeclared functions, we must allow
and *implicitly* declare them if they are not declared already.
This function just checks if the id_ exists and returns its entry if so.
Otherwise, creates an implicit declared variable entry and returns it. |
372,172 | def append(self, cert):
if not isinstance(cert, x509.Certificate):
if not isinstance(cert, byte_cls):
raise TypeError(pretty_message(
,
type_name(cert)
))
if pem.detect(cert):
_, _, cert = p... | Appends a cert to the path. This should be a cert issued by the last
cert in the path.
:param cert:
An asn1crypto.x509.Certificate object
:return:
The current ValidationPath object, for chaining |
372,173 | def process_user_input(self):
user_input = self.get_input()
try:
num = int(user_input)
except Exception:
return
if 0 < num < len(self.items) + 1:
self.current_option = num - 1
self.select()
return user_input | Gets the next single character and decides what to do with it |
372,174 | def truncate(text, length=50, ellipsis=):
text = nativestring(text)
return text[:length] + (text[length:] and ellipsis) | Returns a truncated version of the inputted text.
:param text | <str>
length | <int>
ellipsis | <str>
:return <str> |
372,175 | def minimum_pitch(self):
pitch = self.pitch
minimal_pitch = []
for p in pitch:
minimal_pitch.append(min(p))
return min(minimal_pitch) | Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction. |
372,176 | def date_time(self, tzinfo=None, end_datetime=None):
return datetime(1970, 1, 1, tzinfo=tzinfo) + \
timedelta(seconds=self.unix_time(end_datetime=end_datetime)) | Get a datetime object for a date between January 1, 1970 and now
:param tzinfo: timezone, instance of datetime.tzinfo subclass
:example DateTime('2005-08-16 20:39:21')
:return datetime |
372,177 | def advance(self, length):
new_position = self._position + length
if new_position < 0 or new_position > len(self._data):
raise Exception(
% (length, new_position))
self._position = new_position | Advance the cursor in data buffer 'length' bytes. |
372,178 | def send_command_return_multilines(self, obj, command, *arguments):
index_command = obj._build_index_command(command, *arguments)
return self.chassis_list[obj.chassis].sendQuery(index_command, True) | Send command and wait for multiple lines output. |
372,179 | def run_symmetrized_readout(self, program: Program, trials: int) -> np.ndarray:
flipped_program = _get_flipped_protoquil_program(program)
if trials % 2 != 0:
raise ValueError("Using symmetrized measurement functionality requires that you "
"take an even ... | Run a quil program in such a way that the readout error is made collectively symmetric
This means the probability of a bitstring ``b`` being mistaken for a bitstring ``c`` is
the same as the probability of ``not(b)`` being mistaken for ``not(c)``
A more general symmetrization would guarantee t... |
372,180 | def extract_ranges(index_list, range_size_limit=32):
if not index_list:
return [], []
first = index_list[0]
last = first
ranges = []
singles = []
for i in index_list[1:]:
if i == last + 1 and (last - first) <= range_size_limit:
last = i
else:
... | Extract consecutive ranges and singles from index_list.
Args:
index_list: List of monotone increasing non-negative integers.
range_size_limit: Largest size range to return. If a larger
consecutive range exists it will be returned as multiple
ranges.
Returns:
ranges, singles where ranges is... |
372,181 | def arrow_(self, xloc, yloc, text, orientation="v", arrowstyle=):
try:
arrow = hv.Arrow(
xloc,
yloc,
text,
orientation,
arrowstyle=arrowstyle)
return arrow
except Exception as e:
self.err(e, self.arrow_, "Can not draw arrow chart") | Returns an arrow for a chart. Params: the text, xloc and yloc are
coordinates to position the arrow. Orientation is the way to display
the arrow: possible values are ``[<, ^, >, v]``. Arrow style is the
graphic style of the arrow:
possible values: ``[-, ->, -[, -|>, <->, <|-|>]`` |
372,182 | def delete(self, loc):
self.values = np.delete(self.values, loc, 0)
self.mgr_locs = self.mgr_locs.delete(loc) | Delete given loc(-s) from block in-place. |
372,183 | def create_audio_mp3_profile(apps, schema_editor):
Profile = apps.get_model(, )
Profile.objects.get_or_create(profile_name=AUDIO_MP3_PROFILE) | Create audio_mp3 profile |
372,184 | def _make_association(self, clk=None, rst=None) -> None:
if clk is not None:
assert self._associatedClk is None
self._associatedClk = clk
if rst is not None:
assert self._associatedRst is None
self._associatedRst = rst | Associate this object with specified clk/rst |
372,185 | def _write(self, data):
total_sent = 0
length = len(data)
while total_sent < length:
try:
sent = self.socket.send(data[total_sent:])
except socket.error as (err, msg):
self.connected = False
raise ScratchError("[Err... | Writes string data out to Scratch |
372,186 | def update(cls, cluster_id_label, cluster_info):
conn = Qubole.agent(version="v2")
return conn.put(cls.element_path(cluster_id_label), data=cluster_info) | Update the cluster with id/label `cluster_id_label` using information provided in
`cluster_info`. |
372,187 | def get_path_matching(name):
p = os.path.join(os.path.expanduser("~"), name)
if not os.path.isdir(p):
p = None
drive, folders = os.path.splitdrive(os.getcwd())
folders = folders.split(os.sep)
folders.insert(0, os.sep)
if name in folders:
p = os.... | Get path matching a name.
Parameters
----------
name : string
Name to search for.
Returns
-------
string
Full filepath. |
372,188 | def _pypi_head_package(dependency):
if dependency.specs:
_, version = dependency.specs[0]
url = BASE_PYPI_URL_WITH_VERSION.format(name=dependency.project_name, version=version)
else:
url = BASE_PYPI_URL.format(name=dependency.project_name)
logger.debug("Doing HEAD requests again... | Hit pypi with a http HEAD to check if pkg_name exists. |
372,189 | def download(self, path, file):
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | Download remote file to disk. |
372,190 | def _build_index(self):
datasets_index = {}
distributions_index = {}
fields_index = {}
for dataset_index, dataset in enumerate(self.datasets):
if "identifier" in dataset:
datasets_index[dataset["identifier"]] = {
"datase... | Itera todos los datasets, distribucioens y fields indexandolos. |
372,191 | def get_ajax(self, request, *args, **kwargs):
response_data = self.get_json_response_object(self._datatable)
response = HttpResponse(self.serialize_to_json(response_data),
content_type="application/json")
return response | Called when accessed via AJAX on the request method specified by the Datatable. |
372,192 | def create_network(self):
class_ = getattr(networks, self.network_class)
return class_(max_size=self.quorum) | Create a new network by reading the configuration file. |
372,193 | def __r1_hungarian(self, word, vowels, digraphs):
r1 = ""
if word[0] in vowels:
for digraph in digraphs:
if digraph in word[1:]:
r1 = word[word.index(digraph[-1])+1:]
return r1
for i in range(1, len(word)):
... | Return the region R1 that is used by the Hungarian stemmer.
If the word begins with a vowel, R1 is defined as the region
after the first consonant or digraph (= two letters stand for
one phoneme) in the word. If the word begins with a consonant,
it is defined as the region after the fir... |
372,194 | def delete(self, photo, **kwds):
return self._client.post("/photo/%s/delete.json" %
self._extract_id(photo),
**kwds)["result"] | Endpoint: /photo/<id>/delete.json
Deletes a photo.
Returns True if successful.
Raises a TroveboxError if not. |
372,195 | def extern_project_multi(self, context_handle, val, field_str_ptr, field_str_len):
c = self._ffi.from_handle(context_handle)
obj = c.from_value(val[0])
field_name = self.to_py_str(field_str_ptr, field_str_len)
return c.vals_buf(tuple(c.to_value(p) for p in getattr(obj, field_name))) | Given a Key for `obj`, and a field name, project the field as a list of Keys. |
372,196 | def to_excel(self,
workbook=None,
worksheet=None,
xl_app=None,
clear=True,
rename=True,
resize_columns=True):
from win32com.client import Dispatch, constants, gencache
if xl_app is None:
... | Writes worksheet to an Excel Worksheet COM object.
Requires :py:module:`pywin32` to be installed.
:param workbook: xltable.Workbook this sheet belongs to.
:param worksheet: Excel COM Worksheet instance to write to.
:param xl_app: Excel COM Excel Application to write to.
:param b... |
372,197 | def content(self):
if not self.payload:
return
if self.payload.is_multipart():
message_bytes = mime_to_bytes(
self.payload, 0).replace(b, b)
boundary = b + self.payload.get_boundary().encode()
temp = message_bytes.split(boundary... | Function returns the body of the as2 payload as a bytes object |
372,198 | def parse(out):
jsonret = []
in_json = False
for ln_ in out.split():
if in ln_:
in_json = True
if in_json:
jsonret.append(ln_)
if in ln_:
in_json = False
return salt.utils.json.loads(.join(jsonret)) | Extract json from out.
Parameter
out: Type string. The data returned by the
ssh command. |
372,199 | def filtered_context(context):
ctx = Context(context.opt)
for resource in context.resources():
if resource.child:
continue
if resource.filtered():
ctx.add(resource)
return ctx | Filters a context
This will return a new context with only the resources that
are actually available for use. Uses tags and command line
options to make determination. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.