Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
16,300 | def stats(self) -> pd.DataFrame:
cumul = []
for f in self:
info = {
"flight_id": f.flight_id,
"callsign": f.callsign,
"origin": f.origin,
"destination": f.destination,
"duration": f.stop - f.start,
... | Statistics about flights contained in the structure.
Useful for a meaningful representation. |
16,301 | def get_suitable_slot_for_reference(self, reference):
if not IReferenceSample.providedBy(reference):
return -1
occupied = self.get_slot_positions(type=) or [0]
wst = self.getWorksheetTemplate()
if not wst:
slot_to = max(occupied... | Returns the suitable position for reference analyses, taking into
account if there is a WorksheetTemplate assigned to this worksheet.
By default, returns a new slot at the end of the worksheet unless there
is a slot defined for a reference of the same type (blank or control)
in the work... |
16,302 | def deliver_tx(self, raw_transaction):
self.abort_if_abci_chain_is_not_synced()
logger.debug(, raw_transaction)
transaction = self.bigchaindb.is_valid_transaction(
decode_transaction(raw_transaction), self.block_transactions)
if not transaction:
logger... | Validate the transaction before mutating the state.
Args:
raw_tx: a raw string (in bytes) transaction. |
16,303 | def computational_form(data):
if isinstance(data.iloc[0], DataFrame):
dslice = Panel.from_dict(dict([(i,data.iloc[i])
for i in xrange(len(data))]))
elif isinstance(data.iloc[0], Series):
dslice = DataFrame(data.tolist())
dslice.index = data.in... | Input Series of numbers, Series, or DataFrames repackaged
for calculation.
Parameters
----------
data : pandas.Series
Series of numbers, Series, DataFrames
Returns
-------
pandas.Series, DataFrame, or Panel
repacked data, aligned by indices, ready for calculation |
16,304 | def _convolve3_old(data, h, dev=None):
if dev is None:
dev = get_device()
if dev is None:
raise ValueError("no OpenCLDevice found...")
dtype = data.dtype.type
dtypes_options = {np.float32: "",
np.uint16: "-D SHORTTYPE"}
if not dtype in dtypes_options:
... | convolves 3d data with kernel h on the GPU Device dev
boundary conditions are clamping to edge.
h is converted to float32
if dev == None the default one is used |
16,305 | def options(self):
config = self._config
o = {}
o.update(self._default_smtp_options)
o.update(self._default_message_options)
o.update(self._default_backend_options)
o.update(get_namespace(config, , valid_keys=o.keys()))
o[] = int(o[])
o[] = float(... | Reads all EMAIL_ options and set default values. |
16,306 | def update(ctx, no_restart, no_rebuild):
instance = ctx.obj[]
log()
run_process(, [, , , ])
run_process(, [, , , ])
if not no_rebuild:
log()
install_frontend(instance, forcerebuild=True, install=False, development=True)
if not no_restart:
... | Update a HFOS node |
16,307 | def token_is_valid(self,):
elapsed_time = time.time() - self.token_time
logger.debug("ELAPSED TIME : {0}".format(elapsed_time))
if elapsed_time > 3540:
logger.debug("TOKEN HAS EXPIRED")
return False
logger.debug("TOKEN IS STILL VALID")
return Tr... | Check the validity of the token :3600s |
16,308 | def _check_len(self, pkt):
if len(pkt) % 2:
last_chr = pkt[-1]
if last_chr <= b:
return pkt[:-1] + b + last_chr
else:
return pkt[:-1] + b + chb(orb(last_chr) - 1)
else:
return pkt | Check for odd packet length and pad according to Cisco spec.
This padding is only used for checksum computation. The original
packet should not be altered. |
16,309 | def bsrchi(value, ndim, array):
value = ctypes.c_int(value)
ndim = ctypes.c_int(ndim)
array = stypes.toIntVector(array)
return libspice.bsrchi_c(value, ndim, array) | Do a binary search for a key value within an integer array,
assumed to be in increasing order. Return the index of the
matching array entry, or -1 if the key value is not found.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bsrchi_c.html
:param value: Value to find in array.
:type value:... |
16,310 | def load_config(self, filepath=None):
def load_settings(filepath):
instruments_loaded = {}
probes_loaded = {}
scripts_loaded = {}
if filepath and os.path.isfile(filepath):
in_data = load_b26_file(filepath)
... | checks if the file is a valid config file
Args:
filepath: |
16,311 | def exclude(self, target, operation, role, value):
target = {"result": self.data["proxies"]["result"],
"instance": self.data["proxies"]["instance"],
"plugin": self.data["proxies"]["plugin"]}[target]
if operation == "add":
target.add_exclusion(ro... | Exclude a `role` of `value` at `target`
Arguments:
target (str): Destination proxy model
operation (str): "add" or "remove" exclusion
role (str): Role to exclude
value (str): Value of `role` to exclude |
16,312 | def reshape(self, newshape, order=):
oldshape = self.shape
ar = np.asarray(self).reshape(newshape, order=order)
if (newshape is -1 and len(oldshape) is 1 or
(isinstance(newshape, numbers.Integral) and
newshape == oldshape[0]) or
(isi... | If axis 0 is unaffected by the reshape, then returns a Timeseries,
otherwise returns an ndarray. Preserves labels of axis j only if all
axes<=j are unaffected by the reshape.
See ``numpy.ndarray.reshape()`` for more information |
16,313 | def update_variables(X, Z, U, prox_f, step_f, prox_g, step_g, L):
if not hasattr(prox_g, ):
if prox_g is not None:
dX = step_f/step_g * L.T.dot(L.dot(X) - Z + U)
X[:] = prox_f(X - dX, step_f)
LX, R, S = do_the_mm(X, step_f, Z, U, prox_g, step_g, L)
else:
... | Update the primal and dual variables
Note: X, Z, U are updated inline
Returns: LX, R, S |
16,314 | def getclientloansurl(idclient, *args, **kwargs):
getparams = []
if kwargs:
try:
if kwargs["fullDetails"] == True:
getparams.append("fullDetails=true")
else:
getparams.append("fullDetails=false")
except Exception as ex:
pas... | Request Client loans URL.
How to use it? By default MambuLoan uses getloansurl as the urlfunc.
Override that behaviour by sending getclientloansurl (this function)
as the urlfunc to the constructor of MambuLoans (note the final 's')
and voila! you get the Loans just for a certain client.
If idclie... |
16,315 | def input(msg="", default="", title="Lackey Input", hidden=False):
root = tk.Tk()
input_text = tk.StringVar()
input_text.set(default)
PopupInput(root, msg, title, hidden, input_text)
root.focus_force()
root.mainloop()
return str(input_text.get()) | Creates an input dialog with the specified message and default text.
If `hidden`, creates a password dialog instead. Returns the entered value. |
16,316 | def upload(self, timeout=None):
if self._vehicle._wpts_dirty:
self._vehicle._master.waypoint_clear_all_send()
start_time = time.time()
if self._vehicle._wploader.count() > 0:
self._vehicle._wp_uploaded = [False] * self._vehicle._wploader.count()
... | Call ``upload()`` after :py:func:`adding <CommandSequence.add>` or :py:func:`clearing <CommandSequence.clear>` mission commands.
After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an
exception) and future reads will see their effects.
:param int timeout: ... |
16,317 | def _add_rule(self, state, rule):
if rule.strip() == "-":
parsed_rule = None
else:
parsed_rule = rule.split()
if (len(parsed_rule) != 3 or
parsed_rule[1] not in [, , ] or
len(parsed_rule[2]) > 1):
raise Synt... | Parse rule and add it to machine (for internal use). |
16,318 | def clear(self):
self._closed = False
self._ready.clear()
self._connection.clear()
self.http.recreate() | Clears the internal state of the bot.
After this, the bot can be considered "re-opened", i.e. :meth:`.is_closed`
and :meth:`.is_ready` both return ``False`` along with the bot's internal
cache cleared. |
16,319 | def check(self, metainfo, datapath, progress=None):
if datapath:
self.datapath = datapath
def check_piece(filename, piece):
"Callback for new piece"
if piece != metainfo["info"]["pieces"][check_piece.piece_index:check_piece.piece_index+20]:
s... | Check piece hashes of a metafile against the given datapath. |
16,320 | def connect(self):
"Initiate the connection to a proxying hub"
log.info("connecting")
self._peer = connection.Peer(
None, self._dispatcher, self._addrs.popleft(),
backend.Socket(), reconnect=False)
self._peer.start() | Initiate the connection to a proxying hub |
16,321 | def fill_translation_cache(instance):
if hasattr(instance, ):
return
instance._translation_cache = {}
if not instance.pk:
return
for language_code in get_language_code_list():
field_alias = get_translated_field_alias(, language_code)
if geta... | Fill the translation cache using information received in the
instance objects as extra fields.
You can not do this in post_init because the extra fields are
assigned by QuerySet.iterator after model initialization. |
16,322 | def append_hdus(hdulist, srcmap_file, source_names, hpx_order):
sys.stdout.write(" Extracting %i sources from %s" % (len(source_names), srcmap_file))
try:
hdulist_in = fits.open(srcmap_file)
except IOError:
try:
hdulist_in = fits.open( % srcmap_f... | Append HEALPix maps to a list
Parameters
----------
hdulist : list
The list being appended to
srcmap_file : str
Path to the file containing the HDUs
source_names : list of str
Names of the sources to extract from srcmap_file
hpx_order... |
16,323 | def _download_helper(url):
try:
request = urllib.request.urlopen(url)
try:
size = int(dict(request.info())[].strip())
except KeyError:
try:
size = int(dict(request.info())[].strip())
except KeyError:
size = 0
... | Handle the download of an URL, using the proxy currently set in \
:mod:`socks`.
:param url: The URL to download.
:returns: A tuple of the raw content of the downloaded data and its \
associated content-type. Returns None if it was \
unable to download the document. |
16,324 | def predict_proba(self, dataframe):
ret = numpy.ones((dataframe.shape[0], 2))
ret[:, 0] = (1 - self.mean)
ret[:, 1] = self.mean
return ret | Predict probabilities using the model
:param dataframe: Dataframe against which to make predictions |
16,325 | def load_data(flist, drop_duplicates=False):
trainv1_stage1_all_fold.csvv2_stage1_all_fold.csvv3_stage1_all_fold.csvtraintargettarget.csvtargettestv1_stage1_test.csvv2_stage1_test.csvv3_stage1_test.csv
if (len(flist[])==0) or (len(flist[])==0) or (len(flist[])==0):
raise Exception()
X_train = pd.Da... | Usage: set train, target, and test key and feature files.
FEATURE_LIST_stage2 = {
'train':(
TEMP_PATH + 'v1_stage1_all_fold.csv',
TEMP_PATH + 'v2_stage1_all_fold.csv',
TEMP_PATH + 'v3_stage1_all_fold.csv',
... |
16,326 | def set_cache_buster(self, path, hash):
oz.aws_cdn.set_cache_buster(self.redis(), path, hash) | Sets the cache buster value for a given file path |
16,327 | def register(self, request, **cleaned_data):
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
create_user = RegistrationProfile.objects.create_inactive_user
new_user = create_user(
clean... | Given a username, email address and password, register a new
user account, which will initially be inactive.
Along with the new ``User`` object, a new
``registration.models.RegistrationProfile`` will be created,
tied to that ``User``, containing the activation key which
will be ... |
16,328 | def compute_hardwired_weights(rho,N_E,N_I,periodic, onlyI=False):
weight_sizes = np.asarray([[N_I,N_E], [N_I,N_E], [N_E,N_I], [N_E,N_I], [N_I,N_I]])
gamma_param = np.asarray([N_I/N_E, N_I/N_E, N_E/N_I, N_E/N_I, N_I/N_I])
eta_param = np.asarray([1.5*21, 1.5*21, 8, 8, 24])
epsilon_param = np.asarray([0, ... | %This function returns the synaptic weight matrices
%(G_I_EL,G_I_ER,G_EL_I,G_ER_I,G_I_I) and the suppressive envelope
%(A_env), based on:
%
% - the scale of the synaptic profiles (rho)
% - the size of the exctitatory and inhibitory pops (N_E, N_I)
% - the boundary conditions of the network (periodic=1 for p... |
16,329 | def compare_names(first, second):
first = name_to_vector(first)
second = name_to_vector(second)
zipped = zip(first, second)
if not zipped:
return 0
similarity_factor = 0
for fitem, _ in zipped:
if fitem in second:
similarity_factor += 1
return (float(simi... | Compare two names in complicated, but more error prone way.
Algorithm is using vector comparison.
Example:
>>> compare_names("Franta Putšálek", "ing. Franta Putšálek")
100.0
>>> compare_names("F. Putšálek", "ing. Franta Putšálek")
50.0
Args:
first (str): Fisst name... |
16,330 | def transform(self, X=None, y=None):
rotation = random.gauss(self.rotation_range[0], self.rotation_range[1])
self.params = rotation
tx = Rotate2D(rotation,
reference=self.reference,
lazy=self.lazy)
return tx.transform(X,y) | Transform an image using an Affine transform with
rotation parameters randomly generated from the user-specified
range. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another image ... |
16,331 | def setup(app):
app.add_domain(EverettDomain)
app.add_directive(, AutoComponentDirective)
return {
: __version__,
: True,
: True
} | Register domain and directive in Sphinx. |
16,332 | def fcoe_fcoe_map_fcoe_map_fabric_map_fcoe_map_fabric_map_name(self, **kwargs):
config = ET.Element("config")
fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe")
fcoe_map = ET.SubElement(fcoe, "fcoe-map")
fcoe_map_name_key = ET.SubElement(fcoe_map, "f... | Auto Generated Code |
16,333 | def host_resolution_order(ifo, env=, epoch=,
lookback=14*86400):
hosts = []
if env and os.getenv(env):
hosts = parse_nds_env(env)
if to_gps() - to_gps(epoch) > lookback:
ifolist = [None, ifo]
else:
ifolist = [ifo, None]
for difo i... | Generate a logical ordering of NDS (host, port) tuples for this IFO
Parameters
----------
ifo : `str`
prefix for IFO of interest
env : `str`, optional
environment variable name to use for server order,
default ``'NDSSERVER'``. The contents of this variable should
be a co... |
16,334 | def to_string(xml, **kwargs):
if isinstance(xml, OneLogin_Saml2_XML._text_class):
return xml
if isinstance(xml, OneLogin_Saml2_XML._element_class):
OneLogin_Saml2_XML.cleanup_namespaces(xml)
return OneLogin_Saml2_XML._unparse_etree(xml, **kwargs)
r... | Serialize an element to an encoded string representation of its XML tree.
:param xml: The root node
:type xml: str|bytes|xml.dom.minidom.Document|etree.Element
:returns: string representation of xml
:rtype: string |
16,335 | def interval_timer(interval, func, *args, **kwargs):
stopped = Event()
def loop():
while not stopped.wait(interval):
func(*args, **kwargs)
Thread(name=, target=loop).start()
return stopped.set | Interval timer function.
Taken from: http://stackoverflow.com/questions/22498038/improvement-on-interval-python/22498708 |
16,336 | def _pack_with_tf_ops(dataset, keys, length):
empty_example = {}
for k in keys:
empty_example[k] = tf.zeros([0], dtype=tf.int32)
empty_example[k + "_position"] = tf.zeros([0], dtype=tf.int32)
keys_etc = empty_example.keys()
def write_packed_example(partial, outputs):
new_partial = empty_example.... | Helper-function for packing a dataset which has already been batched.
See pack_dataset()
Uses tf.while_loop. Slow.
Args:
dataset: a dataset containing padded batches of examples.
keys: a list of strings
length: an integer
Returns:
a dataset. |
16,337 | def unpackcFunc(self):
self.cFunc = []
for solution_t in self.solution:
self.cFunc.append(solution_t.cFunc)
self.addToTimeVary() | "Unpacks" the consumption functions into their own field for easier access.
After the model has been solved, the consumption functions reside in the
attribute cFunc of each element of ConsumerType.solution. This method
creates a (time varying) attribute cFunc that contains a list of consumption... |
16,338 | def __geo_point(lat, lon, elev):
logger_noaa_lpd.info("enter geo_point")
coordinates = []
geo_dict = OrderedDict()
geometry_dict = OrderedDict()
for index, point in enumerate(lat):
coordinates.append(lat[index])
coordinates.append(lon[index])
... | GeoJSON standard:
Create a geoJson Point-type dictionary
:param list lat:
:param list lon:
:return dict: |
16,339 | def handle_signal(self, sig, frame):
if sig in [signal.SIGINT]:
log.warning("Ctrl-C pressed, shutting down...")
if sig in [signal.SIGTERM]:
log.warning("SIGTERM received, shutting down...")
self.cleanup()
sys.exit(-sig) | Handles signals, surprisingly. |
16,340 | def write_to_file(self, file_path=, date=str(datetime.date.today()),
organization=, members=0, teams=0):
self.checkDir(file_path)
with open(file_path, ) as output:
output.write(
+
+
+ + date +
+ organization + + str(member... | Writes the current organization information to file (csv). |
16,341 | def always_fails(
self,
work_dict):
label = "always_fails"
log.info(("task - {} - start "
"work_dict={}")
.format(label,
work_dict))
raise Exception(
work_dict.get(
"test_failure",
"simulating... | always_fails
:param work_dict: dictionary for key/values |
16,342 | def clone(local_root, new_root, remote, branch, rel_dest, exclude):
log = logging.getLogger(__name__)
output = run_command(local_root, [, , ])
remotes = dict()
for match in RE_ALL_REMOTES.findall(output):
remotes.setdefault(match[0], [None, None])
if match[2] == :
remote... | Clone "local_root" origin into a new directory and check out a specific branch. Optionally run "git rm".
:raise CalledProcessError: Unhandled git command failure.
:raise GitError: Handled git failures.
:param str local_root: Local path to git root directory.
:param str new_root: Local path empty direc... |
16,343 | def default():
return dict(
max_name_length=64,
max_prop_count=32,
max_str_length=100,
max_byte_length=100,
max_array_length=100,
max_file_length=200,
minimal_property=False,
minimal_parameter=False,
... | return default options, available options:
- max_name_length: maximum length of name for additionalProperties
- max_prop_count: maximum count of properties (count of fixed properties + additional properties)
- max_str_length: maximum length of string type
- max_byte_length: maximum lengt... |
16,344 | def install(path, capture_error=False):
cmd = % _process.python_executable()
if has_requirements(path):
cmd +=
logger.info(, cmd)
_process.check_error(shlex.split(cmd), _errors.InstallModuleError, cwd=path, capture_error=capture_error) | Install a Python module in the executing Python environment.
Args:
path (str): Real path location of the Python module.
capture_error (bool): Default false. If True, the running process captures the
stderr, and appends it to the returned Exception message in case of errors. |
16,345 | def subnet_distance(self):
return [(Element.from_href(entry.get()), entry.get())
for entry in self.data.get()] | Specific subnet administrative distances
:return: list of tuple (subnet, distance) |
16,346 | def is_complete(self, zmax=118):
for z in range(1, zmax):
if not self[z]: return False
return True | True if table is complete i.e. all elements with Z < zmax have at least on pseudopotential |
16,347 | def schema_delete_field(cls, key):
root = .join([API_ROOT, , cls.__name__])
payload = {
: cls.__name__,
: {
key: {
:
}
}
}
cls.PUT(root, **payload) | Deletes a field. |
16,348 | def _authenticate_x509(credentials, sock_info):
query = SON([(, 1),
(, )])
if credentials.username is not None:
query[] = credentials.username
elif sock_info.max_wire_version < 5:
raise ConfigurationError(
"A username is required for MONGODB-X509 authenticat... | Authenticate using MONGODB-X509. |
16,349 | def write(text, path):
with open(path, "wb") as f:
f.write(text.encode("utf-8")) | Writer text to file with utf-8 encoding.
Usage::
>>> from angora.dataIO import textfile
or
>>> from angora.dataIO import *
>>> textfile.write("hello world!", "test.txt") |
16,350 | def generate_token(self):
response = self._make_request()
self.auth = response
self.token = response[] | Make request in API to generate a token. |
16,351 | def from_hex_key(cls, key, network=BitcoinMainNet):
if len(key) == 130 or len(key) == 66:
try:
key = unhexlify(key)
except TypeError:
pass
key = ensure_bytes(key)
compressed = False
id_byte = key[0]
if... | Load the PublicKey from a compressed or uncompressed hex key.
This format is defined in PublicKey.get_key() |
16,352 | def get_directory(request):
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
def sort_key(r):
return r[0]
... | Get API directory as a nested list of lists. |
16,353 | def compute_dkl(fsamps, prior_fsamps, **kwargs):
parallel = kwargs.pop(, False)
cache = kwargs.pop(, )
tqdm_kwargs = kwargs.pop(, {})
if kwargs:
raise TypeError( % kwargs)
if cache:
cache = Cache(cache + )
try:
return cache.check(fsamps, prior_fsamps)
... | Compute the Kullback Leibler divergence for function samples for posterior
and prior pre-calculated at a range of x values.
Parameters
----------
fsamps: 2D numpy.array
Posterior function samples, as computed by
:func:`fgivenx.compute_samples`
prior_fsamps: 2D numpy.array
P... |
16,354 | def compute_score(markers, bonus, penalty):
nmarkers = len(markers)
s = [bonus] * nmarkers
f = [-1] * nmarkers
for i in xrange(1, nmarkers):
for j in xrange(i):
mi, mj = markers[i], markers[j]
t = bonus if mi.mlg == mj.mlg else penalty + bonus
if s[i... | Compute chain score using dynamic programming. If a marker is the same
linkage group as a previous one, we add bonus; otherwise, we penalize the
chain switching. |
16,355 | def forProperty(instance,propertyName,useGetter=False):
assert isinstance(propertyName,str)
if propertyName.startswith("get") or propertyName.startswith("set"):
getterName = "get" + propertyName[3:]
setterName = "set" + propertyName[3:]
if len(p... | 2-way binds to an instance property.
Parameters:
- instance -- the object instance
- propertyName -- the name of the property to bind to
- useGetter: when True, calls the getter method to obtain the value. When False, the signal argument is used as input for the target setter. (default ... |
16,356 | def set_inheritance(obj_name, enabled, obj_type=, clear=False):
C:\\Temp
if obj_type not in [, , ]:
raise SaltInvocationError(
.format(obj_name))
if clear:
obj_dacl = dacl(obj_type=obj_type)
else:
obj_dacl = dacl(obj_name, obj_type)
return obj_dacl.save(obj_name... | Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
The type of object. Only three objects allow inheritance. Valid
ob... |
16,357 | def _import_public_names(module):
"Import public names from module into this module, like import *"
self = sys.modules[__name__]
for name in module.__all__:
if hasattr(self, name):
continue
setattr(self, name, getattr(module, name)) | Import public names from module into this module, like import * |
16,358 | def update(self, campaign_id, title, is_smooth, online_status, nick=None):
request = TOPRequest()
request[] = campaign_id
request[] = title
request[] = is_smooth
request[] = online_status
if nick!=None: request[] = nick
self.create(self.execute(request), ... | xxxxx.xxxxx.campaign.update
===================================
更新一个推广计划,可以设置推广计划名字、是否平滑消耗,只有在设置了日限额后平滑消耗才会产生作用。 |
16,359 | def _warning(code):
if isinstance(code, str):
return code
message =
if isinstance(code, tuple):
if isinstance(code[0], str):
message = code[1]
code = code[0]
return CFG_BIBRECORD_WARNING_MSGS.get(code, ) + message | Return a warning message of code 'code'.
If code = (cd, str) it returns the warning message of code 'cd' and appends
str at the end |
16,360 | def expect(
self, re_strings=, timeout=None, output_callback=None, default_match_prefix=,
strip_ansi=True
):
output_callback = output_callback if output_callback else self.output_callback
timeout = timeout if timeout else self.timeout
self.channel.settimeou... | This function takes in a regular expression (or regular expressions)
that represent the last line of output from the server. The function
waits for one or more of the terms to be matched. The regexes are
matched using expression \n<regex>$ so you'll need to provide an
easygoing regex s... |
16,361 | def launch_minecraft(port, installdir="MalmoPlatform", replaceable=False):
launch_script =
if os.name == :
launch_script =
cwd = os.getcwd()
os.chdir(installdir)
os.chdir("Minecraft")
try:
cmd = [launch_script, , str(port), ]
if replaceable:
cmd.append(... | Launch Minecraft listening for malmoenv connections.
Args:
port: the TCP port to listen on.
installdir: the install dir name. Defaults to MalmoPlatform.
Must be same as given (or defaulted) in download call if used.
replaceable: whether or not to automatically restart Minecraft (def... |
16,362 | def alive(opts):
dev = conn()
thisproxy[].connected = ping()
if not dev.connected:
__salt__[]({}, .format(
opts[][]))
return dev.connected | Validate and return the connection status with the remote device.
.. versionadded:: 2018.3.0 |
16,363 | def select_catalogue(self, selector, distance, selector_type=,
distance_metric=, point_depth=None,
upper_eq_depth=None, lower_eq_depth=None):
circlesquareepicentralhypocentralcirclecirclesquaresquare
if selector.catalogue.get_number_events() < 1:
... | Selects the catalogue associated to the point source.
Effectively a wrapper to the two functions select catalogue within
a distance of the point and select catalogue within cell centred on
point
:param selector:
Populated instance of :class:
`openquake.hmtk.seism... |
16,364 | def writePlistToString(rootObject):
rootObject
plistData, error = (
NSPropertyListSerialization.
dataFromPropertyList_format_errorDescription_(
rootObject, NSPropertyListXMLFormat_v1_0, None))
if plistData is None:
if error:
error = error.encode(, )
el... | Return 'rootObject' as a plist-formatted string. |
16,365 | def template(page=None, layout=None, **kwargs):
pkey = "_template_extends__"
def decorator(f):
if inspect.isclass(f):
layout_ = layout or page
extends = kwargs.pop("extends", None)
if extends and hasattr(extends, pkey):
items = getattr(extends, p... | Decorator to change the view template and layout.
It works on both View class and view methods
on class
only $layout is applied, everything else will be passed to the kwargs
Using as first argument, it will be the layout.
:first arg or $layout: The layout to use for that view
... |
16,366 | def _new_name(method, old_name):
old_name, method.__name__
),
DeprecationWarning,
)
return method(*args, **kwargs)
deprecated_msg = .format(
method.__name__
)
if getattr(_method, "__doc__"):
_method.__doc__ += deprecated_msg
... | Return a method with a deprecation warning. |
16,367 | def on_loss_begin(self, last_output:Tuple[Tensor,Tensor,Tensor], **kwargs):
"Save the extra outputs for later and only returns the true output."
self.raw_out,self.out = last_output[1],last_output[2]
return {: last_output[0]} | Save the extra outputs for later and only returns the true output. |
16,368 | def serialize(self, keep_readonly=False):
serializer = Serializer(self._infer_class_models())
return serializer._serialize(self, keep_readonly=keep_readonly) | Return the JSON that would be sent to azure from this model.
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
:param bool keep_readonly: If you want to serialize the readonly attributes
:returns: A dict JSON compatible object
:rtype: dict |
16,369 | def is_standard(action):
boolean_actions = (
_StoreConstAction, _StoreFalseAction,
_StoreTrueAction
)
return (not action.choices
and not isinstance(action, _CountAction)
and not isinstance(action, _HelpAction)
and type(action) not in boolean_... | actions which are general "store" instructions.
e.g. anything which has an argument style like:
$ script.py -f myfilename.txt |
16,370 | def update(self):
is_on = self._device.get_power_state()
if is_on:
self._state = STATE_ON
volume = self._device.get_current_volume()
if volume is not None:
self._volume_level = float(volume) / self._max_volume
input_ = self._dev... | Retrieve latest state of the device. |
16,371 | def name(self):
names = self.names.split()
if len(names) == 1:
return names[0]
elif len(names) == 2:
return .join(names)
else:
return .join([names[0], , names[-1]]) | Compact representation for the names |
16,372 | def get_annotated_list_qs(cls, qs):
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
open = (depth and (prev_depth is None or depth > prev... | Gets an annotated list from a queryset. |
16,373 | def create_track_token(request):
from tracked_model.models import RequestInfo
request_pk = RequestInfo.create_or_get_from_request(request).pk
user_pk = None
if request.user.is_authenticated():
user_pk = request.user.pk
return TrackToken(request_pk=request_pk, user_pk=user_pk) | Returns ``TrackToken``.
``TrackToken' contains request and user making changes.
It can be passed to ``TrackedModel.save`` instead of ``request``.
It is intended to be used when passing ``request`` is not possible
e.g. when ``TrackedModel.save`` will be called from celery task. |
16,374 | def simDeath(self):
how_many_die = int(round(self.AgentCount*(1.0-self.LivPrb[0])))
base_bool = np.zeros(self.AgentCount,dtype=bool)
base_bool[0:how_many_die] = True
who_dies = self.RNG.permutation(base_bool)
if self.T_age is not None:
... | Randomly determine which consumers die, and distribute their wealth among the survivors.
This method only works if there is only one period in the cycle.
Parameters
----------
None
Returns
-------
who_dies : np.array(bool)
Boolean array of size Agent... |
16,375 | def getSubtotal(self):
if self.supplyorder_lineitems:
return sum(
[(Decimal(obj[]) * Decimal(obj[])) for obj in self.supplyorder_lineitems])
return 0 | Compute Subtotal |
16,376 | def create_table(
self,
impala_name,
kudu_name,
primary_keys=None,
obj=None,
schema=None,
database=None,
external=False,
force=False,
):
self._check_connected()
if not external and (primary_keys is None or len(primary_... | Create an Kudu-backed table in the connected Impala cluster. For
non-external tables, this will create a Kudu table with a compatible
storage schema.
This function is patterned after the ImpalaClient.create_table function
designed for physical filesystems (like HDFS).
Parameter... |
16,377 | def deserialize(cls, assoc_s):
pairs = kvform.kvToSeq(assoc_s, strict=True)
keys = []
values = []
for k, v in pairs:
keys.append(k)
values.append(v)
if keys != cls.assoc_keys:
raise ValueError(, keys)
version, handle, secret,... | Parse an association as stored by serialize().
inverse of serialize
@param assoc_s: Association as serialized by serialize()
@type assoc_s: str
@return: instance of this class |
16,378 | def render(self, name, value, attrs=None, renderer=None):
if self.has_template_widget_rendering:
return super(ClearableFileInputWithImagePreview, self).render(
name, value, attrs=attrs, renderer=renderer
)
else:
context = self.get_context(name... | Render the widget as an HTML string.
Overridden here to support Django < 1.11. |
16,379 | def _validate(self, writing=False):
if (((len(self.fragment_offset) != len(self.fragment_length)) or
(len(self.fragment_length) != len(self.data_reference)))):
msg = ("The lengths of the fragment offsets ({len_offsets}), "
"fragment lengths ({len_fragments}),... | Validate internal correctness. |
16,380 | def _use_framework(module):
import txaio
for method_name in __all__:
if method_name in [, ]:
continue
setattr(txaio, method_name,
getattr(module, method_name)) | Internal helper, to set this modules methods to a specified
framework helper-methods. |
16,381 | def _outer_values_update(self, full_values):
super(BayesianGPLVMMiniBatch, self)._outer_values_update(full_values)
if self.has_uncertain_inputs():
meangrad_tmp, vargrad_tmp = self.kern.gradients_qX_expectations(
variational_posterior=self.... | Here you put the values, which were collected before in the right places.
E.g. set the gradients of parameters, etc. |
16,382 | def process_event(self, event_name: str, data: dict) -> None:
if event_name == "after_epoch":
self.epochs_done = data["epochs_done"]
self.batches_seen = data["batches_seen"]
self.train_examples_seen = data["train_examples_seen"]
return | Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None |
16,383 | def _nodeSatisfiesValue(cntxt: Context, n: Node, vsv: ShExJ.valueSetValue) -> bool:
vsv = map_object_literal(vsv)
if isinstance_(vsv, ShExJ.objectValue):
return objectValueMatches(n, vsv)
if isinstance(vsv, ShExJ.Language):
if vsv.languageTag is not None and isinstance(n, Literal) and ... | A term matches a valueSetValue if:
* vsv is an objectValue and n = vsv.
* vsv is a Language with langTag lt and n is a language-tagged string with a language tag l and l = lt.
* vsv is a IriStem, LiteralStem or LanguageStem with stem st and nodeIn(n, st).
* vsv is a IriStemRange, Literal... |
16,384 | def labels(self, hs_dims=None, prune=False):
if self.ca_as_0th:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]
else:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:]
if not prune:
return labels
def pr... | Get labels for the cube slice, and perform pruning by slice. |
16,385 | def nextProperty(self, propuri):
if propuri == self.properties[-1].uri:
return self.properties[0]
flag = False
for x in self.properties:
if flag == True:
return x
if x.uri == propuri:
flag = True
return None | Returns the next property in the list of properties. If it's the last one, returns the first one. |
16,386 | def sync_firmware(self):
serial_no = self.serial_number
if self.firmware_newer():
try:
self.update_firmware()
except errors.JLinkException as e:
pass
... | Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
``None`` |
16,387 | def wrap_text_in_a_box(body=, title=, style=, **args):
r
def _wrap_row(row, max_col, break_long):
spaces = _RE_BEGINNING_SPACES.match(row).group()
row = row[len(spaces):]
spaces = spaces.expandtabs()
return textwrap.wrap(row, initial_indent=spaces,
... | r"""Return a nicely formatted text box.
e.g.
******************
** title **
**--------------**
** body **
******************
Indentation and newline are respected.
:param body: the main text
:param title: an optional title
:param style: the na... |
16,388 | def x_forwarded_for(self):
ip = self._request.META.get()
current_xff = self.headers.get()
return % (current_xff, ip) if current_xff else ip | X-Forwarded-For header value.
This is the amended header so that it contains the previous IP address
in the forwarding change. |
16,389 | def get_client_class(self, client_class_name):
request_url = self._build_url([, client_class_name])
return self._do_request(, request_url) | Returns a specific client class details from CPNR server. |
16,390 | def get_template(template_dict, parameter_overrides=None):
template_dict = template_dict or {}
if template_dict:
template_dict = SamTranslatorWrapper(template_dict).run_plugins()
template_dict = SamBaseProvider._resolve_parameters(template_dict, parameter_overrides)
... | Given a SAM template dictionary, return a cleaned copy of the template where SAM plugins have been run
and parameter values have been substituted.
Parameters
----------
template_dict : dict
unprocessed SAM template dictionary
parameter_overrides: dict
Op... |
16,391 | def _get_username(self, username=None, use_config=True, config_filename=None):
if not username and use_config:
if self._config is None:
self._read_config(config_filename)
username = self._config.get("credentials", "username", fallback=None)
if not userna... | Determine the username
If a username is given, this name is used. Otherwise the configuration
file will be consulted if `use_config` is set to True. The user is asked
for the username if the username is not available. Then the username is
stored in the configuration file.
:para... |
16,392 | def IsOutOfLineMethodDefinition(clean_lines, linenum):
for i in xrange(linenum, max(-1, linenum - 10), -1):
if Match(r, clean_lines.elided[i]):
return Match(r, clean_lines.elided[i]) is not None
return False | Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition. |
16,393 | def insert(self, var, value, index=None):
current = self.__get(var)
if not isinstance(current, list):
raise KeyError("%s: is not a list" % var)
if index is None:
current.append(value)
else:
current.insert(index, value)
if self.auto_sav... | Insert at the index.
If the index is not provided appends to the end of the list. |
16,394 | def datafind_connection(server=None):
if server:
datafind_server = server
else:
if in os.environ:
datafind_server = os.environ["LIGO_DATAFIND_SERVER"]
else:
err = "Trying to obtain the ligo datafind server url from "
err += "the environ... | Return a connection to the datafind server
Parameters
-----------
server : {SERVER:PORT, string}, optional
A string representation of the server and port.
The port may be ommitted.
Returns
--------
connection
The open connection to the datafind server. |
16,395 | def get_source(self, environment, template):
./.././../
_template = template
if template.split(, 1)[0] in (, ):
is_relative = True
else:
is_relative = False
if is_relative:
if not environment or not in environme... | Salt-specific loader to find imported jinja files.
Jinja imports will be interpreted as originating from the top
of each of the directories in the searchpath when the template
name does not begin with './' or '../'. When a template name
begins with './' or '../' then the import will be... |
16,396 | def add_section(self, section):
self._sections = self._ensure_append(section, self._sections) | A block section of code to be used as substitutions
:param section: A block section of code to be used as substitutions
:type section: Section |
16,397 | def teetsv(table, source=None, encoding=None, errors=, write_header=True,
**csvargs):
csvargs.setdefault(, )
return teecsv(table, source=source, encoding=encoding, errors=errors,
write_header=write_header, **csvargs) | Convenience function, as :func:`petl.io.csv.teecsv` but with different
default dialect (tab delimited). |
16,398 | def fundrefxml2json(self, node):
doi = FundRefDOIResolver.strip_doi_host(self.get_attrib(node,
))
oaf_id = FundRefDOIResolver().resolve_by_doi(
"http://dx.doi.org/" + doi)
name = node.find(,
namespaces=... | Convert a FundRef 'skos:Concept' node into JSON. |
16,399 | def _summarize_o_mutation_type(model):
from nautilus.api.util import summarize_mutation_io
object_type_name = get_model_string(model)
return summarize_mutation_io(
name=object_type_name,
type=_summarize_object_type(model),
required=False
) | This function create the actual mutation io summary corresponding to the model |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.