Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def find_rule_classes(extra_path):
files = []
modules = []
if os.path.isfile(extra_path):
files = [os.path.basename(extra_path)]
directory = os.path.dirname(extra_path)
elif os.path.isdir(extra_path):
files = os.listdir(extra_pa... | [
"\n Searches a given directory or python module for rule classes. This is done by\n adding the directory path to the python path, importing the modules and then finding\n any Rule class in those modules.\n\n :param extra_path: absolute directory or file path to search for rule classes\n :return: The ... |
Please provide a description of the function:def assert_valid_rule_class(clazz):
# Rules must extend from LineRule or CommitRule
if not (issubclass(clazz, rules.LineRule) or issubclass(clazz, rules.CommitRule)):
msg = u"User-defined rule class '{0}' must extend from {1}.{2} or {1}.{3}"
rai... | [
"\n Asserts that a given rule clazz is valid by checking a number of its properties:\n - Rules must extend from LineRule or CommitRule\n - Rule classes must have id and name string attributes.\n The options_spec is optional, but if set, it must be a list of gitlint Options.\n - Rule classes mu... |
Please provide a description of the function:def ustr(obj):
if sys.version_info[0] == 2:
# If we are getting a string, then do an explicit decode
# else, just call the unicode method of the object
if type(obj) in [str, basestring]: # pragma: no cover # noqa
return unicode(o... | [
" Python 2 and 3 utility method that converts an obj to unicode in python 2 and to a str object in python 3"
] |
Please provide a description of the function:def handle_option_error(func):
def wrapped(*args):
try:
return func(*args)
except options.RuleOptionError as e:
raise LintConfigError(ustr(e))
return wrapped | [
" Decorator that calls given method/function and handles any RuleOptionError gracefully by converting it to a\n LintConfigError. "
] |
Please provide a description of the function:def get_rule_option(self, rule_name_or_id, option_name):
option = self._get_option(rule_name_or_id, option_name)
return option.value | [
" Returns the value of a given option for a given rule. LintConfigErrors will be raised if the\n rule or option don't exist. "
] |
Please provide a description of the function:def set_rule_option(self, rule_name_or_id, option_name, option_value):
option = self._get_option(rule_name_or_id, option_name)
try:
option.set(option_value)
except options.RuleOptionError as e:
msg = u"'{0}' is not a v... | [
" Attempts to set a given value for a given option for a given rule.\n LintConfigErrors will be raised if the rule or option don't exist or if the value is invalid. "
] |
Please provide a description of the function:def set_config_from_commit(self, commit):
for line in commit.message.body:
pattern = re.compile(r"^gitlint-ignore:\s*(.*)")
matches = pattern.match(line)
if matches and len(matches.groups()) == 1:
self.set_... | [
" Given a git commit, applies config specified in the commit message.\n Supported:\n - gitlint-ignore: all\n "
] |
Please provide a description of the function:def set_config_from_string_list(self, config_options):
for config_option in config_options:
try:
config_name, option_value = config_option.split("=", 1)
if not option_value:
raise ValueError()
... | [
" Given a list of config options of the form \"<rule>.<option>=<value>\", parses out the correct rule and option\n and sets the value accordingly in this factory object. "
] |
Please provide a description of the function:def set_from_config_file(self, filename):
if not os.path.exists(filename):
raise LintConfigError(u"Invalid file path: {0}".format(filename))
self._config_path = os.path.abspath(filename)
try:
parser = ConfigParser()
... | [
" Loads lint config from a ini-style config file "
] |
Please provide a description of the function:def build(self, config=None):
# If we are passed a config object, then rebuild that object instead of building a new lintconfig object from
# scratch
if not config:
config = LintConfig()
config._config_path = self._confi... | [
" Build a real LintConfig object by normalizing and validating the options that were previously set on this\n factory. "
] |
Please provide a description of the function:def clone(self):
builder = LintConfigBuilder()
builder._config_blueprint = copy.deepcopy(self._config_blueprint)
builder._config_path = self._config_path
return builder | [
" Creates an exact copy of a LintConfigBuilder. "
] |
Please provide a description of the function:def _git(*command_parts, **kwargs):
# Special arguments passed to sh: http://amoffat.github.io/sh/special_arguments.html
git_kwargs = {'_tty_out': False}
git_kwargs.update(kwargs)
try:
result = sh.git(*command_parts, **git_kwargs) # pylint: disa... | [
" Convenience function for running git commands. Automatically deals with exceptions and unicode. "
] |
Please provide a description of the function:def git_commentchar():
commentchar = _git("config", "--get", "core.commentchar", _ok_code=[1])
# git will return an exit code of 1 if it can't find a config value, in this case we fall-back to # as commentchar
if hasattr(commentchar, 'exit_code') and comment... | [
" Shortcut for retrieving comment char from git config "
] |
Please provide a description of the function:def from_full_message(commit_msg_str):
all_lines = commit_msg_str.splitlines()
try:
cutline_index = all_lines.index(GitCommitMessage.CUTLINE)
except ValueError:
cutline_index = None
lines = [line for line in al... | [
" Parses a full git commit message by parsing a given string into the different parts of a commit message "
] |
Please provide a description of the function:def from_commit_msg(commit_msg_str):
context = GitContext()
commit_msg_obj = GitCommitMessage.from_full_message(commit_msg_str)
commit = GitCommit(context, commit_msg_obj)
context.commits.append(commit)
return context | [
" Determines git context based on a commit message.\n :param commit_msg_str: Full git commit message.\n "
] |
Please provide a description of the function:def from_local_repository(repository_path, refspec=None):
context = GitContext()
# If no refspec is defined, fallback to the last commit on the current branch
if refspec is None:
# We tried many things here e.g.: defaulting to e... | [
" Retrieves the git context from a local git repository.\n :param repository_path: Path to the git repository to retrieve the context from\n :param refspec: The commit(s) to retrieve\n "
] |
Please provide a description of the function:def should_ignore_rule(self, rule):
return rule.id in self.config.ignore or rule.name in self.config.ignore | [
" Determines whether a rule should be ignored based on the general list of commits to ignore "
] |
Please provide a description of the function:def _apply_line_rules(lines, commit, rules, line_nr_start):
all_violations = []
line_nr = line_nr_start
for line in lines:
for rule in rules:
violations = rule.validate(line, commit)
if violations:
... | [
" Iterates over the lines in a given list of lines and validates a given list of rules against each line "
] |
Please provide a description of the function:def _apply_commit_rules(rules, commit):
all_violations = []
for rule in rules:
violations = rule.validate(commit)
if violations:
all_violations.extend(violations)
return all_violations | [
" Applies a set of rules against a given commit and gitcontext "
] |
Please provide a description of the function:def lint(self, commit):
LOG.debug("Linting commit %s", commit.sha or "[SHA UNKNOWN]")
LOG.debug("Commit Object\n" + ustr(commit))
# Apply config rules
for rule in self.configuration_rules:
rule.apply(self.config, commit)
... | [
" Lint the last commit in a given git context by applying all ignore, title, body and commit rules. "
] |
Please provide a description of the function:def print_violations(self, violations):
for v in violations:
line_nr = v.line_nr if v.line_nr else "-"
self.display.e(u"{0}: {1}".format(line_nr, v.rule_id), exact=True)
self.display.ee(u"{0}: {1} {2}".format(line_nr, v.ru... | [
" Print a given set of violations to the standard error output "
] |
Please provide a description of the function:def _output(self, message, verbosity, exact, stream):
if exact:
if self.config.verbosity == verbosity:
stream.write(message + "\n")
else:
if self.config.verbosity >= verbosity:
stream.write(mess... | [
" Output a message if the config's verbosity is >= to the given verbosity. If exact == True, the message\n will only be outputted if the given verbosity exactly matches the config's verbosity. "
] |
Please provide a description of the function:def setup_logging():
root_log = logging.getLogger("gitlint")
root_log.propagate = False # Don't propagate to child loggers, the gitlint root logger handles everything
handler = logging.StreamHandler()
formatter = logging.Formatter(LOG_FORMAT)
handle... | [
" Setup gitlint logging "
] |
Please provide a description of the function:def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug):
config_builder = LintConfigBuilder()
try:
# Config precedence:
# First, load default config or config from configfile
if config_path:
c... | [
" Creates a LintConfig object based on a set of commandline parameters. "
] |
Please provide a description of the function:def get_stdin_data():
# STDIN can only be 3 different types of things ("modes")
# 1. An interactive terminal device (i.e. a TTY -> sys.stdin.isatty() or stat.S_ISCHR)
# 2. A (named) pipe (stat.S_ISFIFO)
# 3. A regular file (stat.S_ISREG)
# Technic... | [
" Helper function that returns data send to stdin or False if nothing is send "
] |
Please provide a description of the function:def cli( # pylint: disable=too-many-arguments
ctx, target, config, c, commits, extra_path, ignore, msg_filename,
verbose, silent, debug,
):
try:
if debug:
logging.getLogger("gitlint").setLevel(logging.DEBUG)
log_system_... | [
" Git lint tool, checks your git commit messages for styling issues "
] |
Please provide a description of the function:def lint(ctx):
lint_config = ctx.obj[0]
msg_filename = ctx.obj[3]
# Let's determine where our input data is coming from:
# Order of precedence:
# 1. Any data specified via --msg-filename
# 2. Any data sent to stdin
# 3. Fallback to reading f... | [
" Lints a git repository [default command] "
] |
Please provide a description of the function:def install_hook(ctx):
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.install_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Successfu... | [
" Install gitlint as a git commit-msg hook. "
] |
Please provide a description of the function:def uninstall_hook(ctx):
try:
lint_config = ctx.obj[0]
hooks.GitHookInstaller.uninstall_commit_msg_hook(lint_config)
# declare victory :-)
hook_path = hooks.GitHookInstaller.commit_msg_hook_path(lint_config)
click.echo(u"Succe... | [
" Uninstall gitlint commit-msg hook. "
] |
Please provide a description of the function:def generate_config(ctx):
path = click.prompt('Please specify a location for the sample gitlint config file', default=DEFAULT_CONFIG_FILE)
path = os.path.abspath(path)
dir_name = os.path.dirname(path)
if not os.path.exists(dir_name):
click.echo(u... | [
" Generates a sample gitlint config file. "
] |
Please provide a description of the function:def _assert_git_repo(target):
hooks_dir = os.path.abspath(os.path.join(target, HOOKS_DIR_PATH))
if not os.path.isdir(hooks_dir):
raise GitHookInstallerError(u"{0} is not a git repository.".format(target)) | [
" Asserts that a given target directory is a git repository "
] |
Please provide a description of the function:def handle_407(self, r):
num_407_calls = r.request.hooks['response'].count(self.handle_407)
s_auth = r.headers.get('Proxy-authenticate', '')
if 'digest' in s_auth.lower() and num_407_calls < 2:
self.chal = requests.auth.parse_... | [
"Takes the given response and tries digest-auth, if needed."
] |
Please provide a description of the function:def get_job_url(config, hub, group, project):
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((config is... | [
"\n Util method to get job url\n "
] |
Please provide a description of the function:def get_backend_stats_url(config, hub, backend_type):
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if (hub is not None):
return '/Network/{}/devices/{}'.format(hub, backend_type)
return '/Backends/{}'... | [
"\n Util method to get backend stats url\n "
] |
Please provide a description of the function:def get_backend_url(config, hub, group, project):
if ((config is not None) and ('hub' in config) and (hub is None)):
hub = config["hub"]
if ((config is not None) and ('group' in config) and (group is None)):
group = config["group"]
if ((confi... | [
"\n Util method to get backend url\n "
] |
Please provide a description of the function:def obtain_token(self, config=None):
client_application = CLIENT_APPLICATION
if self.config and ("client_application" in self.config):
client_application += ':' + self.config["client_application"]
headers = {'x-qx-client-applicati... | [
"Obtain the token to access to QX Platform.\n\n Raises:\n CredentialsError: when token is invalid or the user has not\n accepted the license.\n ApiError: when the response from the server couldn't be parsed.\n "
] |
Please provide a description of the function:def check_token(self, respond):
if respond.status_code == 401:
self.credential.obtain_token(config=self.config)
return False
return True | [
"\n Check is the user's token is valid\n "
] |
Please provide a description of the function:def post(self, path, params='', data=None):
self.result = None
data = data or {}
headers = {'Content-Type': 'application/json',
'x-qx-client-application': self.client_application}
url = str(self.credential.config['u... | [
"\n POST Method Wrapper of the REST API\n "
] |
Please provide a description of the function:def _response_good(self, respond):
if respond.status_code != requests.codes.ok:
log.warning('Got a {} code response to {}: {}'.format(
respond.status_code,
respond.url,
respond.text))
if... | [
"check response\n\n Args:\n respond (str): HTTP response.\n\n Returns:\n bool: True if the response is good, else False.\n\n Raises:\n ApiError: response isn't formatted properly.\n "
] |
Please provide a description of the function:def _parse_response(self, respond):
# convert error messages into exceptions
mobj = self._max_qubit_error_re.match(respond.text)
if mobj:
raise RegisterSizeError(
'device register size must be <= {}'.format(mobj.gr... | [
"parse text of response for HTTP errors\n\n This parses the text of the response to decide whether to\n retry request or raise exception. At the moment this only\n detects an exception condition.\n\n Args:\n respond (Response): requests.Response object\n\n Returns:\n ... |
Please provide a description of the function:def _check_backend(self, backend, endpoint):
# First check against hacks for old backend names
original_backend = backend
backend = backend.lower()
if endpoint == 'experiment':
if backend in self.__names_backend_ibmqxv2:
... | [
"\n Check if the name of a backend is valid to run in QX Platform\n "
] |
Please provide a description of the function:def get_execution(self, id_execution, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():... | [
"\n Get a execution, by its id\n "
] |
Please provide a description of the function:def get_result_from_execution(self, id_execution, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_cr... | [
"\n Get the result of a execution, by the execution id\n "
] |
Please provide a description of the function:def get_code(self, id_code, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
... | [
"\n Get a code, by its id\n "
] |
Please provide a description of the function:def get_image_code(self, id_code, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
... | [
"\n Get the image of a code, by its id\n "
] |
Please provide a description of the function:def get_last_codes(self, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
... | [
"\n Get the last codes of the user\n "
] |
Please provide a description of the function:def run_experiment(self, qasm, backend='simulator', shots=1, name=None,
seed=None, timeout=60, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
s... | [
"\n Execute an experiment\n "
] |
Please provide a description of the function:def run_job(self, job, backend='simulator', shots=1,
max_credits=None, seed=None, hub=None, group=None,
project=None, hpc=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(acces... | [
"\n Execute a job\n "
] |
Please provide a description of the function:def get_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
... | [
"\n Get the information about a job, by its id\n "
] |
Please provide a description of the function:def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False, filter=None, hub=None, group=None, project=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
... | [
"\n Get the information about the user jobs\n "
] |
Please provide a description of the function:def get_status_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_use... | [
"\n Get the status about a job, by its id\n "
] |
Please provide a description of the function:def cancel_job(self, id_job, hub=None, group=None, project=None,
access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(use... | [
"\n Cancel the information about a job, by its id\n "
] |
Please provide a description of the function:def backend_status(self, backend='ibmqx4', access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
backend_type = self._check_... | [
"\n Get the status of a chip\n "
] |
Please provide a description of the function:def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.... | [
"\n Get the calibration of a real chip\n "
] |
Please provide a description of the function:def available_backends(self, hub=None, group=None, project=None, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if no... | [
"\n Get the backends available to use in the QX Platform\n "
] |
Please provide a description of the function:def available_backend_simulators(self, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials()... | [
"\n Get the backend simulators available to use in the QX Platform\n "
] |
Please provide a description of the function:def get_my_credits(self, access_token=None, user_id=None):
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_credentials():
... | [
"\n Get the credits by user to use in the QX Platform\n "
] |
Please provide a description of the function:def query(self, sql):
'''
根据sql查询
Args:
sql: sql 语句 str
return:
成功: 查询的结果
失败: -1 并打印返回报错信息
'''
try:
self.connect()
with self.con.cursor() as cursor:
cu... | [] |
Please provide a description of the function:def save_one_data(self, data, table):
'''
将一条记录保存到数据库
Args:
table: 表名字 str
data: 记录 dict
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来
'''
key_map = {}
if len(d... | [] |
Please provide a description of the function:def update_by_id(self, data, table, id_value):
'''
通过id更新记录
Args:
table: 表名字 str
data: 记录 dict
id_value: id值
return:
成功: 1
失败: -1 并打印返回报错信息
每条记录都以一个字典的形式传进来
'''
... | [] |
Please provide a description of the function:def find_all(self, table, limit=10):
'''
从数据库里查询所有记录
Args:
table: 表名字 str
limit: 限制数量
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息
'''
sql = "select * from {} limit 0,{}".format(tabl... | [] |
Please provide a description of the function:def find_by_field(self, table, field, field_value):
'''
从数据库里查询指定条件的记录
Args:
table: 表名字 str
field: 字段名
field_value: 字段值
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息
'''
s... | [] |
Please provide a description of the function:def find_by_fields(self, table, queryset={}):
'''
从数据库里查询 符合多个条件的记录
Args:
table: 表名字 str
queryset : key 字段 value 值 dict
return:
成功: [dict] 保存的记录
失败: -1 并打印返回报错信息
''... | [] |
Please provide a description of the function:def _stripStrList(self, raw_str, stop_strs):
'''
去除字符串中的所有指定字符串
args:
raw_str 源字符串
stop_strs 指定字符串 列表
return
str 筛选后的字符串
'''
if type(stop_strs) == list:
for word in stop_strs:
... | [] |
Please provide a description of the function:def _judeNOtIn(self, raw_str, ele_list):
'''
判断ele是否在原始字符串中
args:
raw_str 源字符串
ele_list 待检查的列表
return
boolean
'''
for ele in ele_list:
if ele in raw_str:
return F... | [] |
Please provide a description of the function:def getCookies(self):
'''
从字符串中格式化出字典形式的Cookies
'''
items = self.data
for item in items:
if 'cookie' in item or 'Cookie' in item:
cookies = SimpleCookie(item[7:])
return {i.key: i.value for i... | [] |
Please provide a description of the function:def getHeaders(self):
'''
从字符串中格式化出字典形式的Headers
'''
items = self.data
headers = {}
for item in items:
if len(item) > 0 and self._judeNOtIn(item, ['curl', 'GET', 'Cookie', 'cookie']):
sp = item.split(... | [] |
Please provide a description of the function:def trace(self, predicate):
self._handler = predicate
if self.threading_support is None or self.threading_support:
self._threading_previous = getattr(threading, '_trace_hook', None)
threading.settrace(self)
self._previ... | [
"\n Starts tracing with the given callable.\n\n Args:\n predicate (callable that accepts a single :obj:`hunter.Event` argument):\n Return:\n self\n "
] |
Please provide a description of the function:def stop(self):
if self._handler is not None:
sys.settrace(self._previous)
self._handler = self._previous = None
if self.threading_support is None or self.threading_support:
threading.settrace(self._threadi... | [
"\n Stop tracing. Reinstalls the :ref:`hunter.Tracer.previous` tracer.\n "
] |
Please provide a description of the function:def Q(*predicates, **query):
optional_actions = query.pop("actions", [])
if "action" in query:
optional_actions.append(query.pop("action"))
for p in predicates:
if not callable(p):
raise TypeError("Predicate {0!r} is not callable... | [
"\n Handles situations where :class:`hunter.Query` objects (or other callables) are passed in as positional arguments.\n Conveniently converts that to an :class:`hunter.And` predicate.\n "
] |
Please provide a description of the function:def Or(*predicates, **kwargs):
if kwargs:
predicates += tuple(Query(**{k: v}) for k, v in kwargs.items())
return _flatten(_Or, *predicates) | [
"\n `Or` predicate. Returns ``True`` at the first sub-predicate that returns ``True``.\n "
] |
Please provide a description of the function:def trace(*predicates, **options):
global _last_tracer
predicates, options = load_config(predicates, options)
clear_env_var = options.pop("clear_env_var", False)
threading_support = None
for alias in THREADING_SUPPORT_ALIASES:
if alias in o... | [
"\n Starts tracing. Can be used as a context manager (with slightly incorrect semantics - it starts tracing\n before ``__enter__`` is called).\n\n Parameters:\n *predicates (callables): Runs actions if **all** of the given predicates match.\n Keyword Args:\n clear_env_var: Disables tracing... |
Please provide a description of the function:def wrap(function_to_trace=None, **trace_options):
def tracing_decorator(func):
@functools.wraps(func)
def tracing_wrapper(*args, **kwargs):
predicates = []
local = trace_options.pop('local', False)
if local:
... | [
"\n Functions decorated with this will be traced.\n\n Use ``local=True`` to only trace local code, eg::\n\n @hunter.wrap(local=True)\n def my_function():\n ...\n\n Keyword arguments are allowed, eg::\n\n @hunter.wrap(action=hunter.CallPrinter)\n def my_function():\n ... |
Please provide a description of the function:def threadid(self):
current = self.thread.ident
main = get_main_thread()
if main is None:
return current
else:
return current if current != main.ident else None | [
"\n Current thread ident. If current thread is main thread then it returns ``None``.\n\n :type: int or None\n "
] |
Please provide a description of the function:def module(self):
module = self.frame.f_globals.get('__name__', '')
if module is None:
module = ''
return module | [
"\n A string with module name (like ``\"foo.bar\"``).\n\n :type: str\n "
] |
Please provide a description of the function:def filename(self, exists=os.path.exists, cython_suffix_re=CYTHON_SUFFIX_RE):
filename = self.frame.f_globals.get('__file__', '')
if filename is None:
filename = ''
if filename.endswith(('.pyc', '.pyo')):
filename = f... | [
"\n A string with absolute path to file.\n\n :type: str\n "
] |
Please provide a description of the function:def stdlib(self):
if self.module == 'pkg_resources' or self.module.startswith('pkg_resources.'):
return False
elif self.filename.startswith(SITE_PACKAGES_PATHS):
# if it's in site-packages then its definitely not stdlib
... | [
"\n A boolean flag. ``True`` if frame is in stdlib.\n\n :type: bool\n "
] |
Please provide a description of the function:def source(self, getline=linecache.getline):
try:
return getline(self.filename, self.lineno)
except Exception as exc:
return "??? NO SOURCE: {!r}".format(exc) | [
"\n A string with the sourcecode for the current line (from ``linecache`` - failures are ignored).\n\n Fast but sometimes incomplete.\n\n :type: str\n "
] |
Please provide a description of the function:def _iter_symbols(code):
for node in ast.walk(ast.parse(code)):
if isinstance(node, ast.Name):
yield node.id | [
"\n Iterate all the variable names in the given expression.\n\n Example:\n\n * ``self.foobar`` yields ``self``\n * ``self[foobar]`` yields `self`` and ``foobar``\n "
] |
Please provide a description of the function:def __make_request_url(self, teststep_dict, entry_json):
request_params = utils.convert_list_to_dict(
entry_json["request"].get("queryString", [])
)
url = entry_json["request"].get("url")
if not url:
logging.e... | [
" parse HAR entry request url and queryString, and make teststep url and params\n\n Args:\n entry_json (dict):\n {\n \"request\": {\n \"url\": \"https://httprunner.top/home?v=1&w=2\",\n \"queryString\": [\n ... |
Please provide a description of the function:def __make_request_method(self, teststep_dict, entry_json):
method = entry_json["request"].get("method")
if not method:
logging.exception("method missed in request.")
sys.exit(1)
teststep_dict["request"]["method"] = m... | [
" parse HAR entry request method, and make teststep method.\n "
] |
Please provide a description of the function:def __make_request_headers(self, teststep_dict, entry_json):
teststep_headers = {}
for header in entry_json["request"].get("headers", []):
if header["name"].lower() in IGNORE_REQUEST_HEADERS:
continue
teststep... | [
" parse HAR entry request headers, and make teststep headers.\n header in IGNORE_REQUEST_HEADERS will be ignored.\n\n Args:\n entry_json (dict):\n {\n \"request\": {\n \"headers\": [\n {\"name\": \"Host\... |
Please provide a description of the function:def _make_request_data(self, teststep_dict, entry_json):
method = entry_json["request"].get("method")
if method in ["POST", "PUT", "PATCH"]:
postData = entry_json["request"].get("postData", {})
mimeType = postData.get("mimeTyp... | [
" parse HAR entry request data, and make teststep request data\n\n Args:\n entry_json (dict):\n {\n \"request\": {\n \"method\": \"POST\",\n \"postData\": {\n \"mimeType\": \"application/x-ww... |
Please provide a description of the function:def _make_validate(self, teststep_dict, entry_json):
teststep_dict["validate"].append(
{"eq": ["status_code", entry_json["response"].get("status")]}
)
resp_content_dict = entry_json["response"].get("content")
headers_map... | [
" parse HAR entry response and make teststep validate.\n\n Args:\n entry_json (dict):\n {\n \"request\": {},\n \"response\": {\n \"status\": 200,\n \"headers\": [\n {\n ... |
Please provide a description of the function:def load_har_log_entries(file_path):
with io.open(file_path, "r+", encoding="utf-8-sig") as f:
try:
content_json = json.loads(f.read())
return content_json["log"]["entries"]
except (KeyError, TypeError):
logging.er... | [
" load HAR file and return log entries list\n\n Args:\n file_path (str)\n\n Returns:\n list: entries\n [\n {\n \"request\": {},\n \"response\": {}\n },\n {\n \"request\": {},\n ... |
Please provide a description of the function:def x_www_form_urlencoded(post_data):
if isinstance(post_data, dict):
return "&".join([
u"{}={}".format(key, value)
for key, value in post_data.items()
])
else:
return post_data | [
" convert origin dict to x-www-form-urlencoded\n\n Args:\n post_data (dict):\n {\"a\": 1, \"b\":2}\n\n Returns:\n str:\n a=1&b=2\n\n "
] |
Please provide a description of the function:def convert_x_www_form_urlencoded_to_dict(post_data):
if isinstance(post_data, str):
converted_dict = {}
for k_v in post_data.split("&"):
try:
key, value = k_v.split("=")
except ValueError:
rais... | [
" convert x_www_form_urlencoded data to dict\n\n Args:\n post_data (str): a=1&b=2\n\n Returns:\n dict: {\"a\":1, \"b\":2}\n\n "
] |
Please provide a description of the function:def dump_yaml(testcase, yaml_file):
logging.info("dump testcase to YAML format.")
with io.open(yaml_file, 'w', encoding="utf-8") as outfile:
yaml.dump(testcase, outfile, allow_unicode=True, default_flow_style=False, indent=4)
logging.info("Generate... | [
" dump HAR entries to yaml testcase\n "
] |
Please provide a description of the function:def dump_json(testcase, json_file):
logging.info("dump testcase to JSON format.")
with io.open(json_file, 'w', encoding="utf-8") as outfile:
my_json_str = json.dumps(testcase, ensure_ascii=ensure_ascii, indent=4)
if isinstance(my_json_str, bytes... | [
" dump HAR entries to json testcase\n "
] |
Please provide a description of the function:def main():
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument(
'-V', '--version', dest='version', action='store_true',
help="show version")
parser.add_argument(
'--log-level', default='INFO',
he... | [
" HAR converter: parse command line options and run commands.\n "
] |
Please provide a description of the function:def prepare_request(self, request):
try:
request_id = local.request_id
except AttributeError:
request_id = NO_REQUEST_ID
if self.request_id_header and request_id != NO_REQUEST_ID:
request.headers[self.requ... | [
"Include the request ID, if available, in the outgoing request"
] |
Please provide a description of the function:def short(self, url):
url = self.clean_url(url)
shorten_url = f'{self.api_url}v1/shorten'
payload = {
'domain': getattr(self, 'domain', 'adf.ly'),
'advert_type': getattr(self, 'type', 'int'),
'group_id': ge... | [
"Short implementation for Adf.ly\n Args:\n url: the URL you want to shorten\n\n Returns:\n A string containing the shortened URL\n\n Raises:\n BadAPIResponseException: If the data is malformed or we got a bad\n status code on API response\n ... |
Please provide a description of the function:def expand(self, url):
url = self.clean_url(url)
expand_url = f'{self.api_url}v1/expand'
payload = {
'domain': getattr(self, 'domain', 'adf.ly'),
'advert_type': getattr(self, 'type', 'int'),
'group_id': get... | [
"Expand implementation for Adf.ly\n Args:\n url: the URL you want to expand\n\n Returns:\n A string containing the expanded URL\n\n Raises:\n BadAPIResponseException: If the data is malformed or we got a bad\n status code on API response\n ... |
Please provide a description of the function:def short(self, url):
self.clean_url(url)
shorten_url = f'{self.api_url}v3/shorten'
params = {
'uri': url,
'access_token': self.api_key,
'format': 'txt',
}
response = self._get(shorten_url,... | [
"Short implementation for Bit.ly\n Args:\n url: the URL you want to shorten\n\n Returns:\n A string containing the shortened URL\n\n Raises:\n BadAPIResponseException: If the data is malformed or we got a bad\n status code on API response\n ... |
Please provide a description of the function:def expand(self, url):
expand_url = f'{self.api_url}v3/expand'
params = {
'shortUrl': url,
'access_token': self.api_key,
'format': 'txt',
}
response = self._get(expand_url, params=params)
if... | [
"Expand implementation for Bit.ly\n Args:\n url: the URL you want to shorten\n\n Returns:\n A string containing the expanded URL\n\n Raises:\n ExpandingErrorException: If the API Returns an error as response\n "
] |
Please provide a description of the function:def total_clicks(self, url):
url = self.clean_url(url)
clicks_url = f'{self.api_url}v3/link/clicks'
params = {
'link': url,
'access_token': self.api_key,
'format': 'txt'
}
response = self._g... | [
"Total clicks implementation for Bit.ly\n Args:\n url: the URL you want to get the total clicks count\n\n Returns:\n An int containing the total clicks count\n\n Raises:\n BadAPIResponseException: If the API Returns an error as response\n "
] |
Please provide a description of the function:def _get(self, url, params=None, headers=None):
url = self.clean_url(url)
response = requests.get(url, params=params, verify=self.verify,
timeout=self.timeout, headers=headers)
return response | [
"Wraps a GET request with a url check"
] |
Please provide a description of the function:def _post(self, url, data=None, json=None, params=None, headers=None):
url = self.clean_url(url)
response = requests.post(url, data=data, json=json, params=params,
headers=headers, timeout=self.timeout,
... | [
"Wraps a POST request with a url check"
] |
Please provide a description of the function:def expand(self, url):
url = self.clean_url(url)
response = self._get(url)
if response.ok:
return response.url
raise ExpandingErrorException | [
"Base expand method. Only visits the link, and return the response\n url"
] |
Please provide a description of the function:def clean_url(url):
if not url.startswith(('http://', 'https://')):
url = f'http://{url}'
if not URL_RE.match(url):
raise BadURLException(f'{url} is not valid')
return url | [
"URL Validation function"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.