code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if...
A decorator for caching the result of a function.
Below is the the instruction that describes the task: ### Input: A decorator for caching the result of a function. ### Response: def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wrap...
def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: ...
Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0
Below is the the instruction that describes the task: ### Input: Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ### Response: def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block...
def filter(self, dataset): """Mark unusual trips for all the routes in the dataset.""" self.info('Going to filter infrequent routes in the dataset') for route in dataset.routes.values(): self.filter_line(route)
Mark unusual trips for all the routes in the dataset.
Below is the the instruction that describes the task: ### Input: Mark unusual trips for all the routes in the dataset. ### Response: def filter(self, dataset): """Mark unusual trips for all the routes in the dataset.""" self.info('Going to filter infrequent routes in the dataset') for route in dataset....
def gradient_rgb( self, text=None, fore=None, back=None, style=None, start=None, stop=None, step=1, linemode=True, movefactor=0): """ Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, ...
Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, background will be gradient. back : Background color, foreground will be gradient. style : Name of style to use for the gra...
Below is the the instruction that describes the task: ### Input: Return a black and white gradient. Arguments: text : String to colorize. fore : Foreground color, background will be gradient. back : Background color, foreground will be gr...
def options(self, url, **kwargs): r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response """ kwargs.setdefault('allow_red...
r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response
Below is the the instruction that describes the task: ### Input: r"""Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ### Response: def opt...
def getFileSecurity( self, fileName, securityInformation, securityDescriptor, lengthSecurityDescriptorBuffer, lengthNeeded, dokanFileInfo, ): """Get security attributes of a file. :param fileName: name of file to get security for :type...
Get security attributes of a file. :param fileName: name of file to get security for :type fileName: ctypes.c_wchar_p :param securityInformation: buffer for security information :type securityInformation: PSECURITY_INFORMATION :param securityDescriptor: buffer for security descr...
Below is the the instruction that describes the task: ### Input: Get security attributes of a file. :param fileName: name of file to get security for :type fileName: ctypes.c_wchar_p :param securityInformation: buffer for security information :type securityInformation: PSECURITY_INF...
def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only""" weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, patches = plt.hist(data, bins=25, weights=weights, facecolor='blue', alpha=0.5) plt.title(r'%s %s: $\mu=%.2f$, $\si...
plot a histogram. For internal use only
Below is the the instruction that describes the task: ### Input: plot a histogram. For internal use only ### Response: def _histogram(self, which, mu, sigma, data): """plot a histogram. For internal use only""" weights = np.ones_like(data)/len(data) # make bar heights sum to 100% n, bins, ...
def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc): """Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0. """ self.set_distributed_assembled_rows_cols(irn_loc, jcn_loc) self.set_distributed_assembled_values(a_loc)
Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0.
Below is the the instruction that describes the task: ### Input: Set the distributed assembled matrix. Distributed assembled matrices require setting icntl(18) != 0. ### Response: def set_distributed_assembled(self, irn_loc, jcn_loc, a_loc): """Set the distributed assembled matrix. Distri...
def put_pixel(self, x: int, y: int, color: Tuple[int, int, int]) -> None: """Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int]...
Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]): An (r, g, b) sequence or Color instance.
Below is the the instruction that describes the task: ### Input: Change a pixel on this Image. Args: x (int): X pixel of the Image. Starting from the left at 0. y (int): Y pixel of the Image. Starting from the top at 0. color (Union[Tuple[int, int, int], Sequence[int]]...
def head(self, url: StrOrURL, *, allow_redirects: bool=False, **kwargs: Any) -> '_RequestContextManager': """Perform HTTP HEAD request.""" return _RequestContextManager( self._request(hdrs.METH_HEAD, url, allow_redirects=allow_redirects, ...
Perform HTTP HEAD request.
Below is the the instruction that describes the task: ### Input: Perform HTTP HEAD request. ### Response: def head(self, url: StrOrURL, *, allow_redirects: bool=False, **kwargs: Any) -> '_RequestContextManager': """Perform HTTP HEAD request.""" return _RequestContextManager( ...
def confusion_matrix(exp, obs): """Create a confusion matrix In each axis of the resulting confusion matrix the negative case is 0-index and the positive case 1-index. The labels get sorted, in a True/False scenario true positives will occur at (1,1). The first dimension (rows) of the resulting...
Create a confusion matrix In each axis of the resulting confusion matrix the negative case is 0-index and the positive case 1-index. The labels get sorted, in a True/False scenario true positives will occur at (1,1). The first dimension (rows) of the resulting matrix is the expected class and the s...
Below is the the instruction that describes the task: ### Input: Create a confusion matrix In each axis of the resulting confusion matrix the negative case is 0-index and the positive case 1-index. The labels get sorted, in a True/False scenario true positives will occur at (1,1). The first dimensi...
def attachment_both(self, files, parentid=None): """ Add child attachments using title, filename Arguments: One or more lists or tuples containing title, file path An optional Item ID, which will create child attachments """ orig = self._attachment_template("impor...
Add child attachments using title, filename Arguments: One or more lists or tuples containing title, file path An optional Item ID, which will create child attachments
Below is the the instruction that describes the task: ### Input: Add child attachments using title, filename Arguments: One or more lists or tuples containing title, file path An optional Item ID, which will create child attachments ### Response: def attachment_both(self, files, parentid=No...
def terminal_cfg_line_sessionid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mgmt:brocade-terminal") line = ET.SubElement(terminal_cfg, "line") sessionid = ET.SubEleme...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def terminal_cfg_line_sessionid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mg...
def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: context.trace_id, SPAN_ID_HEADER: context.span_id, FLAGS_HEADER: '0', SAMPLED_ID_HEADER: '1' if context.sampled else '0', ...
Creates dict with zipkin headers from supplied trace context.
Below is the the instruction that describes the task: ### Input: Creates dict with zipkin headers from supplied trace context. ### Response: def make_headers(context: TraceContext) -> Headers: """Creates dict with zipkin headers from supplied trace context. """ headers = { TRACE_ID_HEADER: cont...
def get_class_info(self, xqdm, kcdm, jxbh): """ 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xq...
获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :param xqdm: 学期代码 :param kcdm: 课程代码 :param jxbh: 教学班号
Below is the the instruction that describes the task: ### Input: 获取教学班详情, 包括上课时间地点, 考查方式, 老师, 选中人数, 课程容量等等信息 @structure {'校区': str,'开课单位': str,'考核类型': str,'课程类型': str,'课程名称': str,'教学班号': str,'起止周': str, '时间地点': str,'学分': float,'性别限制': str,'优选范围': str,'禁选范围': str,'选中人数': int,'备注': str} :par...
def encode_pb_list(pb_spans): """Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes """ pb_list = zipkin_pb2.ListOfSpans() pb_list.spans.extend(pb_spans) return pb_list.Serial...
Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes
Below is the the instruction that describes the task: ### Input: Encode list of protobuf Spans to binary. :param pb_spans: list of protobuf Spans. :type pb_spans: list of zipkin_pb2.Span :return: encoded list. :rtype: bytes ### Response: def encode_pb_list(pb_spans): """Encode list of protobuf...
def uinit(self, ushape): """Return initialiser for working variable U.""" if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: # If initial Y is non-zero, initial U is chosen so that # the relevant dual optimality criterion (see (3.10) ...
Return initialiser for working variable U.
Below is the the instruction that describes the task: ### Input: Return initialiser for working variable U. ### Response: def uinit(self, ushape): """Return initialiser for working variable U.""" if self.opt['Y0'] is None: return np.zeros(ushape, dtype=self.dtype) else: ...
def atomic_sa(self, i): r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float """ sa = 4.0 * np.pi * self.rads2[i] neighbors = self.neighbors.get(i) if neighbors is None: return sa XYZi = self.xyzs[i, n...
r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float
Below is the the instruction that describes the task: ### Input: r"""Calculate atomic surface area. :type i: int :param i: atom index :rtype: float ### Response: def atomic_sa(self, i): r"""Calculate atomic surface area. :type i: int :param i: atom index ...
def toHierarchy(self, classView, level, stream, lastChild=False): ''' **Parameters** ``classView`` (bool) ``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy. ``level`` (int) Recursion level used to determine indentation. ...
**Parameters** ``classView`` (bool) ``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy. ``level`` (int) Recursion level used to determine indentation. ``stream`` (StringIO) The stream to write the contents to. ...
Below is the the instruction that describes the task: ### Input: **Parameters** ``classView`` (bool) ``True`` if generating the Class Hierarchy, ``False`` for File Hierarchy. ``level`` (int) Recursion level used to determine indentation. ``stream...
def handle_signal(self, signum, frame): """ handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/...
handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.python.org/2/reference/datamodel.html#frame-objects)
Below is the the instruction that describes the task: ### Input: handles UNIX signals This function currently just handles SIGUSR1. It could be extended to handle more :param signum: The signal number (see man 7 signal) :param frame: The execution frame (https://docs.py...
def htmlNewDocNoDtD(URI, ExternalID): """Creates a new HTML document without a DTD node if @URI and @ExternalID are None """ ret = libxml2mod.htmlNewDocNoDtD(URI, ExternalID) if ret is None:raise treeError('htmlNewDocNoDtD() failed') return xmlDoc(_obj=ret)
Creates a new HTML document without a DTD node if @URI and @ExternalID are None
Below is the the instruction that describes the task: ### Input: Creates a new HTML document without a DTD node if @URI and @ExternalID are None ### Response: def htmlNewDocNoDtD(URI, ExternalID): """Creates a new HTML document without a DTD node if @URI and @ExternalID are None """ ret = lib...
def reset(self, params, repetition): """ Called once at the beginning of each experiment. """ self.startTime = time.time() print(params) seed = params["seed"] + repetition torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) # Get our directories correct self.dataD...
Called once at the beginning of each experiment.
Below is the the instruction that describes the task: ### Input: Called once at the beginning of each experiment. ### Response: def reset(self, params, repetition): """ Called once at the beginning of each experiment. """ self.startTime = time.time() print(params) seed = params["seed"] + re...
def clean(self, value): """ Clean the field values. """ if not self.create: # No new value can be created, use the regular clean field return super(AgnocompleteModelMultipleField, self).clean(value) # We have to do this here before the call to "super". ...
Clean the field values.
Below is the the instruction that describes the task: ### Input: Clean the field values. ### Response: def clean(self, value): """ Clean the field values. """ if not self.create: # No new value can be created, use the regular clean field return super(Agnocomp...
def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter.""" # Only supported in Python 3.7+ with ZipFile(self.zip_filename, 'w', compresslevel=self.compress_level) as backup_zip: for path in tqdm(dirs, desc='Writing Zip Files', total=len(dirs)): ...
Create a backup file with a compresslevel parameter.
Below is the the instruction that describes the task: ### Input: Create a backup file with a compresslevel parameter. ### Response: def _backup_compresslevel(self, dirs): """Create a backup file with a compresslevel parameter.""" # Only supported in Python 3.7+ with ZipFile(self.zip_filenam...
def get(self, token): ''' Check the token, returns a 401 if the token is invalid. Else open the websocket connection ''' log.debug('In the websocket get method') self.token = token # close the connection, if not authenticated if not self.application.auth....
Check the token, returns a 401 if the token is invalid. Else open the websocket connection
Below is the the instruction that describes the task: ### Input: Check the token, returns a 401 if the token is invalid. Else open the websocket connection ### Response: def get(self, token): ''' Check the token, returns a 401 if the token is invalid. Else open the websocket connect...
def _compute_precision(references, translation, n): """Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number ...
Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int Number of matched nth order n-grams candidates Number ...
Below is the the instruction that describes the task: ### Input: Compute ngram precision. Parameters ---------- references: list(list(str)) A list of references. translation: list(str) A translation. n: int Order of n-gram. Returns ------- matches: int ...
def apply(self, collection, ops, **kwargs): """Apply the filter to collection.""" validator = lambda obj: all(op(obj, val) for (op, val) in ops) # noqa return [o for o in collection if validator(o)]
Apply the filter to collection.
Below is the the instruction that describes the task: ### Input: Apply the filter to collection. ### Response: def apply(self, collection, ops, **kwargs): """Apply the filter to collection.""" validator = lambda obj: all(op(obj, val) for (op, val) in ops) # noqa return [o for o in collecti...
def InitializeFD( self, Channel, BitrateFD): """ Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_*...
Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_* values. * parameter and values must be separated by '=' * Couples of Pa...
Below is the the instruction that describes the task: ### Input: Initializes a FD capable PCAN Channel Parameters: Channel : The handle of a FD capable PCAN Channel BitrateFD : The speed for the communication (FD bit rate string) Remarks: See PCAN_BR_* values. * pa...
def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} flavor_accesses = nt_ks.flavor_access.add_tenant_access(flavor_id, project_id) for project in flavor_accesses: ...
Add a project to the flavor access list
Below is the the instruction that describes the task: ### Input: Add a project to the flavor access list ### Response: def flavor_access_add(self, flavor_id, project_id): ''' Add a project to the flavor access list ''' nt_ks = self.compute_conn ret = {flavor_id: []} ...
def getHookStatus(self, *args, **kwargs): """ Get hook status This endpoint will return the current status of the hook. This represents a snapshot in time and may vary from one call to the next. This method is deprecated in favor of listLastFires. This method gives ou...
Get hook status This endpoint will return the current status of the hook. This represents a snapshot in time and may vary from one call to the next. This method is deprecated in favor of listLastFires. This method gives output: ``v1/hook-status.json#`` This method is ``depre...
Below is the the instruction that describes the task: ### Input: Get hook status This endpoint will return the current status of the hook. This represents a snapshot in time and may vary from one call to the next. This method is deprecated in favor of listLastFires. This method g...
def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has_header('Vary'): return False vary_headers = cc_delim_re.split(response['Vary']) existing_headers = set([header.lower() for header in vary_hea...
Checks to see if the response has a given header name in its Vary header.
Below is the the instruction that describes the task: ### Input: Checks to see if the response has a given header name in its Vary header. ### Response: def has_vary_header(response, header_query): """ Checks to see if the response has a given header name in its Vary header. """ if not response.has...
def write_right(self, msg, thread_lock=None): """ msg may or may not be encoded """ if self.cursesScreen: if thread_lock is not None: thread_lock.acquire() try: a_msg = msg.strip() self.cursesScreen.addstr(0, self.width + 5 - len(a_...
msg may or may not be encoded
Below is the the instruction that describes the task: ### Input: msg may or may not be encoded ### Response: def write_right(self, msg, thread_lock=None): """ msg may or may not be encoded """ if self.cursesScreen: if thread_lock is not None: thread_lock.acquire() ...
def parse(self, mimetypes): """ Invoke the RFC 2388 spec compliant parser """ self._parse_top_level_content_type() link = 'tools.ietf.org/html/rfc2388' parts = cgi.FieldStorage( fp=self.req.stream, environ=self.req.env, ) if not parts: ...
Invoke the RFC 2388 spec compliant parser
Below is the the instruction that describes the task: ### Input: Invoke the RFC 2388 spec compliant parser ### Response: def parse(self, mimetypes): """ Invoke the RFC 2388 spec compliant parser """ self._parse_top_level_content_type() link = 'tools.ietf.org/html/rfc2388' parts = ...
def make_router(*routings): """Return a WSGI application that dispatches requests to controllers """ routes = [] for routing in routings: methods, regex, app = routing[:3] if isinstance(methods, basestring): methods = (methods,) vars = routing[3] if len(routing) >= 4 else...
Return a WSGI application that dispatches requests to controllers
Below is the the instruction that describes the task: ### Input: Return a WSGI application that dispatches requests to controllers ### Response: def make_router(*routings): """Return a WSGI application that dispatches requests to controllers """ routes = [] for routing in routings: methods, reg...
def write_how_much(self, file): """ Write component quantities to a table. """ report = CaseReport(self.case) col1_header = "Attribute" col1_width = 24 col2_header = "P (MW)" col3_header = "Q (MVAr)" col_width = 8 sep = "="*col1_width +" "+ "=...
Write component quantities to a table.
Below is the the instruction that describes the task: ### Input: Write component quantities to a table. ### Response: def write_how_much(self, file): """ Write component quantities to a table. """ report = CaseReport(self.case) col1_header = "Attribute" col1_width = 24 ...
def authorize_group_permission( self, group_name, source_group_name, source_group_owner_id): """ This is a convenience function that wraps the "authorize group" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_securit...
This is a convenience function that wraps the "authorize group" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_security_group}.
Below is the the instruction that describes the task: ### Input: This is a convenience function that wraps the "authorize group" functionality of the C{authorize_security_group} method. For an explanation of the parameters, see C{authorize_security_group}. ### Response: def authorize_group_permiss...
def connect(self, *args, **kwargs): """ Proxy to DynamoDBConnection.connect. """ self.connection = DynamoDBConnection.connect(*args, **kwargs) self._session = kwargs.get("session") if self._session is None: self._session = botocore.session.get_session()
Proxy to DynamoDBConnection.connect.
Below is the the instruction that describes the task: ### Input: Proxy to DynamoDBConnection.connect. ### Response: def connect(self, *args, **kwargs): """ Proxy to DynamoDBConnection.connect. """ self.connection = DynamoDBConnection.connect(*args, **kwargs) self._session = kwargs.get("sess...
def flag(request, comment_id, next=None): """ Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(comments.get_model(), pk=comment_id, site__pk...
Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object
Below is the the instruction that describes the task: ### Input: Flags a comment. Confirmation on GET, action on POST. Templates: :template:`comments/flag.html`, Context: comment the flagged `comments.comment` object ### Response: def flag(request, comment_id, next=None): """ F...
def simple_generate_batch(klass, create, size, **kwargs): """Create a factory for the given class, and simple_generate instances.""" return make_factory(klass, **kwargs).simple_generate_batch(create, size)
Create a factory for the given class, and simple_generate instances.
Below is the the instruction that describes the task: ### Input: Create a factory for the given class, and simple_generate instances. ### Response: def simple_generate_batch(klass, create, size, **kwargs): """Create a factory for the given class, and simple_generate instances.""" return make_factory(klass,...
def assert_strong_password(username, password, old_password=None): """Raises ValueError if the password isn't strong. Returns the password otherwise.""" # test the length try: minlength = settings.MIN_PASSWORD_LENGTH except AttributeError: minlength = 12 if len(password) < minl...
Raises ValueError if the password isn't strong. Returns the password otherwise.
Below is the the instruction that describes the task: ### Input: Raises ValueError if the password isn't strong. Returns the password otherwise. ### Response: def assert_strong_password(username, password, old_password=None): """Raises ValueError if the password isn't strong. Returns the password oth...
def notification( self, topic_name, topic_project=None, custom_attributes=None, event_types=None, blob_name_prefix=None, payload_format=NONE_PAYLOAD_FORMAT, ): """Factory: create a notification resource for the bucket. See: :class:`.BucketNot...
Factory: create a notification resource for the bucket. See: :class:`.BucketNotification` for parameters. :rtype: :class:`.BucketNotification`
Below is the the instruction that describes the task: ### Input: Factory: create a notification resource for the bucket. See: :class:`.BucketNotification` for parameters. :rtype: :class:`.BucketNotification` ### Response: def notification( self, topic_name, topic_project=...
def _get_plot_data(data, ndim=None): """Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions """ out = data if isinstance(data, PHATE): out = data...
Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions
Below is the the instruction that describes the task: ### Input: Get plot data out of an input object Parameters ---------- data : array-like, `phate.PHATE` or `scanpy.AnnData` ndim : int, optional (default: None) Minimum number of dimensions ### Response: def _get_plot_data(data, ndim=Non...
def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params """ m = len(data) self.params[:m] += data
Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params
Below is the the instruction that describes the task: ### Input: Updates a Dirichlet distribution. data: sequence of observations, in order corresponding to params ### Response: def Update(self, data): """Updates a Dirichlet distribution. data: sequence of observations, in order correspon...
def create_queue(self, queue_name, visibility_timeout=None): """ Create an SQS Queue. :type queue_name: str or unicode :param queue_name: The name of the new queue. Names are scoped to an account and need to be unique within that ac...
Create an SQS Queue. :type queue_name: str or unicode :param queue_name: The name of the new queue. Names are scoped to an account and need to be unique within that account. Calling this method on an existing queue name ...
Below is the the instruction that describes the task: ### Input: Create an SQS Queue. :type queue_name: str or unicode :param queue_name: The name of the new queue. Names are scoped to an account and need to be unique within that account. Call...
def listDatasetArray(self): """ API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :param dataset_id: lis...
API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :param dataset_id: list of dataset ids [dataset_id1,dataset_id2,..,dat...
Below is the the instruction that describes the task: ### Input: API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :...
def flatten(self, keep_prob=1): """ Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer) :param keep_prob: int. set to 1 for no dropout """ self.count['flat'] += 1 scope = 'flat_' + str(self.count['flat']) with tf.variable_scope(scope): # ...
Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer) :param keep_prob: int. set to 1 for no dropout
Below is the the instruction that describes the task: ### Input: Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer) :param keep_prob: int. set to 1 for no dropout ### Response: def flatten(self, keep_prob=1): """ Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Laye...
def read_dir_tree(self, file_hash): """ Recursively read the directory structure beginning at hash """ json_d = self.read_index_object(file_hash, 'tree') node = {'files' : json_d['files'], 'dirs' : {}} for name, hsh in json_d['dirs'].iteritems(): node['dirs'][name] = self.read_dir_tree(...
Recursively read the directory structure beginning at hash
Below is the the instruction that describes the task: ### Input: Recursively read the directory structure beginning at hash ### Response: def read_dir_tree(self, file_hash): """ Recursively read the directory structure beginning at hash """ json_d = self.read_index_object(file_hash, 'tree') ...
def receive_oaiharvest_job(request, records, name, **kwargs): """Receive a list of harvested OAI-PMH records and schedule crawls.""" spider = kwargs.get('spider') workflow = kwargs.get('workflow') if not spider or not workflow: return files_created, _ = write_to_dir( records, ...
Receive a list of harvested OAI-PMH records and schedule crawls.
Below is the the instruction that describes the task: ### Input: Receive a list of harvested OAI-PMH records and schedule crawls. ### Response: def receive_oaiharvest_job(request, records, name, **kwargs): """Receive a list of harvested OAI-PMH records and schedule crawls.""" spider = kwargs.get('spider') ...
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist, not empty (issue #871) and plugin not disabled if not self.stats or (self.stats == []) or self.is_disable():...
Return the dict to display in the curse interface.
Below is the the instruction that describes the task: ### Input: Return the dict to display in the curse interface. ### Response: def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only proce...
def send_message(self, msg, stats=True): """ Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes """ self.send_jsonified(proto.json_encode(msg), stats)
Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes
Below is the the instruction that describes the task: ### Input: Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes ### Response: def send_message(self, msg, stats=True): """ Send ...
def request_instance(vm_, conn=None, call=None): ''' Request an instance to be built ''' if call == 'function': # Technically this function may be called other ways too, but it # definitely cannot be called with --function. raise SaltCloudSystemExit( 'The request_inst...
Request an instance to be built
Below is the the instruction that describes the task: ### Input: Request an instance to be built ### Response: def request_instance(vm_, conn=None, call=None): ''' Request an instance to be built ''' if call == 'function': # Technically this function may be called other ways too, but it ...
def title(words_quantity=4): """Return a random sentence to be used as e.g. an e-mail subject.""" result = words(quantity=words_quantity) result += random.choice('?.!') return result.capitalize()
Return a random sentence to be used as e.g. an e-mail subject.
Below is the the instruction that describes the task: ### Input: Return a random sentence to be used as e.g. an e-mail subject. ### Response: def title(words_quantity=4): """Return a random sentence to be used as e.g. an e-mail subject.""" result = words(quantity=words_quantity) result += random.choice...
def _unescape_value(value): """Unescape a value.""" def unescape(c): return { "\\\\": "\\", "\\\"": "\"", "\\n": "\n", "\\t": "\t", "\\b": "\b", }[c.group(0)] return re.sub(r"(\\.)", unescape, value)
Unescape a value.
Below is the the instruction that describes the task: ### Input: Unescape a value. ### Response: def _unescape_value(value): """Unescape a value.""" def unescape(c): return { "\\\\": "\\", "\\\"": "\"", "\\n": "\n", "\\t": "\t", "\\b": "\b...
def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver = platform.mac_ver() win_ver = platform.win32_ver() if lin_ver[0]: return ' '.jo...
Report system versions.
Below is the the instruction that describes the task: ### Input: Report system versions. ### Response: def system_information(): ''' Report system versions. ''' def system_version(): ''' Return host system version. ''' lin_ver = linux_distribution() mac_ver =...
def build_self_uri_list(self_uri_list): "parse the self-uri tags, build Uri objects" uri_list = [] for self_uri in self_uri_list: uri = ea.Uri() utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href')) utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-t...
parse the self-uri tags, build Uri objects
Below is the the instruction that describes the task: ### Input: parse the self-uri tags, build Uri objects ### Response: def build_self_uri_list(self_uri_list): "parse the self-uri tags, build Uri objects" uri_list = [] for self_uri in self_uri_list: uri = ea.Uri() utils.set_attr_if_va...
def wait_connected(self, timeout=None): '''Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were mad...
Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all connections were made, ``False`` if one or more failed.
Below is the the instruction that describes the task: ### Input: Wait for connections to be made and their handshakes to finish :param timeout: maximum time to wait in seconds. with None, there is no timeout. :type timeout: float or None :returns: ``True`` if all co...
def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: _log.debug('requesting stop after iteration') self.should_stop = True
Kombu callback for each `drain_events` loop iteration.
Below is the the instruction that describes the task: ### Input: Kombu callback for each `drain_events` loop iteration. ### Response: def on_iteration(self): """ Kombu callback for each `drain_events` loop iteration.""" self._cancel_consumers_if_requested() if len(self._consumers) == 0: ...
def round_to_05(n, exp=None, mode='s'): """ Round to the next 0.5-value. This function applies the round function `func` to round `n` to the next 0.5-value with respect to its exponent with base 10 (i.e. 1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect to the given exponent in...
Round to the next 0.5-value. This function applies the round function `func` to round `n` to the next 0.5-value with respect to its exponent with base 10 (i.e. 1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect to the given exponent in `exp`. Parameters ---------- n: numpy....
Below is the the instruction that describes the task: ### Input: Round to the next 0.5-value. This function applies the round function `func` to round `n` to the next 0.5-value with respect to its exponent with base 10 (i.e. 1.3e-4 will be rounded to 1.5e-4) if `exp` is None or with respect to the ...
def cells_to_series(cells, args): """Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant args are ignored. """ ...
Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant args are ignored.
Below is the the instruction that describes the task: ### Input: Convert a CellImpl into a Series. `args` must be a sequence of argkeys. `args` can be longer or shorter then the number of cell's parameters. If shorter, then defaults are filled if any, else raise error. If longer, then redundant ar...
def variant(self, document_id, gene_panels=None, case_id=None): """Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant...
Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant_id") Returns: variant_object(Variant): A odm va...
Below is the the instruction that describes the task: ### Input: Returns the specified variant. Arguments: document_id : A md5 key that represents the variant or "variant_id" gene_panels(List[GenePanel]) case_id (str): case id (will search with "variant_id") ...
def will_print(level=1): """Returns True if the current global status of messaging would print a message using any of the printing functions in this module. """ if level == 1: #We only affect printability using the quiet setting. return quiet is None or quiet == False else: r...
Returns True if the current global status of messaging would print a message using any of the printing functions in this module.
Below is the the instruction that describes the task: ### Input: Returns True if the current global status of messaging would print a message using any of the printing functions in this module. ### Response: def will_print(level=1): """Returns True if the current global status of messaging would print a ...
def upload_signing_cert(self, cert_body, user_name=None): """ Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type ce...
Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type cert_body: string :param cert_body: The body of the signing certificate....
Below is the the instruction that describes the task: ### Input: Uploads an X.509 signing certificate and associates it with the specified user. If the user_name is not specified, it is determined implicitly based on the AWS Access Key ID used to sign the request. :type cert_body: ...
def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]): """Try to guess a reasonable database name by looking at the repository path""" if value: return value if ctx.params["repository"]: return os.path.join(ctx.params["repository"], DB.DEFAULT_DB_FILE) raise...
Try to guess a reasonable database name by looking at the repository path
Below is the the instruction that describes the task: ### Input: Try to guess a reasonable database name by looking at the repository path ### Response: def default_database(ctx: click.Context, _param: Parameter, value: Optional[str]): """Try to guess a reasonable database name by looking at the repository pat...
def calcMD5(path): """ calc MD5 based on path """ # check that file exists if os.path.exists(path) is False: yield False else: command = ['md5sum', path] p = Popen(command, stdout = PIPE) for line in p.communicate()[0].splitlines(): yield line.decode('...
calc MD5 based on path
Below is the the instruction that describes the task: ### Input: calc MD5 based on path ### Response: def calcMD5(path): """ calc MD5 based on path """ # check that file exists if os.path.exists(path) is False: yield False else: command = ['md5sum', path] p = Popen(c...
def __get_edges_by_vertex(self, vertex, keys=False): """ Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to i...
Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident to it. Wraps each yielded object into :class:`bg.edge.BGEdge` object....
Below is the the instruction that describes the task: ### Input: Iterates over edges that are incident to supplied vertex argument in current :class:`BreakpointGraph` Checks that the supplied vertex argument exists in underlying MultiGraph object as a vertex, then iterates over all edges that are incident ...
def _read_weights(self): """Reads weights from each of the load cells. """ weights = [] grams_per_pound = 453.592 # Read from each of the sensors for ser in self._serials: ser.write('W\r') ser.flush() time.sleep(0.02) for ser in s...
Reads weights from each of the load cells.
Below is the the instruction that describes the task: ### Input: Reads weights from each of the load cells. ### Response: def _read_weights(self): """Reads weights from each of the load cells. """ weights = [] grams_per_pound = 453.592 # Read from each of the sensors ...
def _validate_collections_have_default_values(class_name, property_name, property_descriptor): """Validate that if the property is of collection type, it has a specified default value.""" # We don't want properties of collection type having "null" values, since that may cause # unexpected errors during Grap...
Validate that if the property is of collection type, it has a specified default value.
Below is the the instruction that describes the task: ### Input: Validate that if the property is of collection type, it has a specified default value. ### Response: def _validate_collections_have_default_values(class_name, property_name, property_descriptor): """Validate that if the property is of collection ...
def runContainer(image, **kwargs): '''Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions. ''' container = Non...
Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions.
Below is the the instruction that describes the task: ### Input: Run a docker container using a given image; passing keyword arguments documented to be accepted by docker's client.containers.run function No extra side effects. Handles and reraises ContainerError, ImageNotFound, and APIError exceptions. ...
def shutdown(self, skip_hooks=False): """ Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins. """ if not self._exited: self._exited = True if not skip_hooks: self._run_events(shutd...
Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins.
Below is the the instruction that describes the task: ### Input: Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins. ### Response: def shutdown(self, skip_hooks=False): """ Shuts down the process. `skip_hooks` ...
def poll(self, conn): """Poll DB socket and process async tasks.""" while 1: state = conn.poll() if state == psycopg2.extensions.POLL_OK: while conn.notifies: notify = conn.notifies.pop() self.logger.info( ...
Poll DB socket and process async tasks.
Below is the the instruction that describes the task: ### Input: Poll DB socket and process async tasks. ### Response: def poll(self, conn): """Poll DB socket and process async tasks.""" while 1: state = conn.poll() if state == psycopg2.extensions.POLL_OK: wh...
def on_authenticated(self, authorization): """Device authenticated. :param authorization: Authentication token details :type authorization: dict """ # Acquire condition self.is_authenticating.acquire() # Store authorization for future calls self.authori...
Device authenticated. :param authorization: Authentication token details :type authorization: dict
Below is the the instruction that describes the task: ### Input: Device authenticated. :param authorization: Authentication token details :type authorization: dict ### Response: def on_authenticated(self, authorization): """Device authenticated. :param authorization: Authenticatio...
def connect(self, host, port): ''' Connect to a host and port. ''' # Clear the connect state immediately since we're no longer connected # at this point. self._connected = False # Only after the socket has connected do we clear this state; closed # must b...
Connect to a host and port.
Below is the the instruction that describes the task: ### Input: Connect to a host and port. ### Response: def connect(self, host, port): ''' Connect to a host and port. ''' # Clear the connect state immediately since we're no longer connected # at this point. self._...
def rmi(self, force=False, via_name=False): """ remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID :return: None """ identifier = self.get_full_name() if via_name else (self....
remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID :return: None
Below is the the instruction that describes the task: ### Input: remove this image :param force: bool, force removal of the image :param via_name: bool, refer to the image via name, if false, refer via ID :return: None ### Response: def rmi(self, force=False, via_name=False): """ ...
def add_websocket_route( self, handler, uri, host=None, strict_slashes=None, subprotocols=None, name=None, ): """ A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class ...
A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param uri: URL path that will be mapped to the websocket ...
Below is the the instruction that describes the task: ### Input: A helper method to register a function as a websocket route. :param handler: a callable function or instance of a class that can handle the websocket request :param host: Host IP or FQDN details :param ...
def get_xml_text(source, path=None): """Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path. """ if path is None: return source.text else: return get_xml_text(get_xml_child(source, path))
Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path.
Below is the the instruction that describes the task: ### Input: Get the text of the XML node. If path is not None, it will get the text of the descendant of source indicated by path. ### Response: def get_xml_text(source, path=None): """Get the text of the XML node. If path is not None, it will get the text o...
def get_multi(cls, blob_keys, **ctx_options): """Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None. """ futs = cls.get_multi_async(blob_ke...
Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None.
Below is the the instruction that describes the task: ### Input: Multi-key version of get(). Args: blob_keys: A list of blob keys. **ctx_options: Context options for Model().get_by_id(). Returns: A list whose items are each either a BlobInfo entity or None. ### Response: def get_multi(c...
def default_change_form_template(self): """ Determine what the actual `change_form_template` should be. """ opts = self.model._meta app_label = opts.app_label return select_template_name(( "admin/{0}/{1}/change_form.html".format(app_label, opts.object_name.low...
Determine what the actual `change_form_template` should be.
Below is the the instruction that describes the task: ### Input: Determine what the actual `change_form_template` should be. ### Response: def default_change_form_template(self): """ Determine what the actual `change_form_template` should be. """ opts = self.model._meta app_...
def makeReplacementField(formatSpec, altFormatSpec='', testValue=None): """ Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://doc...
Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.org/3/library/string.html#format-string-syntax https://docs...
Below is the the instruction that describes the task: ### Input: Prepends a colon and wraps the formatSpec in curly braces to yield a replacement field. The format specification is part of a replacement field, which can be used in new-style string formatting. See: https://docs.python.or...
def curve_fit(self): """ Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm. """ if not ha...
Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm.
Below is the the instruction that describes the task: ### Input: Fits `scipy_data_fitting.Fit.function` to the data and returns the output from the specified curve fit function. See `scipy_data_fitting.Fit.options` for details on how to control or override the the curve fitting algorithm. #...
def remove_from_watched(self, watched): """ :calls: `DELETE /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: None """ assert isinstance(watched, github.Repository.Repository...
:calls: `DELETE /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: None
Below is the the instruction that describes the task: ### Input: :calls: `DELETE /repos/:owner/:repo/subscription <http://developer.github.com/v3/activity/watching>`_ :param watched: :class:`github.Repository.Repository` :rtype: None ### Response: def remove_from_watched(self, watched): """...
def write_and_get_hash(path, write_to_file, hash=None): """ write_and_get_hash: write file Args: None Returns: Hash of file's contents """ hash = hash or hashlib.md5() try: # Access path r = config.DOWNLOAD_SESSION.get(path, stream=True) r.raise_for_status() ...
write_and_get_hash: write file Args: None Returns: Hash of file's contents
Below is the the instruction that describes the task: ### Input: write_and_get_hash: write file Args: None Returns: Hash of file's contents ### Response: def write_and_get_hash(path, write_to_file, hash=None): """ write_and_get_hash: write file Args: None Returns: Hash of file's...
def load_formatter_fn(formatter): ''' >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> ''' obj = util.load_object(formatter) if not hasattr(obj, 'ispartial'): obj.ispartial = util.ispartial return obj
>>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...>
Below is the the instruction that describes the task: ### Input: >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <function basescript at 0x...> ### Response: def load_formatter_fn(formatter): ''' >>> load_formatter_fn('logagg.formatters.basescript') #doctest: +ELLIPSIS <fu...
def set_state_process(self, context, process): """Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. ...
Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode
Below is the the instruction that describes the task: ### Input: Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the proc...
def finalize(self): """This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed easily. """ for i in rang...
This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed easily.
Below is the the instruction that describes the task: ### Input: This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed eas...
def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset): ''' This sets a VXR to be the first and last VXR in the VDR ''' # VDR's VXRhead self._update_offset_value(f, vdr_offset+28, 8, VXRoffset) # VDR's VXRtail self._update_offset_value(f, vdr_offset+36, 8, VX...
This sets a VXR to be the first and last VXR in the VDR
Below is the the instruction that describes the task: ### Input: This sets a VXR to be the first and last VXR in the VDR ### Response: def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset): ''' This sets a VXR to be the first and last VXR in the VDR ''' # VDR's VXRhead ...
def to_dict(self) -> OrderedDict: """Dictionary representation of the binning schema. This serves as template method, please implement _update_dict """ result = OrderedDict() result["adaptive"] = self._adaptive result["binning_type"] = type(self).__name__ self._u...
Dictionary representation of the binning schema. This serves as template method, please implement _update_dict
Below is the the instruction that describes the task: ### Input: Dictionary representation of the binning schema. This serves as template method, please implement _update_dict ### Response: def to_dict(self) -> OrderedDict: """Dictionary representation of the binning schema. This serves a...
def math_func(f): """ Statics the methods. wut. """ @wraps(f) def wrapper(*args, **kwargs): if len(args) > 0: return_type = type(args[0]) if kwargs.has_key('return_type'): return_type = kwargs['return_type'] kwargs.pop('return_type') re...
Statics the methods. wut.
Below is the the instruction that describes the task: ### Input: Statics the methods. wut. ### Response: def math_func(f): """ Statics the methods. wut. """ @wraps(f) def wrapper(*args, **kwargs): if len(args) > 0: return_type = type(args[0]) if kwargs.has_key('retur...
def ind2sub(ind, dimensions): """ Calculates subscripts for indices into regularly spaced matrixes. """ # check that the index is within range if ind >= np.prod(dimensions): raise RuntimeError("ind2sub: index exceeds array size") cum_dims = list(dimensions) cum_dims.reverse() m =...
Calculates subscripts for indices into regularly spaced matrixes.
Below is the the instruction that describes the task: ### Input: Calculates subscripts for indices into regularly spaced matrixes. ### Response: def ind2sub(ind, dimensions): """ Calculates subscripts for indices into regularly spaced matrixes. """ # check that the index is within range if ind ...
def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None): """Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)""" E = ElementMaker(namespace="http://relaxng.org/ns/structure/1.0",nsmap={None:'http://relaxng.org/ns/...
Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string)
Below is the the instruction that describes the task: ### Input: Returns a RelaxNG definition for this element (as an XML element (lxml.etree) rather than a string) ### Response: def relaxng(cls, includechildren=True,extraattribs = None, extraelements=None, origclass = None): """Returns a RelaxNG definitio...
def update_ethernet_settings(self, configuration, force=False, timeout=-1): """ Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any probl...
Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any problems with network connectivity or errors on the resource itself. The default is f...
Below is the the instruction that describes the task: ### Input: Updates the Ethernet interconnect settings for the logical interconnect. Args: configuration: Ethernet interconnect settings. force: If set to true, the operation completes despite any problems with network connectivi...
def offlineTable(self, login, tableName): """ Parameters: - login - tableName """ self.send_offlineTable(login, tableName) self.recv_offlineTable()
Parameters: - login - tableName
Below is the the instruction that describes the task: ### Input: Parameters: - login - tableName ### Response: def offlineTable(self, login, tableName): """ Parameters: - login - tableName """ self.send_offlineTable(login, tableName) self.recv_offlineTable()
def setSubTitle(self, title): """ Sets the sub-title for this page to the inputed title. :param title | <str> """ self._subTitleLabel.setText(title) self._subTitleLabel.adjustSize() self.adjustMargins()
Sets the sub-title for this page to the inputed title. :param title | <str>
Below is the the instruction that describes the task: ### Input: Sets the sub-title for this page to the inputed title. :param title | <str> ### Response: def setSubTitle(self, title): """ Sets the sub-title for this page to the inputed title. :param title | <str> ...
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
Return True if apf is running otherwise return False
Below is the the instruction that describes the task: ### Input: Return True if apf is running otherwise return False ### Response: def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: ...
def cut(self, breaks, labels=None, include_lowest=False, right=True, dig_lab=3): """ Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[st...
Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[str] labels: Labels for categorical levels produced. Defaults to set notation of intervals ...
Below is the the instruction that describes the task: ### Input: Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[str] labels: Labels for categorica...
def select(self, *properties, **aliased_properties): """Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties: JME...
Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties: JMESPath to use for the property extraction. ...
Below is the the instruction that describes the task: ### Input: Specify which properties of the dataset must be returned Property extraction is based on `JMESPath <http://jmespath.org>`_ expressions. This method returns a new Dataset narrowed down by the given selection. :param properties...
def from_input(cls, input, workdir=None, manager=None): """ Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object. """ return c...
Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object.
Below is the the instruction that describes the task: ### Input: Create an instance of `AbinitTask` from an ABINIT input. Args: ainput: `AbinitInput` object. workdir: Path to the working directory. manager: :class:`TaskManager` object. ### Response: def from_input(cls, ...
def token(self): """ Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred. """ if not self._token: self._token = self.fetch_token() logger.payment(self) return self._token
Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred.
Below is the the instruction that describes the task: ### Input: Token given by Transbank for payment initialization url. Will raise PaymentError when an error ocurred. ### Response: def token(self): """ Token given by Transbank for payment initialization url. Will raise PaymentEr...
def match_concept(self,string): '''Find all matches in this :class:`Bottle` for ``string`` and return the best match''' matches = self.match_all_concepts(string) if len(matches)>0: return matches[0] return None
Find all matches in this :class:`Bottle` for ``string`` and return the best match
Below is the the instruction that describes the task: ### Input: Find all matches in this :class:`Bottle` for ``string`` and return the best match ### Response: def match_concept(self,string): '''Find all matches in this :class:`Bottle` for ``string`` and return the best match''' matches = self.mat...
def _memoizeArgsOnly (max_cache_size=1000): """Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. ...
Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum expected need. Parameters: max_cache_size - the size to w...
Below is the the instruction that describes the task: ### Input: Python 2.4 compatible memoize decorator. It creates a cache that has a maximum size. If the cache exceeds the max, it is thrown out and a new one made. With such behavior, it is wise to set the cache just a little larger that the maximum...
def write(self, filename=None): """Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename. """ if not filename: ...
Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename.
Below is the the instruction that describes the task: ### Input: Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters ---------- filename : str If not set, XML will be written to self.filename. ### Response...