code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def check(cls, config, strict=False): result = {"errors": [], "warnings": []} validation_errors = validate_object(config, "poetry-schema") result["errors"] += validation_errors if strict: license = config.get("license") if license: try: ...
Checks the validity of a configuration
def to_build_module(build_file_path: str, conf: Config) -> str: build_file = Path(build_file_path) root = Path(conf.project_root) return build_file.resolve().relative_to(root).parent.as_posix().strip('.')
Return a normalized build module name for `build_file_path`.
def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]: return (m // (10 ** n)) % 10
Returns the nth digit of each number in m.
def __load_asset_class(self, ac_id: int): db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
Loads Asset Class entity
def obj_to_string(obj): if not obj: return None elif isinstance(obj, bytes): return obj.decode('utf-8') elif isinstance(obj, basestring): return obj elif is_lazy_string(obj): return obj.value elif hasattr(obj, '__html__'): return obj.__html__() else: ...
Render an object into a unicode string if possible
def reload_me(*args, ignore_patterns=[]): command = [sys.executable, sys.argv[0]] command.extend(args) reload(*command, ignore_patterns=ignore_patterns)
Reload currently running command with given args
def poll_crontab(self): polled_time = self._get_current_time() if polled_time.second >= 30: self.log.debug('Skip cronjobs in {}'.format(polled_time)) return for job in self._crontab: if not job.is_runnable(polled_time): continue job...
Check crontab and run target jobs
def make_url(self, container=None, resource=None, query_items=None): pth = [self._base_url] if container: pth.append(container.strip('/')) if resource: pth.append(resource) else: pth.append('') url = '/'.join(pth) if isinstance(query_it...
Create a URL from the specified parts.
def getFixedStars(self): IDs = const.LIST_FIXED_STARS return ephem.getFixedStarList(IDs, self.date)
Returns a list with all fixed stars.
def watch(filenames, callback, use_sudo=False): filenames = [filenames] if isinstance(filenames, basestring) else filenames old_md5 = {fn: md5sum(fn, use_sudo) for fn in filenames} yield for filename in filenames: if md5sum(filename, use_sudo) != old_md5[filename]: callback() ...
Call callback if any of filenames change during the context
def remove_bookmark(self, name=None, time=None, chan=None): bookmarks = self.rater.find('bookmarks') for m in bookmarks: bookmark_name = m.find('bookmark_name').text bookmark_start = float(m.find('bookmark_start').text) bookmark_end = float(m.find('bookmark_end').text...
if you call it without arguments, it removes ALL the bookmarks.
def create_user(ctx): try: new_user = _create_user(ctx) new_user.save() log("Done") except KeyError: log('User already exists', lvl=warn)
Creates a new local user
def copy_assets(app, exception): if 'getLogger' in dir(logging): log = logging.getLogger(__name__).info else: log = app.info builders = get_compatible_builders(app) if exception: return if app.builder.name not in builders: if not app.config['sphinx_tabs_nowarn']: ...
Copy asset files to the output
def _categorize_file_diffs(self, file_diffs): candidate_feature_diffs = [] valid_init_diffs = [] inadmissible_files = [] for diff in file_diffs: valid, failures = check_from_class( ProjectStructureCheck, diff, self.project) if valid: ...
Partition file changes into admissible and inadmissible changes
def save_device_info(self): if self._workdir is not None: devices = [] for addr in self._devices: device = self._devices.get(addr) if not device.address.is_x10: aldb = {} for mem in device.aldb: ...
Save all device information to the device info file.
def create(self, request, *args, **kwargs): if not request.user.is_authenticated: raise exceptions.NotFound return super().create(request, *args, **kwargs)
Only authenticated usesr can create new collections.
def build_data_availability(datasets_json): data_availability = None if 'availability' in datasets_json and datasets_json.get('availability'): data_availability = datasets_json.get('availability')[0].get('text') return data_availability
Given datasets in JSON format, get the data availability from it if present
def extract_facts(rule): def _extract_facts(ce): if isinstance(ce, Fact): yield ce elif isinstance(ce, TEST): pass else: for e in ce: yield from _extract_facts(e) return set(_extract_facts(rule))
Given a rule, return a set containing all rule LHS facts.
def delete(ctx,tweet): if not ctx.obj['DRYRUN']: try: ctx.obj['TWEETLIST'].delete(tweet) except ValueError as e: click.echo("Now tweet was found with that id.") ctx.exit(1) else: click.echo("Not ran due to dry-run.")
Deletes a tweet from the queue with a given ID
def decode_list(self, integers): integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode_list(integers)
List of ints to list of str.
def calculate_A50(ctgsizes, cutoff=0, percent=50): ctgsizes = np.array(ctgsizes, dtype="int") ctgsizes = np.sort(ctgsizes)[::-1] ctgsizes = ctgsizes[ctgsizes >= cutoff] a50 = np.cumsum(ctgsizes) total = np.sum(ctgsizes) idx = bisect(a50, total * percent / 100.) l50 = ctgsizes[idx] n50 = ...
Given an array of contig sizes, produce A50, N50, and L50 values
def extern_project_multi(self, context_handle, val, field_str_ptr, field_str_len): c = self._ffi.from_handle(context_handle) obj = c.from_value(val[0]) field_name = self.to_py_str(field_str_ptr, field_str_len) return c.vals_buf(tuple(c.to_value(p) for p in getattr(obj, field_name)))
Given a Key for `obj`, and a field name, project the field as a list of Keys.
def dependencies(self, images): for dep in self.commands.dependent_images: if not isinstance(dep, six.string_types): yield dep.name for image, _ in self.dependency_images(): yield image
Yield just the dependency images
def _is_parent(self, roleid1, roleid2): role2 = copy.deepcopy(self.flatten[roleid2]) role1 = copy.deepcopy(self.flatten[roleid1]) if role1 == role2: return False for b1 in role1['backends_groups']: if b1 not in role2['backends_groups']: return Fals...
Test if roleid1 is contained inside roleid2
def _ensure_scope(level, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs): return Scope(level + 1, global_dict=global_dict, local_dict=local_dict, resolvers=resolvers, target=target)
Ensure that we are grabbing the correct scope.
def retrieve_loadbalancer_status(self, loadbalancer, **_params): return self.get(self.lbaas_loadbalancer_path_status % (loadbalancer), params=_params)
Retrieves status for a certain load balancer.
def getheader(self, which, use_hash=None, polish=True): header = getheader( which, use_hash=use_hash, target=self.target, no_tco=self.no_tco, strict=self.strict, ) if polish: header = self.polish(header) return heade...
Get a formatted header.
def _calculate_weights(self, this_samples, N): this_weights = self.weights.append(N)[:,0] if self.target_values is None: for i in range(N): tmp = self.target(this_samples[i]) - self.proposal.evaluate(this_samples[i]) this_weights[i] = _exp(tmp) else: ...
Calculate and save the weights of a run.
def OnInit(self): self.frame = SimpleSCardAppFrame( self.appname, self.apppanel, self.appstyle, self.appicon, self.pos, self.size) self.frame.Show(True) self.SetTopWindow(self.frame) return True
Create and display application frame.
def setHeader(self, fileHeader): self.technician = fileHeader["technician"] self.recording_additional = fileHeader["recording_additional"] self.patient_name = fileHeader["patientname"] self.patient_additional = fileHeader["patient_additional"] self.patient_code = fileHeader["pati...
Sets the file header
def _add(a, b, relicAdd): assertSameType(a,b) result = type(a)() relicAdd(byref(result), byref(a), byref(b)) return result
Adds two elements @a,@b of the same type into @result using @relicAddFunc.
def _skip_lines(self, n): for i in range(n): self.line = next(self.output) return self.line
Skip a number of lines from the output.
def response(self): values = [] sum_values = 0. ma_coefs = self.ma_coefs ar_coefs = self.ar_coefs ma_order = self.ma_order for idx in range(len(self.ma.delays)): value = 0. if idx < ma_order: value += ma_coefs[idx] for j...
Return the response to a standard dt impulse.
def termfinder(self, pattern): if Config.options.regex: flags = re.M | re.S | \ (0 if Config.options.case_sensitive else re.I) self.project.set_search_regex( pattern, flags=flags) else: self.project.set_search_string( pa...
Search srt in project for cells matching term.
def nonlocal_check(self, original, loc, tokens): return self.check_py("3", "nonlocal statement", original, loc, tokens)
Check for Python 3 nonlocal statement.
def start_fileoutput (self): path = os.path.dirname(self.filename) try: if path and not os.path.isdir(path): os.makedirs(path) self.fd = self.create_fd() self.close_fd = True except IOError: msg = sys.exc_info()[1] log.w...
Start output to configured file.
def visit_classdef(self, node, parent, newstyle=None): node, doc = self._get_doc(node) newnode = nodes.ClassDef(node.name, doc, node.lineno, node.col_offset, parent) metaclass = None if PY3: for keyword in node.keywords: if keyword.arg == "metaclass": ...
visit a ClassDef node to become astroid
def restore(self, url): self._run( [ "heroku", "pg:backups:restore", "{}".format(url), "DATABASE_URL", "--app", self.name, "--confirm", self.name, ] )
Restore the remote database from the URL of a backup.
def _domain_event_balloon_change_cb(conn, domain, actual, opaque): _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'actual': actual })
Domain balloon change events handler
def safe_lshift(a, b): if b > MAX_SHIFT: raise RuntimeError("Invalid left shift, max left shift is {}".format(MAX_SHIFT)) return a << b
safe version of lshift
def combine(self, a, b): for l in (a, b): for x in l: yield x
A generator that combines two iterables.
def handleArgs(self, event): if self.djsettings: os.environ['DJANGO_SETTINGS_MODULE'] = self.djsettings if self.djconfig: os.environ['DJANGO_CONFIGURATION'] = self.djconfig try: from configurations import importer importer.install() except ...
Nose2 hook for the handling the command line args
def _clone(self): clone = self.__class__(self._entity_cls, criteria=self._criteria, offset=self._offset, limit=self._limit, order_by=self._order_by) return clone
Return a copy of the current QuerySet.
def measures(self): from ambry.valuetype.core import ROLE return [c for c in self.columns if c.role == ROLE.MEASURE]
Iterate over all measures
def mainview(request, **criterias): 'View that handles all page requests.' view_data = initview(request) wrap = lambda func: ft.partial(func, _view_data=view_data, **criterias) return condition( etag_func=wrap(cache_etag), last_modified_func=wrap(cache_last_modified) )\ (_mainview)(request, view_data, **cri...
View that handles all page requests.
def retrieve(self): data = self.resource(self.id).get() self.data = data return data
Retrieves all data for this document and saves it.
def load(self, dtype_out_time, dtype_out_vert=False, region=False, plot_units=False, mask_unphysical=False): msg = ("Loading data from disk for object={0}, dtype_out_time={1}, " "dtype_out_vert={2}, and region=" "{3}".format(self, dtype_out_time, dtype_out_vert, region...
Load the data from the object if possible or from disk.
def choose_font(self, font=None): fmt_widget = self.parent() if font is None: if self.current_font: font, ok = QFontDialog.getFont( self.current_font, fmt_widget, 'Select %s font' % self.fmto_name, QFontDialog.DontUs...
Choose a font for the label through a dialog
def fill_with_defaults(process_input, input_schema): for field_schema, fields, path in iterate_schema(process_input, input_schema): if 'default' in field_schema and field_schema['name'] not in fields: dict_dot(process_input, path, field_schema['default'])
Fill empty optional fields in input with default values.
def _onMessage(self, ws, message): try: data = json.loads(message)['NotificationContainer'] log.debug('Alert: %s %s %s', *data) if self._callback: self._callback(data) except Exception as err: log.error('AlertListener Msg Error: %s', err)
Called when websocket message is recieved.
def serial(self): asnint = libcrypto.X509_get_serialNumber(self.cert) bio = Membio() libcrypto.i2a_ASN1_INTEGER(bio.bio, asnint) return int(str(bio), 16)
Serial number of certificate as integer
def service_table(format='simple', authenticated=False): if authenticated: all_services = ExchangeUniverse.get_authenticated_services() else: all_services = ALL_SERVICES if format == 'html': linkify = lambda x: "<a href='{0}' target='_blank'>{0}</a>".format(x) else: linki...
Returns a string depicting all services currently installed.
def _extra_regression_kwargs(self): omega_switch_test = 0.019 extra_args = [] extra_args.append({ 'omega0': 5e-3, 'PN_approximant': 'SpinTaylorT4', 'PN_dt': 0.1, 'PN_spin_order': 7, 'PN_phase_order': 7, 'omega_switch': omega...
List of additional kwargs to use in regression tests.
def _extract_info_from_useragent(user_agent): parsed_string = user_agent_parser.Parse(user_agent) return { 'os': parsed_string.get('os', {}).get('family'), 'browser': parsed_string.get('user_agent', {}).get('family'), 'browser_version': parsed_string.get('user_agent', {}).get('major'), ...
Extract extra informations from user.
def from_json(buffer): buffer = to_bytes(buffer) return Index._from_ptr(rustcall( _lib.lsm_index_from_json, buffer, len(buffer)))
Creates an index from a JSON string.
def _get_uid(name): if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
Returns an uid, given a user name.
def format(self, action): item = { 'id': self.get_uri(action), 'url': self.get_url(action), 'verb': action.verb, 'published': rfc3339_date(action.timestamp), 'actor': self.format_actor(action), 'title': text_type(action), } ...
Returns a formatted dictionary for the given action.
def extract_entity(found): obj = dict() for prop in found.entity.property: obj[prop.name] = prop.value.string_value return obj
Copy found entity to a dict.
def cancel_queue(self): q = list(self.queue) self.queue = [] log.debug("Canceling requests: {}".format(q)) for req in q: req.response = APIServerNotRunningErrorResponse() for req in q: req.signal()
Cancel all requests in the queue so we can exit.
def quit(self, *args, **kwargs): self.stop() self._stop = True self.msleep(2* int(1e3 / self.settings['update frequency'])) super(Plant, self).quit(*args, **kwargs)
quit the instrument thread
def render(self, path): return ReactComponent( self.layout, self.src_file, self.component_id, props=self.props, static_path=path)
Render the component to a javascript file.
def create_hierarchy(self, *args, **kwargs): return Hierarchy( self._provider_manager, self._get_provider_session('hierarchy_admin_session').create_hierarchy(*args, **kwargs), self._runtime, self._proxy)
Pass through to provider HierarchyAdminSession.create_hierarchy
def _cast_to_type(self, value): if isinstance(value, str) or value is None: return value return str(value)
Convert the value to its string representation
def sanitize_cloud(cloud: str) -> str: if len(cloud) < 4: return cloud if not cloud[3].isdigit() and cloud[3] != '/': if cloud[3] == 'O': cloud = cloud[:3] + '0' + cloud[4:] else: cloud = cloud[:3] + cloud[4:] + cloud[3] return cloud
Fix rare cloud layer issues
def to_json(self): result = super(Locale, self).to_json() result.update({ 'code': self.code, 'name': self.name, 'fallbackCode': self.fallback_code, 'optional': self.optional, 'contentDeliveryApi': self.content_delivery_api, 'content...
Returns the JSON representation of the locale.
def color(colors, export_type, output_file=None): all_colors = flatten_colors(colors) template_name = get_export_type(export_type) template_file = os.path.join(MODULE_DIR, "templates", template_name) output_file = output_file or os.path.join(CACHE_DIR, template_name) if os.path.isfile(template_file)...
Export a single template file.
def migrateDown(self): subStore = self.store.parent.getItemByID(self.store.idInParent) ssph = self.store.parent.findUnique( _SubSchedulerParentHook, _SubSchedulerParentHook.subStore == subStore, default=None) if ssph is not None: te = self.store.pa...
Remove the components in the site store for this SubScheduler.
def _calculate_areas(self, label): heights = np.maximum(0, label[:, 3] - label[:, 1]) widths = np.maximum(0, label[:, 2] - label[:, 0]) return heights * widths
Calculate areas for multiple labels
def mongodb_auth_uri(self, hosts): parts = ['mongodb://'] if self.login: parts.append(self.login) if self.password: parts.append(':' + self.password) parts.append('@') parts.append(hosts + '/') if self.login: parts.append('?...
Get a connection string with all info necessary to authenticate.
def clear(self): layout = self.layout() for index in reversed(range(layout.count())): item = layout.takeAt(index) try: item.widget().deleteLater() except AttributeError: item = None
Removes all child widgets.
def marshmallow_loader(schema_class): def json_loader(): request_json = request.get_json() context = {} pid_data = request.view_args.get('pid_value') if pid_data: pid, _ = pid_data.data context['pid'] = pid result = schema_class(context=context).load(r...
Marshmallow loader for JSON requests.
def pool_delete(storage_pool, logger): path = etree.fromstring(storage_pool.XMLDesc(0)).find('.//path').text volumes_delete(storage_pool, logger) try: storage_pool.destroy() except libvirt.libvirtError: logger.exception("Unable to delete storage pool.") try: if os.path.exists...
Storage Pool deletion, removes all the created disk images within the pool and the pool itself.
def func_globals_inject(func, **overrides): if hasattr(func, 'im_func'): func = func.__func__ func_globals = func.__globals__ injected_func_globals = [] overridden_func_globals = {} for override in overrides: if override in func_globals: overridden_func_globals[override] ...
Override specific variables within a function's global context.
def run_dict_method(self, request): state_method_name, args, kwargs = ( request[Msgs.info], request[Msgs.args], request[Msgs.kwargs], ) with self.mutate_safely(): self.reply(getattr(self.state, state_method_name)(*args, **kwargs))
Execute a method on the state ``dict`` and reply with the result.
def _get_calls(data, cnv_only=False): cnvs_supported = set(["cnvkit", "battenberg"]) out = {} for sv in data.get("sv", []): if not cnv_only or sv["variantcaller"] in cnvs_supported: out[sv["variantcaller"]] = sv return out
Retrieve calls, organized by name, to use for heterogeneity analysis.
def gone_online(stream): while True: packet = yield from stream.get() session_id = packet.get('session_key') if session_id: user_owner = get_user_from_session(session_id) if user_owner: logger.debug('User ' + user_owner.username + ' gone online'...
Distributes the users online status to everyone he has dialog with
def update_band_description(self): self.clear_further_steps() selected_band = self.selected_band() statistics = self.parent.layer.dataProvider().bandStatistics( selected_band, QgsRasterBandStats.All, self.parent.layer.extent(), 0) band_desc...
Helper to update band description.
def write_generator_cost_data(self, file): file.write("\n%%%% generator cost data\n") file.write("%%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n") file.write("%%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\n") file.write("%sgencost = [\n" % self._prefix) for generator in self.c...
Writes generator cost data to file.
def _compute_v1_factor(self, imt): if imt.name == "SA": t = imt.period if t <= 0.50: v1 = 1500.0 elif t > 0.50 and t <= 1.0: v1 = np.exp(8.0 - 0.795 * np.log(t / 0.21)) elif t > 1.0 and t < 2.0: v1 = np.exp(6.76 - 0....
Compute and return v1 factor, equation 6, page 77.
def post_outcome_request(self): if not self.has_required_attributes(): raise InvalidLTIConfigError( 'OutcomeRequest does not have all required attributes') consumer = oauth2.Consumer(key=self.consumer_key, secret=self.consumer_secret) ...
POST an OAuth signed request to the Tool Consumer.
def xpathNewParserContext(self, str): ret = libxml2mod.xmlXPathNewParserContext(str, self._o) if ret is None:raise xpathError('xmlXPathNewParserContext() failed') __tmp = xpathParserContext(_obj=ret) return __tmp
Create a new xmlXPathParserContext
def request_time(self, req): r = time.time() self._time_result.set_value(r) return ("ok", r)
Return the current time in ms since the Unix Epoch.
def __notify(self, sender, content): if self.handle_message is not None: try: self.handle_message(sender, content) except Exception as ex: logging.exception("Error calling message listener: %s", ex)
Calls back listener when a message is received
def simple_parse_file(filename: str) -> Feed: pairs = ( (rss.parse_rss_file, _adapt_rss_channel), (atom.parse_atom_file, _adapt_atom_feed), (json_feed.parse_json_feed_file, _adapt_json_feed) ) return _simple_parse(pairs, filename)
Parse an Atom, RSS or JSON feed from a local file.
def position(self, node): rv = 'line %d' % node.lineno if self.name is not None: rv += ' in ' + repr(self.name) return rv
Return a human readable position for the node.
def stop(self) -> None: self._shutdown = True self._protocol.close() self.cancel_pending_tasks()
Stop monitoring the base unit.
def prepare(self): SCons.Node.Node.prepare(self) if self.get_state() != SCons.Node.up_to_date: if self.exists(): if self.is_derived() and not self.precious: self._rmv_existing() else: try: self._createDir() ...
Prepare for this file to be created.
def modify_subroutine(subroutine): subroutine['use'] = {'shtools': {'map': {subroutine['name']: subroutine['name']}, 'only': 1}} for varname, varattribs in subroutine['vars'].items(): if varname == subroutine['name']: subroutine['vars']['py' + varname] = subroutine['vars'].pop(varname) ...
loops through variables of a subroutine and modifies them
def baltree(ntips, treeheight=1.0): if ntips % 2: raise ToytreeError("balanced trees must have even number of tips.") rtree = toytree.tree() rtree.treenode.add_child(name="0") rtree.treenode.add_child(name="1") for i in range(2, ntips): node = return_small...
Returns a balanced tree topology.
def _rnd_date(start, end): return date.fromordinal(random.randint(start.toordinal(), end.toordinal()))
Internal random date generator.
def gravatar(self, size=20): default = "mm" gravatar_url = "//www.gravatar.com/avatar/" + hashlib.md5(self.email.lower()).hexdigest() + "?" gravatar_url += urllib.urlencode({'d': default, 's': str(size)}) return gravatar_url
Construct a gravatar image address for the user
def divides(self): acc = [0] for s in self.chunks: acc.append(acc[-1] + len(s)) return acc
List of indices of divisions between the constituent chunks.
def _createGeometry(self, session, spatialReferenceID): session.flush() for link in self.getFluvialLinks(): nodes = link.nodes nodeCoordinates = [] for node in nodes: coordinates = '{0} {1} {2}'.format(node.x, node.y, node.elevation) no...
Create PostGIS geometric objects
def resolve(self, pubID, sysID): ret = libxml2mod.xmlACatalogResolve(self._o, pubID, sysID) return ret
Do a complete resolution lookup of an External Identifier
def _from_jd_equinox(jd): jd = trunc(jd) + 0.5 equinoxe = premier_da_la_annee(jd) an = gregorian.from_jd(equinoxe)[0] - YEAR_EPOCH mois = trunc((jd - equinoxe) / 30.) + 1 jour = int((jd - equinoxe) % 30) + 1 return (an, mois, jour)
Calculate the FR day using the equinox as day 1
def _validate_iso8601_string(self, value): ISO8601_REGEX = r'(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})([+-](\d{2})\:(\d{2})|Z)' if re.match(ISO8601_REGEX, value): return value else: raise ValueError('{} must be in ISO8601 format.'.format(value))
Return the value or raise a ValueError if it is not a string in ISO8601 format.
def new_term(self, term, value, **kwargs): tc = self.doc.get_term_class(term.lower()) t = tc(term, value, doc=self.doc, parent=None, section=self).new_children(**kwargs) self.doc.add_term(t) return t
Create a new root-level term in this section
def matchSubset(**kwargs): ret = [] for m in self.matches: allMatched = True for k,v in iteritems(kwargs): mVal = getattr(m, k) try: if v == mVal or v in mVal: continue except Exception: pass allM...
extract matches from player's entire match history given matching criteria kwargs
def visit_DictComp(self, node: ast.DictComp) -> Any: result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result return result
Compile the dictionary comprehension as a function and call it.
def restore_configuration_files(self): try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if not os.path.isfile(config_file): if os.pa...
restore a previously saved postgresql.conf