Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
4,900 | def run(self):
obj_reaction = self._get_objective()
genes = set()
gene_assoc = {}
for reaction in self._model.reactions:
assoc = None
if reaction.genes is None:
continue
elif isinstance(reaction.genes, string_types):
... | Delete the specified gene and solve using the desired method. |
4,901 | def lipisha_ipn(self):
if not (self.request.POST.get() == LIPISHA_API_KEY and
self.request.POST.get() == LIPISHA_API_SIGNATURE):
raise HTTPBadRequest
return process_lipisha_payment(self.request) | Process lipisha IPN - Initiate/Acknowledge |
4,902 | def process_details():
results = {"argv": sys.argv, "working.directory": os.getcwd()}
for key, method in {
"pid": "getpid",
"ppid": "getppid",
"login": "getlogin",
"uid": "getuid",
"euid": "geteuid",
"gid": "getgi... | Returns details about the current process |
4,903 | def _proxy(self):
if self._context is None:
self._context = AwsContext(self._version, sid=self._solution[], )
return self._context | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: AwsContext for this AwsInstance
:rtype: twilio.rest.accounts.v1.credential.aws.AwsContext |
4,904 | def submit(self, password=):
url = .format(BASE_URL)
try:
r = requests.post(url,
data=self.dumps(),
headers={: },
auth=(self[][], password))
response = r.json()
except re... | Submits the participation to the web site.
The passwords is sent as plain text.
:return: the evaluation results. |
4,905 | def save_file(fullpath, entry):
with tempfile.NamedTemporaryFile(, delete=False) as file:
tmpfile = file.name
for key, val in entry.items():
print(.format(key, str(val)), file=file)
print(, file=file)
file.write(entry.get_payload())
shutil.move(... | Save a message file out, without mangling the headers |
4,906 | def make_list_table(headers, data, title=, columns=None):
results = []
add = results.append
add( % title)
add()
if columns:
add( % (.join(str(c) for c in columns)))
add()
add( % headers[0])
for h in headers[1:]:
add( % h)
for row in data:
add( % row[0])
... | Build a list-table directive.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the columns. |
4,907 | def version(versioninfo=False):
contextkey =
contextkey_info =
if contextkey not in __context__:
try:
version_ = _git_run([, ])[]
except CommandExecutionError as exc:
log.error(
,
exc
)
version_ =
... | .. versionadded:: 2015.8.0
Returns the version of Git installed on the minion
versioninfo : False
If ``True``, return the version in a versioninfo list (e.g. ``[2, 5,
0]``)
CLI Example:
.. code-block:: bash
salt myminion git.version |
4,908 | def enforce_reset(self):
ub = (self.ubnd * (1.0+self.bound_tol)).to_dict()
lb = (self.lbnd * (1.0 - self.bound_tol)).to_dict()
val_arr = self.values
for iname, name in enumerate(self.columns):
val_arr[val_arr[:,i... | enforce parameter bounds on the ensemble by resetting
violating vals to bound |
4,909 | def _rtg_add_summary_file(eval_files, base_dir, data):
out_file = os.path.join(base_dir, "validate-summary.csv")
if not utils.file_uptodate(out_file, eval_files.get("tp", eval_files.get("fp", eval_files["fn"]))):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_fil... | Parse output TP FP and FN files to generate metrics for plotting. |
4,910 | def plot_lnp(fignum, s, datablock, fpars, direction_type_key):
plot_net(fignum)
dec_key, inc_key, tilt_key = , ,
if in datablock[0].keys():
dec_key, inc_key, tilt_key = , ,
coord = datablock[0][tilt_key]
title = s
if coord == :
title = title + ": specimen coordinate... | plots lines and planes on a great circle with alpha 95 and mean
Parameters
_________
fignum : number of plt.figure() object
datablock : nested list of dictionaries with keys in 3.0 or 2.5 format
3.0 keys: dir_dec, dir_inc, dir_tilt_correction = [-1,0,100], direction_type_key =['p','l']
... |
4,911 | def write(series, output, scale=None):
fsamp = int(series.sample_rate.decompose().value)
if scale is None:
scale = 1 / numpy.abs(series.value).max()
data = (series.value * scale).astype()
return wavfile.write(output, fsamp, data) | Write a `TimeSeries` to a WAV file
Parameters
----------
series : `TimeSeries`
the series to write
output : `file`, `str`
the file object or filename to write to
scale : `float`, optional
the factor to apply to scale the data to (-1.0, 1.0),
pass `scale=1` to not a... |
4,912 | def command(
commands: str or list,
prefix: str or list = "/",
separator: str = " ",
case_sensitive: bool = False
):
def func(flt, message):
text = message.text or message.caption
if text:
for p in flt.p:
... | Filter commands, i.e.: text messages starting with "/" or any other custom prefix.
Args:
commands (``str`` | ``list``):
The command or list of commands as string the filter should look for.
Examples: "start", ["start", "help", "settings"]. When a message text contain... |
4,913 | def get_objects_for_subject(subject=None,
object_category=None,
relation=None,
**kwargs):
searchresult = search_associations(subject=subject,
fetch_objects=True,
... | Convenience method: Given a subject (e.g. gene, disease, variant), return all associated objects (phenotypes, functions, interacting genes, etc) |
4,914 | def wrap_make_secure_channel(make_secure_channel_func, tracer=None):
def call(*args, **kwargs):
channel = make_secure_channel_func(*args, **kwargs)
try:
host = kwargs.get()
tracer_interceptor = OpenCensusClientInterceptor(tracer, host)
intercepted_channel = ... | Wrap the google.cloud._helpers.make_secure_channel. |
4,915 | def sample_categorical(prob, rng):
ret = numpy.empty(prob.shape[0], dtype=numpy.float32)
for ind in range(prob.shape[0]):
ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0,
max=prob.shape[
... | Sample from independent categorical distributions
Each batch is an independent categorical distribution.
Parameters
----------
prob : numpy.ndarray
Probability of the categorical distribution. Shape --> (batch_num, category_num)
rng : numpy.random.RandomState
Returns
-------
ret... |
4,916 | def from_zip(cls, src=, dest=):
try:
zf = zipfile.ZipFile(src, )
except FileNotFoundError:
raise errors.InvalidPathError(src)
except zipfile.BadZipFile:
raise errors.InvalidZipFileError(src)
[zf.extract(file, dest) for file in zf.namelist()]
zf.close()
return cls.from_path... | Unzips a zipped app project file and instantiates it.
:param src: zipfile path
:param dest: destination folder to extract the zipfile content
Returns
A project instance. |
4,917 | def text_pixels(self, text, clear_screen=True, x=0, y=0, text_color=, font=None):
if clear_screen:
self.clear()
if font is not None:
if isinstance(font, str):
assert font in fonts.available(), "%s is an invalid font" % font
font = fonts.... | Display `text` starting at pixel (x, y).
The EV3 display is 178x128 pixels
- (0, 0) would be the top left corner of the display
- (89, 64) would be right in the middle of the display
'text_color' : PIL says it supports "common HTML color names". There
are 140 HTML color names ... |
4,918 | def parse(
args: typing.List[str] = None,
arg_parser: ArgumentParser = None
) -> dict:
parser = arg_parser or create_parser()
return vars(parser.parse_args(args)) | Parses the arguments for the cauldron server |
4,919 | def authenticate(user=None):
if connexion.request.is_json:
user = UserAuth.from_dict(connexion.request.get_json())
credentials = mapUserAuthToCredentials(user)
auth = ApitaxAuthentication.login(credentials)
if(not auth):
return ErrorResponse(status=401, message="Invalid credent... | Authenticate
Authenticate with the API # noqa: E501
:param user: The user authentication object.
:type user: dict | bytes
:rtype: UserAuth |
4,920 | def remove_security_group(self, name):
for group in self.security_groups:
if group.isc_name == name:
group.delete() | Remove a security group from container |
4,921 | def pformat_dict_summary_html(dict):
if not dict:
return
html = []
for key, value in sorted(six.iteritems(dict)):
if not isinstance(value, DICT_EXPANDED_TYPES):
value =
html.append(_format_dict_item(key, value))
return mark_safe(u.join(html)) | Briefly print the dictionary keys. |
4,922 | def main():
args = CLI.parse_args(__doc__)
if args[]:
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
logging.basicConfig(level=logging.DEBUG)
if not args[]:
print("No API key given. Please create an API key on <https:... | entry point of the application.
Parses the CLI commands and runs the actions. |
4,923 | def prob_t_profiles(self, profile_pair, multiplicity, t,
return_log=False, ignore_gaps=True):
if t<0:
logP = -ttconf.BIG_NUMBER
else:
Qt = self.expQt(t)
if len(Qt.shape)==3:
res = np.einsum(, profile_pair[1], Qt, profil... | Calculate the probability of observing a node pair at a distance t
Parameters
----------
profile_pair: numpy arrays
Probability distributions of the nucleotides at either
end of the branch. pp[0] = parent, pp[1] = child
multiplicity : numpy array
... |
4,924 | def normalize_lcdict_byinst(
lcdict,
magcols=,
normto=,
normkeylist=(,,,,,),
debugmode=False,
quiet=False
):
stfccdfltfldprjexpallallzerojmaghmagkmagbmagvmagsdssgsdssrsdssizeroobjectinfoera
if in lcdict and len(lcdict[]) > 0:
if not quiet:
... | This is a function to normalize light curves across all instrument
combinations present.
Use this to normalize a light curve containing a variety of:
- HAT station IDs ('stf')
- camera IDs ('ccd')
- filters ('flt')
- observed field names ('fld')
- HAT project IDs ('prj')
- exposure tim... |
4,925 | def get_event_timelines(self, event_ids, session=None, lightweight=None):
url = % (self.url, )
params = {
: .join(str(x) for x in event_ids),
: ,
: ,
:
}
(response, elapsed_time) = self.request(params=params, session=session, url... | Returns a list of event timelines based on event id's
supplied.
:param list event_ids: List of event id's to return
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: list[resources.EventTimeline] |
4,926 | def make_if_statement(instr, queue, stack, context):
test_expr = make_expr(stack)
if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)
first_block = popwhile(op.is_not(instr.arg), queue, side=)
if isinstance(first_block[-1], instrs.RETURN_... | Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. |
4,927 | def write_file(filename, contents):
contents = "\n".join(contents)
contents = contents.encode("utf-8")
with open(filename, "wb") as f:
f.write(contents) | Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it. |
4,928 | def provides(self):
plist = self.metadata.provides
s = % (self.name, self.version)
if s not in plist:
plist.append(s)
return plist | A set of distribution names and versions provided by this distribution.
:return: A set of "name (version)" strings. |
4,929 | def page_models(self, constructor, paging, constraints=None, *, columns=None, order_by=None):
records, count = self.page(constructor.table_name, paging, constraints, columns=columns,
order_by=order_by)
return ([constructor(r) for r in records], count) | Specialization of DataAccess.page that returns models instead of cursor objects. |
4,930 | def insert(self, packet, **kwargs):
values = [ ]
pd = packet._defn
for defn in pd.fields:
val = getattr(packet.raw, defn.name)
if val is None and defn.name in pd.history:
val = getattr(packet.history, defn.name)
valu... | Insert a packet into the database
Arguments
packet
The :class:`ait.core.tlm.Packet` instance to insert into
the database |
4,931 | def _get_db_version(self):
dbname = self._cfg.get(, )
self._execute("SELECT description FROM pg_shdescription JOIN pg_database ON objoid = pg_database.oid WHERE datname = " % dbname)
comment = self._curs_pg.fetchone()
if comment is None:
raise NipapDatabaseNoVersion... | Get the schema version of the nipap psql db. |
4,932 | def slot_availability_array(events, slots):
array = np.ones((len(events), len(slots)))
for row, event in enumerate(events):
for col, slot in enumerate(slots):
if slot in event.unavailability or event.duration > slot.duration:
array[row, col] = 0
return array | Return a numpy array mapping events to slots
- Rows corresponds to events
- Columns correspond to stags
Array has value 0 if event cannot be scheduled in a given slot
(1 otherwise) |
4,933 | def build_text_part(name, thread, struct):
part_w = None
width = None
minw = 0
maxw = None
width_tuple = struct[]
if width_tuple is not None:
if width_tuple[0] == :
minw, maxw = width_tuple[1:]
content = prepare_string(name, thread, maxw)
if minw:
... | create an urwid.Text widget (wrapped in approproate Attributes)
to display a plain text parts in a threadline.
create an urwid.Columns widget (wrapped in approproate Attributes)
to display a list of tag strings, as part of a threadline.
:param name: id of part to build
:type name: str
:param th... |
4,934 | def mul(mean1, var1, mean2, var2):
mean = (var1*mean2 + var2*mean1) / (var1 + var2)
var = 1 / (1/var1 + 1/var2)
return (mean, var) | Multiply Gaussian (mean1, var1) with (mean2, var2) and return the
results as a tuple (mean, var).
Strictly speaking the product of two Gaussian PDFs is a Gaussian
function, not Gaussian PDF. It is, however, proportional to a Gaussian
PDF, so it is safe to treat the output as a PDF for any filter using
... |
4,935 | def EnumerateFilesystemsFromClient(args):
del args
for drive in win32api.GetLogicalDriveStrings().split("\x00"):
if not drive:
continue
try:
volume = win32file.GetVolumeNameForVolumeMountPoint(drive).rstrip("\\")
label, _, _, _, fs_type = win32api.GetVolumeInformation(drive)
exce... | List all local filesystems mounted on this system. |
4,936 | def DecodeValueFromAttribute(self, attribute_name, value, ts):
try:
attribute = Attribute.PREDICATES[attribute_name]
cls = attribute.attribute_type
self._AddAttributeToCache(attribute, LazyDecoder(cls, value, ts),
self.synced_attributes)
except KeyEr... | Given a serialized value, decode the attribute.
Only attributes which have been previously defined are permitted.
Args:
attribute_name: The string name of the attribute.
value: The serialized attribute value.
ts: The timestamp of this attribute. |
4,937 | def fill_tree_from_xml(tag, ar_tree, namespace):
for child in tag:
name_elem = child.find( + namespace + )
if name_elem is not None and child is not None:
fill_tree_from_xml(child, ar_tree.append_child(name_elem.text, child), namespace)
if name_elem is None a... | Parse the xml tree into ArTree objects. |
4,938 | def tournament_selection(random, population, args):
num_selected = args.setdefault(, 1)
tournament_size = args.setdefault(, 2)
if tournament_size > len(population):
tournament_size = len(population)
selected = []
for _ in range(num_selected):
tourn = random.sample(population, to... | Return a tournament sampling of individuals from the population.
This function selects ``num_selected`` individuals from the population.
It selects each one by using random sampling without replacement
to pull ``tournament_size`` individuals and adds the best of the
tournament as its selection. If... |
4,939 | def delete_service(self, service_name, params=None):
if not self.space.has_service_with_name(service_name):
logging.warning("Service not found so... succeeded?")
return True
guid = self.get_instance_guid(service_name)
logging.info("Deleting service %s with guid ... | Delete the service of the given name. It may fail if there are
any service keys or app bindings. Use purge() if you want
to delete it all. |
4,940 | def suggest_next_locations(self, context = None, pending_X = None, ignored_X = None):
self.model_parameters_iterations = None
self.num_acquisitions = 0
self.context = context
self._update_model(self.normalization_type)
suggested_locations = self._compute_next_evaluation... | Run a single optimization step and return the next locations to evaluate the objective.
Number of suggested locations equals to batch_size.
:param context: fixes specified variables to a particular context (values) for the optimization run (default, None).
:param pending_X: matrix of input conf... |
4,941 | def sojourn_time(p):
p = np.asarray(p)
pii = p.diagonal()
if not (1 - pii).all():
print("Sojourn times are infinite for absorbing states!")
return 1 / (1 - pii) | Calculate sojourn time based on a given transition probability matrix.
Parameters
----------
p : array
(k, k), a Markov transition probability matrix.
Returns
-------
: array
(k, ), sojourn times. Each element is the expected time a Markov
... |
4,942 | def set_breakpoint(self, file_name, line_number, condition=None, enabled=True):
c_file_name = self.canonic(file_name)
import linecache
line = linecache.getline(c_file_name, line_number)
if not line:
return "Line %s:%d does not exist." % (c_file_name, line_number), No... | Create a breakpoint, register it in the class's lists and returns
a tuple of (error_message, break_number) |
4,943 | def setup(self, app):
self.logger = app.logger
self.shell.logger = self.logger
if not self.command_name:
raise EmptyCommandNameException()
self.app = app
self.arguments_declaration = self.arguments
self.arguments = app.arguments
if self.use... | Setup properties from parent app on the command |
4,944 | def pre_init(self, value, obj):
try:
if obj._state.adding:
pass
return value | Convert a string value to JSON only if it needs to be deserialized.
SubfieldBase metaclass has been modified to call this method instead of
to_python so that we can check the obj state and determine if it needs to be
deserialized |
4,945 | def bounds(self):
bounds = [np.inf,-np.inf, np.inf,-np.inf, np.inf,-np.inf]
def update_bounds(ax, nb, bounds):
if nb[2*ax] < bounds[2*ax]:
bounds[2*ax] = nb[2*ax]
if nb[2*ax+1] > bounds[2*ax+1]:
bounds[2*ax+1] = nb[2*ax+1]
... | Finds min/max for bounds across blocks
Returns:
tuple(float):
length 6 tuple of floats containing min/max along each axis |
4,946 | def prior_from_config(cp, variable_params, prior_section,
constraint_section):
logging.info("Setting up priors for each parameter")
dists = distributions.read_distributions_from_config(cp, prior_section)
constraints = distributions.read_constraints_fro... | Gets arguments and keyword arguments from a config file.
Parameters
----------
cp : WorkflowConfigParser
Config file parser to read.
variable_params : list
List of of model parameter names.
prior_section : str
Section to read prior(s) from.
... |
4,947 | def WriteSerialized(cls, attribute_container):
json_dict = cls.WriteSerializedDict(attribute_container)
return json.dumps(json_dict) | Writes an attribute container to serialized form.
Args:
attribute_container (AttributeContainer): attribute container.
Returns:
str: A JSON string containing the serialized form. |
4,948 | def packageipa(env, console):
ipa_path, app_path = _get_ipa(env)
output_dir = path.dirname(ipa_path)
if path.exists(ipa_path):
console.quiet( % ipa_path)
os.remove(ipa_path)
zf = zipfile.ZipFile(ipa_path, mode=)
payload_dir =
for (dirpath, dirnames, filenames) in os.walk... | Package the built app as an ipa for distribution in iOS App Store |
4,949 | def _default_output_dir():
try:
dataset_name = gin.query_parameter("inputs.dataset_name")
except ValueError:
dataset_name = "random"
dir_name = "{model_name}_{dataset_name}_{timestamp}".format(
model_name=gin.query_parameter("train.model").configurable.name,
dataset_name=dataset_name,
... | Default output directory. |
4,950 | def thaicheck(word: str) -> bool:
pattern = re.compile(r"[ก-ฬฮ]", re.U)
res = re.findall(pattern, word)
if res == []:
return False
if _check1(res[len(res) - 1]) or len(res) == 1:
if _check2(word):
word2 = list(word)
i = 0
thai = True
... | Check if a word is an "authentic Thai word"
:param str word: word
:return: True or False |
4,951 | def _do_connect(self):
self.load_system_host_keys()
if self.username is None or self.port is None:
self._configure()
try:
self.connect(hostname=self.hostname,
port=self.port,
username=self.username,
... | Connect to the remote. |
4,952 | def _unsign_data(self, data, options):
if options[] not in self.signature_algorithms:
raise Exception(
% options[])
signature_algorithm = \
self.signature_algorithms[options[]]
algorithm = self._get_algorithm_info(signature_algorith... | Verify and remove signature |
4,953 | def node_list_to_coordinate_lines(G, node_list, use_geom=True):
edge_nodes = list(zip(node_list[:-1], node_list[1:]))
lines = []
for u, v in edge_nodes:
data = min(G.get_edge_data(u, v).values(), key=lambda x: x[])
if in data and use_geom:
xs... | Given a list of nodes, return a list of lines that together follow the path
defined by the list of nodes.
Parameters
----------
G : networkx multidigraph
route : list
the route as a list of nodes
use_geom : bool
if True, use the spatial geometry attribute of the edges to draw
... |
4,954 | def with_timeout(timeout, d, reactor=reactor):
if timeout is None or not isinstance(d, Deferred):
return d
ret = Deferred(canceller=lambda _: (
d.cancel(),
timeout_d.cancel(),
))
timeout_d = sleep(timeout, reactor)
timeout_d.addCallback(lambda _: (
d.cancel(),
... | Returns a `Deferred` that is in all respects equivalent to `d`, e.g. when `cancel()` is called on it `Deferred`,
the wrapped `Deferred` will also be cancelled; however, a `Timeout` will be fired after the `timeout` number of
seconds if `d` has not fired by that time.
When a `Timeout` is raised, `d` will be... |
4,955 | def reset(self):
self.config = None
self.html = None
self.parsed_tree = None
self.tidied = False
self.next_page_link = None
self.title = None
self.author = set()
self.language = None
self.date = None
self.body = None
self.... | (re)set all instance attributes to default.
Every attribute is set to ``None``, except :attr:`author`
and :attr:`failures` which are set to ``[]``. |
4,956 | async def getiter(self, url: str, url_vars: Dict[str, str] = {},
*, accept: str = sansio.accept_format(),
jwt: Opt[str] = None,
oauth_token: Opt[str] = None
) -> AsyncGenerator[Any, None]:
data, more = await self._m... | Return an async iterable for all the items at a specified endpoint. |
4,957 | def serialize(ad_objects, output_format=, indent=2, attributes_only=False):
if attributes_only:
ad_objects = [key for key in sorted(ad_objects[0].keys())]
if output_format == :
return json.dumps(ad_objects, indent=indent, ensure_ascii=False, sort_keys=True)
elif output_... | Serialize the object to the specified format
:param ad_objects list: A list of ADObjects to serialize
:param output_format str: The output format, json or yaml. Defaults to json
:param indent int: The number of spaces to indent, defaults to 2
:param attributes only: Only serialize the attributes found... |
4,958 | def linear_trend_timewise(x, param):
ix = x.index
times_seconds = (ix - ix[0]).total_seconds()
times_hours = np.asarray(times_seconds / float(3600))
linReg = linregress(times_hours, x.values)
return [("attr_\"{}\"".format(config["attr"]), getattr(linReg, config["attr"]))
... | Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to
length of the time series minus one.
This feature uses the index of the time series to fit the model, which must be of a datetime
dtype.
The parameters control which of the characteristics are ret... |
4,959 | def __build_cmd_maps(cls):
cmd_map_all = {}
cmd_map_visible = {}
cmd_map_internal = {}
for name in dir(cls):
obj = getattr(cls, name)
if iscommand(obj):
for cmd in getcommands(obj):
if cmd in cmd_map_all.keys():
... | Build the mapping from command names to method names.
One command name maps to at most one method.
Multiple command names can map to the same method.
Only used by __init__() to initialize self._cmd_map. MUST NOT be used
elsewhere.
Returns:
A tuple (cmd_map, hidden_... |
4,960 | def load(self, filename, params=None, force=False, depthrange=None, timerange=None, output_is_dict=True, **kwargs):
if (params is not None) & isinstance(params,str): params=[params]
self._filename = filename
try:
ncf = ncfile(self._filename,... | NetCDF data loader
:parameter filename: file name
:parameter params: a list of variables to load (default : load ALL variables).
:parameter depthrange: if a depth dimension is found, subset along this dimension.
:parameter timerange: if a time dimension is found, ... |
4,961 | def minor_releases(self, manager):
return [
key for key, value in six.iteritems(manager)
if any(x for x in value if not x.startswith())
] | Return all minor release line labels found in ``manager``. |
4,962 | def splitter(structured):
actives = []
decoys = []
for mol in structured:
status = mol[3]
if status == :
actives.append(mol)
elif status == :
decoys.append(mol)
return actives, decoys | Separates structured data into a list of actives or a list of decoys. actives are labeled with a '1' in their status
fields, while decoys are labeled with a '0' in their status fields.
:param structured: either roc_structure or score_structure.
roc_structure: list [(id, best_score, best_query, status, fpf, ... |
4,963 | def scope(self, *args, **kwargs):
_scopes = self.scopes(*args, **kwargs)
if len(_scopes) == 0:
raise NotFoundError("No scope fits criteria")
if len(_scopes) != 1:
raise MultipleFoundError("Multiple scopes fit criteria")
return _scopes[0] | Return a single scope based on the provided name.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional query parameters.
:return: a single :class:`models.Scope`
:raises NotF... |
4,964 | def get_sub_extractors_by_property(extractor, property_name, return_property_list=False):
if isinstance(extractor, RecordingExtractor):
if property_name not in extractor.get_channel_property_names():
raise ValueError(" must be must be a property of the recording channels")
else:
... | Divides Recording or Sorting Extractor based on the property_name (e.g. group)
Parameters
----------
extractor: RecordingExtractor or SortingExtractor
The extractor to be subdivided in subextractors
property_name: str
The property used to subdivide the extractor
return_property_list... |
4,965 | def processRequest(self, arg, **kw):
if self.debug:
log.msg( %str(arg), debug=1)
if arg is None:
return
for h in self.handlers:
arg = h.processRequest(arg, **kw)
s = str(arg)
if self.debug:
log.msg(s, debug=1... | Parameters:
arg -- XML Soap data string |
4,966 | def pop(self, count=1):
if count < 0:
return self.popleft(-count)
new_right_list, new_left_list = PDeque._pop_lists(self._right_list, self._left_list, count)
return PDeque(new_left_list, new_right_list, max(self._length - count, 0), self._maxlen) | Return new deque with rightmost element removed. Popping the empty queue
will return the empty queue. A optional count can be given to indicate the
number of elements to pop. Popping with a negative index is the same as
popleft. Executes in amortized O(k) where k is the number of elements to pop... |
4,967 | def GetZipInfo(self):
if not self._zip_info:
location = getattr(self.path_spec, , None)
if location is None:
raise errors.PathSpecError()
if not location.startswith(self._file_system.LOCATION_ROOT):
raise errors.PathSpecError()
if len(location) == 1:
return Non... | Retrieves the ZIP info object.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect. |
4,968 | def check_url (self):
try:
url_data = self.urlqueue.get(timeout=QUEUE_POLL_INTERVALL_SECS)
if url_data is not None:
try:
self.check_url_data(url_data)
finally:
self.urlqueue.task_done(url_data)
... | Try to get URL data from queue and check it. |
4,969 | def get_sequences_from_cluster(c1, c2, data):
seqs1 = data[c1][]
seqs2 = data[c2][]
seqs = list(set(seqs1 + seqs2))
names = []
for s in seqs:
if s in seqs1 and s in seqs2:
names.append("both")
elif s in seqs1:
names.append(c1)
else:
na... | get all sequences from on cluster |
4,970 | def render(self, fname=):
import qnet.visualization.circuit_pyx as circuit_visualization
from tempfile import gettempdir
from time import time, sleep
if not fname:
tmp_dir = gettempdir()
fname = os.path.join(tmp_dir, "tmp_{}.png".format(hash(time)))
... | Render the circuit expression and store the result in a file
Args:
fname (str): Path to an image file to store the result in.
Returns:
str: The path to the image file |
4,971 | def _local_to_shape(self, local_x, local_y):
return (
local_x - self.shape_offset_x,
local_y - self.shape_offset_y
) | Translate local coordinates point to shape coordinates.
Shape coordinates have the same unit as local coordinates, but are
offset such that the origin of the shape coordinate system (0, 0) is
located at the top-left corner of the shape bounding box. |
4,972 | def modis_filename2modisdate(modis_fname):
if not isinstance(modis_fname,list) : modis_fname=[modis_fname]
return [os.path.splitext(os.path.basename(m))[0][1:12] for m in modis_fname] | #+
# MODIS_FILENAME2DATE : Convert MODIS file name to MODIS date
#
# @author: Renaud DUSSURGET (LER PAC/IFREMER)
# @history: Created by RD on 29/10/2012
#
#- |
4,973 | def windyields(self, ini, end, delta, **keyw):
if ("tmass" in keyw) == False:
keyw["tmass"] = "mass"
if ("abund" in keyw) == False:
keyw["abund"] = "iso_massf"
if ("cycle" in keyw) == False:
keyw["cycle"] = "cycle"
print("Windyields() initia... | This function returns the wind yields and ejected masses.
X_i, E_i = data.windyields(ini, end, delta)
Parameters
----------
ini : integer
The starting cycle.
end : integer
The finishing cycle.
delta : integer
The cycle interval.
... |
4,974 | def create_organisation(self, organisation_json):
return trolly.organisation.Organisation(
trello_client=self,
organisation_id=organisation_json[],
name=organisation_json[],
data=organisation_json,
) | Create an Organisation object from a JSON object
Returns:
Organisation: The organisation from the given `organisation_json`. |
4,975 | def on_peer_down(self, peer):
LOG.debug(,
peer.ip_address, peer.version_num)
self._table_manager.clean_stale_routes(peer) | Peer down handler.
Cleans up the paths in global tables that was received from this peer. |
4,976 | def main():
src_dir = sys.argv[1]
os.chdir(src_dir)
config = get_config(src_dir)
cmd =
version = \
subprocess.check_output([cmd], shell=True).strip()
tmp_dist = "/var/deb_dist"
project = config[]
tmp_dist = "/var/deb_dist"
os_version = "1404"
deb_dir = "%s/deb_dist"... | main
Entrypoint to this script. This will execute the functionality as a standalone
element |
4,977 | def key_expand(self, key):
key = self._process_value(key, )
payload = {"key": key}
resp = self.call(, payload)
return resp | Derive public key and account number from **private key**
:param key: Private key to generate account and public key of
:type key: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.key_expand(
key="781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3"
... |
4,978 | def binary_report(self, sha256sum, apikey):
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, data=params)
if response.status_co... | retrieve report from file scan |
4,979 | def save(self):
if not self.dirty:
return
data = .join(map(self.make_relative, self.paths))
if data:
log.debug("Saving %s", self.filename)
data = (
"import sys; sys.__plen = len(sys.path)\n"
"%s\n"
"imp... | Write changed .pth file back to disk |
4,980 | def encrypt(self, txt, key):
assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt)
assert isinstance(key, six.text_type), "key: %s is not text type!" % repr(key)
if len(txt) != len(key):
raise SecureJSLoginError("encrypt error: %s and must... | XOR ciphering with a PBKDF2 checksum |
4,981 | def gct2gctx_main(args):
in_gctoo = parse_gct.parse(args.filename, convert_neg_666=False)
if args.output_filepath is None:
basename = os.path.basename(args.filename)
out_name = os.path.splitext(basename)[0] + ".gctx"
else:
out_name = args.output_filepath
if args.row_... | Separate from main() in order to make command-line tool. |
4,982 | def patch_namespaced_role(self, name, namespace, body, **kwargs):
kwargs[] = True
if kwargs.get():
return self.patch_namespaced_role_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_role_with_http_info(name, namespace, body, **... | partially update the specified Role
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_role(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req ... |
4,983 | def query(self):
query = (
self.book.session.query(Account)
.join(Commodity)
.filter(Commodity.namespace != "template")
.filter(Account.type != AccountType.root.value)
)
return query | Main accounts query |
4,984 | def _premis_version_from_data(data):
for child in data:
if isinstance(child, dict):
version = child.get("version")
if version:
return version
return utils.PREMIS_VERSION | Given tuple ``data`` encoding a PREMIS element, attempt to return the
PREMIS version it is using. If none can be found, return the default PREMIS
version. |
4,985 | def msg_curse(self, args=None, max_width=None):
ret = []
if not self.stats or self.is_disable():
return ret
name_max_width = max_width - 12
msg = .format(, width=name_max_width)
ret.append(self.curse_add_line(msg, "TITLE... | Return the dict to display in the curse interface. |
4,986 | def write(self):
if not self.output_files.valid():
raise ValueError(
f
)
else:
if in env.config[] or in env.config[]:
env.log_to_file(
,
f
)
ret = super(RuntimeI... | Write signature file with signature of script, input, output and dependent files.
Because local input and output files can only be determined after the execution
of workflow. They are not part of the construction. |
4,987 | def save(self, *args, **kwargs):
after_save = kwargs.pop(, True)
super(LayerExternal, self).save(*args, **kwargs)
if after_save:
try:
synchronizer = self.synchronizer
except ImproperlyConfigured:
pass
else:
... | call synchronizer "after_external_layer_saved" method
for any additional operation that must be executed after save |
4,988 | def saelgv(vec1, vec2):
vec1 = stypes.toDoubleVector(vec1)
vec2 = stypes.toDoubleVector(vec2)
smajor = stypes.emptyDoubleVector(3)
sminor = stypes.emptyDoubleVector(3)
libspice.saelgv_c(vec1, vec2, smajor, sminor)
return stypes.cVectorToPython(smajor), stypes.cVectorToPython(sminor) | Find semi-axis vectors of an ellipse generated by two arbitrary
three-dimensional vectors.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/saelgv_c.html
:param vec1: First vector used to generate an ellipse.
:type vec1: 3-Element Array of floats
:param vec2: Second vector used to generate ... |
4,989 | def stateDict(self):
state = {
: self._duration,
: self._intensity,
: self._risefall,
: self.name
}
return state | Saves internal values to be loaded later
:returns: dict -- {'parametername': value, ...} |
4,990 | def hash_array(vals, encoding=, hash_key=None, categorize=True):
if not hasattr(vals, ):
raise TypeError("must pass a ndarray-like")
dtype = vals.dtype
if hash_key is None:
hash_key = _default_hash_key
if np.issubdtype(dtype, np.complex128):
return hash_arr... | Given a 1d array, return an array of deterministic integers.
.. versionadded:: 0.19.2
Parameters
----------
vals : ndarray, Categorical
encoding : string, default 'utf8'
encoding for data & key when strings
hash_key : string key to encode, default to _default_hash_key
categorize : ... |
4,991 | def _start_again(self, message=None):
logging.debug("Start again message delivered: {}".format(message))
the_answer = self._get_text_answer()
return "{0} The correct answer was {1}. Please start a new game.".format(
message,
the_answer
) | Simple method to form a start again message and give the answer in readable form. |
4,992 | def seqToKV(seq, strict=False):
def err(msg):
formatted = % (msg, seq)
if strict:
raise KVFormError(formatted)
else:
logging.warning(formatted)
lines = []
for k, v in seq:
if isinstance(k, bytes):
k = k.decode()
elif not isi... | Represent a sequence of pairs of strings as newline-terminated
key:value pairs. The pairs are generated in the order given.
@param seq: The pairs
@type seq: [(str, (unicode|str))]
@return: A string representation of the sequence
@rtype: bytes |
4,993 | def load(patterns, full_reindex):
header()
for pattern in patterns:
for filename in iglob(pattern):
echo(.format(white(filename)))
with open(filename) as f:
reader = csv.reader(f)
reader.next()
for idx, row in ... | Load one or more CADA CSV files matching patterns |
4,994 | def rotation(f, line = ):
if f.unstructured:
raise ValueError("Rotation requires a structured file")
lines = { : f.fast,
: f.slow,
: f.iline,
: f.xline,
}
if line not in lines:
error = "Unknown line {}".format(line)
soluti... | Find rotation of the survey
Find the clock-wise rotation and origin of `line` as ``(rot, cdpx, cdpy)``
The clock-wise rotation is defined as the angle in radians between line
given by the first and last trace of the first line and the axis that gives
increasing CDP-Y, in the direction that gives incre... |
4,995 | def _add_https(self, q):
t include http
or https, add it.
Parameters
==========
q: the parsed image query (names), including the original
registryhttporiginalhttp:registryhttp://%sregistryoriginalhttps:registryhttps://%sregistrys environment
else... | for push, pull, and other api interactions, the user can optionally
define a custom registry. If the registry name doesn't include http
or https, add it.
Parameters
==========
q: the parsed image query (names), including the original |
4,996 | def list_virtual_machine_scale_set_vm_network_interfaces(scale_set,
vm_index,
resource_group,
**kwargs):
result = {}
netconn = __utils__... | .. versionadded:: 2019.2.0
Get information about all network interfaces in a specific virtual machine within a scale set.
:param scale_set: The name of the scale set to query.
:param vm_index: The virtual machine index.
:param resource_group: The resource group name assigned to the
scale set... |
4,997 | def remove(self, component):
with self.__lock:
factory = self.__names.pop(component)
components = self.__queue[factory]
del components[component]
if not components:
del self.__queue[fact... | Kills/Removes the component with the given name
:param component: A component name
:raise KeyError: Unknown component |
4,998 | def _get_nets_lacnic(self, *args, **kwargs):
from warnings import warn
warn(
)
return self.get_nets_lacnic(*args, **kwargs) | Deprecated. This will be removed in a future release. |
4,999 | def increase_route_count(self, crawled_request):
for route in self.__routing_options.routes:
if re.compile(route).match(crawled_request.url):
count_key = str(route) + crawled_request.method
if count_key in self.__routing_count.keys():
... | Increase the count that determines how many times a URL of a certain route has been crawled.
Args:
crawled_request (:class:`nyawc.http.Request`): The request that possibly matches a route. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.