code stringlengths 1 18.2k |
|---|
def getworker(): ''' return settings dictionnary ''' if not Configuration.worker_initialized: Configuration._initconf() Configuration.worker_settings = Configuration.settings['worker'] Configuration.worker_initialized = True return Configuration.worker_settings |
def getbroker(): ''' return settings dictionnary ''' if not Configuration.broker_initialized: Configuration._initconf() Configuration.broker_settings = Configuration.settings['broker'] Configuration.broker_initialized = True return Configuration.broker_settings |
def execute(prog_name, args=None): """ Adapted `compilemessages <http://bit.ly/1r3glSu>`_ command from Django. """ args = _get_parser().parse_args(args or []) locale, locale_dir = args.locale, args.locale_dir program = 'msgfmt' ensure_programs(program) def has_bom(fn): with open(fn, 'rb') as f: sample = f.read(4) retur... |
'.po'), ] output, errors, status = popen_wrapper(args) if status: if errors: msg = "Execution of %s failed: %s" % (program, errors) else: msg = "Execution of %s failed" % program raise RuntimeError(msg) |
def getConf(self, conftype): ''' conftype must be a Zooborg constant ''' if conftype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]: raise Exception('Zooborg.getConf: invalid type') zooconf={} #TODO: specialconf entries for the mock if conftype == ZooConst.CLIENT: zooconf['broker'] = {} zooconf['broker']['c... |
def register(self, itemtype, item_id, handler): ''' register the item in zookeeper /list/ itemtype must be a Zooborg constant item_id must be a string handler: method to call on conf change ''' # Create a node with data #TODO: add system properties in data (ip, os) #TODO: add uniq client id if itemtype not in [ZooConst... |
def unregister(self, itemtype, item_id): ''' deregister the item in zookeeper /list/ itemtype must be a Zooborg constant item_id must be a string ''' if itemtype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]: raise Exception('Zooborg.unregister: invalid type') self.initconn() self.zk.ensure_path("/distark/... |
def getList(self, listtype): ''' listtype must be a Zooborg constant ''' if listtype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]: raise Exception('Zooborg.getList: invalid type') self.initconn() return self.zk.get_children('/distark/' + listtype + '/list') |
def getConf(self, conftype): ''' conftype must be a Zooborg constant ''' zooconf={} if conftype not in [ZooConst.CLIENT, ZooConst.WORKER, ZooConst.BROKER]: raise Exception('Zooborg.getConf: invalid type') self.initconn() if conftype in [ZooConst.CLIENT, ZooConst.WORKER]: zooconf={'broker': {'connectionstr': None}} zoop... |
def get_object_or_none(model, *args, **kwargs): """ Like get_object_or_404, but doesn't throw an exception. Allows querying for an object that might not exist without triggering an exception. """ try: return model._default_manager.get(*args, **kwargs) except model.DoesNotExist: return None |
def parse_text(text: str, schema: dict) -> Any: """ Validate and parse the BMA answer from websocket :param text: the bma answer :param schema: dict for jsonschema :return: the json data """ try: data = json.loads(text) jsonschema.validate(data, schema) except (TypeError, json.decoder.JSONDecodeError): raise jsonschema... |
def parse_error(text: str) -> Any: """ Validate and parse the BMA answer from websocket :param text: the bma error :return: the json data """ try: data = json.loads(text) jsonschema.validate(data, ERROR_SCHEMA) except (TypeError, json.decoder.JSONDecodeError) as e: raise jsonschema.ValidationError("Could not parse json... |
async def parse_response(response: ClientResponse, schema: dict) -> Any: """ Validate and parse the BMA answer :param response: Response of aiohttp request :param schema: The expected response structure :return: the json data """ try: data = await response.json() response.close() if schema is not None: jsonschema.valid... |
def reverse_url(self, scheme: str, path: str) -> str: """ Reverses the url using scheme and path given in parameter. :param scheme: Scheme of the url :param path: Path of the url :return: """ # remove starting slash in path if present path = path.lstrip('/') server, port = self.connection_handler.server, self.connectio... |
async def requests_get(self, path: str, **kwargs) -> ClientResponse: """ Requests GET wrapper in order to use API parameters. :param path: the request path :return: """ logging.debug("Request : {0}".format(self.reverse_url(self.connection_handler.http_scheme, path))) url = self.reverse_url(self.connection_handler.http_... |
async def requests_post(self, path: str, **kwargs) -> ClientResponse: """ Requests POST wrapper in order to use API parameters. :param path: the request path :return: """ if 'self_' in kwargs: kwargs['self'] = kwargs.pop('self_') logging.debug("POST : {0}".format(kwargs)) response = await self.connection_handler.sessio... |
def connect_ws(self, path: str) -> _WSRequestContextManager: """ Connect to a websocket in order to use API parameters In reality, aiohttp.session.ws_connect returns a aiohttp.client._WSRequestContextManager instance. It must be used in a with statement to get the ClientWebSocketResponse instance from it (__aenter__). ... |
async def post(self, url_path: str, params: dict = None, rtype: str = RESPONSE_JSON, schema: dict = None) -> Any: """ POST request on self.endpoint + url_path :param url_path: Url encoded path following the endpoint :param params: Url query string parameters dictionary :param rtype: Response type :param schema: Json Sc... |
def connect_ws(self, path: str) -> _WSRequestContextManager: """ Connect to a websocket in order to use API parameters :param path: the url path :return: """ client = API(self.endpoint.conn_handler(self.session, self.proxy)) return client.connect_ws(path) |
def extract_version(filepath='jeni.py', name='__version__'): """Parse __version__ out of given Python file. Given jeni.py has dependencies, `from jeni import __version__` will fail. """ context = {} for line in open(filepath): if name in line: exec(line, context) break else: raise RuntimeError('{} not found in {}'.form... |
def quote_value(value): """return the value ready to be used as a value in a SQL string. For example you can safely do this: cursor.execute('select * from table where key = %s' % quote_value(val)) and you don't have to worry about possible SQL injections. """ adapted = adapt(value) if hasattr(adapted, 'getquoted'): ada... |
def load(self,dset): '''load a dataset from given filename into the object''' self.dset_filename = dset self.dset = nib.load(dset) self.data = self.dset.get_data() self.header = self.dset.get_header() |
def voxel_loop(self): '''iterator that loops through each voxel and yields the coords and time series as a tuple''' # Prob not the most efficient, but the best I can do for now: for x in xrange(len(self.data)): for y in xrange(len(self.data[x])): for z in xrange(len(self.data[x][y])): yield ((x,y,z),self.data[x][y][z]) |
def get_engine(name): """ get an engine from string (engine class without Engine) """ name = name.capitalize() + 'Engine' if name in globals(): return globals()[name] raise KeyError("engine '%s' does not exist" % name) |
def init(scope): """ Initialize the xqt system with the PySide wrapper for the Qt system. :param scope | <dict> """ # define wrapper compatibility symbols QtCore.THREADSAFE_NONE = XThreadNone() QtGui.QDialog = QDialog # define the importable symbols scope['QtCore'] = QtCore scope['QtGui'] = QtGui scope['QtWebKit'] = la... |
def createAction(self, parent=None, name=''): """ Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str> """ action = super(UiLoader, self).createAction(parent, name) if not action.parent(): action.setParent(... |
def createActionGroup(self, parent=None, name=''): """ Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param parent | <QWidget> || None name | <str> """ actionGroup = super(UiLoader, self).createActionGroup(parent, name) if not actionGroup.parent(... |
def createLayout(self, className, parent=None, name=''): """ Overloads teh create action method to handle the proper base instance information, similar to the PyQt4 loading system. :param className | <str> parent | <QWidget> || None name | <str> """ layout = super(UiLoader, self).createLayout(className, parent, name) s... |
def createWidget(self, className, parent=None, name=''): """ Overloads the createWidget method to handle the proper base instance information similar to the PyQt4 loading system. :param className | <str> parent | <QWidget> || None name | <str> :return <QWidget> """ className = str(className) # create a widget off one o... |
def loadUi(self, filename, baseinstance=None): """ Generate a loader to load the filename. :param filename | <str> baseinstance | <QWidget> :return <QWidget> || None """ try: xui = ElementTree.parse(filename) except xml.parsers.expat.ExpatError: log.exception('Could not load file: %s' % filename) return None loader = U... |
ui = loader.load(filename) QtCore.QMetaObject.connectSlotsByName(ui) return ui |
def showEvent(self, event): """ Displays this dialog, centering on its parent. :param event | <QtCore.QShowEvent> """ super(QDialog, self).showEvent(event) if not self._centered: self._centered = True try: window = self.parent().window() center = window.geometry().center() except AttributeError: return else: self.move(... |
def get_uri_obj(uri, storage_args={}): """ Retrieve the underlying storage object based on the URI (i.e., scheme). :param str uri: URI to get storage object for :param dict storage_args: Keyword arguments to pass to the underlying storage object """ if isinstance(uri, BaseURI): return uri uri_obj = None o = urlparse(ur... |
def uri_open(uri, mode='rb', auto_compress=True, in_memory=True, delete_tempfile=True, textio_args={}, storage_args={}): """ Opens a URI for reading / writing. Analogous to the :func:`open` function. This method supports ``with`` context handling:: with uri_open('http://www.example.com', mode='r') as f: print(f.read())... |
to URI """ if isinstance(uri, BaseURI): uri = str(uri) uri_obj = get_uri_obj(uri, storage_args) if mode == 'rb': read_mode, binary_mode = True, True elif mode == 'r': read_mode, binary_mode = True, False elif mode == 'w': read_mode, binary_mode = False, False elif mode == 'wb': read_mode, binary_mode = False, True else... |
TextIOWrapper(file_obj, **textio_args) #end if if not hasattr(file_obj, 'temp_name'): setattr(file_obj, 'temp_name', temp_name) return file_obj |
def uri_read(*args, **kwargs): """ Reads the contents of a URI into a string or bytestring. See :func:`uri_open` for complete description of keyword parameters. :returns: Contents of URI :rtype: str, bytes """ with uri_open(*args, **kwargs) as f: content = f.read() return content |
def uri_dump(uri, content, mode='wb', **kwargs): """ Dumps the contents of a string/bytestring into a URI. See :func:`uri_open` for complete description of keyword parameters. :param str uri: URI to dump contents to :param str content: Contents to write to URI :param str mode: Either ``w``, or ``wb`` to write binary/te... |
def uri_exists_wait(uri, timeout=300, interval=5, storage_args={}): """ Block / waits until URI exists. :param str uri: URI to check existence :param float timeout: Number of seconds before timing out :param float interval: Calls :func:`uri_exists` every ``interval`` seconds :param dict storage_args: Keyword arguments ... |
def payment(self, amount, **kwargs): """Get payment URL and new transaction ID Usage:: >>> import sofort >>> client = sofort.Client('123456', '123456', '123456', abort_url='https://mysite.com/abort') >>> t = client.pay(12, success_url='http://mysite.com?paid') >>> t.transaction 123123-321231-56A3BE0E-ACAB >>> t.payment... |
def load_env(print_vars=False): """Load environment variables from a .env file, if present. If an .env file is found in the working directory, and the listed environment variables are not already set, they will be set according to the values listed in the file. """ env_file = os.environ.get('ENV_FILE', '.env') try: var... |
async def main(): """ Main code (synchronous requests) """ # Create Client from endpoint string in Duniter format client = Client(ES_CORE_ENDPOINT) # Get the current node (direct REST GET request) print("\nGET g1-test/block/current/_source:") response = await client.get('g1-test/block/current/_source') print(response) ... |
def fill_model(self, model=None): """ Populates a model with normalized properties. If no model is provided (None) a new one will be created. :param model: model to be populade :return: populated model """ normalized_dct = self.normalize() if model: if not isinstance(model, self._model_class): raise ModelFormSecurityEr... |
def fill_with_model(self, model, *fields): """ Populates this form with localized properties from model. :param fields: string list indicating the fields to include. If None, all fields defined on form will be used :param model: model :return: dict with localized properties """ model_dct = model.to_dict(include=self._f... |
def get_config(config_schema, env=None): """Parse config from the environment against a given schema Args: config_schema: A dictionary mapping keys in the environment to envpy Schema objects describing the expected value. env: An optional dictionary used to override the environment rather than getting it from the os. R... |
def Log(self, messages): """ Parameters: - messages """ self._seqid += 1 d = self._reqs[self._seqid] = defer.Deferred() self.send_Log(messages) return d |
def get_line_matches(input_file: str, pattern: str, max_occurrencies: int = 0, loose_matching: bool = True) -> dict: r"""Get the line numbers of matched patterns. :parameter input_file: the file that needs to be read. :parameter pattern: the pattern that needs to be searched. :parameter max_occurrencies: the maximum nu... |
if the first occurrency of pattern is at line y then: x[1] = y. :rtype: dict :raises: a built-in exception. .. note:: Line numbers start from ``1``. """ assert max_occurrencies >= 0 occurrency_counter = 0.0 occurrency_matches = dict() if max_occurrencies == 0: max_occurrencies = float('inf') if loose_matching: pattern ... |
def insert_string_at_line(input_file: str, string_to_be_inserted: str, put_at_line_number: int, output_file: str, append: bool = True, newline_character: str = '\n'): r"""Write a string at the specified line. :parameter input_file: the file that needs to be read. :parameter string_to_be_inserted: the string that needs ... |
:raises: LineOutOfFileBoundsError or a built-in exception. .. note:: Line numbers start from ``1``. """ assert put_at_line_number >= 1 with open(input_file, 'r') as f: lines = f.readlines() line_counter = 1 i = 0 loop = True extra_lines_done = False line_number_after_eof = len(lines) + 1 with atomic_write(output_file, ... |
line_counter == line_number_after_eof: for additional_newlines in range( 0, put_at_line_number - len(lines) - 1): # Skip the newline in the line where we need to insert # the new string. f.write(newline_character) line_counter += 1 i += 1 extra_lines_done = True if line_counter == put_at_line_number: # A very simple ap... |
and not extra_lines_done: loop = True |
def remove_line_interval(input_file: str, delete_line_from: int, delete_line_to: int, output_file: str): r"""Remove a line interval. :parameter input_file: the file that needs to be read. :parameter delete_line_from: the line number from which start deleting. :parameter delete_line_to: the line number to which stop del... |
== 0: single line. if delete_line_to - delete_line_from < 0: raise NegativeLineRangeError if delete_line_from > len(lines) or delete_line_to > len(lines): raise LineOutOfFileBoundsError line_counter = 1 # Rewrite the file without the string. with atomic_write(output_file, overwrite=True) as f: for line in lines: # Igno... |
def upload_dataset( dataset_name, file_path, task=None, dataset_attributes=None, **kwargs): """Uploads the given file to dataset store. Parameters ---------- dataset_name : str The name of the dataset to upload. file_path : str The full path to the file to upload task : str, optional The task for which the given datase... |
= ntpath.basename(file_path) blob_name = _blob_name( dataset_name=dataset_name, file_name=fname, task=task, dataset_attributes=dataset_attributes, ) print(blob_name) _blob_service().create_blob_from_path( container_name=BARN_CFG['azure']['container_name'], blob_name=blob_name, file_path=file_path, **kwargs, ) |
def download_dataset( dataset_name, file_path, task=None, dataset_attributes=None, **kwargs): """Downloads the given dataset from dataset store. Parameters ---------- dataset_name : str The name of the dataset to upload. file_path : str The full path to the file to upload task : str, optional The task for which the giv... |
= ntpath.basename(file_path) blob_name = _blob_name( dataset_name=dataset_name, file_name=fname, task=task, dataset_attributes=dataset_attributes, ) # print("Downloading blob: {}".format(blob_name)) try: _blob_service().get_blob_to_path( container_name=BARN_CFG['azure']['container_name'], blob_name=blob_name, file_path... |
def _resolve_name(name, package, level): """Resolve a relative module name to an absolute one.""" bits = package.rsplit('.', level - 1) if len(bits) < level: raise ValueError('attempted relative import beyond top-level package') base = bits[0] return '{}.{}'.format(base, name) if name else base |
def resolve_name(name, package): """Resolve a relative module name to an absolute one.""" if not name.startswith('.'): return name elif not package: raise ValueError('{!r} is not a relative name ' '(no leading dot)'.format(name)) level = 0 for character in name: if character != '.': break level += 1 return _resolve_nam... |
def _find_spec_from_path(name, path=None): """Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys... |
module.__spec__ except AttributeError: six.raise_from(ValueError('{}.__spec__ is not set'.format(name)), None) else: if spec is None: raise ValueError('{}.__spec__ is None'.format(name)) return spec |
def find_spec(name, package=None): """Return the spec for the specified module. First, sys.modules is checked to see if the module was already imported. If so, then sys.modules[name].__spec__ is returned. If that happens to be set to None, then ValueError is raised. If the module is not in sys.modules, then sys.meta_pa... |
Use builtins.__import__() in case someone replaced it. parent = __import__(parent_name, fromlist=['__path__']) return _find_spec(fullname, parent.__path__) else: return _find_spec(fullname, None) else: module = sys.modules[fullname] if module is None: return None try: spec = module.__spec__ except AttributeError: six.r... |
def set_package(fxn): """Set __package__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_package_wrapper(*args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2) module = fxn(*args, **kwargs) if getattr(module, '_... |
def set_loader(fxn): """Set __loader__ on the returned module. This function is deprecated. """ @functools.wraps(fxn) def set_loader_wrapper(self, *args, **kwargs): warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2) module = fxn(self, *args, **kwargs) if getattr(m... |
def module_for_loader(fxn): """Decorator to handle selecting the proper module for loaders. The decorated function is passed the module to use instead of the module name. The module passed in to the function is either from sys.modules if it already exists or is a new module. If the module is new, then __name__ is set t... |
second argument. """ warnings.warn('The import system now takes care of this automatically.', DeprecationWarning, stacklevel=2) @functools.wraps(fxn) def module_for_loader_wrapper(self, fullname, *args, **kwargs): with _module_to_load(fullname) as module: module.__loader__ = self try: is_package = self.is_package(fulln... |
def print_fields(fields, sort_by_date=False, sort_by_open_projects=False): """ Print a list of available fields and works sort_by_date : boolean whether we print works by their due date """ if (not sort_by_date) and (not sort_by_open_projects): for (_, name, works) in fields: print(name) for work in works: print('- '+s... |
def send_work(baseurl, work_id=None, filename=None, command="make"): """Ask user for a file to send to a work""" while 1: if not work_id: try: work_id = input("id? ") except KeyboardInterrupt: exit(0) work = get_work(work_id) if not work: print("id '{0}' not found".format(work_id)) work_id = None continue if not work.i... |
def activate(): """Install the path-based import components.""" global PathFinder, FileFinder, ff_path_hook path_hook_index = len(sys.path_hooks) sys.path_hooks.append(ff_path_hook) # Resetting sys.path_importer_cache values, # to support the case where we have an implicit package inside an already loaded package, # si... |
def send(self): """Sends the broadcast message. :returns: tuple of (:class:`adnpy.models.Message`, :class:`adnpy.models.APIMeta`) """ parse_links = self.parse_links or self.parse_markdown_links message = { 'annotations': [], 'entities': { 'parse_links': parse_links, 'parse_markdown_links': self.parse_markdown_links, } ... |
def add_server(self,address,port=default_port,password=None,speed=None,valid_times=None,invalid_times=None): ''' :address: remote address of server, or special string ``local`` to run the command locally :valid_times: times when this server is available, given as a list of tuples of 2 strings of form "HH:MM" that defin... |
'address':address, 'port':port, 'password':password, 'speed':speed, 'valid_times':valid_times, 'invalid_times':invalid_times }) |
def archive_compile(filename, command="make"): """ Returns if the given archive properly compile. Extract it in a temporary directory, run the given command, and return True it's result is 0 """ if not tarfile.is_tarfile(filename): print("Cannot extract archive") return False if command == "": return True with tempfile... |
def haversine(lat_lng1, lat_lng2, native=True): if native: return _native.haversine(lat_lng1, lat_lng2) """Cf https://github.com/mapado/haversine""" lat1, lng1 = lat_lng1 lat2, lng2 = lat_lng2 lat1, lng1, lat2, lng2 = map(math.radians, (lat1, lng1, lat2, lng2)) lat = lat2 - lat1 lng = lng2 - lng1 d = math.sin(lat * 0.5... |
def run(arguments: List[str], execution_directory: str=None, execution_environment: Dict=None) -> str: """ Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory). :param arguments: the CLI arguments to run :param execution_directory: the directory to execute the ... |
def raw(self): """Make request to url and return the raw response object. """ try: return urlopen(str(self.url)) except HTTPError as error: try: # parse error body as json and use message property as error message parsed = self._parsejson(error) exc = RequestError(parsed['message']) exc.__cause__ = None raise exc excep... |
def csv(self): """Parse raw response as csv and return row object list. """ lines = self._parsecsv(self.raw) # set keys from header line (first line) keys = next(lines) for line in lines: yield dict(zip(keys, line)) |
def _parsecsv(x): """Deserialize file-like object containing csv to a Python generator. """ for line in x: # decode as utf-8, whitespace-strip and split on delimiter yield line.decode('utf-8').strip().split(config.DELIMITER) |
def construct_exc_class(cls): """Constructs proxy class for the exception.""" class ProxyException(cls, BaseException): __pep3134__ = True @property def __traceback__(self): if self.__fixed_traceback__: return self.__fixed_traceback__ current_exc, current_tb = sys.exc_info()[1:] if current_exc is self: return current_t... |
def prepare_raise(func): """ Just a short decorator which shrinks full ``raise (E, V, T)`` form into proper ``raise E(V), T``. """ @functools.wraps(func) def decorator(type_, value=None, traceback=None): if value is not None and isinstance(type_, Exception): raise TypeError("instance exception may not have a separate v... |
def from_url(cls, url, **kwargs): """ Downloads a zipped app source code from an url. :param url: url to download the app source from Returns A project instance. """ username = kwargs.get('username') password = kwargs.get('password') headers = kwargs.get('headers', {}) auth = None path = kwargs.get('path', '/tmp/app.zi... |
def from_path(cls, path): """ Instantiates a project class from a given path. :param path: app folder path source code Returns A project instance. """ if os.path.exists(path) is False: raise errors.InvalidPathError(path) return cls(path=path) |
def from_zip(cls, src='/tmp/app.zip', dest='/app'): """ Unzips a zipped app project file and instantiates it. :param src: zipfile path :param dest: destination folder to extract the zipfile content Returns A project instance. """ try: zf = zipfile.ZipFile(src, 'r') except FileNotFoundError: raise errors.InvalidPathErro... |
def inspect(self, tab_width=2, ident_char='-'): """ Inspects a project file structure based based on the instance folder property. :param tab_width: width size for subfolders and files. :param ident_char: char to be used to show identation level Returns A string containing the project structure. """ startpath = self.pa... |
def log(self, ctx='all'): """ Gets the build log output. :param ctx: specifies which log message to show, it can be 'validate', 'build' or 'all'. """ path = '%s/%s.log' % (self.path, ctx) if os.path.exists(path) is True: with open(path, 'r') as f: print(f.read()) return validate_path = '%s/validate.log' % self.path bui... |
def second_order_diff(arr, x): """Compute second order difference of an array. A 2nd order forward difference is used for the first point, 2nd order central difference for interior, and 2nd order backward difference for last point, returning an array the same length as the input array. """ # Convert to array, so this w... |
arr[-3])/(2*dxb) # For all interior points, use 2nd order central difference interior = (arr[2:] - arr[:-2])/(2*dx) # Create entire array darr = np.concatenate(([first], interior, [last])) return darr |
def _freeze(self) -> OrderedDict: """ Evaluate all of the column values and return the result :return: column/value tuples """ return OrderedDict(**{k: getattr(self, k, None) for k in super().__getattribute__("_columns")}) |
def _eval(self, m: EvalParam) -> object: """ Evaluate m returning the method / function invocation or value. Kind of like a static method :param m: object to evaluate :return: return """ if inspect.ismethod(m) or inspect.isroutine(m): return m() elif inspect.isfunction(m): return m(self) if len(inspect.signature(m)) > ... |
def _process_json(response_body): """ Returns a UwPassword objects """ data = json.loads(response_body) uwpassword = UwPassword(uwnetid=data["uwNetID"], kerb_status=data["kerbStatus"], interval=None, last_change=None, last_change_med=None, expires_med=None, interval_med=None, minimum_length=int(data["minimumLength"]), ... |
def create_next_tag(): """ creates a tag based on the date and previous tags """ date = datetime.utcnow() date_tag = '{}.{}.{}'.format(date.year, date.month, date.day) if date_tag in latest_tag(): # if there was an update already today latest = latest_tag().split('.') # split by spaces if len(latest) == 4: # if it is n... |
def sync_readmes(): """ just copies README.md into README for pypi documentation """ print("syncing README") with open("README.md", 'r') as reader: file_text = reader.read() with open("README", 'w') as writer: writer.write(file_text) |
def similarity(self, other): """Get similarity as a ratio of the two numbers.""" numerator, denominator = sorted((self.value, other.value)) try: ratio = float(numerator) / denominator except ZeroDivisionError: ratio = 0.0 if numerator else 1.0 similarity = self.Similarity(ratio) return similarity |
def similarity(self, other): """Get similarity as a ratio of the two texts.""" ratio = SequenceMatcher(a=self.value, b=other.value).ratio() similarity = self.Similarity(ratio) return similarity |
def similarity(self, other): """Get similarity as a discrete ratio (1.0 or 0.0).""" ratio = 1.0 if (str(self).lower() == str(other).lower()) else 0.0 similarity = self.Similarity(ratio) return similarity |
def _strip(text): """Strip articles/whitespace and remove case.""" text = text.strip() text = text.replace(' ', ' ') # remove duplicate spaces text = text.lower() for joiner in TextTitle.JOINERS: text = text.replace(joiner, 'and') for article in TextTitle.ARTICLES: if text.startswith(article + ' '): text = text[len(art... |
def similarity(self, other): """Get similarity as a ratio of the stripped text.""" logging.debug("comparing %r and %r...", self.stripped, other.stripped) ratio = SequenceMatcher(a=self.stripped, b=other.stripped).ratio() similarity = self.Similarity(ratio) return similarity |
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True): ''' use bet to strip skull from given anatomy ''' # should add options to use betsurf and T1/T2 in the future # Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :) if prefix==None: pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.