function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def __init__(self, *sentences):
"""Create a new `Paragraph` with zero or more `sentences`.
:param sentences: document sections (`RhetRel` or `Element` type)
"""
self._sentences = [promote_to_string(s) for s in sentences] | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __hash__(self):
return hash(str(self)) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __str__(self):
return ' '.join([str(s) for s in self.sentences]).strip() | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def sentences(self):
return self._sentences | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def sentences(self, *sentences):
self._sentences = [promote_to_string(s) for s in sentences] | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def to_xml(self, depth=0, indent=' '):
"""Return an XML representation of the document"
:param depth: the initial indentation offset (depth * indent)
:param indent: the indent for nested elements.
"""
offset = indent * depth
result = offset + '<paragraph>\n'
result += offset + indent + '<sentences>\n'
for s in self.sentences:
result += s.to_xml(depth=depth + 1)
result += offset + indent + '</sentences>\n'
result += offset + '</paragraph>\n'
return result | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(
self,
relation,
*nuclei,
satellite=None,
features=None,
marker=None,
last_element_marker=None | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __repr__(self):
elements = ' '.join(repr(x) for x in self.order)
return '<RhetRel ({}): {}>'.format(self.relation, elements) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __eq__(self, other):
return (
other.category == self.category and self.relation == other.relation and
self.nuclei == other.nuclei and self.satellite == other.satellite and
self.marker == other.marker
) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def nucleus(self):
return self.nuclei[0] | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def to_xml(self, lvl=0, indent=' '):
spaces = indent * lvl
data = spaces + '<RhetRel name="' + self.relation + '">\n'
data += indent + spaces + '<marker>' + self.marker + '</marker>\n'
data += indent + spaces + '<nuclei>\n'
data += indent * 2 + spaces + '<nucleus>\n'
for n in self.nuclei:
data += n.to_xml(lvl + 3) + '\n'
data += indent * 2 + spaces + '</nucleus>\n'
data += indent * 2 + spaces + '<satellite>\n'
data += self.satellite.to_xml(lvl + 3)
data += indent * 2 + spaces + '</satellite>\n'
data += spaces + '</RhetRel>\n'
return data | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self, name, features=None):
self.name = name
self.features = features or {} | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __str__(self):
return str(self.name) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def id(self):
return self.name | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def accept(self, visitor, element='Element'):
"""Implementation of the Visitor pattern."""
visitor_name = 'visit_' + self.category.lower()
# get the appropriate method of the visitor instance
m = getattr(visitor, visitor_name)
# ensure that the method is callable
if not hasattr(m, '__call__'):
msg = 'Error: cannot call undefined method: %s on visitor'
raise ValueError(msg % visitor_name)
sig = inspect.signature(m)
# and finally call the callback
if len(sig.parameters) == 1:
return m(self)
if len(sig.parameters) == 2:
return m(self, element) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self, text):
super().__init__('string_message_spec')
self.text = str(text) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def value_for(self, _):
return String(self.text) | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self, pred, *arguments, features=None):
"""Representation of a predicate. | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __str__(self):
""" Return a suitable string representation. """
if len(self.args) == 0:
return self.name
else:
return self.name + '(' + ', '.join([str(x) for x in self.args]) + ')' | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def value_for(self, key):
"""Return a replacement for a var with argument number or key. | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self):
self.referents = []
self.history = []
self.referent_info = {} | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self):
self.variables = []
self.symbols = []
self.negations = 0 | roman-kutlak/nlglib | [
45,
18,
45,
3,
1444561978
] |
def __init__(self, *args, **kwargs):
super(SilenceableStreamHandler, self).__init__(*args, **kwargs)
self.silenced = False | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def __init__(self, *args, **kwargs):
super(SilenceableFileHandler, self).__init__(*args, **kwargs)
self.silenced = False | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def __init__(self):
self._loggers = {}
self._verbosity = {}
self._filename = None | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def set_verbosity(self, mid, value):
"""Sets the verbosity.
Turn logging on/off for logger identified by `mid`.
Parameters
----------
mid : str
The module id of the logger to change the verbosity of.
value : bool
Whether to turn the verbosity on or off.
"""
handlers = self._loggers[mid].handlers
for hdl in handlers:
hdl.silenced = value | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def add_handler(self, mid, htype=LOG_TYPE_STREAM, hlevel=LOG_INFO, fmt=None, filename=None):
"""Add a handler to the logger.
Parameters
----------
mid : str
The module id of the logger
htype : int, optional
The logging type to add to the handler. Default is LOG_TYPE_STREAM.
hlevel : int, optional
The logging level. Default is LOG_INFO.
fmt : str, optional
The format in which the information is presented.
Default is "[%(levelname)-8s ] %(name)s: %(funcName)s: %(message)s"
filename : str, optional
The name of the file the file handler writes the logs to.
Default is a generated filename.
"""
if fmt is None:
fmt = "[%(levelname)-8s ] %(name)s: %(funcName)s: %(message)s"
formatter = logging.Formatter(fmt)
if htype == self.LOG_TYPE_STREAM or htype == self.LOG_TYPE_ALL:
handler = SilenceableStreamHandler()
self._add_handler(mid, hlevel, handler, formatter)
if htype == self.LOG_TYPE_FILE or htype == self.LOG_TYPE_ALL:
if self._filename is None:
if not os.path.exists("logs"):
os.makedirs("logs")
dt = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
self._filename = "logs\logfile " + dt + ".log"
filename = filename if filename is not None else self._filename
handler = SilenceableFileHandler(filename)
self._add_handler(mid, hlevel, handler, formatter) | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def change_level(self, mid, hlevel, htype=LOG_TYPE_ALL):
"""Set the log level for a handler.
Parameters
----------
mid : str
The module id of the logger
hlevel : int
The logging level.
htype : int, optional
The logging type of handler for which to change the
log level. Default is LOG_TYPE_ALL.
"""
handlers = self._loggers[mid].handlers
if hlevel < self._loggers[mid].level:
self._loggers[mid].level = hlevel
for hdl in handlers:
if htype == self.LOG_TYPE_ALL:
hdl.level = hlevel
elif htype == self.LOG_TYPE_FILE and isinstance(hdl, logging.FileHandler):
hdl.level = hlevel
elif htype == self.LOG_TYPE_STREAM and isinstance(hdl, logging.StreamHandler):
hdl.level = hlevel | evenmarbles/mlpy | [
7,
2,
7,
2,
1439328535
] |
def __init__(self, board, coord):
self.board = board
self.coord = coord
self.left = (board.squareSize + board.innerSize)*coord.col
self.xMiddle = self.left + int(board.squareSize/2)
self.right = self.left + board.squareSize
self.top = (board.squareSize + board.innerSize)*coord.row
self.yMiddle = self.top + int(board.squareSize/2)
self.bottom = self.top + board.squareSize
self.topLeft = Point(self.left, self.top)
self.topRight = Point(self.right, self.top)
self.bottomLeft = Point(self.left, self.bottom)
self.bottomRight = Point(self.right, self.bottom)
self.middle = Point(self.xMiddle, self.yMiddle) | alainrinder/quoridor.py | [
10,
7,
10,
3,
1496351378
] |
def update_deps(post, lang, task):
"""Update file dependencies as they might have been updated during compilation.
This is done for example by the ReST page compiler, which writes its
dependencies into a .dep file. This file is read and incorporated when calling
post.fragment_deps(), and only available /after/ compiling the fragment.
"""
task.file_dep.update([p for p in post.fragment_deps(lang) if not p.startswith("####MAGIC####")]) | getnikola/nikola | [
2410,
439,
2410,
52,
1334411602
] |
def gen_tasks(self):
"""Build HTML fragments from metadata and text."""
self.site.scan_posts()
kw = {
"translations": self.site.config["TRANSLATIONS"],
"timeline": self.site.timeline,
"default_lang": self.site.config["DEFAULT_LANG"],
"show_untranslated_posts": self.site.config['SHOW_UNTRANSLATED_POSTS'],
"demote_headers": self.site.config['DEMOTE_HEADERS'],
}
self.tl_changed = False
yield self.group_task()
def tl_ch():
self.tl_changed = True
yield {
'basename': self.name,
'name': 'timeline_changes',
'actions': [tl_ch],
'uptodate': [utils.config_changed({1: kw['timeline']})],
}
for lang in kw["translations"]:
deps_dict = copy(kw)
deps_dict.pop('timeline')
for post in kw['timeline']:
if not post.is_translation_available(lang) and not self.site.config['SHOW_UNTRANSLATED_POSTS']:
continue
# Extra config dependencies picked from config
for p in post.fragment_deps(lang):
if p.startswith('####MAGIC####CONFIG:'):
k = p.split('####MAGIC####CONFIG:', 1)[-1]
deps_dict[k] = self.site.config.get(k)
dest = post.translated_base_path(lang)
file_dep = [p for p in post.fragment_deps(lang) if not p.startswith("####MAGIC####")]
extra_targets = post.compiler.get_extra_targets(post, lang, dest)
task = {
'basename': self.name,
'name': dest,
'file_dep': file_dep,
'targets': [dest] + extra_targets,
'actions': [(post.compile, (lang, )),
(update_deps, (post, lang, )),
],
'clean': True,
'uptodate': [
utils.config_changed(deps_dict, 'nikola.plugins.task.posts'),
lambda p=post, l=lang: self.dependence_on_timeline(p, l)
] + post.fragment_deps_uptodate(lang),
'task_dep': ['render_posts:timeline_changes']
}
# Apply filters specified in the metadata
ff = [x.strip() for x in post.meta('filters', lang).split(',')]
flist = []
for i, f in enumerate(ff):
if not f:
continue
_f = self.site.filters.get(f)
if _f is not None: # A registered filter
flist.append(_f)
else:
flist.append(f)
yield utils.apply_filters(task, {os.path.splitext(dest)[-1]: flist}) | getnikola/nikola | [
2410,
439,
2410,
52,
1334411602
] |
def __init__(self):
self._roles = {}
self._resources = {}
self._allowed = {}
self._denied = {}
# to allow additional short circuiting, track roles that only
# ever deny access
self._denial_only_roles = set()
self._children = {} | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def add_resource(self, resource, parents=[]):
"""Add a resource or append parents resources to a special resource.
All added resources should be hashable.
(http://docs.python.org/glossary.html#term-hashable)
"""
self._resources.setdefault(resource, set())
self._resources[resource].update(parents) | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def deny(self, role, operation, resource, assertion=None):
"""Add a denied rule.
The added rule will deny the role and its all children roles to
operate the resource.
"""
assert not role or role in self._roles
assert not resource or resource in self._resources
self._denied[role, operation, resource] = assertion | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def DefaultAssertion(*args, **kwargs):
return True | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def is_any_allowed(self, roles, operation, resource, **assertion_kwargs):
"""Check the permission with many roles."""
is_allowed = None # no matching rules
for i, role in enumerate(roles):
# if access not yet allowed and all remaining roles could
# only deny access, short-circuit and return False
if not is_allowed and self._roles_are_deny_only(roles[i:]):
return False
check_allowed = not is_allowed
# if another role gave access,
# don't bother checking if this one is allowed
is_current_allowed = self.is_allowed(role, operation, resource,
check_allowed=check_allowed,
**assertion_kwargs)
if is_current_allowed is False:
return False # denied by rule
elif is_current_allowed is True:
is_allowed = True
return is_allowed | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def get_family(all_parents, current):
"""Iterate current object and its all parents recursively."""
yield current
for parent in get_parents(all_parents, current):
yield parent
yield None | tonyseek/simple-rbac | [
268,
66,
268,
4,
1336538333
] |
def test_pickle_dumps():
data = {"hello": "world", "test": 123}
expected = [
b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.",
b"\x80\x04\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x04test\x94K{\x8c\x05hello\x94\x8c\x05world\x94u.",
b"\x80\x02}q\x00(X\x04\x00\x00\x00testq\x01K{X\x05\x00\x00\x00helloq\x02X\x05\x00\x00\x00worldq\x03u.",
b"\x80\x05\x95\x1e\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\x05hello\x94\x8c\x05world\x94\x8c\x04test\x94K{u.",
]
msg = pickle_dumps(data)
assert msg in expected | explosion/srsly | [
345,
29,
345,
1,
1543634516
] |
def writeFile(file, content):
"""Writes a file at given location | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def delete_file(file):
os.remove(file) | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def getUniqueId(length=5):
return str(uuid.uuid1()).replace('-', '')[:length] | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def getKey(item):
return item[0] | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def fetchUrlsFromSitemap(url, limit=None):
"""Given a URL of a sitemap or sitemapindex the contained URLs are returned as a list with tuples. Optional to limit the age of URLs. | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def fetchUrlsFromPage(url, num_limit=None, local_only=True):
"""Given a URL contained URLs are returned as a list with tuples. Optional to number of URLs and if to only include URLs within the local website. | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def getGzipedContentFromUrl(url):
"""
Fetching a gziped file from Internet, unpacks it and returns its contents.
"""
unique_id = getUniqueId(5)
file_name = 'tmp/file-{0}.gz'.format(unique_id) | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def httpRequestGetContent(url):
"""Trying to fetch the response content
Attributes: url, as for the URL to fetch
"""
if '.gz' in url or '.gzip' in url:
# the url indicates that it is compressed using Gzip
return getGzipedContentFromUrl(url) | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def is_sitemap(content):
"""Check a string to see if its content is a sitemap or siteindex. | Vastra-Gotalandsregionen/verifierad.nu | [
6,
1,
6,
8,
1485536132
] |
def __init__(self, client):
self.client = client | andreagrandi/toshl-python | [
4,
4,
4,
4,
1459807911
] |
def setUp(self):
self.url = "http://importpython.com/newsletter/no/60/"
test_fixture = 'fixture_test_import_importpython_test_get_blocks.txt'
self.patcher = patch(
'digest.management.commands.import_importpython.urlopen')
self.urlopen_mock = self.patcher.start()
self.urlopen_mock.return_value = MockResponse(
read_fixture(test_fixture))
self.parser = ImportPythonParser() | pythondigest/pythondigest | [
150,
52,
150,
36,
1382697520
] |
def test_correctly_creates_issue_urls(self):
self.assertEqual(ImportPythonParser.get_issue_url(2),
"http://importpython.com/static/files/issue2.html")
self.assertEqual(ImportPythonParser.get_issue_url(12),
"http://importpython.com/newsletter/draft/12")
self.assertEqual(ImportPythonParser.get_issue_url(56),
"http://importpython.com/newsletter/no/56")
with self.assertRaises(ValueError):
ImportPythonParser.get_issue_url(-100) | pythondigest/pythondigest | [
150,
52,
150,
36,
1382697520
] |
def test_correctly_parses_block(self):
blocks = self.parser.get_blocks(self.url)
block = blocks[0]
self.assertEqual(block['link'],
"https://talkpython.fm/episodes/show/44/project-jupyter-and-ipython")
self.assertEqual(block['title'],
"Project Jupyter and IPython Podcast Interview")
self.assertEqual(block['content'],
"One of the fastest growing areas in Python is scientific computing. In scientific computing with Python, there are a few key packages that make it special. These include NumPy / SciPy / and related packages. The one that brings it all together, visually, is IPython (now known as Project Jupyter). That's the topic on episode 44 of Talk Python To Me. ") | pythondigest/pythondigest | [
150,
52,
150,
36,
1382697520
] |
def main():
sdk = SDK(APP_KEY, APP_SECRET, SERVER)
platform = sdk.platform()
platform.login(USERNAME, EXTENSION, PASSWORD)
to_numbers = "1234567890"
params = {'from': {'phoneNumber': USERNAME},'to': [{'phoneNumber': to_number}],'text': "SMS message"}
response = platform.post('/restapi/v1.0/account/~/extension/~/sms', params)
print 'Sent SMS: ' + response.json().uri | ringcentral/python-sdk | [
34,
23,
34,
8,
1424395863
] |
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) + six.text_type(timestamp) +
six.text_type(user.username)
) | Datateknologerna-vid-Abo-Akademi/date-website | [
5,
1,
5,
54,
1535991511
] |
def forcecalcx(x, y, d) :
if abs(x) > eps and abs(y) > eps :
x *= 1.0 / d
else :
x = 0.0
return x | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def forcecalcy(x, y, d) :
if abs(x) > eps and abs(y) > eps :
y *= 1.0 / d
else :
y = 0.0
return y | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def project_point_on_line(pt, line):
""" Projects point onto line, needed for compatibility computation """
v0 = line.vertexAt(0)
v1 = line.vertexAt(1)
length = max(line.length(), 10**(-6))
r = ((v0.y() - pt.y()) * (v0.y() - v1.y()) -
(v0.x() - pt.x()) * (v1.x() - v0.x())) / (length**2)
return QgsPoint(v0.x() + r * (v1.x() - v0.x()), v0.y() + r * (v1.y() - v0.y())) | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def __init__(self, edges):
self.S = initial_step_size # Weighting factor (needs to be cached, because will be decreased in every cycle)
self.I = iterations # Number of iterations per cycle (needs to be cached, because will be decreased in every cycle)
self.edges = edges # Edges to bundle in this cluster
self.edge_lengths = [] # Array to cache edge lenghts
self.E = len(edges) # Number of edges
self.EP = 2 # Current number of edge points
self.SP = 0 # Current number of subdivision points
self.compatibility_matrix = np.zeros(shape=(self.E,self.E)) # Compatibility matrix
self.direction_matrix = np.zeros(shape=(self.E,self.E)) # Encodes direction of edge pairs
self.N = (2**cycles ) + 1 # Maximum number of points per edge
self.epm_x = np.zeros(shape=(self.E,self.N)) # Bundles edges (x-values)
self.epm_y = np.zeros(shape=(self.E,self.N)) # Bundles edges (y-values) | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def compute_compatibilty_matrix(self):
"""
Compatibility is stored in a matrix (rows = edges, columns = edges).
Every coordinate in the matrix tells whether the two edges (r,c)/(c,r)
are compatible, or not. The diagonal is always zero, and the other fields
are filled with either -1 (not compatible) or 1 (compatible).
The matrix is symmetric.
"""
edges_as_geom = []
edges_as_vect = []
for e_idx, edge in enumerate(self.edges):
geom = edge.geometry()
edges_as_geom.append(geom)
edges_as_vect.append(QgsVector(geom.vertexAt(1).x() - geom.vertexAt(0).x(),
geom.vertexAt(1).y() - geom.vertexAt(0).y()))
self.edge_lengths.append(edges_as_vect[e_idx].length()) | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def force_directed_eb(self):
""" Force-directed edge bundling """ | dts-ait/qgis-edge-bundling | [
62,
14,
62,
12,
1504520907
] |
def init(app):
app.hooks.connect("pre-arg-parse", add_argparse)
app.hooks.connect("post-arg-parse", post_argparse) | oVirt/imgbased | [
9,
7,
9,
1,
1449779074
] |
def md5_hexdigest(s):
return hashlib.md5(s).hexdigest() | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def __init__(self, req, env, data):
if isinstance(data, dict):
self.__dict__ = data
else:
self.__dict__ = dict(zip(self.columns, data))
self.env = env
self.req = req
if self._empty('version'):
self.version = VERSION
if self._empty('path'):
self.path = ''
self.html = format_to_html(self.req, self.env, self.text)
email = self.email_map().get(self.author, 'baba@baba.net')
self.email_md5 = md5_hexdigest(email)
attachment_info = self.attachment_info()
self.is_comment_to_attachment = 'attachment' == self.type
self.attachment_ticket = attachment_info['ticket']
self.attachment_filename = attachment_info['filename']
self.is_comment_to_changeset = 'changeset' == self.type
self.is_comment_to_file = 'browser' == self.type | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def email_map(self):
if Comment._email_map is None:
Comment._email_map = {}
for username, name, email in self.env.get_known_users():
if email:
Comment._email_map[username] = email
return Comment._email_map | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def href(self):
if self.is_comment_to_file:
href = self.req.href.browser(self.path, rev=self.revision,
codecomment=self.id)
elif self.is_comment_to_changeset:
href = self.req.href.changeset(self.revision, codecomment=self.id)
elif self.is_comment_to_attachment:
href = self.req.href('/attachment/ticket/%d/%s'
% (self.attachment_ticket,
self.attachment_filename),
codecomment=self.id)
if self.line and not self.is_comment_to_changeset:
href += '#L' + str(self.line)
return href | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def changeset_link_text(self):
if 0 != self.line:
return 'Changeset @%s#L%d (in %s)' % (self.revision, self.line,
self.path)
else:
return 'Changeset @%s' % self.revision | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def trac_link(self):
if self.is_comment_to_attachment:
return '[%s %s]' % (self.req.href())
return 'source:' + self.link_text() | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def path_link_tag(self):
return Markup('<a href="%s">%s</a>' % (self.href(), self.link_text())) | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def get_ticket_relations(self):
query = """
SELECT ticket FROM ticket_custom
WHERE name = 'code_comment_relation' AND
(VALUE LIKE '%(comment_id)d' OR
VALUE LIKE '%(comment_id)d,%%' OR
VALUE LIKE '%%,%(comment_id)d' OR
VALUE LIKE '%%,%(comment_id)d,%%')
""" % {'comment_id': self.id}
return set([int(row[0]) for row in self.env.db_query(query)]) | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def delete(self):
self.env.db_transaction("""
DELETE FROM code_comments WHERE id=%s
""", (self.id,)) | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def default(self, o):
if isinstance(o, Comment):
for_json = dict([
(name, getattr(o, name))
for name in o.__dict__
if isinstance(getattr(o, name), (basestring, int, list, dict))
])
for_json['formatted_date'] = o.formatted_date()
for_json['permalink'] = o.href()
return for_json
else:
return json.JSONEncoder.default(self, o) | Automattic/trac-code-comments-plugin | [
53,
21,
53,
33,
1321528764
] |
def write_word(addr, data):
global BLEN
temp = data
if BLEN == 1:
temp |= 0x08
else:
temp &= 0xF7
BUS.write_byte(addr ,temp) | sunfounder/SunFounder_Dragit | [
10,
12,
10,
7,
1493782204
] |
def send_data(data):
# Send bit7-4 firstly
buf = data & 0xF0
buf |= 0x05 # RS = 1, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf)
# Send bit3-0 secondly
buf = (data & 0x0F) << 4
buf |= 0x05 # RS = 1, RW = 0, EN = 1
write_word(LCD_ADDR ,buf)
time.sleep(0.002)
buf &= 0xFB # Make EN = 0
write_word(LCD_ADDR ,buf) | sunfounder/SunFounder_Dragit | [
10,
12,
10,
7,
1493782204
] |
def clear():
send_command(0x01) # Clear Screen | sunfounder/SunFounder_Dragit | [
10,
12,
10,
7,
1493782204
] |
def write(x, y, str):
if x < 0:
x = 0
if x > 15:
x = 15
if y <0:
y = 0
if y > 1:
y = 1
# Move cursor
addr = 0x80 + 0x40 * y + x
send_command(addr)
for chr in str:
send_data(ord(chr)) | sunfounder/SunFounder_Dragit | [
10,
12,
10,
7,
1493782204
] |
def authinfo_list(request):
all_authinfo = AuthInfo.objects.all()
results = {
'all_authinfo': all_authinfo,
}
return render(request, 'appconf/authinfo_list.html', results) | guohongze/adminset | [
3103,
1399,
3103,
63,
1489593417
] |
def authinfo_del(request):
authinfo_id = request.GET.get('id', '')
if authinfo_id:
AuthInfo.objects.filter(id=authinfo_id).delete()
authinfo_id_all = str(request.POST.get('authinfo_id_all', ''))
if authinfo_id_all:
for authinfo_id in authinfo_id_all.split(','):
AuthInfo.objects.filter(id=authinfo_id).delete()
return HttpResponseRedirect(reverse('authinfo_list')) | guohongze/adminset | [
3103,
1399,
3103,
63,
1489593417
] |
def authinfo_add(request):
if request.method == 'POST':
form = AuthInfoForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('authinfo_list'))
else:
form = AuthInfoForm()
results = {
'form': form,
'request': request,
'page_type': "whole"
}
return render(request, 'appconf/authinfo_add_edit.html', results) | guohongze/adminset | [
3103,
1399,
3103,
63,
1489593417
] |
def authinfo_add_mini(request):
status = 0
authinfo_id = 0
if request.method == 'POST':
form =AuthInfoForm(request.POST)
if form.is_valid():
form.save()
auth_name = request.POST.get('dis_name', '')
auth_info = AuthInfo.objects.get(dis_name=auth_name)
authinfo_id = auth_info.id
status = 1
else:
status = 2
else:
form = AuthInfoForm()
results = {
'form': form,
'request': request,
'status': status,
'auth_id': authinfo_id,
'auth_name': request.POST.get('dis_name', ''),
'page_type': "mini"
}
return render(request, 'appconf/authinfo_add_edit_mini.html', results) | guohongze/adminset | [
3103,
1399,
3103,
63,
1489593417
] |
def __init__(self, propertiesPane, *args, **kwargs):
self.propertiesPane = propertiesPane | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def UpdateItem(self, item):
pass | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def ItemExpanding(self, item):
pass | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetErrorMessage(self, node):
return '\n'.join( "- %s" % error for error in node.errors.itervalues() ) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def SetItemImage(self, item, image):
self.propertiesPane.tree.SetItemImage(item, self.propertiesPane.TreeImages()[image]) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def SetItemWindow(self, item, itemWindow, modifyWindowFactory = None):
self.propertiesPane.tree.DeleteItemWindow(item)
errorMessage = self.GetErrorMessage(item.xmlNode)
if errorMessage or itemWindow is not None:
itemWindow = ItemWindowWithError(self.propertiesPane.tree, errorMessage, itemWindow, modifyWindowFactory, item.xmlNode)
self.propertiesPane.tree.SetItemWindow(item, itemWindow) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetActualImageName(self, itemImageName):
return self.propertiesPane.ImageListItemNames()[ itemImageName ] | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def UpdateItem(self, item):
if item.xmlChangeCount != item.xmlNode.changeCount:
self.UpdateLocalChanges(item)
item.xmlChangeCount = item.xmlNode.changeCount | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def UpdateLocalChanges(self, item):
pass | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def UpdateLocalChanges(self, item):
if self.propertiesPane.tree.GetItemImage(item) < 0:
self.SetItemImage( item, self.GetItemImage() )
self.propertiesPane.tree.SetItemText( item, self.GetItemText() ) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemImage(self):
return '' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemText(self):
return '' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def CreateModifyWindow(self, parent, node):
return ModifyWindowData( parent, node, self.GetItemText(), self.GetActualImageName( self.GetItemImage() ) ) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def __init__(self, parent, node, nodeName, imageName):
wx.TextCtrl.__init__(self, parent, value = node.GetText(), style = wx.TE_MULTILINE | wx.TE_DONTWRAP)
self.node = node
self.nodeName = nodeName
self.imageName = imageName | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetAction(self):
return ModifyXmlDataAction( self.nodeName, self.imageName, self.node, self.GetValue() ) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemImage(self):
return 'text' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemText(self):
return 'Text' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemImage(self):
return 'comment' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def GetItemText(self):
return 'Comment' | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def UpdateLocalChanges(self, item):
if self.propertiesPane.tree.GetItemImage(item) < 0:
self.SetItemImage(item, 'attribute') | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def CreateModifyWindow(self, parent, node):
return ModifyWindowAttribute( parent, node, self.GetActualImageName('attribute') ) | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
def __init__(self, parent, node, imageName):
wx.TextCtrl.__init__( self, parent, value = node.GetValue() )
self.node = node
self.imageName = imageName | nsmoooose/csp | [
8,
1,
8,
3,
1285610983
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.