_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q49900
typechecked
train
def typechecked(call_: typing.Callable[..., T]) -> T: """A decorator to make a callable object checks its types .. code-block:: python from typing import Callable @typechecked def foobar(x: str) -> bool: return x == 'hello world' @typechecked def hello_world(fo...
python
{ "resource": "" }
q49901
_format_background
train
def _format_background(background): """Formats the background section :param background: the background content or file. :type background: str or file :returns: the background content. :rtype: str """ # Getting the background if os.path.isfile(background): with open(backgroun...
python
{ "resource": "" }
q49902
_create_summary_table
train
def _create_summary_table(fn, template, nb_samples, nb_markers): """Creates the final table. :param fn: the name of the file containing the summary. :param template: the Jinja2 template. :param nb_samples: the final number of samples. :param nb_markers: the final number of markers. :type fn: s...
python
{ "resource": "" }
q49903
weld_str_lower
train
def weld_str_lower(array): """Convert values to lowercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """...
python
{ "resource": "" }
q49904
weld_str_upper
train
def weld_str_upper(array): """Convert values to uppercase. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = """...
python
{ "resource": "" }
q49905
weld_str_capitalize
train
def weld_str_capitalize(array): """Capitalize first letter. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = ""...
python
{ "resource": "" }
q49906
weld_str_get
train
def weld_str_get(array, i): """Retrieve character at index i. Parameters ---------- array : numpy.ndarray or WeldObject Input data. i : int Index of character to retrieve. If greater than length of string, returns None. Returns ------- WeldObject Representation ...
python
{ "resource": "" }
q49907
weld_str_strip
train
def weld_str_strip(array): """Strip whitespace from start and end of elements. Note it currently only looks for whitespace (Ascii 32), not tabs or EOL. Parameters ---------- array : numpy.ndarray or WeldObject Input data. Returns ------- WeldObject Representation of th...
python
{ "resource": "" }
q49908
weld_str_slice
train
def weld_str_slice(array, start=None, stop=None, step=None): """Slice each element. Parameters ---------- array : numpy.ndarray or WeldObject Input data. start : int, optional stop : int, optional step : int, optional Returns ------- WeldObject Representation of...
python
{ "resource": "" }
q49909
weld_str_startswith
train
def weld_str_startswith(array, pat): """Check which elements start with pattern. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To check for. Returns ------- WeldObject Representation of this computation. """ obj_id, wel...
python
{ "resource": "" }
q49910
weld_str_find
train
def weld_str_find(array, sub, start, end): """Return index of sub in elements if found, else -1. Parameters ---------- array : numpy.ndarray or WeldObject Input data. sub : str To check for. start : int Start index for searching. end : int or None Stop index ...
python
{ "resource": "" }
q49911
weld_str_replace
train
def weld_str_replace(array, pat, rep): """Replace first occurrence of pat with rep. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To find. rep : str To replace with. Returns ------- WeldObject Representation of this ...
python
{ "resource": "" }
q49912
weld_str_split
train
def weld_str_split(array, pat, side): """Split on pat and return side. Parameters ---------- array : numpy.ndarray or WeldObject Input data. pat : str To find. side : {0, 1} Which side to return, with 0 being left and 1 being right Returns ------- WeldObject...
python
{ "resource": "" }
q49913
listPromise
train
def listPromise(*args): """ A special function that takes a bunch of promises and turns them into a promise for a vector of values. In other words, this turns an list of promises for values into a promise for a list of values. """ ret = Promise() def handleSuccess(v, ret): for a...
python
{ "resource": "" }
q49914
Promise.fulfill
train
def fulfill(self, value): """ Fulfill the promise with a given value. """ assert self._state==self.PENDING self._state=self.FULFILLED; self.value = value for callback in self._callbacks: try: callback(value) except Excepti...
python
{ "resource": "" }
q49915
Promise.reject
train
def reject(self, reason): """ Reject this promise for a given reason. """ assert self._state==self.PENDING self._state=self.REJECTED; self.reason = reason for errback in self._errbacks: try: errback(reason) except Exception...
python
{ "resource": "" }
q49916
Promise.get
train
def get(self, timeout=None): """Get the value of the promise, waiting if necessary.""" self.wait(timeout) if self._state==self.FULFILLED: return self.value else: raise ValueError("Calculation didn't yield a value")
python
{ "resource": "" }
q49917
Promise.wait
train
def wait(self, timeout=None): """ An implementation of the wait method which doesn't involve polling but instead utilizes a "real" synchronization scheme. """ import threading if self._state!=self.PENDING: return e = threading.Event() ...
python
{ "resource": "" }
q49918
samples_from_getdist_chains
train
def samples_from_getdist_chains(params, file_root, latex=False): """ Extract samples and weights from getdist chains. Parameters ---------- params: list(str) Names of parameters to be supplied to second argument of f(x|theta). file_root: str, optional Root name for getdist chains f...
python
{ "resource": "" }
q49919
APNSWorker.opened
train
def opened(self): """Connect to the websocket, and ensure the account is connected and the INBOX is being watched, and then start watchingAll. """ def post_setup((cmds, resps)): """Post setup callback.""" logger.info("Setup complete, listening...") self.s...
python
{ "resource": "" }
q49920
valuedispatch
train
def valuedispatch(func): """Decorates a function to dispatch handler of the value of the first argument. """ registry = {} def dispatch(value): return registry.get(value, func) def register(value, func=None): if func is None: return lambda f: register(value, f) ...
python
{ "resource": "" }
q49921
weld_align
train
def weld_align(df_index_arrays, df_index_weld_types, series_index_arrays, series_index_weld_types, series_data, series_weld_type): """Returns the data from the Series aligned to the DataFrame index. Parameters ---------- df_index_arrays : list of (numpy.ndarray or WeldObje...
python
{ "resource": "" }
q49922
save_heterozygosity
train
def save_heterozygosity(heterozygosity, samples, out_prefix): """Saves the heterozygosity data. :param heterozygosity: the heterozygosity data. :param samples: the list of samples. :param out_prefix: the prefix of the output files. :type heterozygosity: numpy.array :type samples: list of tuple...
python
{ "resource": "" }
q49923
compute_nb_samples
train
def compute_nb_samples(in_prefix): """Check the number of samples. :param in_prefix: the prefix of the input file. :type in_prefix: str :returns: the number of sample in ``prefix.fam``. """ file_name = in_prefix + ".tfam" nb = None with open(file_name, 'rb') as input_file: nb...
python
{ "resource": "" }
q49924
FwTabWidget.addEmptyTab
train
def addEmptyTab(self, text=''): """ Add a new DEFAULT_TAB_WIDGET, open editor to set text if no text is given """ tab = self.defaultTabWidget() c = self.count() self.addTab(tab, text) self.setCurrentIndex(c) if not text: self.tabBar().editTab(c...
python
{ "resource": "" }
q49925
FwTabWidget._mkAddBtnVisible
train
def _mkAddBtnVisible(self): """ Ensure that the Add button is visible also when there are no tabs """ if not self._btn_add_height: # self._btn_add_height = self.cornerWidget().height() self._btn_add_height = self._cwBtn.height() if self.count() == 0: ...
python
{ "resource": "" }
q49926
FwTabWidget.removeTab
train
def removeTab(self, tab): """allows to remove a tab directly -not only by giving its index""" if not isinstance(tab, int): tab = self.indexOf(tab) return super(FwTabWidget, self).removeTab(tab)
python
{ "resource": "" }
q49927
FwTabWidget.tabText
train
def tabText(self, tab): """ allow index or tab widget instance""" if not isinstance(tab, int): tab = self.indexOf(tab) return super(FwTabWidget, self).tabText(tab)
python
{ "resource": "" }
q49928
CeleryLayer.on_failure
train
def on_failure(self, entity): """ Callback function when there is a failure in a connection to whatsapp server """ logger.error("Login failed, reason: %s" % entity.getReason()) self.connected = False
python
{ "resource": "" }
q49929
CeleryLayer.on_message
train
def on_message(self, message_protocol_entity): """ Callback function when receiving message from whatsapp server """ logger.info("Message id %s received" % message_protocol_entity.getId()) # answer with receipt self.toLower(message_protocol_entity.ack())
python
{ "resource": "" }
q49930
get_prefix_dir
train
def get_prefix_dir(archive): """ Often, all files are in a single directory. If so, they'll all have the same prefix. Determine any such prefix. archive is a ZipFile """ names = archive.namelist() shortest_name = sorted(names, key=len)[0] candidate_prefixes = [ shortest_name[:len...
python
{ "resource": "" }
q49931
Parser.find_files
train
def find_files(self): '''Find files in `paths` which match valid extensions''' for path in self.paths: for subpath, dirs, files in os.walk(path): for filename in files: (name, ext) = os.path.splitext(filename) if ext in self.extensions:...
python
{ "resource": "" }
q49932
is_boolean
train
def is_boolean(node): """Checks if node is True or False""" return any([ isinstance(node, ast.Name) and node.id in ('True', 'False'), hasattr(ast, 'NameConstant') # Support for Python 3 NameConstant and isinstance(node, getattr(ast, 'NameConstant')) # screw you pylint! ...
python
{ "resource": "" }
q49933
call_name_is
train
def call_name_is(siter, name): """Checks the function call name""" return ( isinstance(siter, ast.Call) and hasattr(siter.func, 'attr') and siter.func.attr == name )
python
{ "resource": "" }
q49934
target_names
train
def target_names(targets): """Retrieves the target names""" names = [] for entry in targets: if isinstance(entry, ast.Name): names.append(entry.id) elif isinstance(entry, ast.Tuple): for element in entry.elts: if isinstance(element, ast.Name): ...
python
{ "resource": "" }
q49935
labeled
train
def labeled(**kwargs): """decorator to give practices labels""" def for_practice(practice): """assigns label to practice""" practice.code = kwargs.pop('code') practice.msg = kwargs.pop('msg') practice.solution = kwargs.pop('solution') return practice return for_practi...
python
{ "resource": "" }
q49936
daemonize
train
def daemonize(pidfile=None): """ Turn the running process into a proper daemon according to PEP3143. Args: pidfile --The pidfile to create. """ # Prevent core dumps resource.setrlimit(resource.RLIMIT_CORE, (0, 0)) # Change working directory os.chdir("/") # Change file creati...
python
{ "resource": "" }
q49937
config_str2dict
train
def config_str2dict(option_value): """ Parse the value of a config option and convert it to a dictionary. The configuration allows lines formatted like: foo = Bar:1,Baz,Flub:0.75 This gets converted to a dictionary: foo = { 'Bar': 1, 'Baz': 0, 'Flub': 0.75 } Args: option_value -- The c...
python
{ "resource": "" }
q49938
log_to_syslog
train
def log_to_syslog(): """ Configure logging to syslog. """ # Get root logger rl = logging.getLogger() rl.setLevel('INFO') # Stderr gets critical messages (mostly config/setup issues) # only when not daemonized stderr = logging.StreamHandler(stream=sys.stderr) stderr.setLevel(l...
python
{ "resource": "" }
q49939
Dialogs.getSaveFileName
train
def getSaveFileName(self, *args, **kwargs): """ analogue to QtWidgets.QFileDialog.getSaveFileNameAndFilter but returns the filename + chosen file ending even if not typed in gui """ if 'directory' not in kwargs: if self.opts['save']: if self.opts['save...
python
{ "resource": "" }
q49940
load_dependencies
train
def load_dependencies(req, history=None): """ Load the dependency tree as a Python object tree, suitable for JSON serialization. >>> deps = load_dependencies('jaraco.packaging') >>> import json >>> doc = json.dumps(deps) """ if history is None: history = set() dist = pkg_res...
python
{ "resource": "" }
q49941
check_dependencies_remote
train
def check_dependencies_remote(args): """ Invoke this command on a remote Python. """ cmd = [args.python, '-m', 'depends', args.requirement] env = dict(PYTHONPATH=os.path.dirname(__file__)) return subprocess.check_call(cmd, env=env)
python
{ "resource": "" }
q49942
DspamClient._send
train
def _send(self, line): """ Write a line of data to the server. Args: line -- A single line of data to write to the socket. """ if not line.endswith('\r\n'): if line.endswith('\n'): logger.debug('Fixing bare LF before sending data to socket') ...
python
{ "resource": "" }
q49943
DspamClient._read
train
def _read(self): """ Read a single response line from the server. """ line = '' finished = False while not finished: char = self._socket.recv(1) if char == '': return '' elif char == '\r': continue ...
python
{ "resource": "" }
q49944
DspamClient._peek
train
def _peek(self, chars=1): """ Peek at the data in the server response. Peeking should only be done when the response can be predicted. Make sure that the socket will not block by requesting too much data from it while peeking. Args: chars -- the number of charac...
python
{ "resource": "" }
q49945
DspamClient.connect
train
def connect(self): """ Connect to TCP or domain socket, and process the server LMTP greeting. """ # extract proto from socket setting try: (proto, spec) = self.socket.split(':') except ValueError: raise DspamClientError( 'Failed to...
python
{ "resource": "" }
q49946
DspamClient.lhlo
train
def lhlo(self): """ Send LMTP LHLO greeting, and process the server response. A regular LMTP greeting is sent, and if accepted by the server, the capabilities it returns are parsed. DLMTP authentication starts here by announcing the dlmtp_ident in the LHLO as our hostna...
python
{ "resource": "" }
q49947
DspamClient.mailfrom
train
def mailfrom(self, sender=None, client_args=None): """ Send LMTP MAIL FROM command, and process the server response. In DLMTP mode, the server expects the client to identify itself. Because the envelope sender is of no importance to DSPAM, the client is expected to send an ident...
python
{ "resource": "" }
q49948
DspamClient.rcptto
train
def rcptto(self, recipients): """ Send LMTP RCPT TO command, and process the server response. The DSPAM server expects to find one or more valid DSPAM users as envelope recipients. The set recipient will be the user DSPAM processes mail for. When you need want DSPAM to ...
python
{ "resource": "" }
q49949
DspamClient.rset
train
def rset(self): """ Send LMTP RSET command and process the server response. """ self._send('RSET\r\n') resp = self._read() if not resp.startswith('250'): logger.warn('Unexpected server response at RSET: ' + resp) self._recipients = [] self.res...
python
{ "resource": "" }
q49950
DspamClient.quit
train
def quit(self): """ Send LMTP QUIT command, read the server response and disconnect. """ self._send('QUIT\r\n') resp = self._read() if not resp.startswith('221'): logger.warning('Unexpected server response at QUIT: ' + resp) self._socket.close() ...
python
{ "resource": "" }
q49951
get_resource_method
train
def get_resource_method(name, template): """ Creates a function that is suitable as a method for ResourceCollection. """ def rsr_meth(self, **kwargs): http_method = template['http_method'] extra_path = template.get('extra_path') if extra_path: fills = {'res_id': kwarg...
python
{ "resource": "" }
q49952
Getter
train
def Getter(accessor, normalizer=lambda x: x): """ Returns a function that will access an attribute off of an object. If that attribute is callable, it will call it. Accepts a normalizer to call on the value at the end. """ if not callable(accessor): short_description = get_pretty_name(...
python
{ "resource": "" }
q49953
DisplayGetter
train
def DisplayGetter(accessor, *args, **kwargs): """ Returns a Getter that gets the display name for a model field with choices. """ short_description = get_pretty_name(accessor) accessor = 'get_%s_display' % accessor getter = Getter(accessor, *args, **kwargs) getter.short_description = short_d...
python
{ "resource": "" }
q49954
Cordic.initial_step
train
def initial_step(self, phase, x, y): """ Transform input to the CORDIC working quadrants """ self.x[0] = x self.y[0] = y self.phase[0] = phase if self.MODE == CordicMode.ROTATION: if phase > 0.5: # > np.pi/2 self.x[0] = ...
python
{ "resource": "" }
q49955
Cordic.main
train
def main(self, x, y, phase): """ Runs one step of pipelined CORDIC Returned phase is in 1 to -1 range """ self.initial_step(phase, x, y) # pipelined CORDIC for i in range(self.ITERATIONS - 1): if self.MODE == CordicMode.ROTATION: direc...
python
{ "resource": "" }
q49956
Parameter.replaceWith
train
def replaceWith(self, param): """replace this parameter with another""" i = self.parent().children().index(self) # TODO: transfer the children: p = self.parent() self.parent().removeChild(self) p.insertChild(i, param) self = param
python
{ "resource": "" }
q49957
Command.deploy
train
def deploy(self): """ Open a ZIP archive, validate requirements then deploy the webfont into project static files """ self._info("* Opening archive: {}", self.archive_path) if not os.path.exists(self.archive_path): self._error("Given path does not exists: {}",...
python
{ "resource": "" }
q49958
Command.extract
train
def extract(self, zip_archive, font_files): """ Extract files to install """ # Get a temp directory tmp_container = tempfile.mkdtemp(prefix='icomoon-tmp') self._debug("* Temporary dir for extracted archive: {}", tmp_container) # Extract manifest to temp directory...
python
{ "resource": "" }
q49959
Command.install
train
def install(self, tmp_container, font_tmpdir, css_content): """ Install extracted files and builded css """ # Write builded css file to its destination with open(self.webfont_settings['csspart_path'], 'w') as css_file: css_file.write(css_content) # Clean prev...
python
{ "resource": "" }
q49960
create_authors
train
def create_authors(project_dir=os.curdir): """ Creates the authors file, if not in a package. Returns: None Raises: RuntimeError: If the authors could not be retrieved """ pkg_info_file = os.path.join(project_dir, 'PKG-INFO') authors_file = os.path.join(project_dir, 'AUTHOR...
python
{ "resource": "" }
q49961
create_changelog
train
def create_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False): """ Creates the changelog file, if not in a package. :param project_dir: Path to the git repo of the project. :type project_dir: str :param bugtracker_url: Url to the bug tracker for the issues. ...
python
{ "resource": "" }
q49962
create_releasenotes
train
def create_releasenotes(project_dir=os.curdir, bugtracker_url=''): """ Creates the release notes file, if not in a package. Args: project_dir(str): Path to the git repo of the project. bugtracker_url(str): Url to the bug tracker for the issues. Returns: None Raises: ...
python
{ "resource": "" }
q49963
Cleaver.identity
train
def identity(self): """ A unique identifier for the current visitor. """ if hasattr(self._identity, 'get_identity'): return self._identity.get_identity(self._environ) return self._identity(self._environ)
python
{ "resource": "" }
q49964
Cleaver.split
train
def split(self, experiment_name, *variants): """ Used to split and track user experience amongst one or more variants. :param experiment_name a unique string name for the experiment :param *variants can take many forms, depending on usage. Variants should be provided as arb...
python
{ "resource": "" }
q49965
Dock.setWidget
train
def setWidget(self, widget, index=0, row=None, col=0, rowspan=1, colspan=1): """ Add new widget inside dock, remove old one if existent """ if row is None: row = self.currentRow self.currentRow = max(row + 1, self.currentRow) if index > len(s...
python
{ "resource": "" }
q49966
_saferound
train
def _saferound(value, decimal_places): """ Rounds a float value off to the desired precision """ try: f = float(value) except ValueError: return '' format = '%%.%df' % decimal_places return format % f
python
{ "resource": "" }
q49967
capfirst
train
def capfirst(value, failure_string='N/A'): """ Capitalizes the first character of the value. If the submitted value isn't a string, returns the `failure_string` keyword argument. Cribbs from django's default filter set """ try: value = value.lower() return value[0]....
python
{ "resource": "" }
q49968
dollar_signs
train
def dollar_signs(value, failure_string='N/A'): """ Converts an integer into the corresponding number of dollar sign symbols. If the submitted value isn't a string, returns the `failure_string` keyword argument. Meant to emulate the illustration of price range on Yelp. """ try: ...
python
{ "resource": "" }
q49969
image
train
def image(value, width='', height=''): """ Accepts a URL and returns an HTML image tag ready to be displayed. Optionally, you can set the height and width with keyword arguments. """ style = "" if width: style += "width:%s" % width if height: style += "height:%s" % heigh...
python
{ "resource": "" }
q49970
intcomma
train
def intcomma(value): """ Borrowed from django.contrib.humanize Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. """ orig = str(value) new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', orig) if orig == ne...
python
{ "resource": "" }
q49971
percentage
train
def percentage(value, decimal_places=1, multiply=True, failure_string='N/A'): """ Converts a floating point value into a percentage value. Number of decimal places set by the `decimal_places` kwarg. Default is one. By default the number is multiplied by 100. You can prevent it from doing t...
python
{ "resource": "" }
q49972
title
train
def title(value, failure_string='N/A'): """ Converts a string into titlecase. Lifted from Django. """ try: value = value.lower() t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title()) result = re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t) ...
python
{ "resource": "" }
q49973
StringMethods.get
train
def get(self, i): """Extract i'th character of each element. Parameters ---------- i : int Returns ------- Series """ check_type(i, int) return _series_str_result(self, weld_str_get, i=i)
python
{ "resource": "" }
q49974
StringMethods.slice
train
def slice(self, start=None, stop=None, step=None): """Slice substrings from each element. Note that negative step is currently not supported. Parameters ---------- start : int stop : int step : int Returns ------- Series """ ...
python
{ "resource": "" }
q49975
StringMethods.contains
train
def contains(self, pat): """Test if pat is included within elements. Parameters ---------- pat : str Returns ------- Series """ check_type(pat, str) return _series_bool_result(self, weld_str_contains, pat=pat)
python
{ "resource": "" }
q49976
StringMethods.startswith
train
def startswith(self, pat): """Test if elements start with pat. Parameters ---------- pat : str Returns ------- Series """ check_type(pat, str) return _series_bool_result(self, weld_str_startswith, pat=pat)
python
{ "resource": "" }
q49977
StringMethods.endswith
train
def endswith(self, pat): """Test if elements end with pat. Parameters ---------- pat : str Returns ------- Series """ check_type(pat, str) return _series_bool_result(self, weld_str_endswith, pat=pat)
python
{ "resource": "" }
q49978
StringMethods.find
train
def find(self, sub, start=0, end=None): """Test if elements contain substring. Parameters ---------- sub : str start : int, optional Index to start searching from. end : int, optional Index to stop searching from. Returns ------- ...
python
{ "resource": "" }
q49979
StringMethods.replace
train
def replace(self, pat, rep): """Replace first occurrence of pat with rep in each element. Parameters ---------- pat : str rep : str Returns ------- Series """ check_type(pat, str) check_type(rep, str) return _series_str_...
python
{ "resource": "" }
q49980
StringMethods.split
train
def split(self, pat, side='left'): """Split once each element from the left and select a side to return. Note this is unlike pandas split in that it essentially combines the split with a select. Parameters ---------- pat : str side : {'left', 'right'} Which ...
python
{ "resource": "" }
q49981
admin_tagify
train
def admin_tagify(short_description=None, allow_tags=True): """ Decorator that add short_description and allow_tags to ModelAdmin list_display function. Example: class AlbumAdmin(admin.ModelAdmin): ...
python
{ "resource": "" }
q49982
foreign_field_func
train
def foreign_field_func(field_name, short_description=None, admin_order_field=None): """ Allow to use ForeignKey field attributes at list_display in a simple way. Example: from misc.admin import foreign_field_func as ff class SongAdmin(admin.ModelAdmin): ...
python
{ "resource": "" }
q49983
SoftDeleteAdmin.queryset
train
def queryset(self, request): """Returns a Queryset of all model instances that can be edited by the admin site. This is used by changelist_view.""" query_set = self.model._default_manager.all_with_deleted() ordering = self.ordering or () if ordering: query_set = quer...
python
{ "resource": "" }
q49984
handle_response
train
def handle_response (response): """ Handle a response from the newton API """ response = json.loads(response.read()) # Was the expression valid? if 'error' in response: raise ValueError(response['error']) else: # Some of the strings returned can be parsed to integer...
python
{ "resource": "" }
q49985
expose_endpoints
train
def expose_endpoints (module, *args): """ Expose methods to the given module for each API endpoint """ for op in args: # Capture the closure state def create_method (o): return lambda exp: send_request(o, exp) setattr(sys.modules[__name__], op, create_me...
python
{ "resource": "" }
q49986
get_config_path
train
def get_config_path(config_file): """ Given the name of a config file, returns the full path """ config_path = os.getenv('XDG_CONFIG_HOME') if not config_path: config_path = os.path.join(os.getenv('HOME'), ".config") if not config_file: config_file = "default" return os.path....
python
{ "resource": "" }
q49987
read_config
train
def read_config(config_path): """ Loads config data from the specified file path. If config_file doesn't exist, returns an empty authentication config for localhost. """ section = "DUMMY" defaults = {'host': 'localhost', 'consumerKey': '', 'consumerSecret': '', ...
python
{ "resource": "" }
q49988
Expression.etype
train
def etype(self) -> Tuple[str, str]: '''Returns the expression's type.''' if self._expr[0] in ['number', 'boolean']: return ('constant', str(type(self._expr[1]))) elif self._expr[0] == 'pvar_expr': return ('pvar', self._expr[1][0]) elif self._expr[0] == 'randomvar'...
python
{ "resource": "" }
q49989
Expression.args
train
def args(self) -> Union[Value, Sequence[ExprArg]]: '''Returns the expression's arguments.''' if self._expr[0] in ['number', 'boolean']: return self._expr[1] elif self._expr[0] == 'pvar_expr': return self._expr[1] elif self._expr[0] == 'randomvar': retu...
python
{ "resource": "" }
q49990
Expression.__expr_str
train
def __expr_str(cls, expr, level): '''Returns string representing the expression.''' ident = ' ' * level * 4 if isinstance(expr, tuple): return '{}{}'.format(ident, str(expr)) if expr.etype[0] in ['pvar', 'constant']: return '{}Expression(etype={}, args={})'.form...
python
{ "resource": "" }
q49991
Expression.__get_scope
train
def __get_scope(cls, expr: Union['Expression', Tuple]) -> Set[str]: '''Returns the set of fluents in the expression's scope. Args: expr: Expression object or nested tuple of Expressions. Returns: The set of fluents in the expression's scope. ''' ...
python
{ "resource": "" }
q49992
get_client_ip
train
def get_client_ip(request): """ Get the client IP from the request """ # set the default value of the ip to be the REMOTE_ADDR if available # else None ip = request.META.get('REMOTE_ADDR') # try to get the first non-proxy ip (not a private ip) from the # HTTP_X_FORWARDED_FOR x_forwar...
python
{ "resource": "" }
q49993
FileHistoryBrowseSpec.browse
train
def browse(self): ''' Browse the history of a single file adds one commit that doesn't contain changes in test_file_1. there are four commits in summary, so the check for buffer line count compares with 3. at the end, a fifth commit must be present due to resetting the fi...
python
{ "resource": "" }
q49994
_take
train
def _take(d, key, default=None): """ If the key is present in dictionary, remove it and return it's value. If it is not present, return None. """ if key in d: cmd = d[key] del d[key] return cmd else: return default
python
{ "resource": "" }
q49995
_get_cmds_id
train
def _get_cmds_id(*cmds): """ Returns an identifier for a group of partially tagged commands. If there are no tagged commands, returns None. """ tags = [cmd[2] if len(cmd) == 3 else None for cmd in cmds] if [tag for tag in tags if tag != None]: return tuple(tags) else: return ...
python
{ "resource": "" }
q49996
Client.received_message
train
def received_message(self, msg): """ Handle receiving a message by checking whether it is in response to a command or unsolicited, and dispatching it to the appropriate object method. """ logger.debug("Received message: %s", msg) if msg.is_binary: rais...
python
{ "resource": "" }
q49997
Client._tag_cmds
train
def _tag_cmds(self, *cmds): """ Yields tagged commands. """ for (method, args) in cmds: tagged_cmd = [method, args, self._tag] self._tag = self._tag + 1 yield tagged_cmd
python
{ "resource": "" }
q49998
Client.send_cmds
train
def send_cmds(self, *cmds): """ Tags and sends the commands to the Switchboard server, returning None. Each cmd be a 2-tuple where the first element is the method name, and the second is the arguments, e.g. ("connect", {"host": ...}). """ promise = aplus.Promise(...
python
{ "resource": "" }
q49999
FIR.main
train
def main(self, x): """ Transposed form FIR implementation, uses full precision """ for i in range(len(self.taps_fix_reversed)): self.next.mul[i] = x * self.taps_fix_reversed[i] if i == 0: self.next.acc[0] = self.mul[i] else: ...
python
{ "resource": "" }