code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def config_set_acl(args): acl_updates = [{"user": user, "role": args.role} \ for user in set(expand_fc_groups(args.users)) \ if user != fapi.whoami()] id = args.snapshot_id if not id: r = fapi.list_repository_configs(namespace=args.namespace, ...
Assign an ACL role to a list of users for a config.
def layers(self): if self._layers is None: self.__init() lyrs = [] for lyr in self._layers: lyr['object'] = GlobeServiceLayer(url=self._url + "/%s" % lyr['id'], securityHandler=self._securityHandler, ...
gets the globe service layers
def payload(self, value): if not isinstance(value, rdfvalue.RDFValue): raise RuntimeError("Payload must be an RDFValue.") self.Set("args", value.SerializeToString()) if value._age is not None: self.args_age = value._age self.args_rdf_name = value.__class__.__name__
Automatically encode RDFValues into the message.
def filter_stopwords(phrase): if not isinstance(phrase, list): phrase = phrase.split() stopwords = ['the', 'a', 'in', 'to'] return [word.lower() for word in phrase if word.lower() not in stopwords]
Filter out stop words and return as a list of words
def discover_glitter_apps(self): for app_name in settings.INSTALLED_APPS: module_name = '{app_name}.glitter_apps'.format(app_name=app_name) try: glitter_apps_module = import_module(module_name) if hasattr(glitter_apps_module, 'apps'): s...
Find all the Glitter App configurations in the current project.
def register_view_for(cls, app, action, classview, attr): if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr)
Register a classview and viewhandler for a given app and action
def check(text): err = "glaad.terms" msg = "Possibly offensive term. Consider using '{}' instead of '{}'." list = [ ["gay man", ["homosexual man"]], ["gay men", ["homosexual men"]], ["lesbian", ["homosexual woman"]], ["lesbians", ["h...
Suggest preferred forms given the reference document.
def Reset(self): self.pan = self.world_center self.desired_pan = self.pos
Reset the camera back to its defaults.
def exempt(self, obj): name = '%s.%s' % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_routes.add(name) return __inner
decorator to mark a view as exempt from htmlmin.
def _resolve_username(self, account, username): if account is not None: warnings.warn( "Use keyword argument 'username' instead of 'account'", DeprecationWarning) return username or account or self.username
Resolve username and handle deprecation of account kwarg
def _process(self, project, build_system, job_priorities): jobs = [] cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system) ref_data_names_map = cache.get(cache_key) if not ref_data_names_map: ref_data_names_map = self._build_ref_data_names(project, build_syst...
Return list of ref_data_name for job_priorities
def Initialize(self): if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
Open the delegate object.
def card(self): body, more, is_markdown = self._entry_content return TrueCallableProxy( self._get_card, body or more) if is_markdown else CallableProxy(None)
Get the entry's OpenGraph card
def main(): log = logging.getLogger('sip.mock_workflow_stage') if len(sys.argv) != 2: log.critical('Expecting JSON string as first argument!') return config = json.loads(sys.argv[1]) log.info('Running mock_workflow_stage (version: %s).', __version__) log.info('Received configuration:...
Run the workflow task.
def _get_struct_encodedu32(self): useful = [] while True: byte = ord(self._src.read(1)) useful.append(byte) if byte < 127: break useful = ['00000000' + bin(b)[2:] for b in useful[::-1]] return int(''.join([b[-7:] for b in useful]), 2)
Get a EncodedU32 number.
def _discretize(a): arr = np.asarray(a) index = np.argsort(arr) inverse_index = np.zeros(arr.size, dtype=np.intp) inverse_index[index] = np.arange(arr.size, dtype=np.intp) arr = arr[index] obs = np.r_[True, arr[1:] != arr[:-1]] return obs.cumsum()[inverse_index] - 1
Discretizes array values to class labels.
def to_json(self): result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
Returns the JSON representation of the environment.
def load_objects(self, directory_name=None): if directory_name is not None: if directory_name == parameters.REAL_KBO_AST_DIR: kbos = parsers.ossos_discoveries(all_objects=True, data_release=None) else: kbos = parsers.ossos_discoveries(directory_name, all_o...
Load the targets from a file.
def report_status(self, status): status = Instance('', TaskStatus).validate(None, status) print(r'{taskname} | {percent:>3}% | {message}'.format( taskname=self.__class__.__name__, percent=int(round(100*status.progress)), message=status.message if status.message else '...
Hook for reporting the task status towards completion
def deserialize(self, xml_input, *args, **kwargs): return xmltodict.parse(xml_input, *args, **kwargs)
Convert XML to dict object
def write_id (self): self.writeln(u"<tr>") self.writeln(u'<td>%s</td>' % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
Write ID for current URL.
def _get_last_tag(self): current_version = LooseVersion( self._get_version_from_tag(self.release_notes_generator.current_tag) ) versions = [] for tag in self.repo.tags(): if not tag.name.startswith(self.github_info["prefix_prod"]): continue ...
Gets the last release tag before self.current_tag
def save(self, *args, **kwargs): if self.order == '' or self.order is None: try: self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1 except IndexError: self.order = 0 super(BaseOrdered, self).save()
if order left blank
def update(self, enabled=None): if enabled is None: enabled = self.checkState(0) == QtCore.Qt.Checked elif not enabled or self._element.get('enabled', 'True') != 'True': self.setCheckState(0, QtCore.Qt.Unchecked) else: self.setCheckState(0, QtCore.Qt.Che...
Updates this item based on the interface.
def future_import(feature, node): root = find_root(node) if does_tree_import(u"__future__", feature, node): return shebang_encoding_idx = None for idx, node in enumerate(root.children): if is_shebang_comment(node) or is_encoding_comment(node): shebang_encoding_idx = idx ...
This seems to work
def order_by(self, order_by: Union[set, str]): clone = self._clone() if isinstance(order_by, str): order_by = {order_by} clone._order_by = clone._order_by.union(order_by) return clone
Update order_by setting for filter set
def guard(ctx, opts=""): return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
Execute all tests and then watch for changes, re-running.
def Reset(self): hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString( self._hasher_names_string) self._hashers = hashers_manager.HashersManager.GetHashers(hasher_names)
Resets the internal state of the analyzer.
def options(self, parser, env=None): if env is None: env = os.environ env_opt_name = 'NOSE_%s' % self.__dest_opt_name.upper() parser.add_option("--%s" % self.__opt_name, dest=self.__dest_opt_name, type="string", ...
Adds command-line options for this plugin.
def _commands(ctx): ctx = ctx.parent ctx.show_hidden_subcommands = False main = ctx.command for subcommand in main.list_commands(ctx): cmd = main.get_command(ctx, subcommand) if cmd is None: continue help = cmd.short_help or "" click.echo("{}:{}".format(subcom...
Prints a list of commands for shell completion hooks.
def cursesMain(_scr, sheetlist): 'Populate VisiData object with sheets from a given list.' colors.setup() for vs in sheetlist: vd().push(vs) status('Ctrl+H opens help') return vd().run(_scr)
Populate VisiData object with sheets from a given list.
def _remove_duplicates(self): contained = set() for m1, m2 in itertools.combinations(self._max_rects, 2): if m1.contains(m2): contained.add(m2) elif m2.contains(m1): contained.add(m1) self._max_rects = [m for m in self._max_rects if m not i...
Remove every maximal rectangle contained by another one.
def _local_times_from_hours_since_midnight(times, hours): tz_info = times.tz naive_times = times.tz_localize(None) return pd.DatetimeIndex( (naive_times.normalize().astype(np.int64) + (hours * NS_PER_HR).astype(np.int64)).astype('datetime64[ns]'), tz=tz_info)
converts hours since midnight from an array of floats to localized times
def create_admin_object_resource(name, server=None, **kwargs): defaults = { 'description': '', 'className': 'com.sun.messaging.Queue', 'enabled': True, 'id': name, 'resAdapter': 'jmsra', 'resType': 'javax.jms.Queue', 'target': 'server' } data = default...
Create a JMS destination
def list_bzip2 (archive, compression, cmd, verbosity, interactive): return stripext(cmd, archive, verbosity)
List a BZIP2 archive.
def percentile(self, lst_data, percent , key=lambda x:x): new_list = sorted(lst_data) k = (len(new_list)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return key(new_list[int(k)]) d0 = float(key(new_list[int(f)])) * (c-k) d1 = float(key(ne...
calculates the 'num' percentile of the items in the list
def get(self): self._cast = type([]) source_value = os.getenv(self.env_name) if source_value is None: os.environ[self.env_name] = json.dumps(self.default) return self.default try: val = json.loads(source_value) except JSONDecodeError as e: ...
convert json env variable if set to list
def flatten_path_lists(env_dict, env_root=None): for (key, val) in env_dict.items(): if isinstance(val, list): env_dict[key] = os.path.join(env_root, os.path.join(*val)) if (env_root and not os.path.isabs(os.path.join(*val))) else os.path.join(*val) return env_dict
Join paths in environment dict down to strings.
def abspath(relpath, root=None): root = root or cwd() if op.isfile(root): root = op.dirname(root) return op.abspath(op.join(root, relpath))
Returns an absolute path based on the given root and relative path.
def Handle(self, unused_args, token=None): result = ApiGrrUser(username=token.username) if data_store.RelationalDBEnabled(): user_record = data_store.REL_DB.ReadGRRUser(token.username) result.InitFromDatabaseObject(user_record) else: try: user_record = aff4.FACTORY.Open( ...
Fetches and renders current user's settings.
def parse_altitude(cls, distance, unit): if distance is not None: distance = float(distance) CONVERTERS = { 'km': lambda d: d, 'm': lambda d: units.kilometers(meters=d), 'mi': lambda d: units.kilometers(miles=d), 'ft': lambd...
Parse altitude managing units conversion
def format_number_field(__, prec, number, locale): prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a number field.
async def _async_stop(self): if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() if self.is_alive(): self.client.stop() aexit = s...
Stops an agent and kills all its behaviours.
def write_config(filename, config, mode="w"): with open(filename, mode) as filey: config.write(filey) return filename
use configparser to write a config object to filename
def build_computation(self, message: Message, transaction: BaseOrSpoofTransaction) -> BaseComputation: transaction_context = self.vm_state.get_transaction_context(transaction) if message.is_create: is_collision = self.vm_state.has_code_or_n...
Apply the message to the VM.
def func(self, name: str): for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and f._name == name): return f
return the first func defined named name
def _compileSmsRegexes(self): if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0...
Compiles regular expression used for parsing SMS messages based on current mode
def do_WhoIsRequest(self, apdu): if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu) if not self.localDevice: if _debug: WhoIsIAmServices._debug(" - no local device") return low_limit = apdu.deviceInstanceRangeLowLimit high_limit = apdu.deviceInstanc...
Respond to a Who-Is request.
def allow_origin(self, request): origins = self.origins if origins is AnyOrigin: return '*' else: origin = request.origin return origin if origin in origins else ''
Generate allow origin header
def add_events(self, **kwargs): event_q = kwargs.get('event_queue') pri = kwargs.get('priority') if not event_q or not pri: return try: event_type = 'server.failure.recovery' payload = {} timestamp = time.ctime() data = (event_t...
Add failure event into the queue.
def _make_parameters(self): self.value_means = [] self.value_ranges = [] self.arrangement = [] self.variable_parameters = [] current_var = 0 for parameter in self.parameters: if parameter.type == ParameterType.DYNAMIC: self.value_means.append(p...
Converts a list of Parameters into DEAP format.
def split_data(data, subset, splits): return dict([(k, data[k][splits[subset]]) for k in data])
Returns the data for a given protocol
def list(self): connection = self._backend._get_connection() return list(self._backend.list(connection))
List the tables in the database
def _gdal_write_datasets(self, dst_ds, datasets): for i, band in enumerate(datasets['bands']): chn = datasets.sel(bands=band) bnd = dst_ds.GetRasterBand(i + 1) bnd.SetNoDataValue(0) bnd.WriteArray(chn.values)
Write datasets in a gdal raster structure dts_ds
def _perform_merge(self, other): if len(other.value) > len(self.value): self.value = other.value[:] return True
Merges the longer string
def auc(y_true, y_pred, round=True): y_true, y_pred = _mask_value_nan(y_true, y_pred) if round: y_true = y_true.round() if len(y_true) == 0 or len(np.unique(y_true)) < 2: return np.nan return skm.roc_auc_score(y_true, y_pred)
Area under the ROC curve
def from_representation(self, data): if data in self._TRUE_VALUES: return True elif data in self._FALSE_VALUES: return False else: raise ValueError( "{type} type value must be one of {values}".format( type=self.type, ...
Convert representation value to ``bool`` if it has expected form.
def _load_webgl_backend(ipython): from .. import app app_instance = app.use_app("ipynb_webgl") if app_instance.backend_name == "ipynb_webgl": ipython.write("Vispy IPython module has loaded successfully") else: ipython.write_err("Unable to load webgl backend of Vispy")
Load the webgl backend for the IPython notebook
def deftypes(self): for f in self.body: if (hasattr(f, '_ctype') and (f._ctype._storage == Storages.TYPEDEF or (f._name == '' and isinstance(f._ctype, ComposedType)))): yield f
generator on all definition of type
def strip_pad(hdu): l = hdu.header.ascardlist() d = [] for index in range(len(l)): if l[index].key in __comment_keys and str(l[index])==__cfht_padding: d.append(index) d.reverse() for index in d: del l[index] return(0)
Remove the padding lines that CFHT adds to headers
def _is_api_key_correct(request): api_key = getattr(settings, 'GECKOBOARD_API_KEY', None) if api_key is None: return True auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: if auth[0].lower() == b'basic': request_key = base64.b64decode(auth[1]).split...
Return whether the Geckoboard API key on the request is correct.
def _hcn_func(self): self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr()) return
Eq. 56 from Barack and Cutler 2004
def _get_db(): with cd(env.remote_path): file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '')) run(env.python + ' manage.py dump_database | gzip > ' + file_path) local_file_path = './backups/' + _sql_paths('remote', datetime.now()) ...
Get database from server
def generate_table_results(output=None, without_header=None): array = [] str_output = str(output) if not without_header: array.append('RESULT') array.append('-' * max(6, len(str_output))) array.append(str_output) return os.linesep.join(array)
Convert returned data from non-list actions into a nice table for command line usage
def __updateNavButtons(self): navButtons = None for v in self.views: if v.getId() == 'com.android.systemui:id/nav_buttons': navButtons = v break if navButtons: self.navBack = self.findViewById('com.android.systemui:id/back', navButtons) ...
Updates the navigation buttons that might be on the device screen.
def _get_filesystem_config(file_types): out = " filesystems {\n" for file_type in sorted(list(file_types)): if file_type in _FILESYSTEM_CONFIG: out += _FILESYSTEM_CONFIG[file_type] out += " }\n" return out
Retrieve filesystem configuration, including support for specified file types.
def Shift(self, value, copy=False): numPoints = self.GetN() if copy: shiftGraph = self.Clone() else: shiftGraph = self X = self.GetX() EXlow = self.GetEXlow() EXhigh = self.GetEXhigh() Y = self.GetY() EYlow = self.GetEYlow() ...
Shift the graph left or right by value
def read(self, size=-1): buf = self._fd.read(size) self._progress_cb(len(buf)) return buf
Read bytes and update the progress bar.
def fromRoman(strng): if not strng: raise TypeError('Input can not be blank') if not romanNumeralPattern.search(strng): raise ValueError('Invalid Roman numeral: %s', strng) result = 0 index = 0 for numeral, integer in romanNumeralMap: while strng[index:index+len(numeral)] == ...
convert Roman numeral to integer
def dot_v2(vec1, vec2): return vec1.x * vec2.x + vec1.y * vec2.y
Return the dot product of two vectors
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: try: return create_backend(name, git_index, args) except KeyError: log.critical("No such backend: %s (looked in %s)", ...
Initialize a new Backend, return None if there was a known problem.
def remove_path(target_path): if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.unlink(target_path)
Delete the target path
def begin(self, access_mode=None): if self._active_transaction: raise SystemError("Transaction in progress") self._active_transaction = self.driver.session(access_mode=access_mode).begin_transaction()
Begins a new transaction, raises SystemError exception if a transaction is in progress
def load(self): print("[DEBUG] Loading plugin {} from {}".format(self.name, self.source)) import pydoc path, attr = self.source.split(":") module = pydoc.locate(path) return getattr(module, attr)
Load the object defined by the plugin entry point
def send_bytes(self): data = b''.join(self.bytes_to_send) self.bytes_to_send = [] return data
Retrieve all pending bytes to send on the network
def on_motion(self, event): 'on motion we will move the rect if the mouse is over us' if self.press is None: return if event.inaxes != self.ax: return x0, y0, btn = self.press x0.append(event.xdata) y0.append(event.ydata)
on motion we will move the rect if the mouse is over us
def _clean_name(fname, data): for to_remove in dd.get_batches(data) + [dd.get_sample_name(data), data["sv"]["variantcaller"]]: for ext in ("-", "_"): if fname.startswith("%s%s" % (to_remove, ext)): fname = fname[len(to_remove) + len(ext):] if fname.startswith(to_remove): ...
Remove standard prefixes from a filename before renaming with useful names.
def print_result_for_plain_cgi_script(contenttype: str, headers: TYPE_WSGI_RESPONSE_HEADERS, content: bytes, status: str = '200 OK') -> None: headers = [ ("Status", status), ("Content-Ty...
Writes HTTP request result to stdout.
def git_hash(blob): head = str("blob " + str(len(blob)) + "\0").encode("utf-8") return sha1(head + blob).hexdigest()
Return git-hash compatible SHA-1 hexdigits for a blob of data.
def find_link(self, device): for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] if (str(i) == device or conn.address == device or getattr(conn, 'label', None) == device): return i return None
find a device based on number, name or label
def kl_error(self, input_data, targets, average=True, cache=None, prediction=True): if cache is not None: activations = cache else: activations = \ self.feed_forward(input_data, prediction=prediction) targets_non_nan = gpuarray.empty_like(ta...
The KL divergence error
def rgb2cmy(self, img, whitebg=False): tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/...
transforms image from RGB to CMY
def _cli_check_readfmt(readfmt): if readfmt is None: return None readfmt = readfmt.lower() if not readfmt in curate.get_reader_formats(): errstr = "Reader for file type '" + readfmt + "' does not exist.\n" errstr += "For a complete list of file types, use the 'bsecurate get-reader-fo...
Checks that a file type exists and if not, raises a helpful exception
def _load_from_string(data): global _CACHE if PYTHON_3: data = json.loads(data.decode("utf-8")) else: data = json.loads(data) _CACHE = _recursively_convert_unicode_to_str(data)['data']
Loads the cache from the string
def create(self, request): variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) product_request = ProductRequest(variant=variant) product_request.save() serializer = self.serialize...
Create a new product request
def normalize_hostname(hostname): try: new_hostname = hostname.encode('idna').decode('ascii').lower() except UnicodeError as error: raise UnicodeError('Hostname {} rejected: {}'.format(hostname, error)) from error if hostname != new_hostname: new_hostname.encode('idna') return ne...
Normalizes a hostname so that it is ASCII and valid domain name.
def count(self, low, high=None): if high is None: high = low return self.database.zcount(self.key, low, high)
Return the number of items between the given bounds.
def _get_pygments_extensions(): import pygments.lexers as lexers extensions = [] for lx in lexers.get_all_lexers(): lexer_exts = lx[2] if lexer_exts: other_exts = [le for le in lexer_exts if not le.startswith('*')] lexer_exts = [le[1:] for le in lexer_exts if le.start...
Return all file type extensions supported by Pygments
def _man_args(self, f): argcount = f.func_code.co_argcount if isinstance(f, types.MethodType): argcount -= 1 if f.func_defaults is None: return argcount return argcount - len(f.func_defaults)
Returns number of mandatory arguments required by given function.
def format_sourcefile_name(self, fileName, runSet): if fileName.startswith(runSet.common_prefix): fileName = fileName[len(runSet.common_prefix):] return fileName.ljust(runSet.max_length_of_filename + 4)
Formats the file name of a program for printing on console.
def check(ctx, meta_model_file, model_file, ignore_case): debug = ctx.obj['debug'] check_model(meta_model_file, model_file, debug, ignore_case)
Check validity of meta-model and optionally model.
def cli(env): mask = ('openTicketCount, closedTicketCount, ' 'openBillingTicketCount, openOtherTicketCount, ' 'openSalesTicketCount, openSupportTicketCount, ' 'openAccountingTicketCount') account = env.client['Account'].getObject(mask=mask) table = formatting.Table(['Stat...
Summary info about tickets.
async def get_shade(self, shade_id, from_cache=True) -> BaseShade: if not from_cache: await self.get_shades() for _shade in self.shades: if _shade.id == shade_id: return _shade raise ResourceNotFoundException("Shade not found. Id: {}".format(shade_id))
Get a shade instance based on shade id.
def build_cpp(build_context, target, compiler_config, workspace_dir): rmtree(workspace_dir) binary = join(*split(target.name)) objects = link_cpp_artifacts(build_context, target, workspace_dir, True) buildenv_workspace = build_context.conf.host_to_buildenv_path( workspace_dir) objects.extend...
Compile and link a C++ binary for `target`.
def main(): argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n') else: raise sys.exit(returncode)
The main command-line entry point, with system interactions.
def _get_jobs_url(self): if self._jobs_url is None: self.get_instance_status() if self._jobs_url is None: raise ValueError("Cannot obtain jobs URL") return self._jobs_url
Get & save jobs URL from the status call.
def fnames(self, names): names = list(names[:len(self._fnames)]) self._fnames = names + self._fnames[len(names):]
Ensure constant size of fnames
def generate_pdf(self): printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path = unique_filename(suffix='.pdf') printer.setOutp...
Generate a PDF from the displayed content.
def logout(self): logger.debug('Logout') method = self._anaconda_client_api.remove_authentication return self._create_worker(method)
Logout from anaconda cloud.
def parse_ast(source, filename=None): if isinstance(source, text_type) and sys.version_info[0] == 2: source = CODING_COOKIE_RE.sub(r'\1', source, 1) return ast.parse(source, filename or '<unknown>')
Parse source into a Python AST, taking care of encoding.