Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
17,200 | def bind(self, family, type, proto=0):
self.socket = sockets.Socket(family, type, proto)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setblocking(0)
self.socket.bind(self.bind_addr) | Create (or recreate) the actual socket object. |
17,201 | def ValidateLanguageCode(lang, column_name=None, problems=None):
if util.IsEmpty(lang):
return True
bcp47_obj = parser.ParseLanguage(str(lang.lower()))
if not bcp47_obj.wellformed:
if problems:
problems.InvalidValue(column_name, lang,
%
lan... | Validates a non-required language code value using the pybcp47 module:
- if invalid adds InvalidValue error (if problems accumulator is provided)
- distinguishes between 'not well-formed' and 'not valid' and adds error
reasons accordingly
- an empty language code is regarded as valid! Otherwise we mig... |
17,202 | def visit_ListComp(self, node: ast.ListComp) -> Any:
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
return result | Compile the list comprehension as a function and call it. |
17,203 | def remover(self, id_perms):
if not is_valid_int_param(id_perms):
raise InvalidParameterError(
u)
url = + str(id_perms) +
code, xml = self.submit(None, , url)
return self.response(code, xml) | Remove Administrative Permission from by the identifier.
:param id_perms: Identifier of the Administrative Permission. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Administrative Permission is null and invalid.
:raise PermissaoAdmi... |
17,204 | def wait(self):
now = _monotonic()
if now < self._ref:
delay = max(0, self._ref - now)
self.sleep_func(delay)
self._update_ref() | Blocks until the rate is met |
17,205 | def update_file(url, filename):
resp = urlopen(url)
if resp.code != 200:
raise Exception(.format(url))
with open(_get_package_path(filename), ) as fp:
for l in resp:
if not l.startswith(b):
fp.write(l.decode())
print(.format(filename)) | Update the content of a single file. |
17,206 | def CreateMuskingumKfacFile(in_drainage_line,
river_id,
length_id,
slope_id,
celerity,
formula_type,
in_connectivity_file,
o... | r"""
Creates the Kfac file for calibration.
The improved methods using slope to generate values
for Kfac were used here:
Tavakoly, A. A., A. D. Snow, C. H. David, M. L. Follum, D. R. Maidment,
and Z.-L. Yang, (2016) "Continental-Scale River Flow Modeling of the
Mississippi River Basin Using Hi... |
17,207 | def plotConvergenceByObject(results, objectRange, featureRange, numTrials,
linestyle=):
convergence = numpy.zeros((max(featureRange), max(objectRange) + 1))
for r in results:
if r["numFeatures"] in featureRange:
convergence[r["numFeatures"] - 1, r["numObje... | Plots the convergence graph: iterations vs number of objects.
Each curve shows the convergence for a given number of unique features. |
17,208 | def evaluate(self, batchsize):
sum_loss, sum_accuracy = 0, 0
for i in range(0, self.testsize, batchsize):
x = Variable(self.x_test[i: i + batchsize])
y = Variable(self.y_test[i: i + batchsize])
loss = self.model(x, y)
sum_loss += loss.data * batch... | Evaluate how well the classifier is doing. Return mean loss and mean accuracy |
17,209 | def ttfautohint(in_file, out_file, args=None, **kwargs):
arg_list = ["ttfautohint"]
file_args = [in_file, out_file]
if args is not None:
if kwargs:
raise TypeError("Should not provide both cmd args and kwargs.")
rv = subprocess.call(arg_list + args.split() + file_args)
... | Thin wrapper around the ttfautohint command line tool.
Can take in command line arguments directly as a string, or spelled out as
Python keyword arguments. |
17,210 | def get_query_string(environ):
qs = wsgi_get_bytes(environ.get("QUERY_STRING", ""))
return try_coerce_native(url_quote(qs, safe=":&%=+$!*'(),")) | Returns the `QUERY_STRING` from the WSGI environment. This also takes
care about the WSGI decoding dance on Python 3 environments as a
native string. The string returned will be restricted to ASCII
characters.
.. versionadded:: 0.9
:param environ: the WSGI environment object to get the query str... |
17,211 | def block(self, tofile="block.dat"):
with self.client.connect(*self.bestip):
data = self.client.get_and_parse_block_info(tofile)
return self.client.to_df(data) | 获取证券板块信息
:param tofile:
:return: pd.dataFrame or None |
17,212 | def do_lisp(self, subcmd, opts, folder=""):
client = MdClient(self.maildir, filesystem=self.filesystem)
client.lisp(
foldername=folder,
stream=self.stdout,
reverse=getattr(opts, "reverse", False),
since=float(getattr(opts, "since", -1))
... | ${cmd_name}: list messages in the specified folder in JSON format
${cmd_usage} |
17,213 | def createDataport(self, auth, desc, defer=False):
return self._call(, auth, [, desc], defer) | Create a dataport resource.
"format" and "retention" are required
{
"format": "float" | "integer" | "string",
"meta": string = "",
"name": string = "",
"preprocess": list = [],
"public": boolean = false,
... |
17,214 | def ReleaseObject(self, identifier):
if identifier not in self._values:
raise KeyError(.format(
identifier))
cache_value = self._values[identifier]
if not cache_value:
raise RuntimeError(.format(
identifier))
cache_value.DecrementReferenceCount() | Releases a cached object based on the identifier.
This method decrements the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing. |
17,215 | def apply(self, im):
from scipy.ndimage.interpolation import shift
return shift(im, map(lambda x: -x, self.delta), mode=) | Apply an n-dimensional displacement by shifting an image or volume.
Parameters
----------
im : ndarray
The image or volume to shift |
17,216 | def masked(name, runtime=False, root=None):
**
_check_for_unit_changes(name)
root_dir = _root( if runtime else , root)
link_path = os.path.join(root_dir,
,
,
_canonical_unit_name(name))
try:
return os.read... | .. versionadded:: 2015.8.0
.. versionchanged:: 2015.8.5
The return data for this function has changed. If the service is
masked, the return value will now be the output of the ``systemctl
is-enabled`` command (so that a persistent mask can be distinguished
from a runtime mask). If th... |
17,217 | def list_users(self, limit=None, marker=None):
return self._user_manager.list(limit=limit, marker=marker) | Returns a list of the names of all users for this instance. |
17,218 | def build_payment_parameters(amount: Money, client_ref: str) -> PaymentParameters:
merchant_id = web_merchant_id
amount, currency = money_to_amount_and_currency(amount)
refno = client_ref
sign = sign_web(merchant_id, amount, currency, refno)
parameters = PaymentParameters(
merchant_id=... | Builds the parameters needed to present the user with a datatrans payment form.
:param amount: The amount and currency we want the user to pay
:param client_ref: A unique reference for this payment
:return: The parameters needed to display the datatrans form |
17,219 | def gaussian(df, width=0.3, downshift=-1.8, prefix=None):
df = df.copy()
imputed = df.isnull()
for i in mycols:
data = df.iloc[:, i]
mask = data.isnull().values
mean = data.mean(axis=0)
stddev = data.std(axis=0)
m = mean + downshift[i]*stddev
s = st... | Impute missing values by drawing from a normal distribution
:param df:
:param width: Scale factor for the imputed distribution relative to the standard deviation of measured values. Can be a single number or list of one per column.
:param downshift: Shift the imputed values down, in units of std. dev. Can ... |
17,220 | def get_stock_quote(self, code_list):
code_list = unique_and_normalize_list(code_list)
if not code_list:
error_str = ERROR_STR_PREFIX + "the type of code_list param is wrong"
return RET_ERROR, error_str
query_processor = self._get_sync_query_processor(
... | 获取订阅股票报价的实时数据,有订阅要求限制。
对于异步推送,参见StockQuoteHandlerBase
:param code_list: 股票代码列表,必须确保code_list中的股票均订阅成功后才能够执行
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ===============... |
17,221 | def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):
if maskvol is not None:
indices = (roivol == roivalue) * (maskvol > 0)
else:
indices = roivol == roivalue
if datavol.ndim == 4:
ts = datavol[indices, :]
else:
ts = datavol[in... | Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.
The ROI can be masked by `maskvol`.
Parameters
----------
datavol: numpy.ndarray
4D timeseries volume or a 3D volume to be partitioned
roivol: numpy.ndarray
3D ROIs volume
roivalue: int or ... |
17,222 | def generate(self, model_len=None, model_width=None):
if model_len is None:
model_len = Constant.MODEL_LEN
if model_width is None:
model_width = Constant.MODEL_WIDTH
pooling_len = int(model_len / 4)
graph = Graph(self.input_shape, False)
temp_inp... | Generates a CNN.
Args:
model_len: An integer. Number of convolutional layers.
model_width: An integer. Number of filters for the convolutional layers.
Returns:
An instance of the class Graph. Represents the neural architecture graph of the generated model. |
17,223 | def _load_params(params, logger=logging):
if isinstance(params, str):
cur_path = os.path.dirname(os.path.realpath(__file__))
param_file_path = os.path.join(cur_path, params)
logger.info( % param_file_path)
save_dict = nd_load(param_file_path)
arg_params = {}
aux_... | Given a str as a path to the .params file or a pair of params,
returns two dictionaries representing arg_params and aux_params. |
17,224 | def namedb_query_execute( cur, query, values, abort=True):
return db_query_execute(cur, query, values, abort=abort) | Execute a query. If it fails, abort. Retry with timeouts on lock
DO NOT CALL THIS DIRECTLY. |
17,225 | def reference(self, refobj, taskfileinfo):
with common.preserve_namespace(":"):
jbfile = JB_File(taskfileinfo)
filepath = jbfile.get_fullpath()
ns_suggestion = reftrack.get_namespace(taskfileinfo)
newnodes = cmds.file(filepath, reference=True, na... | Reference the given taskfileinfo into the scene and return the created reference node
The created reference node will be used on :meth:`RefobjInterface.set_reference` to
set the reference on a reftrack node.
Do not call :meth:`RefobjInterface.set_reference` yourself.
This will also cre... |
17,226 | def export_osm_file(self):
osm = create_elem(, {: self.generator,
: self.version})
osm.extend(obj.toosm() for obj in self)
return etree.ElementTree(osm) | Generate OpenStreetMap element tree from ``Osm``. |
17,227 | def read_committed_file(gitref, filename):
repo = Repo()
commitobj = repo.commit(gitref)
blob = commitobj.tree[_delta_dir() + filename]
return blob.data_stream.read() | Retrieve the content of a file in an old commit and returns it.
Ketword Arguments:
:gitref: (str) -- full reference of the git commit
:filename: (str) -- name (full path) of the file
Returns:
str -- content of the file |
17,228 | def calc_fc_size(img_height, img_width):
height, width = img_height, img_width
for _ in range(5):
height, width = _get_conv_outsize(
(height, width),
4, 2, 1)
conv_out_layers = 512
return conv_out_layers, height, width | Calculates shape of data after encoding.
Parameters
----------
img_height : int
Height of input image.
img_width : int
Width of input image.
Returns
-------
encoded_shape : tuple(int)
Gives back 3-tuple with new dims. |
17,229 | def set_path(self, data, path, value):
self.say( + str(value) +
+ str(path) + + str(data))
if isinstance(path, str):
path = path.split()
if len(path) > 1:
self.set_path(data.setdefault(path[0], {}), path[1:], value)
else:
d... | Sets the given key in the given dict object to the given value. If the
given path is nested, child dicts are created as appropriate.
Accepts either a dot-delimited path or an array of path elements as the
`path` variable. |
17,230 | def get_instance(cls, state):
if cls.instance is None:
cls.instance = UserStorageHandler(state)
return cls.instance | :rtype: UserStorageHandler |
17,231 | def set_scale_alpha_from_selection(self):
selection = self.treeview_layers.get_selection()
list_store, selected_iter = selection.get_selected()
if selected_iter is None:
self.adjustment_alpha.set_value(100)
self.scale_alpha.set_sen... | Set scale marker to alpha for selected layer. |
17,232 | def get(self, field, value=None):
self.value = value
val = self.input(field)
if field == :
while True:
if val != :
break
print("Name cannot be empty.")
val = self.input(field)
elif field == :
... | Gets user input for given field and checks if it is valid.
If input is invalid, it will ask the user to enter it again.
Defaults values to empty or :value:.
It does not check validity of parent index. It can only be tested
further down the road, so for now accept anything.
:fi... |
17,233 | def _writeFASTA(self, i, image):
if isinstance(self._titlesAlignments.readsAlignments.reads,
FastqReads):
format_ =
else:
format_ =
filename = % (self._outputDir, i, format_)
titleAlignments = self._titlesAlignments[image[]]
... | Write a FASTA file containing the set of reads that hit a sequence.
@param i: The number of the image in self._images.
@param image: A member of self._images.
@return: A C{str}, either 'fasta' or 'fastq' indicating the format
of the reads in C{self._titlesAlignments}. |
17,234 | def write_totals(self, file_path=, date=str(datetime.date.today()),
organization=, members=0, teams=0):
total_exists = os.path.isfile(file_path)
with open(file_path, ) as out_total:
if not total_exists:
out_total.write(
+
... | Updates the total.csv file with current data. |
17,235 | def tiles(self) -> np.array:
return self._tiles.T if self._order == "F" else self._tiles | An array of this consoles tile data.
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
Colors include an alpha channel but how alpha works is currently
undefined.
Example::
>>> con = tcod.console.Console(10, 2, order="F")
>>> con.tiles[0, 0] = (... |
17,236 | def Convert(self, metadata, checkresult, token=None):
if checkresult.HasField("anomaly"):
for anomaly in checkresult.anomaly:
exported_anomaly = ExportedAnomaly(
type=anomaly.type,
severity=anomaly.severity,
confidence=anomaly.confidence)
if anomaly.sym... | Converts a single CheckResult.
Args:
metadata: ExportedMetadata to be used for conversion.
checkresult: CheckResult to be converted.
token: Security token.
Yields:
Resulting ExportedCheckResult. Empty list is a valid result and means that
conversion wasn't possible. |
17,237 | def select_waveform_generator(approximant):
if approximant in waveform.fd_approximants():
return FDomainCBCGenerator
elif approximant in waveform.td_approximants():
return TDomainCBCGenerator
elif approximant in ringdown.ringdown_fd_approximants:
if approximant... | Returns the single-IFO generator for the approximant.
Parameters
----------
approximant : str
Name of waveform approximant. Valid names can be found using
``pycbc.waveform`` methods.
Returns
-------
generator : (PyCBC generator instance)
A waveform generator object.
... |
17,238 | def lat(self):
try:
for domname, dom in self.domains.items():
try:
thislat = dom.axes[].points
except:
pass
return thislat
except:
raise ValueError(t resolve a lat axis.') | Latitude of grid centers (degrees North)
:getter: Returns the points of axis ``'lat'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lat'`` axis can be found. |
17,239 | def show(self, temp_file_name = , **kwargs):
assert type(temp_file_name) is str
self.save(temp_file_name, **kwargs)
return HTML( % (640, 300, temp_file_name)) | ## Arguments:
- 'args' and 'kwargs' will be passed to 'self.save()' |
17,240 | def angle(self, deg=False):
if self.dtype.str[1] != :
warnings.warn(,
RuntimeWarning, 1)
da = distob.vectorize(np.angle)(self, deg)
return _dts_from_da(da, self.tspan, self.labels) | Return the angle of a complex Timeseries
Args:
deg (bool, optional):
Return angle in degrees if True, radians if False (default).
Returns:
angle (Timeseries):
The counterclockwise angle from the positive real axis on
the complex plane, with dtype... |
17,241 | def get_proficiency_form_for_create(self, objective_id, resource_id, proficiency_record_types):
from dlkit.abstract_osid.id.primitives import Id as ABCId
from dlkit.abstract_osid.type.primitives import Type as ABCType
if not isinstance(objective_id, ABCId):
... | Gets the proficiency form for creating new proficiencies.
A new form should be requested for each create transaction.
arg: objective_id (osid.id.Id): the ``Id`` of the
``Objective``
arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource``
arg: proficiency_... |
17,242 | def AddFXrefRead(self, method, classobj, field):
if field not in self._fields:
self._fields[field] = FieldClassAnalysis(field)
self._fields[field].AddXrefRead(classobj, method) | Add a Field Read to this class
:param method:
:param classobj:
:param field:
:return: |
17,243 | def get_book_progress(self, asin):
kbp = self._get_api_call(, % asin)
return KindleCloudReaderAPI._kbp_to_progress(kbp) | Returns the progress data available for a book.
NOTE: A summary of the two progress formats can be found in the
docstring for `ReadingProgress`.
Args:
asin: The asin of the book to be queried.
Returns:
A `ReadingProgress` instance corresponding to the book associated with
`asin`. |
17,244 | def collapse(cls, holomap, ranges=None, mode=):
if cls.definitions == []:
return holomap
clone = holomap.clone(shared_data=False)
data = zip(ranges[1], holomap.data.values()) if ranges else holomap.data.items()
for key, overlay in data:
... | Given a map of Overlays, apply all applicable compositors. |
17,245 | def claim_invitations(user):
invitation_user_id = % (
models.User.EMAIL_INVITATION, user.email_address)
invitation_user = models.User.query.get(invitation_user_id)
if invitation_user:
invited_build_list = list(invitation_user.builds)
if not invited_build_list:
... | Claims any pending invitations for the given user's email address. |
17,246 | def get_ascii(self, show_internal=True, compact=False, attributes=None):
(lines, mid) = self._asciiArt(show_internal=show_internal,
compact=compact,
attributes=attributes)
return +.join(lines) | Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per tip.
attributes:
A list of node attributes to shown in the ASCII represe... |
17,247 | def log2_lut(v):
res = np.zeros(v.shape, dtype=np.int32)
tt = v >> 16
tt_zero = (tt == 0)
tt_not_zero = ~tt_zero
t_h = tt >> 8
t_zero_h = (t_h == 0) & tt_not_zero
t_not_zero_h = ~t_zero_h & tt_not_zero
res[t_zero_h] = LogTable256[tt[t_zero_h]] + 16
res[t_not_zero_h] = LogTabl... | See `this algo <https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogLookup>`__ for
computing the log2 of a 32 bit integer using a look up table
Parameters
----------
v : int
32 bit integer
Returns
------- |
17,248 | def main():
parser = argparse.ArgumentParser()
parser.add_argument(
, default="md5", help="Digest to use",
choices=sorted(
getattr(hashlib, , None)
or hashlib.algorithms_available))
parser.add_argument(
, default="http://example.org", help="URL to load")
... | Main function of this example. |
17,249 | def open_ioc(fn):
parsed_xml = xmlutils.read_xml_no_ns(fn)
if not parsed_xml:
raise IOCParseError()
root = parsed_xml.getroot()
metadata_node = root.find()
top_level_indicator = get_top_level_indicator_node(root)
parameters_node = root.find()
... | Opens an IOC file, or XML string. Returns the root element, top level
indicator element, and parameters element. If the IOC or string fails
to parse, an IOCParseError is raised.
This is a helper function used by __init__.
:param fn: This is a path to a file to open, or a string conta... |
17,250 | def poll(self):
start_time = time.time()
for agent in self.agents:
for collect in agent.reader:
(time.time() - start_time) * 1000)
collected_data_length = len(self.__collected_data)
if not self.first_data_received and self.__collected_d... | Poll agents for data |
17,251 | def convert_to_python(self, xmlrpc=None):
if xmlrpc:
return xmlrpc.get(self.name, self.default)
elif self.default:
return self.default
else:
return None | Extracts a value for the field from an XML-RPC response. |
17,252 | def rsdl(self):
diff = self.Xf - self.Yfprv
return sl.rfl2norm2(diff, self.X.shape, axis=self.cri.axisN) | Compute fixed point residual in Fourier domain. |
17,253 | def names2dnsrepr(x):
if type(x) is str:
if x and x[-1] == :
return x.encode()
x = [x.encode()]
elif type(x) is bytes:
if x and x[-1] == 0:
return x
x = [x]
res = []
for n in x:
if type(n) is str:
n = n.encode()
... | Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the moment, compression is not implemented !!! |
17,254 | def config_md5(self, source_config):
file_contents = source_config + "\n"
file_contents = file_contents.encode("UTF-8")
return hashlib.md5(file_contents).hexdigest() | Compute MD5 hash of file. |
17,255 | def _get_kind(self, limit):
histo = self.fetch("custom_kind")
if histo:
histo = [i.split("%_") for i in str(histo).split()]
histo = [(int(val, 10), ext) for val, ext in histo]
else:
histo = traits.get_filetypes(... | Get a set of dominant file types. The files must contribute
at least C{limit}% to the item's total size. |
17,256 | def tracker_index():
stats = server.stats
if stats and stats.snapshots:
stats.annotate()
timeseries = []
for cls in stats.tracked_classes:
series = []
for snapshot in stats.snapshots:
series.append(snapshot.classes.get(cls, {}).get(, 0))
... | Get tracker overview. |
17,257 | def configure_gateway(
cls, launch_jvm: bool = True,
gateway: Union[GatewayParameters, Dict[str, Any]] = None,
callback_server: Union[CallbackServerParameters, Dict[str, Any]] = False,
javaopts: Iterable[str] = (), classpath: Iterable[str] = ):
assert che... | Configure a Py4J gateway.
:param launch_jvm: ``True`` to spawn a Java Virtual Machine in a subprocess and connect to
it, ``False`` to connect to an existing Py4J enabled JVM
:param gateway: either a :class:`~py4j.java_gateway.GatewayParameters` object or a
dictionary of keyword ... |
17,258 | def avl_join_dir_recursive(t1, t2, node, direction):
other_side = 1 - direction
if _DEBUG_JOIN_DIR:
print( % (direction,))
ascii_tree(t1, )
ascii_tree(t2, )
if direction == 0:
large, small = t2, t1
elif direction == 1:
large, small = t1, t2
else:
... | Recursive version of join_left and join_right
TODO: make this iterative using a stack |
17,259 | def popen(fn, *args, **kwargs) -> subprocess.Popen:
args = popen_encode(fn, *args, **kwargs)
logging.getLogger(__name__).debug(, args)
p = subprocess.Popen(args)
return p | Please ensure you're not killing the process before it had started properly
:param fn:
:param args:
:param kwargs:
:return: |
17,260 | def get_tunnel_info_input_filter_type_filter_by_dip_dest_ip(self, **kwargs):
config = ET.Element("config")
get_tunnel_info = ET.Element("get_tunnel_info")
config = get_tunnel_info
input = ET.SubElement(get_tunnel_info, "input")
filter_type = ET.SubElement(input, "filter-... | Auto Generated Code |
17,261 | def delete(self):
return self._client._delete(
self.__class__.base_url(
self.sys[].id,
self.sys[],
environment_id=self._environment_id
)
) | Deletes the resource. |
17,262 | def bsinPoints(pb, pe):
v = pe - pb
assert v.y == 0, "begin and end points must have same y coordinate"
f = abs(v) * 0.5 / math.pi
cp1 = 5.34295228e-01
cp2 = 1.01474288e+00
y_ampl = (0, f)
y_cp1 = (0, f * cp1)
y_cp2 = (0, f * cp2)
p0 = pb
p4 = pe
p1 = pb +... | Return Bezier control points, when pb and pe stand for a full period
from (0,0) to (2*pi, 0), respectively, in the user's coordinate system.
The returned points can be used to draw up to four Bezier curves for
the complete phase of the sine function graph (0 to 360 degrees). |
17,263 | def _import_submodules(
__all__, __path__, __name__, include=None, exclude=None,
include_private_modules=False, require__all__=True, recursive=True):
mod = sys.modules[__name__]
if exclude is None:
exclude = []
for (_, submodname, ispkg) in pkgutil.iter_modules(path=__path__):
... | Import all available submodules, all objects defined in the `__all__` lists
of those submodules, and extend `__all__` with the imported objects.
Args:
__all__ (list): The list of public objects in the "root" module
__path__ (str): The path where the ``__init__.py`` file for the "root"
... |
17,264 | def process_query(self):
self.query = wt(self.query)
self.processed_query = []
for word in self.query:
if word not in self.stop_words and word not in self.punctuation:
self.processed_query.append(self.stemmer.stem(word)) | Q.process_query() -- processes the user query,
by tokenizing and stemming words. |
17,265 | def destination(self, value):
if value is not None and (not isinstance(value, tuple) or len(value)) != 2:
raise AttributeError
self._destination = value | Set the destination of the message.
:type value: tuple
:param value: (ip, port)
:raise AttributeError: if value is not a ip and a port. |
17,266 | def get_order(self, order_id):
if order_id in self.blotter.orders:
return self.blotter.orders[order_id].to_api_obj() | Lookup an order based on the order id returned from one of the
order functions.
Parameters
----------
order_id : str
The unique identifier for the order.
Returns
-------
order : Order
The order object. |
17,267 | def put(self, url, data=None, verify=False,
headers=None, proxies=None, timeout=60, **kwargs):
self.log.debug("Put a request to %s with data: %s",
url, data)
response = requests.put(url, data=data,
verify=verify, headers=header... | Sends a PUT request. Refactor from requests module
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to
send in the body of the :class:`Request`.
:param verify: (optional) if ``True``, the SSL cert will be verified.
... |
17,268 | def list_flavors(self, limit=None, marker=None):
return self._flavor_manager.list(limit=limit, marker=marker) | Returns a list of all available Flavors. |
17,269 | def response(uri, method, res, token=, keyword=,
content=, raw_flag=False):
if method == or (method == and not token):
data = res.read()
data_utf8 = data.decode()
if token:
datas = json.loads(data_utf8)
else:
token = json.loads(dat... | Response of tonicdns_client request
Arguments:
uri: TonicDNS API URI
method: TonicDNS API request method
res: Response of against request to TonicDNS API
token: TonicDNS API token
keyword: Processing keyword
content: JSON data
raw_flag: True... |
17,270 | def restart_listener(self, topics):
if self.listener is not None:
if self.listener.running:
self.stop()
self.__init__(topics=topics) | Restart listener after configuration update. |
17,271 | def is_valid_preview(preview):
if not preview:
return False
if mimetype(preview) not in [ExportMimeType.PNG, ExportMimeType.PDF]:
return False
return True | Verifies that the preview is a valid filetype |
17,272 | def delete_records(self, domain, name, record_type=None):
records = self.get_records(domain)
if records is None:
return False
return True | Deletes records by name. You can also add a record type, which will only delete records with the
specified type/name combo. If no record type is specified, ALL records that have a matching name will be
deleted.
This is haphazard functionality. I DO NOT recommend using this in Production cod... |
17,273 | def occurrences_after(self, after=None):
from schedule.models import Occurrence
if after is None:
after = timezone.now()
occ_replacer = OccurrenceReplacer(
Occurrence.objects.filter(event__in=self.events))
generators = [event._occurrences_after_generator... | It is often useful to know what the next occurrence is given a list of
events. This function produces a generator that yields the
the most recent occurrence after the date ``after`` from any of the
events in ``self.events`` |
17,274 | def timer_expired(self):
if self._http_conn.sock is not None:
self._shutdown = True
self._http_conn.sock.shutdown(socket.SHUT_RDWR)
else:
self._timer.cancel()
self._timer = threading.Timer(self._retrytime,
... | This method is invoked in context of the timer thread, so we cannot
directly throw exceptions (we can, but they would be in the wrong
thread), so instead we shut down the socket of the connection.
When the timeout happens in early phases of the connection setup,
there is no socket object... |
17,275 | def make_order_string(cls, order_specification):
registry = get_current_registry()
visitor_cls = registry.getUtility(IOrderSpecificationVisitor,
name=EXPRESSION_KINDS.CQL)
visitor = visitor_cls()
order_specification.accept(visitor)
... | Converts the given order specification to a CQL order expression. |
17,276 | def write_contents(self, table, reader):
f = self.FileObjFaker(table, reader.read(table), self.process_row, self.verbose)
self.copy_from(f, % table.name, [ % c[] for c in table.columns]) | Write the contents of `table`
:Parameters:
- `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write.
- `reader`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader` object that allows reading from... |
17,277 | def support_autoupload_param_hostip(self, **kwargs):
config = ET.Element("config")
support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras")
autoupload_param = ET.SubElement(support, "autoupload-param")
hostip = ET.SubElement(autoupload_param, "hostip"... | Auto Generated Code |
17,278 | def get_template_by_name(name,**kwargs):
try:
tmpl_i = db.DBSession.query(Template).filter(Template.name == name).options(joinedload_all()).one()
return tmpl_i
except NoResultFound:
log.info("%s is not a valid identifier for a template",name)
raise HydraError(%name) | Get a specific resource template, by name. |
17,279 | def request(self, path, method=, headers=None, **kwargs):
headers = {} if headers is None else headers.copy()
headers["User-Agent"] = "Bugsy"
kwargs[] = headers
url = % (self.bugzilla_url, path)
return self._handle_errors(self.session.request(method, url, **kwargs)) | Perform a HTTP request.
Given a relative Bugzilla URL path, an optional request method,
and arguments suitable for requests.Request(), perform a
HTTP request. |
17,280 | def gpg_interactive_input(self, sub_keys_number):
deselect_sub_key = "key 0\n"
_input = self._main_key_command()
for sub_key_number in range(1, sub_keys_number + 1):
_input += self._sub_key_command(sub_key_number) + deselect_sub_key
return "%ssave\n" % _input | processes series of inputs normally supplied on --edit-key but passed through stdin
this ensures that no other --edit-key command is actually passing through. |
17,281 | def importobj(modpath, attrname):
module = __import__(modpath, None, None, [])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retval | imports a module, then resolves the attrname on it |
17,282 | def _get_connection(self):
if getattr(self, , None):
logger.debug()
else:
dsn = self._dsn
if dsn == :
dsn =
else:
dsn = dsn.replace(, )
logger.debug(
.format(dsn, self.... | Returns connection to sqlite db.
Returns:
connection to the sqlite db who stores mpr data. |
17,283 | def __wrap( self, method_name ):
return lambda *args, **kwargs: Facade( self.__cache( method_name, *args, **kwargs ), list(self.__exclusion_list) ) | This method actually does the wrapping. When it's given a method to copy it
returns that method with facilities to log the call so it can be repeated.
:param str method_name: The name of the method precisely as it's called on
the object to wrap.
:rtype lambda function: |
17,284 | def check_input(prolog_file):
if prolog_file == None:
return
for pred in illegal_predicates:
if type(pred) == tuple:
print_name = pred[1]
pred = pred[0]
else:
print_name = pred
if re.search(r + pred + r, prolog_file):
raise Exc... | Check for illegal predicates (like reading/writing, opening sockets, etc). |
17,285 | def _learnPhase1(self, activeColumns, readOnly=False):
self.lrnActiveState[].fill(0)
numUnpredictedColumns = 0
for c in activeColumns:
predictingCells = numpy.where(self.lrnPredictedState[][c] == 1)[0]
numPredictedCells = len(predictingCells)
assert numPredictedCells <... | Compute the learning active state given the predicted state and
the bottom-up input.
:param activeColumns list of active bottom-ups
:param readOnly True if being called from backtracking logic.
This tells us not to increment any segment
duty cycles or ... |
17,286 | def purge_old_user_tasks():
limit = now() - settings.USER_TASKS_MAX_AGE
UserTaskStatus.objects.filter(created__lt=limit).delete() | Delete any UserTaskStatus and UserTaskArtifact records older than ``settings.USER_TASKS_MAX_AGE``.
Intended to be run as a scheduled task. |
17,287 | def copy_ifcfg_file(source_interface, dest_interface):
log = logging.getLogger(mod_logger + )
if not isinstance(source_interface, basestring):
msg =
log.error(msg)
raise TypeError(msg)
if not isinstance(dest_interface, basestring):
msg =
log.error(msg)
... | Copies an existing ifcfg network script to another
:param source_interface: String (e.g. 1)
:param dest_interface: String (e.g. 0:0)
:return: None
:raises TypeError, OSError |
17,288 | def fig_intro(params, ana_params, T=[800, 1000], fraction=0.05, rasterized=False):
ana_params.set_PLOS_2column_fig_style(ratio=0.5)
networkSim = CachedNetwork(**params.networkSimParams)
if analysis_params.bw:
networkSim.colors = phlp.get_colors(len(networkSim.X))
fig = plt.f... | set up plot for introduction |
17,289 | def log_queries(recipe):
logger.debug(
,
recipe.slug,
sum([float(q[]) for q in connection.queries])) | Logs recipe instance SQL queries (actually, only time). |
17,290 | def move_part_instance(part_instance, target_parent, part_model, name=None, include_children=True):
if not name:
name = part_instance.name
moved_model = get_mapping_dictionary()[part_model.id]
if moved_model.multiplicity == Multiplicity.ONE:
moved_inst... | Move the `Part` instance to target parent and updates the properties based on the original part instance.
.. versionadded:: 2.3
:param part_instance: `Part` object to be moved
:type part_instance: :class:`Part`
:param part_model: `Part` object representing the model of part_instance
:type part_mod... |
17,291 | def replace_free_shipping_promotion_by_id(cls, free_shipping_promotion_id, free_shipping_promotion, **kwargs):
kwargs[] = True
if kwargs.get():
return cls._replace_free_shipping_promotion_by_id_with_http_info(free_shipping_promotion_id, free_shipping_promotion, **kwargs)
els... | Replace FreeShippingPromotion
Replace all attributes of FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_free_shipping_promotion_by_id(free_shipping_promotion_id, free_shi... |
17,292 | def FindSolFile(shot=0, t=0, Dt=None, Mesh=, Deg=2, Deriv=, Sep=True, Pos=True, OutPath=):
assert None in [t,Dt] and not (t is None and Dt is None), "Arg t or Dt must be None, but not both !"
LF = [ff for ff in os.listdir(OutPath) if in ff]
LF = [ff for ff in LF if all([ss in ff for ss in [+str(shot)+... | Identify the good Sol2D saved file in a given folder (OutPath), based on key ToFu criteria
When trying to load a Sol2D object (i.e.: solution of a tomographic inversion), it may be handy to provide the key parameters (shot, time, mesh name, degree of basis functions, regularisation functional) instead of copy-past... |
17,293 | def invert_inventory(inventory):
inverted = dict()
for binding, items in inventory.iteritems():
for item in items:
if isinstance(item, dict):
item = item.keys()[0]
item = str(item)
if item in inverted:
echo("Warning: Duplicate ... | Return {item: binding} from {binding: item}
Protect against items with additional metadata
and items whose type is a number
Returns:
Dictionary of inverted inventory |
17,294 | def get_std_end_date(self):
_, second = self._val
if second != datetime.max:
return second.strftime("%Y-%m-%d %H:%M:%S")
else:
return "" | If the date is custom, return the end datetime with the format %Y-%m-%d %H:%M:%S. Else, returns "". |
17,295 | def stringify(req, resp):
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_500 | dumps all valid jsons
This is the latest after hook |
17,296 | def refresh(self):
grant_type = "https://oauth.reddit.com/grants/installed_client"
self._request_token(grant_type=grant_type, device_id=self._device_id) | Obtain a new access token. |
17,297 | def log_event(cls, event, text = None):
if not text:
if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT:
what = event.get_exception_description()
if event.is_first_chance():
what = % what
else:
wh... | Log lines of text associated with a debug event.
@type event: L{Event}
@param event: Event object.
@type text: str
@param text: (Optional) Text to log. If no text is provided the default
is to show a description of the event itself.
@rtype: str
@return: ... |
17,298 | def memoize(max_cache_size=1000):
def wrapper(f):
@wraps(f)
def fn(*args, **kwargs):
if kwargs:
key = (args, tuple(kwargs.items()))
else:
key = args
try:
return fn.cache[key]
except KeyError:
... | Python 2.4 compatible memoize decorator.
It creates a cache that has a maximum size. If the cache exceeds the max,
it is thrown out and a new one made. With such behavior, it is wise to set
the cache just a little larger that the maximum expected need.
Parameters:
max_cache_size - the size to w... |
17,299 | def eth_getTransactionByBlockNumberAndIndex(self, block=BLOCK_TAG_LATEST,
index=0):
block = validate_block(block)
result = yield from self.rpc_call(,
[block, hex(index)])
return result | https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblocknumberandindex
:param block: Block tag or number (optional)
:type block: int or BLOCK_TAGS
:param index: Index position (optional)
:type index: int
:return: transaction
:rtype: dict or None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.