function
stringlengths
16
7.61k
repo_name
stringlengths
9
46
features
sequence
def get_page(url): """Retrieve the given page.""" return urllib2.urlopen(url).read()
pytroll/satpy
[ 901, 261, 901, 407, 1455049783 ]
def get_all_coeffs(): """Get all available calibration coefficients for the satellites.""" coeffs = {} for platform in URLS: if platform not in coeffs: coeffs[platform] = {} for chan in URLS[platform].keys(): url = URLS[platform][chan] print(url) page = get_page(url) coeffs[platform][chan] = get_coeffs(page) return coeffs
pytroll/satpy
[ 901, 261, 901, 407, 1455049783 ]
def main(): """Create calibration coefficient files for AVHRR.""" out_dir = sys.argv[1] coeffs = get_all_coeffs() save_coeffs(coeffs, out_dir=out_dir)
pytroll/satpy
[ 901, 261, 901, 407, 1455049783 ]
def _pure_pattern(regex): pattern = regex.pattern if pattern.startswith('^'): pattern = pattern[1:] return pattern
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def escape(text, quote=False, smart_amp=True): """Replace special characters "&", "<" and ">" to HTML-safe sequences. The original cgi.escape will always escape "&", but you can control this one for a smart escape amp. :param quote: if set to True, " and ' will be escaped. :param smart_amp: if set to False, & will always be escaped. """ if smart_amp: text = _escape_pattern.sub('&amp;', text) else: text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') if quote: text = text.replace('"', '&quot;') text = text.replace("'", '&#39;') return text
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def preprocessing(text, tab=4): text = _newline_pattern.sub('\n', text) text = text.expandtabs(tab) text = text.replace('\u00a0', ' ') text = text.replace('\u2424', '\n') pattern = re.compile(r'^ +$', re.M) return pattern.sub('', text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def __init__(self, rules=None, **kwargs): self.tokens = [] self.def_links = {} self.def_footnotes = {} if not rules: rules = self.grammar_class() self.rules = rules
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse(self, text, rules=None): text = text.rstrip('\n') if not rules: rules = self.default_rules def manipulate(text): for key in rules: rule = getattr(self.rules, key) m = rule.match(text) if not m: continue getattr(self, 'parse_%s' % key)(m) return m return False # pragma: no cover while text: m = manipulate(text) if m is not False: text = text[len(m.group(0)):] continue if text: # pragma: no cover raise RuntimeError('Infinite loop at: %s' % text) return self.tokens
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_block_code(self, m): # clean leading whitespace code = _block_code_leading_pattern.sub('', m.group(0)) self.tokens.append({ 'type': 'code', 'lang': None, 'text': code, })
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_heading(self, m): self.tokens.append({ 'type': 'heading', 'level': len(m.group(1)), 'text': m.group(2), })
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_hrule(self, m): self.tokens.append({'type': 'hrule'})
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def _process_list_item(self, cap, bull): cap = self.rules.list_item.findall(cap) _next = False length = len(cap) for i in range(length): item = cap[i][0] # remove the bullet space = len(item) item = self.rules.list_bullet.sub('', item) # outdent if '\n ' in item: space = space - len(item) pattern = re.compile(r'^ {1,%d}' % space, flags=re.M) item = pattern.sub('', item) # determine whether item is loose or not loose = _next if not loose and re.search(r'\n\n(?!\s*$)', item): loose = True rest = len(item) if i != length - 1 and rest: _next = item[rest-1] == '\n' if not loose: loose = _next if loose: t = 'loose_item_start' else: t = 'list_item_start' self.tokens.append({'type': t}) # recurse self.parse(item, self.list_rules) self.tokens.append({'type': 'list_item_end'})
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_def_links(self, m): key = _keyify(m.group(1)) self.def_links[key] = { 'link': m.group(2), 'title': m.group(3), }
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_table(self, m): item = self._process_table(m) cells = re.sub(r'(?: *\| *)?\n$', '', m.group(3)) cells = cells.split('\n') for i, v in enumerate(cells): v = re.sub(r'^ *\| *| *\| *$', '', v) cells[i] = re.split(r' *\| *', v) item['cells'] = cells self.tokens.append(item)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def _process_table(self, m): header = re.sub(r'^ *| *\| *$', '', m.group(1)) header = re.split(r' *\| *', header) align = re.sub(r' *|\| *$', '', m.group(2)) align = re.split(r' *\| *', align) for i, v in enumerate(align): if re.search(r'^ *-+: *$', v): align[i] = 'right' elif re.search(r'^ *:-+: *$', v): align[i] = 'center' elif re.search(r'^ *:-+ *$', v): align[i] = 'left' else: align[i] = None item = { 'type': 'table', 'header': header, 'align': align, } return item
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def parse_paragraph(self, m): text = m.group(1).rstrip('\n') self.tokens.append({'type': 'paragraph', 'text': text})
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def hard_wrap(self): """Grammar for hard wrap linebreak. You don't need to add two spaces at the end of a line. """ self.linebreak = re.compile(r'^ *\n(?!\s*$)') self.text = re.compile( r'^[\s\S]+?(?=[\\<!\[_*`~]|https?://| *\n|$)' )
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def __init__(self, renderer, rules=None, **kwargs): self.renderer = renderer self.links = {} self.footnotes = {} self.footnote_index = 0 if not rules: rules = self.grammar_class() kwargs.update(self.renderer.options) if kwargs.get('hard_wrap'): rules.hard_wrap() self.rules = rules self._in_link = False self._in_footnote = False self._parse_inline_html = kwargs.get('parse_inline_html')
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def setup(self, links, footnotes): self.footnote_index = 0 self.links = links or {} self.footnotes = footnotes or {}
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def manipulate(text): for key in rules: pattern = getattr(self.rules, key) m = pattern.match(text) if not m: continue self.line_match = m out = getattr(self, 'output_%s' % key)(m) if out is not None: return m, out return False # pragma: no cover
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_escape(self, m): text = m.group(1) return self.renderer.escape(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_url(self, m): link = m.group(1) if self._in_link: return self.renderer.text(link) return self.renderer.autolink(link, False)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_footnote(self, m): key = _keyify(m.group(1)) if key not in self.footnotes: return None if self.footnotes[key]: return None self.footnote_index += 1 self.footnotes[key] = self.footnote_index return self.renderer.footnote_ref(key, self.footnote_index)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_reflink(self, m): key = _keyify(m.group(2) or m.group(1)) if key not in self.links: return None ret = self.links[key] return self._process_link(m, ret['link'], ret['title'])
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def _process_link(self, m, link, title=None): line = m.group(0) text = m.group(1) if line[0] == '!': return self.renderer.image(link, title, text) self._in_link = True text = self.output(text) self._in_link = False return self.renderer.link(link, title, text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_emphasis(self, m): text = m.group(2) or m.group(1) text = self.output(text) return self.renderer.emphasis(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_linebreak(self, m): return self.renderer.linebreak()
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_text(self, m): text = m.group(0) return self.renderer.text(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def __init__(self, **kwargs): self.options = kwargs
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def block_code(self, code, lang=None): """Rendering block level code. ``pre > code``. :param code: text content of the code block. :param lang: language of the given code. """ code = code.rstrip('\n') if not lang: code = escape(code, smart_amp=False) return '<pre><code>%s\n</code></pre>\n' % code code = escape(code, quote=True, smart_amp=False) return '<pre><code class="lang-%s">%s\n</code></pre>\n' % (lang, code)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def block_html(self, html): """Rendering block level pure html content. :param html: text content of the html snippet. """ if self.options.get('skip_style') and \ html.lower().startswith('<style'): return '' if self.options.get('escape'): return escape(html) return html
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def hrule(self): """Rendering method for ``<hr>`` tag.""" if self.options.get('use_xhtml'): return '<hr />\n' return '<hr>\n'
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def list_item(self, text): """Rendering list item snippet. Like ``<li>``.""" return '<li>%s</li>\n' % text
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def table(self, header, body): """Rendering table element. Wrap header and body in it. :param header: header part of the table. :param body: body part of the table. """ return ( '<table>\n<thead>%s</thead>\n' '<tbody>\n%s</tbody>\n</table>\n' ) % (header, body)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def table_cell(self, content, **flags): """Rendering a table cell. Like ``<th>`` ``<td>``. :param content: content of current table cell. :param header: whether this is header or not. :param align: align of current table cell. """ if flags['header']: tag = 'th' else: tag = 'td' align = flags['align'] if not align: return '<%s>%s</%s>\n' % (tag, content, tag) return '<%s style="text-align:%s">%s</%s>\n' % ( tag, align, content, tag )
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def emphasis(self, text): """Rendering *emphasis* text. :param text: text content for emphasis. """ return '<em>%s</em>' % text
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def linebreak(self): """Rendering line break like ``<br>``.""" if self.options.get('use_xhtml'): return '<br />\n' return '<br>\n'
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def text(self, text): """Rendering unformatted text. :param text: text content. """ if self.options.get('parse_block_html'): return text return escape(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def autolink(self, link, is_email=False): """Rendering a given link or email address. :param link: link content or email address. :param is_email: whether this is an email or not. """ text = link = escape(link) if is_email: link = 'mailto:%s' % link return '<a href="%s">%s</a>' % (link, text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def image(self, src, title, text): """Rendering a image with title and text. :param src: source link of the image. :param title: title text of the image. :param text: alt text of the image. """ src = escape_link(src) text = escape(text, quote=True) if title: title = escape(title, quote=True) html = '<img src="%s" alt="%s" title="%s"' % (src, text, title) else: html = '<img src="%s" alt="%s"' % (src, text) if self.options.get('use_xhtml'): return '%s />' % html return '%s>' % html
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def newline(self): """Rendering newline element.""" return ''
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def footnote_item(self, key, text): """Rendering a footnote item. :param key: identity key for the footnote. :param text: text content of the footnote. """ back = ( '<a href="#fnref-%s" rev="footnote">&#8617;</a>' ) % escape(key) text = text.rstrip() if text.endswith('</p>'): text = re.sub(r'<\/p>$', r'%s</p>' % back, text) else: text = '%s<p>%s</p>' % (text, back) html = '<li id="fn-%s">%s</li>\n' % (escape(key), text) return html
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def __init__(self, renderer=None, inline=None, block=None, **kwargs): if not renderer: renderer = Renderer(**kwargs) else: kwargs.update(renderer.options) self.renderer = renderer if inline and inspect.isclass(inline): inline = inline(renderer, **kwargs) if block and inspect.isclass(block): block = block(**kwargs) if inline: self.inline = inline else: self.inline = InlineLexer(renderer, **kwargs) self.block = block or BlockLexer(BlockGrammar()) self.footnotes = [] self.tokens = [] # detect if it should parse text in block html self._parse_block_html = kwargs.get('parse_block_html')
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def render(self, text): """Render the Markdown text. :param text: markdown formatted text content. """ return self.parse(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def pop(self): if not self.tokens: return None self.token = self.tokens.pop() return self.token
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output(self, text, rules=None): self.tokens = self.block(text, rules) self.tokens.reverse() self.inline.setup(self.block.def_links, self.block.def_footnotes) out = self.renderer.placeholder() while self.pop(): out += self.tok() return out
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def tok_text(self): text = self.token['text'] while self.peek()['type'] == 'text': text += '\n' + self.pop()['text'] return self.inline(text)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_hrule(self): return self.renderer.hrule()
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_code(self): return self.renderer.block_code( self.token['text'], self.token['lang'] )
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_block_quote(self): body = self.renderer.placeholder() while self.pop()['type'] != 'block_quote_end': body += self.tok() return self.renderer.block_quote(body)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_list_item(self): body = self.renderer.placeholder() while self.pop()['type'] != 'list_item_end': if self.token['type'] == 'text': body += self.tok_text() else: body += self.tok() return self.renderer.list_item(body)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_footnote(self): self.inline._in_footnote = True body = self.renderer.placeholder() key = self.token['key'] while self.pop()['type'] != 'footnote_end': body += self.tok() self.footnotes.append({'key': key, 'text': body}) self.inline._in_footnote = False return self.renderer.placeholder()
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_open_html(self): text = self.token['text'] tag = self.token['tag'] if self._parse_block_html and tag not in _pre_tags: text = self.inline(text, rules=self.inline.inline_html_rules) extra = self.token.get('extra') or '' html = '<%s%s>%s</%s>' % (tag, extra, text, tag) return self.renderer.block_html(html)
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def output_text(self): return self.renderer.paragraph(self.tok_text())
ebursztein/SiteFab
[ 13, 5, 13, 89, 1482968859 ]
def __init__(self): self.mainFrame = gui.mainFrame.MainFrame.getInstance()
DarkFenX/Pyfa
[ 1401, 374, 1401, 265, 1370894453 ]
def getText(self, callingWindow, itmContext, mainItem): return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item")
DarkFenX/Pyfa
[ 1401, 374, 1401, 265, 1370894453 ]
def getBitmap(self, callingWindow, context, mainItem): return None
DarkFenX/Pyfa
[ 1401, 374, 1401, 265, 1370894453 ]
def eye(N, M=None, k=0, typecode=None, dtype=None): """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones, and everything else is zeros. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def tri(N, M=None, k=0, typecode=None, dtype=None): """ returns a N-by-M array where all the diagonals starting from lower left corner up to the k-th are all ones. """ dtype = convtypecode(typecode, dtype) if M is None: M = N m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def trapz(y, x=None, axis=-1): return _Ntrapz(y, x, axis=axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def ptp(x, axis=0): return _Nptp(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def cumprod(x, axis=0): return _Ncumprod(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def max(x, axis=0): return _Nmax(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def min(x, axis=0): return _Nmin(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def prod(x, axis=0): return _Nprod(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def std(x, axis=0): N = asarray(x).shape[axis] return _Nstd(x, axis)*sqrt(N/(N-1.))
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def mean(x, axis=0): return _Nmean(x, axis)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def cov(m, y=None, rowvar=0, bias=0): if y is None: y = m else: y = y if rowvar: m = transpose(m) y = transpose(y) if (m.shape[0] == 1): m = transpose(m) if (y.shape[0] == 1): y = transpose(y) N = m.shape[0] if (y.shape[0] != N): raise ValueError("x and y must have the same number of observations") m = m - _Nmean(m,axis=0) y = y - _Nmean(y,axis=0) if bias: fact = N*1.0 else: fact = N-1.0 return squeeze(dot(transpose(m), conjugate(y)) / fact)
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def corrcoef(x, y=None): c = cov(x, y) d = diag(c) return c/sqrt(multiply.outer(d,d))
beiko-lab/gengis
[ 28, 14, 28, 18, 1363614616 ]
def forwards(self, orm): # Adding model 'ArticleComment' db.create_table('cms_articlecomment', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('article', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['cms.Article'])), ('created_at', self.gf('django.db.models.fields.DateField')(auto_now_add=True, blank=True)), ('author', self.gf('django.db.models.fields.CharField')(max_length=60)), ('comment', self.gf('django.db.models.fields.TextField')()), )) db.send_create_signal('cms', ['ArticleComment'])
josircg/raizcidadanista
[ 1, 2, 1, 23, 1431355072 ]
def _find_acl_template(conn, acl_template): query = ( sa.sql.select([acl_template_table.c.id]) .where(acl_template_table.c.template == acl_template) .limit(1) ) return conn.execute(query).scalar()
wazo-pbx/xivo-auth
[ 8, 5, 8, 1, 1480100085 ]
def _get_policy_uuid(conn, policy_name): policy_query = sa.sql.select([policy_table.c.uuid]).where( policy_table.c.name == policy_name ) for policy in conn.execute(policy_query).fetchall(): return policy[0]
wazo-pbx/xivo-auth
[ 8, 5, 8, 1, 1480100085 ]
def _get_acl_template_ids(conn, policy_uuid): query = sa.sql.select([policy_template.c.template_id]).where( policy_template.c.policy_uuid == policy_uuid ) return [acl_template_id for (acl_template_id,) in conn.execute(query).fetchall()]
wazo-pbx/xivo-auth
[ 8, 5, 8, 1, 1480100085 ]
def _find_packages(path='.', prefix=''): yield prefix prefix = prefix + "." for _, name, ispkg in walk_packages(path, prefix, onerror=lambda x: x): if ispkg: yield name
cfelton/minnesota
[ 12, 6, 12, 1, 1359060192 ]
def find_packages(): return list(_find_packages(mn.__path__, mn.__name__))
cfelton/minnesota
[ 12, 6, 12, 1, 1359060192 ]
def __init__(self): args = self.arg_parser.parse_known_args()[0] super(ScikitBase, self).__init__() self.pipeline = self.load_pipeline(args.pipeline) if args.feature_names: self.feature_names = self.load_pipeline(args.feature_names)
miti0/mosquito
[ 250, 54, 250, 17, 1497815837 ]
def load_pipeline(pipeline_file): """ Loads scikit model/pipeline """ print(colored('Loading pipeline: ' + pipeline_file, 'green')) return joblib.load(pipeline_file)
miti0/mosquito
[ 250, 54, 250, 17, 1497815837 ]
def combine_browsers_logs(udid): cmd = 'rebot -N Combined --outputdir browserlogs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\\browserlogs\\" + device + "\output.xml " else: cmd += os.getcwd() + "/browserlogs/" + device + "/output.xml "
younglim/hats-ci
[ 7, 13, 7, 1, 1498120077 ]
def combine_logs(udid): cmd = 'rebot -N Combined --outputdir logs/ ' for idx, device in enumerate(udid): #Get all the output.xml files for the devices if platform.system() == "Windows": cmd += os.getcwd() + "\logs\\" + device + "_" + "*\output.xml " else: cmd += os.getcwd() + "/logs/" + device + "_" + "*/output.xml "
younglim/hats-ci
[ 7, 13, 7, 1, 1498120077 ]
def zip_logs(): if platform.system() == "Windows": cmd = "Compress-Archive logs logs-$(date +%Y-%m-%d-%H%M).zip" subprocess.call(["powershell.exe", cmd]) elif platform.system() == "Linux" or platform.system() == "Darwin": cmd = "zip -vr logs-$(date +%Y-%m-%d-%H%M).zip" + " logs/" cr.run_command(cmd)
younglim/hats-ci
[ 7, 13, 7, 1, 1498120077 ]
def delete_previous_logs(): cmd = 'rm -rf logs/*' cr.run_command(cmd)
younglim/hats-ci
[ 7, 13, 7, 1, 1498120077 ]
def trappedWater(a, size) :
jainaman224/Algo_Ds_Notes
[ 2143, 2078, 2143, 224, 1466242715 ]
def setUpTestData(cls): batch_num = 0 section_num = 0 voter_num = 0 party_num = 0 position_num = 0 candidate_num = 0 num_elections = 2 voters = list() positions = dict() for i in range(num_elections): election = Election.objects.create(name='Election {}'.format(i)) positions[str(election.name)] = list() num_batches = 2 for j in range(num_batches): batch = Batch.objects.create(year=batch_num, election=election) batch_num += 1 num_sections = 2 if j == 0 else 1 for k in range(num_sections): section = Section.objects.create( section_name=str(section_num) ) section_num += 1 num_students = 2 for l in range(num_students): voter = User.objects.create( username='user{}'.format(voter_num), first_name=str(voter_num), last_name=str(voter_num), type=UserType.VOTER ) voter.set_password('voter') voter.save() voter_num += 1 VoterProfile.objects.create( user=voter, batch=batch, section=section ) voters.append(voter) num_positions = 3 for i in range(num_positions): position = CandidatePosition.objects.create( position_name='Position {}'.format(position_num), election=election ) positions[str(election.name)].append(position) position_num += 1 num_parties = 3 for j in range(num_parties): party = CandidateParty.objects.create( party_name='Party {}'.format(party_num), election=election ) party_num += 1 if j != 2: # Let every third party have no candidates. num_positions = 3 for k in range(num_positions): position = positions[str(election.name)][k] candidate = Candidate.objects.create( user=voters[candidate_num], party=party, position=position, election=election ) Vote.objects.create( user=voters[candidate_num], candidate=candidate, election=election ) candidate_num += 1 # Let's give one candidate an additional vote to really make sure that # we all got the correct number of votes. Vote.objects.create( user=voters[0], # NOTE: The voter in voter[1] is a Position 1 candidate of # Party 1, where the voter in voter[0] is a member. candidate=Candidate.objects.get(user=voters[1]), election=Election.objects.get(name='Election 0') ) _admin = User.objects.create(username='admin', type=UserType.ADMIN) _admin.set_password('root') _admin.save()
seanballais/botos
[ 4, 1, 4, 5, 1464711039 ]
def test_anonymous_get_requests_redirected_to_index(self): self.client.logout() response = self.client.get(reverse('results-export'), follow=True) self.assertRedirects(response, '/?next=%2Fadmin%2Fresults')
seanballais/botos
[ 4, 1, 4, 5, 1464711039 ]
def test_get_all_elections_xlsx(self): response = self.client.get(reverse('results-export')) self.assertEqual(response.status_code, 200) self.assertEqual( response['Content-Disposition'], 'attachment; filename="Election Results.xlsx"' ) wb = openpyxl.load_workbook(io.BytesIO(response.content)) self.assertEqual(len(wb.worksheets), 2) # Check first worksheet. ws = wb.worksheets[0] self.assertEqual(wb.sheetnames[0], 'Election 0') row_count = ws.max_row col_count = ws.max_column self.assertEqual(row_count, 25) self.assertEqual(col_count, 5) self.assertEqual(str(ws.cell(1, 1).value), 'Election 0 Results') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') cellContents = [ 'Position 0', 'Party 0', '0, 0', 'Party 1', '3, 3', 'Party 2', 'None', 'Position 1', 'Party 0', '1, 1', 'Party 1', '4, 4', 'Party 2', 'None', 'Position 2', 'Party 0', '2, 2', 'Party 1', '5, 5', 'Party 2', 'None' ] for cellIndex, content in enumerate(cellContents, 5): self.assertEqual(str(ws.cell(cellIndex, 1).value), content) self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes') self.assertEqual(str(ws.cell(3, 2).value), '0') self.assertEqual(str(ws.cell(4, 2).value), '0') # Section self.assertEqual(str(ws.cell(7, 2).value), '1') self.assertEqual(str(ws.cell(9, 2).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 2).value), '2') self.assertEqual(str(ws.cell(16, 2).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 2).value), '0') self.assertEqual(str(ws.cell(23, 2).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(4, 3).value), '1') # Section self.assertEqual(str(ws.cell(7, 3).value), '0') self.assertEqual(str(ws.cell(9, 3).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 3).value), '0') self.assertEqual(str(ws.cell(16, 3).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 3).value), '1') self.assertEqual(str(ws.cell(23, 3).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 4).value), '1') self.assertEqual(str(ws.cell(4, 4).value), '2') # Section self.assertEqual(str(ws.cell(7, 4).value), '0') self.assertEqual(str(ws.cell(9, 4).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 4).value), '0') self.assertEqual(str(ws.cell(16, 4).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 4).value), '0') self.assertEqual(str(ws.cell(23, 4).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes') self.assertEqual(str(ws.cell(7, 5).value), '1') self.assertEqual(str(ws.cell(9, 5).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 5).value), '2') self.assertEqual(str(ws.cell(16, 5).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 5).value), '1') self.assertEqual(str(ws.cell(23, 5).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') # Check second worksheet. ws = wb.worksheets[1] self.assertEqual(wb.sheetnames[1], 'Election 1') row_count = ws.max_row col_count = ws.max_column self.assertEqual(row_count, 25) self.assertEqual(col_count, 5) self.assertEqual(str(ws.cell(1, 1).value), 'Election 1 Results') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') self.assertEqual(str(ws.cell(2, 1).value), 'Candidates') cellContents = [ 'Position 3', 'Party 3', '6, 6', 'Party 4', '9, 9', 'Party 5', 'None', 'Position 4', 'Party 3', '7, 7', 'Party 4', '10, 10', 'Party 5', 'None', 'Position 5', 'Party 3', '8, 8', 'Party 4', '11, 11', 'Party 5', 'None' ] for cellIndex, content in enumerate(cellContents, 5): self.assertEqual(str(ws.cell(cellIndex, 1).value), content) self.assertEqual(str(ws.cell(2, 2).value), 'Number of Votes') self.assertEqual(str(ws.cell(3, 2).value), '2') self.assertEqual(str(ws.cell(4, 2).value), '3') # Section self.assertEqual(str(ws.cell(7, 2).value), '1') self.assertEqual(str(ws.cell(9, 2).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 2).value), '1') self.assertEqual(str(ws.cell(16, 2).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 2).value), '0') self.assertEqual(str(ws.cell(23, 2).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(4, 3).value), '4') # Section self.assertEqual(str(ws.cell(7, 3).value), '0') self.assertEqual(str(ws.cell(9, 3).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 3).value), '0') self.assertEqual(str(ws.cell(16, 3).value), '0') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 3).value), '1') self.assertEqual(str(ws.cell(23, 3).value), '0') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 4).value), '3') self.assertEqual(str(ws.cell(4, 4).value), '5') # Section self.assertEqual(str(ws.cell(7, 4).value), '0') self.assertEqual(str(ws.cell(9, 4).value), '0') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 4).value), '0') self.assertEqual(str(ws.cell(16, 4).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 4).value), '0') self.assertEqual(str(ws.cell(23, 4).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A') self.assertEqual(str(ws.cell(3, 5).value), 'Total Votes') self.assertEqual(str(ws.cell(7, 5).value), '1') self.assertEqual(str(ws.cell(9, 5).value), '1') self.assertEqual(str(ws.cell(11, 2).value), 'N/A') self.assertEqual(str(ws.cell(14, 5).value), '1') self.assertEqual(str(ws.cell(16, 5).value), '1') self.assertEqual(str(ws.cell(18, 2).value), 'N/A') self.assertEqual(str(ws.cell(21, 5).value), '1') self.assertEqual(str(ws.cell(23, 5).value), '1') self.assertEqual(str(ws.cell(25, 2).value), 'N/A')
seanballais/botos
[ 4, 1, 4, 5, 1464711039 ]
def test_get_with_invalid_election_id_non_existent_election_id(self): response = self.client.get( reverse('results-export'), { 'election': '69' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified an ID for a non-existent election.' ) self.assertRedirects(response, reverse('results'))
seanballais/botos
[ 4, 1, 4, 5, 1464711039 ]
def test_ref_get_with_invalid_election_id_non_existent_election_id(self): response = self.client.get( reverse('results-export'), { 'election': '69' }, HTTP_REFERER=reverse('results'), follow=True ) messages = list(response.context['messages']) self.assertEqual( messages[0].message, 'You specified an ID for a non-existent election.' ) self.assertRedirects(response, reverse('results'))
seanballais/botos
[ 4, 1, 4, 5, 1464711039 ]
def get_root_input_type_from_json(data): """Return the root input type from JSON formatted string.""" return parse_format(json.loads(data))
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def is_scalar(input_type): """Returns True if input_type is scalar.""" return input_type['base_type'] in SCALAR
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def is_param(value): """Determine whether given value is a parameter string.""" if not isinstance(value, str): return False return RE_PARAM.match(value)
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def _substitute_implementations(): """Replaces implementation ids with input_types.""" impls = {} for id_ in input_type['implementations']: type_ = input_types[id_] impls[type_['name']] = type_ input_type['implementations'] = impls
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def _substitute_key_type(): """Replaces key type with input_type.""" # pylint: disable=unused-variable, invalid-name for __, value in input_type['keys'].items(): value['type'] = input_types[value['type']]
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def _get_input_type(data): """Returns the input_type data structure that defines an input type and its constraints for validation.""" if 'id' not in data or 'input_type' not in data: return None input_type = dict( id=data['id'], base_type=data['input_type'] ) input_type['name'] = data.get('name', '') input_type['full_name'] = data.get('full_name', '') input_type['description'] = data.get('description', '') input_type['attributes'] = data.get('attributes', {}) if input_type['base_type'] in ['Double', 'Integer']: input_type.update(_parse_range(data)) elif input_type['base_type'] == 'Array': input_type.update(_parse_range(data)) if input_type['min'] < 0: input_type['min'] = 0 input_type['subtype'] = data['subtype'] elif input_type['base_type'] == 'FileName': input_type['file_mode'] = data['file_mode'] elif input_type['base_type'] == 'Selection': input_type['values'] = _list_to_dict(data['values'], 'name') elif input_type['base_type'] == 'Record': input_type['keys'] = _list_to_dict(data['keys']) input_type['implements'] = data.get('implements', []) input_type['reducible_to_key'] = data.get('reducible_to_key', None) elif input_type['base_type'] == 'Abstract': input_type['implementations'] = data['implementations'] input_type['default_descendant'] = data.get('default_descendant', None) return input_type
GeoMop/GeoMop
[ 3, 1, 3, 76, 1420793228 ]
def __init__(self, protocol: ProtocolAnalyzerContainer, label_index: int, msg_index: int, proto_view: int, parent=None): super().__init__(parent) self.ui = Ui_FuzzingDialog() self.ui.setupUi(self) self.setAttribute(Qt.WA_DeleteOnClose) self.setWindowFlags(Qt.Window) self.protocol = protocol msg_index = msg_index if msg_index != -1 else 0 self.ui.spinBoxFuzzMessage.setValue(msg_index + 1) self.ui.spinBoxFuzzMessage.setMinimum(1) self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages) self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type]) self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index) self.proto_view = proto_view self.fuzz_table_model = FuzzingTableModel(self.current_label, proto_view) self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked() self.ui.tblFuzzingValues.setModel(self.fuzz_table_model) self.fuzz_table_model.update() self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1) self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end) self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data)) self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data)) self.update_message_data_string() self.ui.tblFuzzingValues.resize_me() self.create_connects() self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def message(self): return self.protocol.messages[int(self.ui.spinBoxFuzzMessage.value() - 1)]
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def current_label_index(self): return self.ui.comboBoxFuzzingLabel.currentIndex()
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def current_label(self) -> ProtocolLabel: if len(self.message.message_type) == 0: return None cur_label = self.message.message_type[self.current_label_index].get_copy() self.message.message_type[self.current_label_index] = cur_label cur_label.fuzz_values = [fv for fv in cur_label.fuzz_values if fv] # Remove empty strings if len(cur_label.fuzz_values) == 0: cur_label.fuzz_values.append(self.message.plain_bits_str[cur_label.start:cur_label.end]) return cur_label
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def current_label_start(self): if self.current_label and self.message: return self.message.get_label_range(self.current_label, self.proto_view, False)[0] else: return -1
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def current_label_end(self): if self.current_label and self.message: return self.message.get_label_range(self.current_label, self.proto_view, False)[1] else: return -1
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]
def message_data(self): if self.proto_view == 0: return self.message.plain_bits_str elif self.proto_view == 1: return self.message.plain_hex_str elif self.proto_view == 2: return self.message.plain_ascii_str else: return None
jopohl/urh
[ 9230, 807, 9230, 35, 1459539787 ]