Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
344,500 | def web_command(command, ro=None, rw=None, links=None,
image=, volumes_from=None, commit=False,
clean_up=False, stream_output=None, entrypoint=None):
binds = ro_rw_to_binds(ro, rw)
c = _get_docker().create_container(
image=image,
command=command,
volu... | Run a single command in a web image optionally preloaded with the ckan
source and virtual envrionment.
:param command: command to execute
:param ro: {localdir: binddir} dict for read-only volumes
:param rw: {localdir: binddir} dict for read-write volumes
:param links: links passed to start
:par... |
344,501 | def patch(self, path, value=None):
def pathGet(dictionary, path):
for item in path.split("/"):
dictionary = dictionary[item]
return dictionary
def pathSet(dictionary, path, value):
path = path.split("/")
key = pa... | Set specified value to yaml path.
Example:
patch('application/components/child/configuration/__locator.application-id','777')
Will change child app ID to 777 |
344,502 | def editor(self, filename, linenum=None, wait=True):
editor = self.editor
if linenum is None or editor==:
linemark =
else:
linemark = % int(linenum)
if in editor and os.path.isfile(editor) and editor[0] != :
editor = % editor
proc = subpr... | Open the default editor at the given filename and linenumber.
This is IPython's default editor hook, you can use it as an example to
write your own modified one. To set your own editor function as the
new editor hook, call ip.set_hook('editor',yourfunc). |
344,503 | def click(self, x, y, button, press):
if button == 1:
if press:
print(self.fibo.next())
else:
self.stop() | Print Fibonacci numbers when the left click is pressed. |
344,504 | def compress(self):
for ast_token in self.ast_tokens:
if type(ast_token) in self.dispatcher:
self.dispatcher[type(ast_token)](ast_token)
else:
self.dispatcher[](ast_token) | Main function of compression. |
344,505 | def run_profile(self, profile, names, vm_overrides=None):
if profile not in self.opts[]:
msg = .format(profile)
log.error(msg)
return {: msg}
ret = {}
if not vm_overrides:
vm_overrides = {}
try:
with salt.utils.files.... | Parse over the options passed on the command line and determine how to
handle them |
344,506 | def memo(f):
def inner(self, memo=None, **kwargs):
if memo is None:
memo = {}
if id(self) in memo:
return memo[id(self)]
else:
c = f(self, memo, **kwargs)
memo[id(self)] = c
return c
... | A decorator function you should apply to ``copy`` |
344,507 | def encode_offset_commit_request_kafka(cls, group, payloads):
return kafka.protocol.commit.OffsetCommitRequest[2](
consumer_group=group,
consumer_group_generation_id=kafka.protocol.commit.OffsetCommitRequest[2].DEFAULT_GENERATION_ID,
consumer_id=,
retenti... | Encode an OffsetCommitRequest struct
Arguments:
group: string, the consumer group you are committing offsets for
payloads: list of OffsetCommitRequestPayload |
344,508 | def transitions(self):
if self._transitions is not None:
return self._transitions
transitions = self.array.astype(np.float)
transitions /= transitions.sum(1)[:, np.newaxis]
self._transitions = transitions
return transitions | Dense [k-1]x4 transition frequency matrix |
344,509 | def default_asset_manager(self):
cache_path = None
cache_directory = self.config[]
if cache_directory:
cache_directory = cache_directory.format(version=__version__)
cache_path = os.path.join(self.instance_path, cache_directory)
return GitHubAssetManager(
... | Returns the default asset manager using the current config.
This is only used if asset_manager is set to None in the constructor. |
344,510 | def add_callbacks(self, future, callback, errback):
assert future is not None
if callback is None:
assert errback is not None
future.addErrback(errback)
else:
future.addCallbacks(callback, errback)
return future | callback or errback may be None, but at least one must be
non-None. |
344,511 | def _parse_relationship(self):
rs_dict = self.data.get(, {})
for rs_name in self.KNOWN_RELATIONSHIPS:
if rs_name in rs_dict:
setattr(
self, rs_name, Relationship(rs_name, rs_dict.get(rs_name)))
else:
se... | Nodes have Relationships, and similarly to properties,
we set it as an attribute on the Organization so we can make calls like
company.current_team
person.degrees |
344,512 | def cleanup(keep_latest=True):
*
removed = []
for kernel in list_installed():
if kernel == active():
continue
if keep_latest and kernel == latest_installed():
continue
removed.extend(remove(kernel)[])
return {: removed} | Remove all unused kernel packages from the system.
keep_latest : True
In the event that the active kernel is not the latest one installed, setting this to True
will retain the latest kernel package, in addition to the active one. If False, all kernel
packages other than the active one will ... |
344,513 | def select_multi_directory_dialog():
import wx.lib.agw.multidirdialog as MDD
app = wx.App(0)
dlg = MDD.MultiDirDialog(None, title="Select directories", defaultPath=os.getcwd(),
agwStyle=MDD.DD_MULTIPLE | MDD.DD_DIR_MUST_EXIST)
if dlg.ShowModal() != wx.ID_OK:
d... | Opens a directory selection dialog
Style - specifies style of dialog (read wx documentation for information) |
344,514 | def _partition_results(self, results):
t darkcontacted']):
results2["dark"][host] = {}
return results2 | seperate results by ones we contacted & ones we didn't |
344,515 | def _print_console_link(region, application_id):
if not region:
region = boto3.Session().region_name
console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace(, ))
msg = "Click the link below to view your application in AWS console:\n{}".format(console_link)
click.sec... | Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application |
344,516 | async def lock(self, device):
device = self._find_device(device)
if not self.is_handleable(device) or not device.is_crypto:
self._log.warn(_(, device))
return False
if not device.is_unlocked:
self._log.info(_(, device))
return True
... | Lock device if unlocked.
:param device: device object, block device path or mount path
:returns: whether the device is locked |
344,517 | def get_signature_params(func):
if is_cython(func):
attrs = [
"__code__", "__annotations__", "__defaults__", "__kwdefaults__"
]
if all(hasattr(func, attr) for attr in attrs):
original_func = func
def func():
return
... | Get signature parameters
Support Cython functions by grabbing relevant attributes from the Cython
function and attaching to a no-op function. This is somewhat brittle, since
funcsigs may change, but given that funcsigs is written to a PEP, we hope
it is relatively stable. Future versions of Python may ... |
344,518 | def getlinelist(self, section, option):
value_list = self.get(section, option)
return list(filter(None, value_list.split())) | Read a list of full-line strings.
The value of `section` and `option` is treated as a newline-separated
list of strings. Each value is stripped of whitespace.
Returns the list of strings. |
344,519 | def _on_fork(cls):
cls._cls_idle_socketpairs = []
while cls._cls_all_sockets:
cls._cls_all_sockets.pop().close() | Clean up any files belonging to the parent process after a fork. |
344,520 | def runCommands(self,commands,args):
errorCounter = 0
if args.list:
print .join(commands)
else:
for command in commands:
process = subprocess.Popen(command, stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
str... | Given a list of commands, runCommands executes them.
This is one of the two key methods of MapExecutor. |
344,521 | def import_freesurfer_LUT(fs_lut=None):
if fs_lut is not None:
lg.info(.format(fs_lut))
fs_lut = Path(fs_lut)
else:
try:
fs_home = environ[]
except KeyError:
raise OSError(
)
else:
fs_lut = Path(fs_home) /... | Import Look-up Table with colors and labels for anatomical regions.
It's necessary that Freesurfer is installed and that the environmental
variable 'FREESURFER_HOME' is present.
Parameters
----------
fs_lut : str or Path
path to file called FreeSurferColorLUT.txt
Returns
-------
... |
344,522 | def columbus_day(year, country=):
if country == :
return nth_day_of_month(2, MON, OCT, year)
else:
return (year, OCT, 12) | in USA: 2nd Monday in Oct
Elsewhere: Oct 12 |
344,523 | def smooth(x, y, degree=1, logx=False, logy=False):
if degree == 0:
return x, y
else:
if logx:
x = np.log10(x)
if logy:
y = np.log10(y)
if degree == 1:
smoothed_x = np.linspace(min(x), max(x), len(x))
... | Smooth y-values and return new x, y pair.
:param x,y: data values
:param degree: degree of smoothing
Smooth data by using a recursive linear interpolation technique. For
degree = 0, return the original values. For degree = 1, generate a
evenly spaced sequence of x-values, with the length equal t... |
344,524 | def save(self, prefix, epoch=None):
if epoch is None:
epoch = self.num_epoch
assert epoch is not None
save_checkpoint(prefix, epoch, self.symbol, self.arg_params, self.aux_params) | Checkpoint the model checkpoint into file.
You can also use `pickle` to do the job if you only work on Python.
The advantage of `load` and `save` (as compared to `pickle`) is that
the resulting file can be loaded from other MXNet language bindings.
One can also directly `load`/`save` fro... |
344,525 | def limited_to(self, left: Set[TLeft], right: Set[TRight]) -> :
return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 in left and n2 in right) | Returns the induced subgraph where only the nodes from the given sets are included. |
344,526 | def auth(alias=None, url=None, cfg="~/.xnat_auth"):
xnatastichttps://www.xnatastic.org/username********
if not alias and not url:
raise ValueError()
if alias and url:
raise ValueError()
cfg = os.path.expanduser(cfg)
if not os.path.exists(cfg):
raise AuthError("could not ... | Read connection details from an xnat_auth XML file
Example:
>>> import yaxil
>>> auth = yaxil.auth('xnatastic')
>>> auth.url, auth.username, auth.password
('https://www.xnatastic.org/', 'username', '********')
:param alias: XNAT alias
:type alias: str
:param url: XNAT U... |
344,527 | def fit(self, X, y):
X, event_num, time = self._pre_fit(X, y)
create_path, alphas, penalty = self._check_params(X.shape[1])
coef, alphas, deviance_ratio, n_iter = call_fit_coxnet(
X, time, event_num, penalty, alphas, create_path,
self.alpha_min_ratio, self.l1_ra... | Fit estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
Data matrix
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censorin... |
344,528 | def positions(self, x, y):
return [(Point(x, v), Point(x + 1 + v, y - 1 - v)) for v in range(y)] | Get all positions, that can be combined to get word parsed at specified position.
:param x: X coordinate.
:param y: Y coordinate.
:return: List of tuples with two Point instances. |
344,529 | def get_mon_initial_members(args, error_on_empty=False, _cfg=None):
if _cfg:
cfg = _cfg
else:
cfg = conf.ceph.load(args)
mon_initial_members = cfg.safe_get(, )
if not mon_initial_members:
if error_on_empty:
raise exc.NeedHostError(
)
... | Read the Ceph config file and return the value of mon_initial_members
Optionally, a NeedHostError can be raised if the value is None. |
344,530 | def delete(self,removed):
if isinstance(removed,dict):
removed = [removed]
else:
removed = [ r for r in removed ]
if not removed:
return 0
_ids = [ r[] for r in removed ]
_ids.sort()
keys = s... | Remove a single record, or the records in an iterable
Before starting deletion, test if all records are in the base
and don't have twice the same __id__
Return the number of deleted items |
344,531 | def uri_to_iri(uri, charset=, errors=):
r
uri = url_fix(str(uri), charset)
scheme, auth, hostname, port, path, query, fragment = _uri_split(uri)
scheme = _decode_unicode(scheme, , errors)
try:
hostname = hostname.decode()
except UnicodeError:
if errors not in ... | r"""Converts a URI in a given charset to a IRI.
Examples for URI versus IRI
>>> uri_to_iri('http://xn--n3h.net/')
u'http://\u2603.net/'
>>> uri_to_iri('http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th')
u'http://\xfcser:p\xe4ssword@\u2603.net/p\xe5th'
Query strings are left unchanged:
... |
344,532 | def find_type(self, txt):
searchString = txt.upper()
match =
for i in self.lst_type:
if searchString in i:
match = i
return match | top level function used to simply return the
ONE ACTUAL string used for data types |
344,533 | def add(x1, x2, output_shape=None, name=None):
output_shape = convert_to_shape(output_shape)
if not isinstance(x2, Tensor):
return ScalarAddOperation(x1, x2).outputs[0]
with tf.name_scope(name, default_name="add"):
x1, x2 = binary_arguments_to_tensors(x1, x2)
return AddOperation(
x1, x2, ou... | Binary addition with broadcsting.
Args:
x1: a Tensor
x2: a Tensor
output_shape: an optional Shape
name: an optional string
Returns:
a Tensor |
344,534 | def _update_annotations(discretized_pulse: Callable) -> Callable:
undecorated_annotations = list(discretized_pulse.__annotations__.items())
decorated_annotations = undecorated_annotations[1:]
decorated_annotations.insert(0, (, int))
discretized_pulse.__annotations__ = dict(decorated_annotations)
... | Update annotations of discretized continuous pulse function with duration.
Args:
discretized_pulse: Discretized decorated continuous pulse. |
344,535 | def MergeFlags(self, args, unique=1, dict=None):
if dict is None:
dict = self
if not SCons.Util.is_Dict(args):
args = self.ParseFlags(args)
if not unique:
self.Append(**args)
return self
for key, value in args.items():
... | Merge the dict in args into the construction variables of this
env, or the passed-in dict. If args is not a dict, it is
converted into a dict using ParseFlags. If unique is not set,
the flags are appended rather than merged. |
344,536 | def read_int(self, signed=True):
return int.from_bytes(self.read(4), byteorder=, signed=signed) | Reads an integer (4 bytes) value. |
344,537 | def run_output(self):
for f in logdissect.output.__formats__:
ouroutput = self.output_modules[f]
ouroutput.write_output(self.data_set[],
args=self.args)
del(ouroutput)
if not self.args.silentmode:
if self.args.verbose... | Output finalized data |
344,538 | def get_subdomain_entry_at_sequence(self, fqn, sequence, include_unaccepted=False, cur=None):
get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? AND sequence = ?".format(self.subdomain_table)
if not include_unaccepted:
get_cmd += " AND accepted=1"
cursor = None
... | Given a fully-qualified subdomain and a sequence number, get its historic subdomain record at that sequence.
Raises SubdomainNotFound if there is no such subdomain |
344,539 | def plot_ic_by_group(ic_group, ax=None):
if ax is None:
f, ax = plt.subplots(1, 1, figsize=(18, 6))
ic_group.plot(kind=, ax=ax)
ax.set(title="Information Coefficient By Group", xlabel="")
ax.set_xticklabels(ic_group.index, rotation=45)
return ax | Plots Spearman Rank Information Coefficient for a given factor over
provided forward returns. Separates by group.
Parameters
----------
ic_group : pd.DataFrame
group-wise mean period wise returns.
ax : matplotlib.Axes, optional
Axes upon which to plot.
Returns
-------
a... |
344,540 | def fix_missing_electronic_locator_tag(dom, url):
electronic_locator = dom.match(
"mods:mods",
"mods:location",
"mods:holdingSimple",
"mods:copyInformation",
"mods:electronicLocator",
)
if electronic_locator:
return
location = dom.match("mo... | In case that MODS contains no URL and the location is wrong (physical), add
url from `url` parameter. |
344,541 | def _init_weights(self,
X):
X = np.asarray(X, dtype=np.float64)
if self.scaler is not None:
X = self.scaler.fit_transform(X)
if self.initializer is not None:
self.weights = self.initializer(X, self.num_neurons)
for v in self.param... | Set the weights and normalize data before starting training. |
344,542 | def _ConvertValueBinaryDataToUBInt64(self, value):
if not value:
return None
integer_map = self._GetDataTypeMap()
try:
return self._ReadStructureFromByteStream(value, 0, integer_map)
except (ValueError, errors.ParseError) as exception:
raise errors.ParseError(
.format(... | Converts a binary data value into an integer.
Args:
value (bytes): binary data value containing an unsigned 64-bit big-endian
integer.
Returns:
int: integer representation of binary data value or None if value is
not set.
Raises:
ParseError: if the integer value cann... |
344,543 | def json_qs_parser(body):
try:
return json.loads(body)
except (OverflowError, TypeError, ValueError):
pass
try:
return ElementTree.fromstring(body)
except (ElementTree.ParseError, TypeError, ValueError):
pass
return dict(parse.parse_qsl(b... | Parses response body from JSON, XML or query string.
:param body:
string
:returns:
:class:`dict`, :class:`list` if input is JSON or query string,
:class:`xml.etree.ElementTree.Element` if XML. |
344,544 | def jquery_js(version=None, migrate=False):
version = version or settings.JQUERY_VERSION
suffix = if not settings.DEBUG else
libs = [js_lib( % (version, suffix))]
if _boolean(migrate):
libs.append(js_lib( % (JQUERY_MIGRATE_VERSION, suffix)))
return .join(libs) | A shortcut to render a ``script`` tag for the packaged jQuery |
344,545 | def _init():
global config, _data_path, _allowed_config_keys
app_dir = _get_vispy_app_dir()
if app_dir is not None:
_data_path = op.join(app_dir, )
_test_data_path = op.join(app_dir, )
else:
_data_path = _test_data_path = None
_allowed_config_keys = {
: st... | Create global Config object, parse command flags |
344,546 | def sgn_prod(p1, p2):
r
phase = Pauli._prod_phase(p1, p2)
new_pauli = p1 * p2
return new_pauli, phase | r"""
Multiply two Paulis and track the phase.
$P_3 = P_1 \otimes P_2$: X*Y
Args:
p1 (Pauli): pauli 1
p2 (Pauli): pauli 2
Returns:
Pauli: the multiplied pauli
complex: the sign of the multiplication, 1, -1, 1j or -1j |
344,547 | def from_tablib(self, tablib_dataset):
self.headers = tablib_dataset.headers
self.value_matrix = [row for row in tablib_dataset] | Set tabular attributes to the writer from :py:class:`tablib.Dataset`. |
344,548 | def band_width(high_data, low_data, period):
catch_errors.check_for_input_len_diff(high_data, low_data)
diff = np.array(high_data) - np.array(low_data)
bw = sma(diff, period)
return bw | Bandwidth.
Formula:
BW = SMA(H - L) |
344,549 | def publish_brightness(self, brightness):
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.brightness(self.sequence_number, brightness))
return self.sequence_number | publish changed brightness |
344,550 | def get_elements(self, center=, asteroid=False, comet=False):
objectname = urllib.quote(self.targetname.encode("utf8"))
url = "https://ssd.jpl.nasa.gov/horizons_batch.cgi?batch=l" \
+ "&TABLE_TYPE=" \
+ "&CSV_FORMAT=" \
+ "&CENTER=" \
... | Call JPL HORIZONS website to obtain orbital elements based on the
provided targetname, epochs, and center code. For valid center
codes, please refer to http://ssd.jpl.nasa.gov/horizons.cgi
:param center: str;
center body (default: 500@10 = Sun)
:result: int; number of epochs... |
344,551 | def map_legend_attributes(self):
LOGGER.debug()
legend_attribute_list = [
,
,
]
legend_attribute_dict = {}
for legend_attribute in legend_attribute_list:
try:
legend_attribute_dict[legend_attribute] = \... | Get the map legend attribute from the layer keywords if possible.
:returns: None on error, otherwise the attributes (notes and units).
:rtype: None, str |
344,552 | def add_marker_to_qtl(qtl, map_list):
closest =
diff = None
for marker in map_list:
if qtl[1] == marker[1]:
tmp_diff = float(qtl[2]) - float(marker[2])
if diff is None or abs(diff) > abs(tmp_diff):
diff = tmp_diff
closest = marker
if ... | Add the closest marker to the given QTL.
:arg qtl: a row of the QTL list.
:arg map_list: the genetic map containing the list of markers. |
344,553 | def create(self, name):
if self.queue_exists(name):
raise exc.DuplicateQueue("The queue already exists." % name)
return self._manager.create(name) | Cloud Queues works differently, in that they use the name as the ID for
the resource. So for create(), we need to check if a queue by that name
exists already, and raise an exception if it does. If not, create the
queue and return a reference object for it. |
344,554 | def _interpret_angle(name, angle_object, angle_float, unit=):
if angle_object is not None:
if isinstance(angle_object, Angle):
return angle_object.radians
elif angle_float is not None:
return _unsexagesimalize(angle_float) * _from_degrees
raise ValueError(
... | Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interp... |
344,555 | def setenv(self, env=None, clean=True, silent=True, filename=None):
env = env or self.ENV_FOR_DYNACONF
if not isinstance(env, str):
raise AttributeError("env should be a string")
if "_" in env:
raise AttributeError("env should not contains _")
self.logg... | Used to interactively change the env
Example of settings.toml::
[development]
message = 'This is in dev'
[other]
message = 'this is in other env'
Program::
>>> from dynaconf import settings
>>> print settings.MESSAGE
... |
344,556 | def clean_email(self):
email = self.cleaned_data.get("email")
qs = User.objects.exclude(id=self.instance.id).filter(email=email)
if len(qs) == 0:
return email
raise forms.ValidationError(
ugettext("This email is already registered")) | Ensure the email address is not already registered. |
344,557 | def autostrip(cls):
warnings.warn(
"django-annoying autostrip is deprecated and will be removed in a "
"future version. Django now has native support for stripping form "
"fields. "
"https://docs.djangoproject.com/en/stable/ref/forms/fields/
DeprecationWarning,
s... | strip text fields before validation
example:
@autostrip
class PersonForm(forms.Form):
name = forms.CharField(min_length=2, max_length=10)
email = forms.EmailField()
Author: nail.xx |
344,558 | def heads(config, **kwargs):
with alembic_lock(
config.registry["sqlalchemy.engine"], config.alembic_config()
) as alembic_config:
alembic.command.heads(alembic_config, **kwargs) | Show current available heads. |
344,559 | def shuffle_genome(genome, cat, fraction = float(100), plot = True, \
alpha = 0.1, beta = 100000, \
min_length = 1000, max_length = 200000):
header = % (genome.name)
sequence = list(.join([i[1] for i in parse_fasta(genome)]))
length = len(sequence)
shuffled = []
while sequ... | randomly shuffle genome |
344,560 | def extract_indexes(coords):
for name, variable in coords.items():
variable = as_variable(variable, name=name)
if variable.dims == (name,):
yield name, variable.to_index() | Yields the name & index of valid indexes from a mapping of coords |
344,561 | def device_event_list(self, **kwargs):
kwargs[] = True
if kwargs.get():
return self.device_event_list_with_http_info(**kwargs)
else:
(data) = self.device_event_list_with_http_info(**kwargs)
return data | List all device events. # noqa: E501
List all device events for an account. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_event_list(asynchronous=True)
>>> resul... |
344,562 | def to_dict(self):
pipeline_desc_as_dict = {
: self._uid,
: self._name,
: self._state,
: self._state_history,
: self._completed_flag.is_set()
}
return pipeline_desc_as_dict | Convert current Pipeline (i.e. its attributes) into a dictionary
:return: python dictionary |
344,563 | def grep(rootdir, searched):
"grep -l <searched>"
to_inspect = []
for root, dirs, files in os.walk(rootdir):
for _file in files:
if _file.endswith():
to_inspect.append(join(root, _file))
to_check = ((_file, open(_file, ).read()) for _file in to_inspect)
to_check ... | grep -l <searched> |
344,564 | def __loop_recur_to_py_ast(ctx: GeneratorContext, node: Recur) -> GeneratedPyAST:
assert node.op == NodeOp.RECUR
recur_deps: List[ast.AST] = []
recur_targets: List[ast.Name] = []
recur_exprs: List[ast.AST] = []
for name, expr in zip(ctx.recur_point.binding_names, node.exprs):
expr_ast ... | Return a Python AST node for `recur` occurring inside a `loop`. |
344,565 | def _get_deltas(self, sites):
siteclass = sites.siteclass
delta_C = np.zeros_like(siteclass, dtype=np.float)
delta_C[siteclass == b] = 1
delta_D = np.zeros_like(siteclass, dtype=np.float)
delta_D[siteclass == b] = 1
return delta_C, delta_D | Return delta's for equation 4
delta_C = 1 for site class C, 0 otherwise
delta_D = 1 for site class D, 0 otherwise |
344,566 | def parse_form(self, req, name, field):
return get_value(req.body_arguments, name, field) | Pull a form value from the request. |
344,567 | def edit(self, state):
if state and state.lower() == :
data = dumps({: state.lower()})
json = self._json(self._patch(self._api, data=data))
self._update_attributes(json)
return self | Edit the user's membership.
:param str state: (required), the state the membership should be in.
Only accepts ``"active"``.
:returns: itself |
344,568 | def _column_type(strings, has_invisible=True, numparse=True):
types = [_type(s, has_invisible, numparse) for s in strings]
return reduce(_more_generic, types, _bool_type) | The least generic type all column values are convertible to.
>>> _column_type([True, False]) is _bool_type
True
>>> _column_type(["1", "2"]) is _int_type
True
>>> _column_type(["1", "2.3"]) is _float_type
True
>>> _column_type(["1", "2.3", "four"]) is _text_type
True
>>> _column_typ... |
344,569 | def untar_file(filename, location):
ensure_dir(location)
if filename.lower().endswith() or filename.lower().endswith():
mode =
elif filename.lower().endswith(BZ2_EXTENSIONS):
mode =
elif filename.lower().endswith():
mode =
else:
logger.warning(
, f... | Untar the file (with path `filename`) to the destination `location`.
All files are written based on system defaults and umask (i.e. permissions
are not preserved), except that regular file members with any execute
permissions (user, group, or world) have "chmod +x" applied after being
written. Note tha... |
344,570 | def get_data_modality(self):
resource_types = self.get_resource_types()
first_type = resource_types[0]
if first_type != :
return first_type
elif len(resource_types) == 1:
return
else:
second_type = resource_types[1]
if s... | Detect the data modality based on the resource_types.
resource_types == ['table'] => 'single_table'
resource_types == ['something_else'...] => 'something_else' # this is not likely
resource_types == ['table', 'table'...] => 'multi_table'
resource_types == ['table', 'something_else'...... |
344,571 | def filter_by_missing(max_miss=0.01):
def f(G, bim):
Isnp = sp.isnan(G).mean(0) < max_miss
G_out = G[:, Isnp]
bim_out = bim[Isnp]
return G_out, bim_out
return f | return function that filters by missing values
(takes maximum fraction of missing values, default is 0.01) |
344,572 | def clean_html(self, html):
result_type = type(html)
if isinstance(html, six.string_types):
doc = html_fromstring(html)
else:
doc = copy.deepcopy(html)
self(doc)
if issubclass(result_type, six.binary_type):
return tostring(doc, encodin... | Apply ``Cleaner`` to HTML string or document and return a cleaned string or document. |
344,573 | def bucketCSVs(csvFile, bucketIdx=2):
try:
with open(csvFile, "rU") as f:
reader = csv.reader(f)
headers = next(reader, None)
dataDict = OrderedDict()
for lineNumber, line in enumerate(reader):
if line[bucketIdx] in dataDict:
dataDict[line[bucketIdx]].append(line)
... | Write the individual buckets in csvFile to their own CSV files. |
344,574 | def pprint_arg(vnames, value):
ret =
for name, v in zip(vnames, value):
ret += % (name, str(v))
return ret; | pretty print argument
:param vnames:
:param value:
:return: |
344,575 | def inc(self, key, key_length=0):
if key_length < 1:
key_length = len(key)
val = self.add_method(self, key, key_length, 1)
if self.k:
self._update(key, val)
return val | Add value to key-value
Params:
<str> key
<int> value
<int> key_length
Return:
<int> key_value |
344,576 | def _prefix_is_authorized(self, path):
path = os.path.abspath(path)
while True:
if path in self._prefixes:
return True
if path == :
break
path = os.path.dirname(path)
return False | Return the set of all possible directory prefixes for `path`.
:func:`os.path.abspath` is used to ensure the path is absolute.
:param str path:
The path.
:returns: Set of prefixes. |
344,577 | def download_financialzip():
result = get_filename()
res = []
for item, md5 in result:
if item in os.listdir(download_path) and md5==QA_util_file_md5(.format(download_path,os.sep,item)):
print(.format(item, download_path))
else:
print(.format(item[0:... | 会创建一个download/文件夹 |
344,578 | def load_class(path):
package, klass = path.rsplit(, 1)
module = import_module(package)
return getattr(module, klass) | dynamically load a class given a string of the format
package.Class |
344,579 | def force_user_presence(self, user: User, presence: UserPresence):
self._userid_to_presence[user.user_id] = presence | Forcibly set the ``user`` presence to ``presence``.
This method is only provided to cover an edge case in our use of the Matrix protocol and
should **not** generally be used. |
344,580 | def peek(self, default=_marker):
if not self._cache:
try:
self._cache.append(next(self._it))
except StopIteration:
if default is _marker:
raise
return default
return self._cache[0] | Return the item that will be next returned from ``next()``.
Return ``default`` if there are no items left. If ``default`` is not
provided, raise ``StopIteration``. |
344,581 | def decrypt_gpp(password):
iv = b"\x00" * 16
password += "=" * ((4 - len(password) % 4) % 4)
password = b64decode(password)
key = .replace(" ","").replace("\n","")
key = unhexlify(key)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = ... | Decrypt the password of local users added via Windows 2008 Group Policy Preferences.
This value is the 'cpassword' attribute embedded in the Groups.xml file, stored in the domain controller's Sysvol share.
Example:
\b
# habu.decrypt.gpp AzVJmXh/J9KrU5n0czX1uBPLSUjzFE8j7dOltPD8tLk
testpassword |
344,582 | def calc_am_um_v1(self):
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
if flu.h <= 0.:
flu.am = 0.
flu.um = 0.
elif flu.h < con.hm:
flu.am = flu.h*(con.bm+flu.h*con.bnm)
flu.um = con.bm+2.*flu.h*(1.+con.bnm**2)**.5
else:
... | Calculate the flown through area and the wetted perimeter
of the main channel.
Note that the main channel is assumed to have identical slopes on
both sides and that water flowing exactly above the main channel is
contributing to |AM|. Both theoretical surfaces seperating water
above the main chann... |
344,583 | def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None,
update_endpoint=False, tags=None, kms_key=None):
if not self.sagemaker_session:
if instance_type in (, ):
self.sagemaker_session = local.LocalSession()
... | Deploy this ``Model`` to an ``Endpoint`` and optionally return a ``Predictor``.
Create a SageMaker ``Model`` and ``EndpointConfig``, and deploy an ``Endpoint`` from this ``Model``.
If ``self.predictor_cls`` is not None, this method returns a the result of invoking
``self.predictor_cls`` on the ... |
344,584 | def add_mutually_exclusive_args(parser, args, required=False, prefix=DATA_PREFIX):
parser = parser.add_mutually_exclusive_group(required=required)
for arg, kwargs in iteritems(args):
arg_name = kwargs.pop(, arg.replace(, ))
if not in kwargs:
kwargs[] = arg.upper()
parse... | Helper method that populates mutually exclusive arguments. The argument values can
be later retrieved with `extract_arguments` method.
The `args` argument to this method should be a dict with strings as
keys and dicts as values. The keys will be used as keys in returned
data. Their values will be passe... |
344,585 | def U_ij(q_vars: List[fl.Var], mass: np.ndarray, i: int, j: int):
assert len(q_vars) == 3 * len(mass)
mi = mass[i]
mj = mass[j]
U = -(G * mi * mj) / flux_r(q_vars, i, j)
return U | Make Fluxion with the gratiational potential energy beween body i and j |
344,586 | def check_version(actver, version, cmp_op):
if isinstance(actver, tuple):
actver = .join([str(i) for i in actver])
if is_stable_version(version) and not is_stable_version(actver) and \
actver.startswith(version) and version != actver:
version = version +
elif i... | Check version string of an active module against a required version.
If dev/prerelease tags result in TypeError for string-number comparison,
it is assumed that the dependency is satisfied.
Users on dev branches are responsible for keeping their own packages up to
date.
Copyright (C) 20... |
344,587 | def _req_upload(self, filename, directory):
self._upload_url = self._load_upload_url()
self.http.get()
b = os.path.basename(filename)
target = + str(directory.cid)
files = {
: (, quote(b), ),
: (, target, ),
: (quote(b), open(filename... | Raw request to upload a file ``filename`` |
344,588 | def lookup_whois(self, hr=True, show_name=False, colorize=True, **kwargs):
ret = self.obj.lookup_whois(**kwargs)
if script_args.json:
output = json.dumps(ret)
else:
output = self.generate_output_header(query_type=)
... | The function for wrapping IPWhois.lookup_whois() and generating
formatted CLI output.
Args:
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show shor... |
344,589 | def refresh(self):
try:
if self._timeout_event:
self._scheduler.cancel(self._timeout_event)
except exception.EventNotFound:
pass
finally:
self._timeout_event = self._scheduler.event_later(
... | Refresh timeout timer |
344,590 | def _recursively_convert_unicode_to_str(input):
if isinstance(input, dict):
return {_recursively_convert_unicode_to_str(key): _recursively_convert_unicode_to_str(value) for key, value in input.items()}
elif isinstance(input, list):
return [_recursively_convert_unicode_to_str(element) for el... | Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list, |
344,591 | def report_score_vs_rmsd_funnels(designs, path):
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
print "Reporting score vs RMSD funnels..."
pdf = PdfPages(path)
designs = sorted(designs, key=lambda x: x.fancy_path)
for index, design in enumerate(desig... | Create a PDF showing the score vs. RMSD funnels for all the reasonable
designs. This method was copied from an old version of this script, and
does not currently work. |
344,592 | def search( self, base=False, trim=False, objects=False, **kwargs ):
scope = pyldap.SCOPE_SUBTREE
if not base:
base = self.users
filterstr =
for key, value in kwargs.iteritems():
filterstr += .format(key,value)
if key == :
fil... | Returns matching entries for search in ldap
structured as [(dn, {attributes})]
UNLESS searching by dn, in which case the first match
is returned |
344,593 | def add_room(model, solution=None, linear=False, delta=0.03, epsilon=1E-03):
r
if in model.solver.variables:
raise ValueError()
if solution is None:
solution = pfba(model)
prob = model.problem
variable = prob.Variable("room_old_objective", ub=solution.objective_value)
co... | r"""
Add constraints and objective for ROOM.
This function adds variables and constraints for applying regulatory
on/off minimization (ROOM) to the model.
Parameters
----------
model : cobra.Model
The model to add ROOM constraints and objective to.
solution : cobra.Solution, option... |
344,594 | def _linelength(self, x0, y0, x1, y1):
a = pow(abs(x0 - x1), 2)
b = pow(abs(y0 - y1), 2)
return sqrt(a + b) | Returns the length of the line. |
344,595 | def make_html_items( self, items ):
lines = []
for item in items:
if item.lines:
lines.append( self.make_html_code( item.lines ) )
else:
lines.append( self.make_html_para( item.words ) )
return string.join( lines, ) | convert a field's content into some valid HTML |
344,596 | def parse_range_header(header, maxlen=0):
if not header or header[:6] != : return
ranges = [r.split(, 1) for r in header[6:].split() if in r]
for start, end in ranges:
try:
if not start:
start, end = max(0, maxlen-int(end)), maxlen
elif not end:
... | Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive. |
344,597 | def list_themes_user():
themes = [*os.scandir(os.path.join(CONF_DIR, "colorschemes/dark/")),
*os.scandir(os.path.join(CONF_DIR, "colorschemes/light/"))]
return [t for t in themes if os.path.isfile(t.path)] | List user theme files. |
344,598 | def manipulate(self, stored_instance, component_instance):
self._ipopo_instance = stored_instance
self._context = stored_instance.bundle_context
setattr(component_instance, self._field, {}) | Stores the given StoredInstance bean.
:param stored_instance: The iPOPO component StoredInstance
:param component_instance: The component instance |
344,599 | def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False):
self._setSmsMemory(readDelete=memory)
messages = []
delMessages = set()
if self._smsTextMode:
cmglRegex= re.compile(r)
for key, val in dictItemsIter(Sms.TEXT_MODE_STATUS_MAP):
... | Returns SMS messages currently stored on the device/SIM card.
The messages are read from the memory set by the "memory" parameter.
:param status: Filter messages based on this read status; must be 0-4 (see Sms class)
:type status: int
:param memory: The memory type to r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.