code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: self.check_valid() _header_list = [] for k,v in self.inputs.items(): if v is None: return {self.__class__.__name__.replace('_','-'):None} elif k == 'value': _header_list.insert(0,str(v)) elif isinstance(v,bool): if v is True: _header_list.append(k) else: _he...
def create_header(self)
return header dict
2.730226
2.695407
1.012918
if self.inputs is not None: for k,v in defaultHeaders.items(): if k not in self.inputs: self.inputs[k] = v if k == 'pins': self.inputs[k] = self.inputs[k] + defaultHeaders[k] return self.inputs else: return self.inputs
def update_policy(self,defaultHeaders)
rewrite update policy so that additional pins are added and not overwritten
2.678849
2.347302
1.141246
try: self.check_valid() _header_list = [] for k,v in self.inputs.items(): if v is None: return {self.__class__.__name__.replace('_','-'):None} elif k == 'value': _header_list.insert(0,str(v)) elif isinstance(v,bool): if v is True: _header_list.append(k) elif type(v) is list...
def create_header(self)
rewrite return header dict for HPKP
3.541822
3.45041
1.026493
try: self.check_valid(cspDefaultHeaders) if self.inputs is not None: for p,l in self.inputs.items(): cspDefaultHeaders[p] = cspDefaultHeaders[p]+ list(set(self.inputs[p]) - set(cspDefaultHeaders[p])) return cspDefaultHeaders else: return self.inputs except Exception, e: raise
def update_policy(self,cspDefaultHeaders)
add items to existing csp policies
3.163314
3.089727
1.023817
try: self.check_valid(cspDefaultHeaders) if self.inputs is not None: for p,l in cspDefaultHeaders.items(): if p in self.inputs: cspDefaultHeaders[p] = self.inputs[p] else: cspDefaultHeaders[p] = [] return cspDefaultHeaders else: return self.inputs except Exception, e: ...
def rewrite_policy(self,cspDefaultHeaders)
fresh csp policy
2.613106
2.62767
0.994457
encapsulate = re.compile("|".join(['^self','^none','^unsafe-inline','^unsafe-eval','^sha[\d]+-[\w=-]+','^nonce-[\w=-]+'])) csp = {} for p,array in self.inputs.items(): csp[p] = ' '.join(["'%s'" % l if encapsulate.match(l) else l for l in array]) return {self.header:'; '.join(['%s %s' % (k, v) for k, v i...
def create_header(self)
return CSP header dict
6.731833
5.408294
1.244724
extra_context = { 'topic': Topic.objects.published().get(slug=topic_slug), } return object_detail(request, queryset=Question.objects.published(), extra_context=extra_context, template_object_name='question', slug=slug)
def question_detail(request, topic_slug, slug)
A detail view of a Question. Templates: :template:`faq/question_detail.html` Context: question A :model:`faq.Question`. topic The :model:`faq.Topic` object related to ``question``.
2.885241
3.884161
0.742822
retval = defaultdict(lambda: defaultdict(list)) if len(filenames): extensions = [e.lstrip('.') for e in self.get_file_extensions()] filenames = [f for f in filenames if f.split('.')[-1] in extensions] if not filenames: # There were a specifie...
def invoke(self, dirname, filenames=set(), linter_configs=set())
Main entrypoint for all plugins. Returns results in the format of: {'filename': { 'line_number': [ 'error1', 'error2' ] } }
3.579784
3.710727
0.964712
if not hasattr(self, 'response_format'): raise NotImplementedError() match = self.response_format.search(line) if match is not None: if len(self.filenames) != 0: if match.group('filename') not in self.filenames: return ...
def process_line(self, dirname, line)
Processes a line return a 3-element tuple representing (filename, line_number, error_messages) or None to indicate no error. :param: dirname - directory the code is running in For default implementation, regex in `self.response_format` is expected to have the capture groups `filename`,...
4.215985
2.725396
1.546926
for comment in comments: if ((comment['path'] == file_name and comment['position'] == position and comment['user']['login'] == self.requester.username)): return [m for m in message if m not in comment['body']] return message
def clean_already_reported(self, comments, file_name, position, message)
message is potentially a list of messages to post. This is later converted into a string.
4.202404
3.779691
1.111838
final_message = '' for submessage in message: final_message += '* {submessage}\n'.format(submessage=submessage) return final_message
def convert_message_to_string(self, message)
Convert message from list to string for GitHub API.
4.416986
3.414665
1.293534
report_url = ( 'https://api.github.com/repos/%s/issues/%s/comments' % (self.repo_name, self.pr_number) ) result = self.requester.post(report_url, {'body': message}) if result.status_code >= 400: log.error("Error posting comment to github. %s",...
def post_comment(self, message)
Comments on an issue, not on a particular line.
2.749759
2.65264
1.036612
kwargs = {"initial": self.get_initial()} if self.request.method == "GET": kwargs.update({"data": self.request.GET}) kwargs.update({"searchqueryset": self.get_query_set()}) return kwargs
def get_form_kwargs(self)
Returns the keyword arguments for instantiating the form.
3.147256
2.962131
1.062497
form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
def get(self, request, *args, **kwargs)
Handles GET requests and instantiates a blank version of the form.
1.896082
1.71795
1.103689
form = self.get_form(request) self.form = form start_date = form.start_date() end_date = form.end_date() if form.is_valid() and (start_date or end_date): args = self.__get_filterargs( start=start_date, end=end_date, ...
def queryset(self, request, queryset)
That's the trick - we create self.form when django tries to get our queryset. This allows to create unbount and bound form in the single place.
3.737798
3.315949
1.127218
parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(help='Docker-tag-naming sub-commands', dest='subparser_name') # # Forge # parser_forge = subparsers.add_parser('forge', help='Create a new...
def parse_args_and_run()
:return: The parsed arguments
2.164285
2.163681
1.000279
dirname = self.clone_dir(repo_name) self.to_cleanup[repo_name] = dirname klass = self.get_repo_class() repo = klass(repo_name, dirname, self.tools, self.executor, shallow=self.shallow_clone) ...
def set_up_clone(self, repo_name, remote_repo)
Sets up the working directory and returns a tuple of (dirname, repo )
5.635682
4.620099
1.219818
self.shallow_clone = False dirname, repo = self.set_up_clone(repo_name, remote_repo) if os.path.isdir("%s/.git" % dirname): log.debug("Updating %s to %s", repo.download_location, dirname) self.executor( "cd %s && git checkout master" % dirname) ...
def clone_repo(self, repo_name, remote_repo, ref)
Clones the given repo and returns the Repository object.
3.207877
3.164747
1.013629
model = obj.__class__ unified_index = connections[using].get_unified_index() index = unified_index.get_index(model) prepped_data = index.full_prepare(obj) final_data = {} for key, value in prepped_data.items(): final_data[key] = connections[using].get_backend()._from_python(value) ...
def prepare_object(obj, using="default")
Returns a Python dictionary representation of the given object, expected to be a Model object with an associated SearchIndex. The optional argument `using` specifies the backend to use from the Haystack connections list.
3.527507
3.026695
1.165465
try: from django.apps import apps from django.core.exceptions import AppRegistryNotReady except ImportError: # Django < 1.7 from django.db import models return models.get_model(app_label, model_name) try: return apps.get_model(app_label, model_name) ...
def get_model(app_label, model_name)
Fetches a Django model using the app registry. This doesn't require that an app with the given app label exists, which makes it safe to call when the registry is being populated. All other methods to access models might raise an exception about the registry not being ready yet. Raises LookupError ...
3.989943
4.066881
0.981082
args = app.parse_args(sys.argv[1:]) params = args.__dict__ params.update(**load_config(args.config_file)) if params['debug']: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig() try: imhotep = app.gen_imhotep(**params) except NoGithubCredential...
def main()
Main entrypoint for the command-line app.
4.253211
4.115685
1.033415
with open(join(dirname(abspath(__file__)), filename)) as f: return f.read()
def read_relative_file(filename)
Returns contents of the given file, which path is supposed relative to this module.
3.595196
3.292658
1.091882
version = args.version commit_id = args.commit_id branch = args.branch try: print(Version(version, commit_id, branch)) except DockerTagNamingException, de: print(de) sys.exit(1)
def run_forge(args)
Handle the forge subcommand :param args: Parsed command line arguments :return: None, output is written to console
5.518981
6.189145
0.89172
# @@@ This is a security hazard as compare-point is user-passed in # data. Doesn't matter until we wrap this in a service. if compare_point is not None: self.apply_commit(compare_point) return self.executor("cd %s && git diff %s" % (self.dirname, commit))
def diff_commit(self, commit, compare_point=None)
Returns a diff as a string from the current HEAD to the given commit.
11.680021
11.04257
1.057727
result = [] z = None before_line_number, after_line_number = 0, 0 position = 0 for line in self.diff_text.splitlines(): # New File match = re.search(r'diff .*a/(?P<origin_filename>.*) ' r'b/(?P<result_filename>.*)...
def parse(self)
Parses everyting into a datastructure that looks like: result = [{ 'origin_filename': '', 'result_filename': '', 'origin_lines': [], // all lines of the original file 'result_lines': [], // all lines of the newest file 'added_l...
2.348575
2.218737
1.058519
image = args.image branch = args.branch try: initial_version = get_latest_version(image, branch) except DockerTagNamingException, de: print(de) sys.exit(1) if initial_version is None: print('No version found') sys.exit(1) print('Initial version is ...
def run_refresh(args)
Handle the refresh subcommand :param args: Parsed command line arguments :return: None, output is written to console
2.945211
3.017899
0.975914
if index is NOT_SET and key is not NOT_SET: try: index, value = self._dict[key] except KeyError: return d else: return value elif index is not NOT_SET and key is NOT_SET: try: key, value = self._list[index] except IndexError: return d else: return value else: raise ...
def get(self, key=NOT_SET, index=NOT_SET, d=None)
Return value with given key or index. If no value is found, return d (None by default).
2.067921
2.138246
0.967111
has_default = d is not NOT_SET if index is NOT_SET and key is not NOT_SET: index, value = self._pop_key(key, has_default) elif key is NOT_SET: key, index, value = self._pop_index(index, has_default) else: raise KEY_AND_INDEX_ERROR if index is None: return d else: self._fix_indices_after_...
def pop(self, key=NOT_SET, index=NOT_SET, d=NOT_SET)
Remove and return value with given key or index (last item by default). If key is not found, returns d if given, otherwise raises KeyError or IndexError. This is generally O(N) unless removing last item, then O(1).
2.921275
3.127311
0.934117
try: index, value = self._dict.pop(key) except KeyError: if has_default: return None, None else: raise key2, value2 = self._list.pop(index) assert key is key2 assert value is value2 return index, value
def _pop_key(self, key, has_default)
Remove an element by key.
2.801228
2.727925
1.026871
try: if index is NOT_SET: index = len(self._list) - 1 key, value = self._list.pop() else: key, value = self._list.pop(index) if index < 0: index += len(self._list) + 1 except IndexError: if has_default: return None, None, None else: raise index2, value2 = self._dict.pop...
def _pop_index(self, index, has_default)
Remove an element by index, or last element.
2.456685
2.42675
1.012336
if index is NOT_SET and key is not NOT_SET: index, popped_value = self._dict.pop(key) elif key is NOT_SET: if index is NOT_SET: index = len(self._list) - 1 key, popped_value2 = self._list[-1] else: key, popped_value2 = self._list[index] if index < 0: index += len(self._list) inde...
def fast_pop(self, key=NOT_SET, index=NOT_SET)
Pop a specific item quickly by swapping it to the end. Remove value with given key or index (last item by default) fast by swapping it to the last place first. Changes order of the remaining items (item that used to be last goes to the popped location). Returns tuple of (poped_value, new_moved_index, moved_...
2.687004
2.536186
1.059467
try: if last: key, value = self._list.pop() index = len(self._list) else: key, value = self._list.pop(0) index = 0 except IndexError: raise KeyError("IndexedDict is empty") index2, value2 = self._dict.pop(key) assert index == index2 assert value is value2 if not last: self._...
def popitem(self, last=True)
Remove and return last (default) or first (last=False) pair (key, value). Raises KeyError if the dictionary is empty. Runs in O(1) for last item, O(N) for first one.
2.870864
2.997532
0.957743
if index is NOT_SET and key is not NOT_SET: index, value = self._dict[key] elif index is not NOT_SET and key is NOT_SET: key, value = self._list[index] # Normalize index if index < 0: index += len(self._list) else: raise KEY_EQ_INDEX_ERROR if last: index_range = range(len(self._list) ...
def move_to_end(self, key=NOT_SET, index=NOT_SET, last=True)
Move an existing element to the end (or beginning if last==False). Runs in O(N).
2.42347
2.457562
0.986128
ret = IndexedDict() ret._dict = self._dict.copy() ret._list = list(self._list) return ret
def copy(self)
Return a shallow copy.
4.580253
4.049142
1.131166
"Returns the PullRequest as a PRInfo object" resp = requester.get( 'https://api.github.com/repos/%s/pulls/%s' % (reponame, number)) return PRInfo(resp.json())
def get_pr_info(requester, reponame, number)
Returns the PullRequest as a PRInfo object
3.829299
2.796201
1.369465
if iterable is None: iterable = tuple() if unique: if ordered: if mutable: return setlist(iterable) else: return frozensetlist(iterable) else: if mutable: return set(iterable) else: return frozenset(iterable) else: if ordered: if mutable: return list(iterable) else: ...
def collection(iterable=None, mutable=True, ordered=False, unique=False)
Return a :class:`Collection` with the specified properties. Args: iterable (Iterable): collection to instantiate new collection from. mutable (bool): Whether or not the new collection is mutable. ordered (bool): Whether or not the new collection is ordered. unique (bool): Whether or not the new collection con...
1.825286
1.868722
0.976756
version, commit, branch = version_string.split('-', 3) # Remove the "v" version_number = version[1:] version_number = int(version_number) return Version(version_number, commit, branch)
def version_parser(version_string)
:param version_string: The version tag as returned by the registry/hub API :return: A tuple with the parsed version / an exception when the version format is unknown/incorrect
3.867381
4.788002
0.807723
logging.debug('Getting %s with authentication' % image_name) url = '%s/%s/images' % (API_URL, image_name) registry_user = os.environ.get('REGISTRY_USER') registry_pass = os.environ.get('REGISTRY_PASS') if registry_user is None or registry_pass is None: msg = ('The docker image seems t...
def get_all_tags_with_auth(image_name, branch=None)
Get the tag information using authentication credentials provided by the user. :param image_name: The image name to query :param branch: The branch to filter by :return: A list of Version instances, latest first
2.588857
2.585136
1.001439
output = [] logging.debug('Getting %s without authentication' % image_name) spec = '/%s/tags' % image_name headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} try: # This works well for any public images: response = requests.get(API_URL ...
def get_all_tags_no_auth(image_name, branch=None)
Try to get the tags without any authentication, this does work only for public images. GET /v1/repositories/<namespace>/<repository_name>/tags :param image_name: The docker image name :param branch: The branch to filter by :return: A list of Version instances, latest first
2.916503
2.909774
1.002313
try: return get_all_tags_no_auth(image_name, branch) except AuthException: return get_all_tags_with_auth(image_name, branch)
def get_all_tags(image_name, branch=None)
GET /v1/repositories/<namespace>/<repository_name>/tags :param image_name: The docker image name :param branch: The branch to filter by :return: A list of Version instances, latest first
3.03203
3.481601
0.870872
_logger.info('Start publishing from %s with:\n%s' % (mysql_settings, kwargs)) kwargs.setdefault('server_id', random.randint(1000000000, 4294967295)) kwargs.setdefault('freeze_schema', True) # connect to binlog stream stream = pymysqlreplication.BinLogStreamReader( mys...
def start_publishing(mysql_settings, **kwargs)
Start publishing MySQL row-based binlog events to blinker signals Args: mysql_settings (dict): information to connect to mysql via pymysql **kwargs: The additional kwargs will be passed to :py:class:`pymysqlreplication.BinLogStreamReader`.
3.98317
3.569591
1.115862
if not isinstance(binlog_pos_memory, _bpm.BaseBinlogPosMemory): if not isinstance(binlog_pos_memory, (tuple, list)): raise ValueError('Invalid binlog position memory: %s' % binlog_pos_memory) binlog_pos_memory = _bpm.FileBasedBinlogPosMemory(*binlog_pos_...
def start_replication(mysql_settings, binlog_pos_memory=(None, 2), **kwargs)
Start replication on server specified by *mysql_settings* Args: mysql_settings (dict): mysql settings that is used to connect to mysql via pymysql binlog_pos_memory (_bpm.BaseBinlogPosMemory): Binlog Position Memory, it should be an instance of subclass ...
3.004668
2.41014
1.246678
#html = html.encode('utf-8', errors='ignore') try: html = unicode(html, errors='ignore') except TypeError: pass assert isinstance(html, unicode) # Create memory file. _file = StringIO() # Convert html to text. f = formatter.AbstractFormatter(formatter.DumbWriter(_...
def extractFromHTML(html, blur=5)
Extracts text from HTML content.
4.562013
4.510301
1.011465
try: from tidylib import tidy_document except ImportError as e: raise ImportError(("%s\nYou need to install pytidylib.\n" + "e.g. sudo pip install pytidylib") % e) options = { 'output-xhtml':1, #add_xml_decl=1,#option in tidy but not pytidylib 'inden...
def tidyHTML(dirtyHTML)
Runs an arbitrary HTML string through Tidy.
4.33243
4.268019
1.015092
h = hashlib.sha1() #h.update(s) h.update(s.encode('utf-8')) return pattern % h.hexdigest()
def generate_key(s, pattern="%s.txt")
Generates the cache key for the given string using the content in pattern to format the output string
2.515645
2.702294
0.930929
filename = os.path.join(cache_dir, cache_key) if os.path.isfile(filename): with open(filename, 'r') as f: return f.read() return default
def cache_get(cache_dir, cache_key, default=None)
Returns the content of a cache item or the given default
1.983409
2.046243
0.969293
filename = os.path.join(cache_dir, cache_key) with open(filename, 'w') as f: f.write(content)
def cache_set(cache_dir, cache_key, content)
Creates a new cache file in the cache directory
2.089022
2.092932
0.998132
filename = os.path.join(cache_dir, cache_key) return os.path.getmtime(filename) if os.path.exists(filename) else 0
def cache_info(cache_dir, cache_key)
Returns the cache files mtime or 0 if it does not exists
2.348214
1.878378
1.250129
headers = {} if userAgent: headers['User-agent'] = str(userAgent) else: headers['User-agent'] = ua.random #request = Request(url=url, headers=headers) #response = urlopen(request, timeout=timeout) response = requests.get(url, headers=headers, timeout=timeout) # Return ...
def fetch(url, timeout=5, userAgent=None, only_mime_types=None)
Retrieves the raw content of the URL.
4.575762
4.614982
0.991502
blur = int(blur) try: import chardet except ImportError as e: raise ImportError(("%s\nYou need to install chardet.\n" + \ "e.g. sudo pip install chardet") % e) if only_mime_types and isinstance(only_mime_types, six.text_type): only_mime_types = only_mime_type...
def extractFromURL(url, cache=False, cacheDir='_cache', verbose=False, encoding=None, filters=None, userAgent=None, timeout=5, blur=5, ignore_robotstxt=False, only_mime_types=None, raw=False)
Extracts text from a URL. Parameters: url := string Remote URL or local filename where HTML will be read. cache := bool True=store and retrieve url from cache False=always retrieve url from the web cacheDir := str Directory where cached url contents will be stored. v...
2.915484
2.960089
0.984931
out = self._from_iterable(None) out._dict = self._dict.copy() out._size = self._size return out
def copy(self)
Create a shallow copy of self. This runs in O(len(self.num_unique_elements()))
5.600542
4.918838
1.13859
if n is None: return sorted(self.counts(), key=itemgetter(1), reverse=True) else: return heapq.nlargest(n, self.counts(), key=itemgetter(1))
def nlargest(self, n=None)
List the n most common elements and their counts. List is from the most common to the least. If n is None, the list all element counts. Run time should be O(m log m) where m is len(self) Args: n (int): The number of elements to return
2.308558
2.398728
0.962409
out = cls() for elem, count in mapping.items(): out._set_count(elem, count) return out
def from_mapping(cls, mapping)
Create a bag from a dict of elem->count. Each key in the dict is added if the value is > 0. Raises: ValueError: If any count is < 0.
5.069864
4.036959
1.255862
if isinstance(other, _basebag): for elem, count in self.counts(): if not count <= other.count(elem): return False else: for elem in self: if self.count(elem) > 1 or elem not in other: return False return True
def is_subset(self, other)
Check that every element in self has a count <= in other. Args: other (Set)
3.47669
3.383133
1.027654
if isinstance(other, _basebag): for elem, count in other.counts(): self._increment_count(elem, count) else: for elem in other: self._increment_count(elem, 1) return self
def _iadd(self, other)
Add all of the elements of other to self. if isinstance(it, _basebag): This runs in O(it.num_unique_elements()) else: This runs in O(len(it))
3.1099
2.072831
1.500315
# TODO do we have to create a bag from the other first? if not isinstance(other, _basebag): other = self._from_iterable(other) for elem, old_count in set(self.counts()): other_count = other.count(elem) new_count = min(other_count, old_count) self._set_count(elem, new_count) return self
def _iand(self, other)
Set multiplicity of each element to the minimum of the two collections. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other))
4.279149
3.148015
1.359317
# TODO do we have to create a bag from the other first? if not isinstance(other, _basebag): other = self._from_iterable(other) for elem, other_count in other.counts(): old_count = self.count(elem) new_count = max(other_count, old_count) self._set_count(elem, new_count) return self
def _ior(self, other)
Set multiplicity of each element to the maximum of the two collections. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other))
4.065785
2.940481
1.382694
if isinstance(other, _basebag): for elem, other_count in other.counts(): count = abs(self.count(elem) - other_count) self._set_count(elem, count) else: # Let a = self.count(elem) and b = other.count(elem) # if a >= b then elem is removed from self b times leaving a - b # if a < b then elem is...
def _ixor(self, other)
Set self to the symmetric difference between the sets. if isinstance(other, _basebag): This runs in O(other.num_unique_elements()) else: This runs in O(len(other))
3.93831
3.459142
1.138522
if isinstance(other, _basebag): for elem, other_count in other.counts(): try: self._increment_count(elem, -other_count) except ValueError: self._set_count(elem, 0) else: for elem in other: try: self._increment_count(elem, -1) except ValueError: pass return self
def _isub(self, other)
Discard the elements of other from self. if isinstance(it, _basebag): This runs in O(it.num_unique_elements()) else: This runs in O(len(it))
2.63828
2.114188
1.247893
if not self.is_superset(other): raise ValueError('Passed collection is not a subset of this bag') self.discard_all(other)
def remove_all(self, other)
Remove all of the elems from other. Raises a ValueError if the multiplicity of any elem in other is greater than in self.
5.816202
6.327761
0.919156
try: # Darwin requires dlopen to be called with mode RTLD_GLOBAL instead # of the default RTLD_LOCAL. Without this, you end up with # libraries not being loadable, resulting in "Symbol not found" # errors if sys.platform == 'darwin': ...
def load(self,path)
Given a path to a library, load it.
3.770472
3.568654
1.056553
commit_id = args.commit_id image = args.image branch = args.branch try: print(version_bump(image, branch, commit_id)) except DockerTagNamingException, de: print(de) sys.exit(1)
def run_bump(args)
Handle the bump subcommand :param args: Parsed command line arguments :return: None, output is written to console
5.192133
5.342099
0.971927
cmd = ['git', 'ls-files'] cmd.extend(cmd_args) return set(subprocess.check_output(cmd).splitlines())
def git_ls_files(*cmd_args)
Run ``git ls-files`` in the top-level project directory. Arguments go directly to execution call. :return: set of file names :rtype: :class:`set`
2.793092
3.42565
0.815347
# Flake8 doesn't have an easy way to run checks using a Python function, so # just fork off another process to do it. # Python 3 compat: # - The result of subprocess call outputs are byte strings, meaning we need # to pass a byte string to endswith. project_python_files = [filename for f...
def _lint()
Run lint and return an exit code.
7.091683
6.822358
1.039477
response = self.session.get(self.signin_url, verify=False) user_param, password_param = self._get_hashed_params(response.text) login_data = { user_param: self.config['username'], password_param: self.config['password'], 'once': self._get_once(response...
def login(self)
Login v2ex, otherwise we can't complete the mission.
3.053482
2.736885
1.115678
soup = BeautifulSoup(page_text, 'html.parser') return [tag['name'] for tag in soup.find_all('input', class_='sl')]
def _get_hashed_params(self, page_text)
Get hashed params which will be used when you login, see issue#10
4.859351
4.403841
1.103435
soup = BeautifulSoup(page_text, 'html.parser') once = soup.find('input', attrs={'name': 'once'})['value'] return once
def _get_once(self, page_text)
Get once which will be used when you login.
3.271459
2.276574
1.437009
response = self.session.get(self.mission_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') onclick = soup.find('input', class_='super normal button')['onclick'] url = onclick.split('=', 1)[1][2:-2] if url == '/balance': return "You have c...
def get_money(self)
Complete daily mission then get the money.
4.27247
3.761622
1.135805
response = self.session.get(self.balance_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') first_line = soup.select( "table.data tr:nth-of-type(2)")[0].text.strip().split('\n') total, today = first_line[-2:] logging.info('%-26sTotal:%-8s',...
def _get_balance(self)
Get to know how much you totally have and how much you get today.
4.463637
4.059563
1.099536
response = self.session.get(self.mission_url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') last = soup.select('#Main div')[-1].text return last
def get_last(self)
Get to know how long you have kept signing in.
4.615563
4.163718
1.10852
_logger.debug('Start log pos saving thread') while not self.save_log_pos_thread_stop_flag.wait(self.interval): self._save_file_and_pos() _logger.debug('Finish log pos saving thread')
def _save_log_pos_thread_runner(self)
Save the position into file after every second :return:
4.324808
4.40357
0.982114
if not self._pos_changed: return with open(self.pos_storage_filename, 'w+') as f: _pos = '%s:%s' % (self._log_file, self._log_pos) _logger.debug('Saving position %s to file %s' % (_pos, self.pos_storage_filename)) f.write...
def _save_file_and_pos(self)
Save current position into file
3.41241
3.134359
1.088711
try: with open(self.pos_storage_filename, 'r+') as f: _pos = f.read() _logger.debug('Got position "%s" from file %s' % (_pos, self.pos_storage_filename)) if not _pos: return log...
def _read_file_and_pos(self)
Read last position from file, store as current position
2.770124
2.664396
1.039682
try: index = self._dict[value] except KeyError: raise ValueError else: start = self._fix_neg_index(start) end = self._fix_end_index(end) if start <= index and index < end: return index else: raise ValueError
def index(self, value, start=0, end=None)
Return the index of value between start and end. By default, the entire setlist is searched. This runs in O(1) Args: value: The value to find the index of start (int): The index to start searching at (defaults to 0) end (int): The index to stop searching at (defaults to the end of the list) Returns:...
2.87692
2.985941
0.963489
start_index = self.index(sub[0], start, end) end = self._fix_end_index(end) if start_index + len(sub) > end: raise ValueError for i in range(1, len(sub)): if sub[i] != self[start_index + i]: raise ValueError return start_index
def sub_index(self, sub, start=0, end=None)
Return the index of a subsequence. This runs in O(len(sub)) Args: sub (Sequence): An Iterable to search for Returns: int: The index of the first element of sub Raises: ValueError: If sub isn't a subsequence TypeError: If sub isn't iterable IndexError: If start or end are out of range
2.708326
2.888721
0.937552
value = self._list.pop(index) del self._dict[value] return value
def pop(self, index=-1)
Remove and return the item at index.
3.973864
3.439798
1.155261
if value in self: raise ValueError index = self._fix_neg_index(index) self._dict[value] = index for elem in self._list[index:]: self._dict[elem] += 1 self._list.insert(index, value)
def insert(self, index, value)
Insert value at index. Args: index (int): Index to insert value at value: Value to insert Raises: ValueError: If value already in self IndexError: If start or end are out of range
3.278198
3.481388
0.941635
try: index = self._dict[value] except KeyError: raise ValueError('Value "%s" is not present.') else: del self[index]
def remove(self, value)
Remove value from self. Args: value: Element to remove from self Raises: ValueError: if element is already present
3.747717
4.106799
0.912564
other = set(other) indices_to_delete = set() for i, elem in enumerate(self): if elem in other: indices_to_delete.add(i) if indices_to_delete: self._delete_values_by_index(indices_to_delete)
def difference_update(self, other)
Update self to include only the difference with other.
2.4616
2.408357
1.022108
other = setlist(other) indices_to_delete = set() for i, item in enumerate(self): if item in other: indices_to_delete.add(i) for item in other: self.add(item) self._delete_values_by_index(indices_to_delete)
def symmetric_difference_update(self, other)
Update self to include only the symmetric difference with other.
2.762205
2.742186
1.0073
random_.shuffle(self._list, random=random) for i, elem in enumerate(self._list): self._dict[elem] = i
def shuffle(self, random=None)
Shuffle all of the elements in self randomly.
5.047742
4.797279
1.052209
self._list.sort(*args, **kwargs) for index, value in enumerate(self._list): self._dict[value] = index
def sort(self, *args, **kwargs)
Sort this setlist in place.
3.267615
2.983277
1.095311
i = self._fix_neg_index(i) j = self._fix_neg_index(j) self._list[i], self._list[j] = self._list[j], self._list[i] self._dict[self._list[i]] = i self._dict[self._list[j]] = j
def swap(self, i, j)
Swap the values at indices i & j. .. versionadded:: 1.1
1.943792
2.187889
0.888433
assert before_values.keys() == after_values.keys() return dict([(k, [before_values[k], after_values[k]]) for k in before_values.keys() if before_values[k] != after_values[k]])
def _get_updated_values(before_values, after_values)
Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_value, after_value)
2.275197
2.671584
0.851628
after_values = row['after_values'] # type: dict before_values = row['before_values'] # type: dict values = after_values return { 'values': values, 'updated_values': _get_updated_values(before_values, after_values) }
def _convert_update_row(row)
Convert a row for update event Args: row (dict): event row data
3.513599
3.754775
0.935768
pk_cols = e.primary_key if isinstance(e.primary_key, (list, tuple)) \ else (e.primary_key, ) if isinstance(e, row_event.UpdateRowsEvent): sig = signals.rows_updated action = 'update' row_converter = _convert_update_row elif isinstance(e, row_event.WriteRowsEvent): ...
def _rows_event_to_dict(e, stream)
Convert RowsEvent to a dict Args: e (pymysqlreplication.row_event.RowsEvent): the event stream (pymysqlreplication.BinLogStreamReader): the stream that yields event Returns: dict: event's data as a dict
2.514656
2.482656
1.012889
rows, meta = _rows_event_to_dict(event, stream) table_name = '%s.%s' % (meta['schema'], meta['table']) if meta['action'] == 'insert': sig = signals.rows_inserted elif meta['action'] == 'update': sig = signals.rows_updated elif meta['action'] == 'delete': sig = signals....
def on_binlog(event, stream)
Process on a binlog event 1. Convert event instance into a dict 2. Send corresponding schema/table/signals Args: event (pymysqlreplication.row_event.RowsEvent): the event
2.75262
2.746978
1.002054
hash_value = hash(type(it)) for value in it: hash_value = hash((hash_value, value)) return hash_value
def hash_iterable(it)
Perform a O(1) memory hash of an iterable of arbitrary length. hash(tuple(it)) creates a temporary tuple containing all values from it which could be a problem if it is large. See discussion at: https://groups.google.com/forum/#!msg/python-ideas/XcuC01a8SYs/e-doB9TbDwAJ
2.746228
3.079515
0.891773
def wrapper(func): docstring = func.__doc__ or '' docstring_msg = '.. deprecated:: {version} {msg}'.format( version=dep_version, msg=msg, ) if docstring: # We don't know how far to indent this message # so instead we just dedent everything. string_list = docstring.splitlines() first_line =...
def deprecated(msg, dep_version)
Decorate a function, method or class to mark as deprecated. Raise DeprecationWarning and add a deprecation notice to the docstring.
2.446269
2.40368
1.017718
_check_start_stop(start, stop) start_loc = self._bisect_right(start) if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) start_val = self._values[start_loc - 1] candidate_keys = [start] + self._keys[start_loc:stop_loc] + [stop] candidate_values = [start_val] + sel...
def ranges(self, start=None, stop=None)
Generate MappedRanges for all mapped ranges. Yields: MappedRange
2.307113
2.232911
1.033231
loc = self._bisect_right(key) - 1 value = self._values[loc] if value is NOT_SET: raise KeyError(key) else: return value
def _getitem(self, key)
Get the value for a key (not a slice).
3.249961
3.162124
1.027778
return self.from_iterable(self.ranges(start, stop))
def get_range(self, start=None, stop=None)
Return a RangeMap for the range start to stop. Returns: A RangeMap
11.432511
19.658699
0.58155
_check_start_stop(start, stop) # start_index, stop_index will denote the sections we are replacing start_index = self._bisect_left(start) if start is not None: # start_index == 0 prev_value = self._values[start_index - 1] if prev_value == value: # We're setting a range where the left range has the...
def set(self, value, start=None, stop=None)
Set the range from start to stop to value.
2.43006
2.43058
0.999786
_check_start_stop(start, stop) start_loc = self._bisect_right(start) - 1 if stop is None: stop_loc = len(self._keys) else: stop_loc = self._bisect_left(stop) for value in self._values[start_loc:stop_loc]: if value is NOT_SET: raise KeyError((start, stop)) # this is inefficient, we've already...
def delete(self, start=None, stop=None)
Delete the range from start to stop from self. Raises: KeyError: If part of the passed range isn't mapped.
3.629562
3.393131
1.069679
self.set(NOT_SET, start=start, stop=stop)
def empty(self, start=None, stop=None)
Empty the range from start to stop. Like delete, but no Error is raised if the entire range isn't mapped.
8.578408
10.511829
0.816072
if self._values[0] is NOT_SET: try: return self._keys[1] except IndexError: # This is empty or everything is mapped to a single value return None else: # This is unbounded to the left return self._keys[0]
def start(self)
Get the start key of the first range. None if RangeMap is empty or unbounded to the left.
7.047679
4.683594
1.504759
def getpath(c): return "%s:%s" % (c.__module__, c.__class__.__name__) tools = [x for x in known_plugins if getpath(x) in whitelist] if not tools: if whitelist: raise UnknownTools(map(getpath, known_plugins)) tools = known_plugins return tools
def get_tools(whitelist, known_plugins)
Filter all known plugins by a whitelist specified. If the whitelist is empty, default to all plugins.
4.15877
3.923479
1.05997
if sys.argv[1] == 'init': return cfg = ctx.ensure_object(Config) if config_path is None: config_path = path.join(sys.path[0], 'v2ex_config.json') if not path.exists(config_path): sys.exit("Can't find config file at {0}.\nPlease read " "https://github.com/lor...
def read_config(ctx, param, config_path)
Callback that is used whenever --config is passed.
3.687976
3.624172
1.017605
username = click.prompt("Input your username") password = click.prompt("Input your password", hide_input=True, confirmation_prompt=True) log_directory = click.prompt("Input your log directory") if not path.exists(log_directory): sys.exit("Invalid log directory, ...
def init(directory)
Init the config fle.
2.636354
2.485325
1.060769
try: v2ex = V2ex(conf.config) v2ex.login() balance = v2ex.get_money() click.echo(balance) except KeyError: click.echo('Keyerror, please check your config file.') except IndexError: click.echo('Please check your username and password.')
def sign(conf)
Sign in and get money.
4.982045
4.164868
1.196207