id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
250,300 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/runner/action_plugins/pause.py | ActionModule._stop | def _stop(self):
''' calculate the duration we actually paused for and then
finish building the task result string '''
duration = time.time() - self.start
self.result['stop'] = str(datetime.datetime.now())
self.result['delta'] = int(duration)
if self.duration_unit == 'minutes':
duration = round(duration / 60.0, 2)
else:
duration = round(duration, 2)
self.result['stdout'] = "Paused for %s %s" % (duration, self.duration_unit) | python | def _stop(self):
''' calculate the duration we actually paused for and then
finish building the task result string '''
duration = time.time() - self.start
self.result['stop'] = str(datetime.datetime.now())
self.result['delta'] = int(duration)
if self.duration_unit == 'minutes':
duration = round(duration / 60.0, 2)
else:
duration = round(duration, 2)
self.result['stdout'] = "Paused for %s %s" % (duration, self.duration_unit) | [
"def",
"_stop",
"(",
"self",
")",
":",
"duration",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"start",
"self",
".",
"result",
"[",
"'stop'",
"]",
"=",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"self",
".",
"result",
"[",
"'delta'",
"]",
"=",
"int",
"(",
"duration",
")",
"if",
"self",
".",
"duration_unit",
"==",
"'minutes'",
":",
"duration",
"=",
"round",
"(",
"duration",
"/",
"60.0",
",",
"2",
")",
"else",
":",
"duration",
"=",
"round",
"(",
"duration",
",",
"2",
")",
"self",
".",
"result",
"[",
"'stdout'",
"]",
"=",
"\"Paused for %s %s\"",
"%",
"(",
"duration",
",",
"self",
".",
"duration_unit",
")"
] | calculate the duration we actually paused for and then
finish building the task result string | [
"calculate",
"the",
"duration",
"we",
"actually",
"paused",
"for",
"and",
"then",
"finish",
"building",
"the",
"task",
"result",
"string"
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/runner/action_plugins/pause.py#L118-L130 |
250,301 | totokaka/pySpaceGDN | pyspacegdn/response.py | Response.add | def add(self, data, status_code, status_reason):
""" Add data to this response.
This method should be used to add data to the response. The data should
be all the data returned in one page from SpaceGDN.
If this method is called before, data will be appended to the existing
data with `+=`, this means dicts, for instance will not work with
multiple pages.
Arguments:
`data`
The data to add
`status_code`
The HTTP response code of the HTTP response containing the data
`status_reason`
The reason or description for the HTTP response code
"""
self.status_code = status_code
self.status_reason = status_reason
self.success = status_code == 200
if data:
if not self.data:
self.data = data
else:
self.data += data | python | def add(self, data, status_code, status_reason):
""" Add data to this response.
This method should be used to add data to the response. The data should
be all the data returned in one page from SpaceGDN.
If this method is called before, data will be appended to the existing
data with `+=`, this means dicts, for instance will not work with
multiple pages.
Arguments:
`data`
The data to add
`status_code`
The HTTP response code of the HTTP response containing the data
`status_reason`
The reason or description for the HTTP response code
"""
self.status_code = status_code
self.status_reason = status_reason
self.success = status_code == 200
if data:
if not self.data:
self.data = data
else:
self.data += data | [
"def",
"add",
"(",
"self",
",",
"data",
",",
"status_code",
",",
"status_reason",
")",
":",
"self",
".",
"status_code",
"=",
"status_code",
"self",
".",
"status_reason",
"=",
"status_reason",
"self",
".",
"success",
"=",
"status_code",
"==",
"200",
"if",
"data",
":",
"if",
"not",
"self",
".",
"data",
":",
"self",
".",
"data",
"=",
"data",
"else",
":",
"self",
".",
"data",
"+=",
"data"
] | Add data to this response.
This method should be used to add data to the response. The data should
be all the data returned in one page from SpaceGDN.
If this method is called before, data will be appended to the existing
data with `+=`, this means dicts, for instance will not work with
multiple pages.
Arguments:
`data`
The data to add
`status_code`
The HTTP response code of the HTTP response containing the data
`status_reason`
The reason or description for the HTTP response code | [
"Add",
"data",
"to",
"this",
"response",
"."
] | 55c8be8d751e24873e0a7f7e99d2b715442ec878 | https://github.com/totokaka/pySpaceGDN/blob/55c8be8d751e24873e0a7f7e99d2b715442ec878/pyspacegdn/response.py#L50-L78 |
250,302 | dnmellen/pycolorterm | pycolorterm/pycolorterm.py | print_pretty | def print_pretty(text, **kwargs):
'''
Prints using pycolorterm formatting
:param text: Text with formatting
:type text: string
:param kwargs: Keyword args that will be passed to the print function
:type kwargs: dict
Example::
print_pretty('Hello {BG_RED}WORLD{END}')
'''
text = _prepare(text)
print('{}{}'.format(text.format(**styles).replace(styles['END'], styles['ALL_OFF']), styles['ALL_OFF'])) | python | def print_pretty(text, **kwargs):
'''
Prints using pycolorterm formatting
:param text: Text with formatting
:type text: string
:param kwargs: Keyword args that will be passed to the print function
:type kwargs: dict
Example::
print_pretty('Hello {BG_RED}WORLD{END}')
'''
text = _prepare(text)
print('{}{}'.format(text.format(**styles).replace(styles['END'], styles['ALL_OFF']), styles['ALL_OFF'])) | [
"def",
"print_pretty",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"text",
"=",
"_prepare",
"(",
"text",
")",
"print",
"(",
"'{}{}'",
".",
"format",
"(",
"text",
".",
"format",
"(",
"*",
"*",
"styles",
")",
".",
"replace",
"(",
"styles",
"[",
"'END'",
"]",
",",
"styles",
"[",
"'ALL_OFF'",
"]",
")",
",",
"styles",
"[",
"'ALL_OFF'",
"]",
")",
")"
] | Prints using pycolorterm formatting
:param text: Text with formatting
:type text: string
:param kwargs: Keyword args that will be passed to the print function
:type kwargs: dict
Example::
print_pretty('Hello {BG_RED}WORLD{END}') | [
"Prints",
"using",
"pycolorterm",
"formatting"
] | f650eb8dbdce1a283e7b1403be1071b57c4849c6 | https://github.com/dnmellen/pycolorterm/blob/f650eb8dbdce1a283e7b1403be1071b57c4849c6/pycolorterm/pycolorterm.py#L71-L86 |
250,303 | MacHu-GWU/windtalker-project | windtalker/symmetric.py | SymmetricCipher.any_text_to_fernet_key | def any_text_to_fernet_key(self, text):
"""
Convert any text to a fernet key for encryption.
"""
md5 = fingerprint.fingerprint.of_text(text)
fernet_key = base64.b64encode(md5.encode("utf-8"))
return fernet_key | python | def any_text_to_fernet_key(self, text):
"""
Convert any text to a fernet key for encryption.
"""
md5 = fingerprint.fingerprint.of_text(text)
fernet_key = base64.b64encode(md5.encode("utf-8"))
return fernet_key | [
"def",
"any_text_to_fernet_key",
"(",
"self",
",",
"text",
")",
":",
"md5",
"=",
"fingerprint",
".",
"fingerprint",
".",
"of_text",
"(",
"text",
")",
"fernet_key",
"=",
"base64",
".",
"b64encode",
"(",
"md5",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"return",
"fernet_key"
] | Convert any text to a fernet key for encryption. | [
"Convert",
"any",
"text",
"to",
"a",
"fernet",
"key",
"for",
"encryption",
"."
] | 1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce | https://github.com/MacHu-GWU/windtalker-project/blob/1dcff7c3692d5883cf1b55d1ea745723cfc6c3ce/windtalker/symmetric.py#L56-L62 |
250,304 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/path_patterns.py | predecesors_pattern | def predecesors_pattern(element, root):
"""
Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
allow use with ``.extend(predecesors_pattern())``).
"""
def is_root_container(el):
return el.parent.parent.getTagName() == ""
if not element.parent or not element.parent.parent or \
is_root_container(element):
return []
trail = [
[
element.parent.parent.getTagName(),
_params_or_none(element.parent.parent.params)
],
[
element.parent.getTagName(),
_params_or_none(element.parent.params)
],
[element.getTagName(), _params_or_none(element.params)],
]
match = root.match(*trail)
if element in match:
return [
PathCall("match", match.index(element), trail)
] | python | def predecesors_pattern(element, root):
"""
Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
allow use with ``.extend(predecesors_pattern())``).
"""
def is_root_container(el):
return el.parent.parent.getTagName() == ""
if not element.parent or not element.parent.parent or \
is_root_container(element):
return []
trail = [
[
element.parent.parent.getTagName(),
_params_or_none(element.parent.parent.params)
],
[
element.parent.getTagName(),
_params_or_none(element.parent.params)
],
[element.getTagName(), _params_or_none(element.params)],
]
match = root.match(*trail)
if element in match:
return [
PathCall("match", match.index(element), trail)
] | [
"def",
"predecesors_pattern",
"(",
"element",
",",
"root",
")",
":",
"def",
"is_root_container",
"(",
"el",
")",
":",
"return",
"el",
".",
"parent",
".",
"parent",
".",
"getTagName",
"(",
")",
"==",
"\"\"",
"if",
"not",
"element",
".",
"parent",
"or",
"not",
"element",
".",
"parent",
".",
"parent",
"or",
"is_root_container",
"(",
"element",
")",
":",
"return",
"[",
"]",
"trail",
"=",
"[",
"[",
"element",
".",
"parent",
".",
"parent",
".",
"getTagName",
"(",
")",
",",
"_params_or_none",
"(",
"element",
".",
"parent",
".",
"parent",
".",
"params",
")",
"]",
",",
"[",
"element",
".",
"parent",
".",
"getTagName",
"(",
")",
",",
"_params_or_none",
"(",
"element",
".",
"parent",
".",
"params",
")",
"]",
",",
"[",
"element",
".",
"getTagName",
"(",
")",
",",
"_params_or_none",
"(",
"element",
".",
"params",
")",
"]",
",",
"]",
"match",
"=",
"root",
".",
"match",
"(",
"*",
"trail",
")",
"if",
"element",
"in",
"match",
":",
"return",
"[",
"PathCall",
"(",
"\"match\"",
",",
"match",
".",
"index",
"(",
"element",
")",
",",
"trail",
")",
"]"
] | Look for `element` by its predecesors.
Args:
element (obj): HTMLElement instance of the object you are looking for.
root (obj): Root of the `DOM`.
Returns:
list: ``[PathCall()]`` - list with one :class:`PathCall` object (to \
allow use with ``.extend(predecesors_pattern())``). | [
"Look",
"for",
"element",
"by",
"its",
"predecesors",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/path_patterns.py#L158-L193 |
250,305 | NAMD/pypln.api | pypln/api.py | Corpus.add_document | def add_document(self, document):
'''
Add a document to this corpus
`document' is passed to `requests.post', so it can be a file-like
object, a string (that will be sent as the file content) or a tuple
containing a filename followed by any of these two options.
'''
documents_url = urljoin(self.base_url, self.DOCUMENTS_PAGE)
data = {"corpus": self.url}
files = {"blob": document}
result = self.session.post(documents_url, data=data, files=files)
if result.status_code == 201:
return Document(session=self.session, **result.json())
else:
raise RuntimeError("Document creation failed with status "
"{}. The response was: '{}'".format(result.status_code,
result.text)) | python | def add_document(self, document):
'''
Add a document to this corpus
`document' is passed to `requests.post', so it can be a file-like
object, a string (that will be sent as the file content) or a tuple
containing a filename followed by any of these two options.
'''
documents_url = urljoin(self.base_url, self.DOCUMENTS_PAGE)
data = {"corpus": self.url}
files = {"blob": document}
result = self.session.post(documents_url, data=data, files=files)
if result.status_code == 201:
return Document(session=self.session, **result.json())
else:
raise RuntimeError("Document creation failed with status "
"{}. The response was: '{}'".format(result.status_code,
result.text)) | [
"def",
"add_document",
"(",
"self",
",",
"document",
")",
":",
"documents_url",
"=",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"DOCUMENTS_PAGE",
")",
"data",
"=",
"{",
"\"corpus\"",
":",
"self",
".",
"url",
"}",
"files",
"=",
"{",
"\"blob\"",
":",
"document",
"}",
"result",
"=",
"self",
".",
"session",
".",
"post",
"(",
"documents_url",
",",
"data",
"=",
"data",
",",
"files",
"=",
"files",
")",
"if",
"result",
".",
"status_code",
"==",
"201",
":",
"return",
"Document",
"(",
"session",
"=",
"self",
".",
"session",
",",
"*",
"*",
"result",
".",
"json",
"(",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Document creation failed with status \"",
"\"{}. The response was: '{}'\"",
".",
"format",
"(",
"result",
".",
"status_code",
",",
"result",
".",
"text",
")",
")"
] | Add a document to this corpus
`document' is passed to `requests.post', so it can be a file-like
object, a string (that will be sent as the file content) or a tuple
containing a filename followed by any of these two options. | [
"Add",
"a",
"document",
"to",
"this",
"corpus"
] | ccb73fd80ca094669a85bd3991dc84a8564ab016 | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L175-L193 |
250,306 | NAMD/pypln.api | pypln/api.py | Corpus.add_documents | def add_documents(self, documents):
'''
Adds more than one document using the same API call
Returns two lists: the first one contains the successfully uploaded
documents, and the second one tuples with documents that failed to be
uploaded and the exceptions raised.
'''
result, errors = [], []
for document in documents:
try:
result.append(self.add_document(document))
except RuntimeError as exc:
errors.append((document, exc))
return result, errors | python | def add_documents(self, documents):
'''
Adds more than one document using the same API call
Returns two lists: the first one contains the successfully uploaded
documents, and the second one tuples with documents that failed to be
uploaded and the exceptions raised.
'''
result, errors = [], []
for document in documents:
try:
result.append(self.add_document(document))
except RuntimeError as exc:
errors.append((document, exc))
return result, errors | [
"def",
"add_documents",
"(",
"self",
",",
"documents",
")",
":",
"result",
",",
"errors",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"document",
"in",
"documents",
":",
"try",
":",
"result",
".",
"append",
"(",
"self",
".",
"add_document",
"(",
"document",
")",
")",
"except",
"RuntimeError",
"as",
"exc",
":",
"errors",
".",
"append",
"(",
"(",
"document",
",",
"exc",
")",
")",
"return",
"result",
",",
"errors"
] | Adds more than one document using the same API call
Returns two lists: the first one contains the successfully uploaded
documents, and the second one tuples with documents that failed to be
uploaded and the exceptions raised. | [
"Adds",
"more",
"than",
"one",
"document",
"using",
"the",
"same",
"API",
"call"
] | ccb73fd80ca094669a85bd3991dc84a8564ab016 | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L195-L210 |
250,307 | NAMD/pypln.api | pypln/api.py | PyPLN.add_corpus | def add_corpus(self, name, description):
'''Add a corpus to your account'''
corpora_url = self.base_url + self.CORPORA_PAGE
data = {'name': name, 'description': description}
result = self.session.post(corpora_url, data=data)
if result.status_code == 201:
return Corpus(session=self.session, **result.json())
else:
raise RuntimeError("Corpus creation failed with status "
"{}. The response was: '{}'".format(result.status_code,
result.text)) | python | def add_corpus(self, name, description):
'''Add a corpus to your account'''
corpora_url = self.base_url + self.CORPORA_PAGE
data = {'name': name, 'description': description}
result = self.session.post(corpora_url, data=data)
if result.status_code == 201:
return Corpus(session=self.session, **result.json())
else:
raise RuntimeError("Corpus creation failed with status "
"{}. The response was: '{}'".format(result.status_code,
result.text)) | [
"def",
"add_corpus",
"(",
"self",
",",
"name",
",",
"description",
")",
":",
"corpora_url",
"=",
"self",
".",
"base_url",
"+",
"self",
".",
"CORPORA_PAGE",
"data",
"=",
"{",
"'name'",
":",
"name",
",",
"'description'",
":",
"description",
"}",
"result",
"=",
"self",
".",
"session",
".",
"post",
"(",
"corpora_url",
",",
"data",
"=",
"data",
")",
"if",
"result",
".",
"status_code",
"==",
"201",
":",
"return",
"Corpus",
"(",
"session",
"=",
"self",
".",
"session",
",",
"*",
"*",
"result",
".",
"json",
"(",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Corpus creation failed with status \"",
"\"{}. The response was: '{}'\"",
".",
"format",
"(",
"result",
".",
"status_code",
",",
"result",
".",
"text",
")",
")"
] | Add a corpus to your account | [
"Add",
"a",
"corpus",
"to",
"your",
"account"
] | ccb73fd80ca094669a85bd3991dc84a8564ab016 | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L227-L237 |
250,308 | NAMD/pypln.api | pypln/api.py | PyPLN.corpora | def corpora(self, full=False):
'''Return list of corpora owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.CORPORA_PAGE
class_ = Corpus
results = self._retrieve_resources(url, class_, full)
return results | python | def corpora(self, full=False):
'''Return list of corpora owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.CORPORA_PAGE
class_ = Corpus
results = self._retrieve_resources(url, class_, full)
return results | [
"def",
"corpora",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"self",
".",
"CORPORA_PAGE",
"class_",
"=",
"Corpus",
"results",
"=",
"self",
".",
"_retrieve_resources",
"(",
"url",
",",
"class_",
",",
"full",
")",
"return",
"results"
] | Return list of corpora owned by user.
If `full=True`, it'll download all pages returned by the HTTP server | [
"Return",
"list",
"of",
"corpora",
"owned",
"by",
"user",
"."
] | ccb73fd80ca094669a85bd3991dc84a8564ab016 | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L266-L273 |
250,309 | NAMD/pypln.api | pypln/api.py | PyPLN.documents | def documents(self, full=False):
'''Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.DOCUMENTS_PAGE
class_ = Document
results = self._retrieve_resources(url, class_, full)
return results | python | def documents(self, full=False):
'''Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.DOCUMENTS_PAGE
class_ = Document
results = self._retrieve_resources(url, class_, full)
return results | [
"def",
"documents",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"self",
".",
"DOCUMENTS_PAGE",
"class_",
"=",
"Document",
"results",
"=",
"self",
".",
"_retrieve_resources",
"(",
"url",
",",
"class_",
",",
"full",
")",
"return",
"results"
] | Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server | [
"Return",
"list",
"of",
"documents",
"owned",
"by",
"user",
"."
] | ccb73fd80ca094669a85bd3991dc84a8564ab016 | https://github.com/NAMD/pypln.api/blob/ccb73fd80ca094669a85bd3991dc84a8564ab016/pypln/api.py#L275-L282 |
250,310 | jkenlooper/chill | src/chill/database.py | insert_node | def insert_node(**kw):
"Insert a node with a name and optional value. Return the node id."
with current_app.app_context():
result = db.execute(text(fetch_query_string('insert_node.sql')), **kw)
# TODO: support for postgres may require using a RETURNING id; sql
# statement and using the inserted_primary_key?
#node_id = result.inserted_primary_key
node_id = result.lastrowid
if (not node_id):
result = result.fetchall()
node_id = result[0]['id']
return node_id | python | def insert_node(**kw):
"Insert a node with a name and optional value. Return the node id."
with current_app.app_context():
result = db.execute(text(fetch_query_string('insert_node.sql')), **kw)
# TODO: support for postgres may require using a RETURNING id; sql
# statement and using the inserted_primary_key?
#node_id = result.inserted_primary_key
node_id = result.lastrowid
if (not node_id):
result = result.fetchall()
node_id = result[0]['id']
return node_id | [
"def",
"insert_node",
"(",
"*",
"*",
"kw",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'insert_node.sql'",
")",
")",
",",
"*",
"*",
"kw",
")",
"# TODO: support for postgres may require using a RETURNING id; sql",
"# statement and using the inserted_primary_key?",
"#node_id = result.inserted_primary_key",
"node_id",
"=",
"result",
".",
"lastrowid",
"if",
"(",
"not",
"node_id",
")",
":",
"result",
"=",
"result",
".",
"fetchall",
"(",
")",
"node_id",
"=",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]",
"return",
"node_id"
] | Insert a node with a name and optional value. Return the node id. | [
"Insert",
"a",
"node",
"with",
"a",
"name",
"and",
"optional",
"value",
".",
"Return",
"the",
"node",
"id",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L60-L71 |
250,311 | jkenlooper/chill | src/chill/database.py | insert_node_node | def insert_node_node(**kw):
"""
Link a node to another node. node_id -> target_node_id. Where `node_id` is
the parent and `target_node_id` is the child.
"""
with current_app.app_context():
insert_query(name='select_link_node_from_node.sql', node_id=kw.get('node_id'))
db.execute(text(fetch_query_string('insert_node_node.sql')), **kw) | python | def insert_node_node(**kw):
"""
Link a node to another node. node_id -> target_node_id. Where `node_id` is
the parent and `target_node_id` is the child.
"""
with current_app.app_context():
insert_query(name='select_link_node_from_node.sql', node_id=kw.get('node_id'))
db.execute(text(fetch_query_string('insert_node_node.sql')), **kw) | [
"def",
"insert_node_node",
"(",
"*",
"*",
"kw",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"insert_query",
"(",
"name",
"=",
"'select_link_node_from_node.sql'",
",",
"node_id",
"=",
"kw",
".",
"get",
"(",
"'node_id'",
")",
")",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'insert_node_node.sql'",
")",
")",
",",
"*",
"*",
"kw",
")"
] | Link a node to another node. node_id -> target_node_id. Where `node_id` is
the parent and `target_node_id` is the child. | [
"Link",
"a",
"node",
"to",
"another",
"node",
".",
"node_id",
"-",
">",
"target_node_id",
".",
"Where",
"node_id",
"is",
"the",
"parent",
"and",
"target_node_id",
"is",
"the",
"child",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L73-L80 |
250,312 | jkenlooper/chill | src/chill/database.py | select_node | def select_node(**kw):
"""
Select node by id.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_node_from_id.sql')), **kw).fetchall()
return result | python | def select_node(**kw):
"""
Select node by id.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_node_from_id.sql')), **kw).fetchall()
return result | [
"def",
"select_node",
"(",
"*",
"*",
"kw",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'select_node_from_id.sql'",
")",
")",
",",
"*",
"*",
"kw",
")",
".",
"fetchall",
"(",
")",
"return",
"result"
] | Select node by id. | [
"Select",
"node",
"by",
"id",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L89-L95 |
250,313 | jkenlooper/chill | src/chill/database.py | add_template_for_node | def add_template_for_node(name, node_id):
"Set the template to use to display the node"
with current_app.app_context():
db.execute(text(fetch_query_string('insert_template.sql')),
name=name, node_id=node_id)
result = db.execute(text(fetch_query_string('select_template.sql')),
name=name, node_id=node_id).fetchall()
if result:
template_id = result[0]['id']
db.execute(text(fetch_query_string('update_template_node.sql')),
template=template_id, node_id=node_id) | python | def add_template_for_node(name, node_id):
"Set the template to use to display the node"
with current_app.app_context():
db.execute(text(fetch_query_string('insert_template.sql')),
name=name, node_id=node_id)
result = db.execute(text(fetch_query_string('select_template.sql')),
name=name, node_id=node_id).fetchall()
if result:
template_id = result[0]['id']
db.execute(text(fetch_query_string('update_template_node.sql')),
template=template_id, node_id=node_id) | [
"def",
"add_template_for_node",
"(",
"name",
",",
"node_id",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'insert_template.sql'",
")",
")",
",",
"name",
"=",
"name",
",",
"node_id",
"=",
"node_id",
")",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'select_template.sql'",
")",
")",
",",
"name",
"=",
"name",
",",
"node_id",
"=",
"node_id",
")",
".",
"fetchall",
"(",
")",
"if",
"result",
":",
"template_id",
"=",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'update_template_node.sql'",
")",
")",
",",
"template",
"=",
"template_id",
",",
"node_id",
"=",
"node_id",
")"
] | Set the template to use to display the node | [
"Set",
"the",
"template",
"to",
"use",
"to",
"display",
"the",
"node"
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L114-L124 |
250,314 | jkenlooper/chill | src/chill/database.py | insert_query | def insert_query(**kw):
"""
Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_query_where_name.sql')), **kw).fetchall()
if result:
kw['query_id'] = result[0]['id']
else:
result = db.execute(text(fetch_query_string('insert_query.sql')), **kw)
kw['query_id'] = result.lastrowid
if (not kw['query_id']):
result = result.fetchall()
kw['query_id'] = result[0]['id']
db.execute(text(fetch_query_string('insert_query_node.sql')), **kw) | python | def insert_query(**kw):
"""
Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table.
"""
with current_app.app_context():
result = db.execute(text(fetch_query_string('select_query_where_name.sql')), **kw).fetchall()
if result:
kw['query_id'] = result[0]['id']
else:
result = db.execute(text(fetch_query_string('insert_query.sql')), **kw)
kw['query_id'] = result.lastrowid
if (not kw['query_id']):
result = result.fetchall()
kw['query_id'] = result[0]['id']
db.execute(text(fetch_query_string('insert_query_node.sql')), **kw) | [
"def",
"insert_query",
"(",
"*",
"*",
"kw",
")",
":",
"with",
"current_app",
".",
"app_context",
"(",
")",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'select_query_where_name.sql'",
")",
")",
",",
"*",
"*",
"kw",
")",
".",
"fetchall",
"(",
")",
"if",
"result",
":",
"kw",
"[",
"'query_id'",
"]",
"=",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]",
"else",
":",
"result",
"=",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'insert_query.sql'",
")",
")",
",",
"*",
"*",
"kw",
")",
"kw",
"[",
"'query_id'",
"]",
"=",
"result",
".",
"lastrowid",
"if",
"(",
"not",
"kw",
"[",
"'query_id'",
"]",
")",
":",
"result",
"=",
"result",
".",
"fetchall",
"(",
")",
"kw",
"[",
"'query_id'",
"]",
"=",
"result",
"[",
"0",
"]",
"[",
"'id'",
"]",
"db",
".",
"execute",
"(",
"text",
"(",
"fetch_query_string",
"(",
"'insert_query_node.sql'",
")",
")",
",",
"*",
"*",
"kw",
")"
] | Insert a query name for a node_id.
`name`
`node_id`
Adds the name to the Query table if not already there. Sets the query field
in Node table. | [
"Insert",
"a",
"query",
"name",
"for",
"a",
"node_id",
".",
"name",
"node_id"
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/database.py#L127-L146 |
250,315 | uw-it-aca/uw-restclients-libraries | uw_libraries/subject_guides.py | get_subject_guide_for_section | def get_subject_guide_for_section(section):
"""
Returns a SubjectGuide model for the passed SWS section model.
"""
return get_subject_guide_for_section_params(
section.term.year, section.term.quarter, section.curriculum_abbr,
section.course_number, section.section_id) | python | def get_subject_guide_for_section(section):
"""
Returns a SubjectGuide model for the passed SWS section model.
"""
return get_subject_guide_for_section_params(
section.term.year, section.term.quarter, section.curriculum_abbr,
section.course_number, section.section_id) | [
"def",
"get_subject_guide_for_section",
"(",
"section",
")",
":",
"return",
"get_subject_guide_for_section_params",
"(",
"section",
".",
"term",
".",
"year",
",",
"section",
".",
"term",
".",
"quarter",
",",
"section",
".",
"curriculum_abbr",
",",
"section",
".",
"course_number",
",",
"section",
".",
"section_id",
")"
] | Returns a SubjectGuide model for the passed SWS section model. | [
"Returns",
"a",
"SubjectGuide",
"model",
"for",
"the",
"passed",
"SWS",
"section",
"model",
"."
] | 2fa2e38be4516d7853c2802e2f23b17fbf4bac3d | https://github.com/uw-it-aca/uw-restclients-libraries/blob/2fa2e38be4516d7853c2802e2f23b17fbf4bac3d/uw_libraries/subject_guides.py#L44-L50 |
250,316 | uw-it-aca/uw-restclients-libraries | uw_libraries/subject_guides.py | get_subject_guide_for_canvas_course_sis_id | def get_subject_guide_for_canvas_course_sis_id(course_sis_id):
"""
Returns a SubjectGuide model for the passed Canvas course SIS ID.
"""
(year, quarter, curriculum_abbr, course_number,
section_id) = course_sis_id.split('-', 4)
return get_subject_guide_for_section_params(
year, quarter, curriculum_abbr, course_number, section_id) | python | def get_subject_guide_for_canvas_course_sis_id(course_sis_id):
"""
Returns a SubjectGuide model for the passed Canvas course SIS ID.
"""
(year, quarter, curriculum_abbr, course_number,
section_id) = course_sis_id.split('-', 4)
return get_subject_guide_for_section_params(
year, quarter, curriculum_abbr, course_number, section_id) | [
"def",
"get_subject_guide_for_canvas_course_sis_id",
"(",
"course_sis_id",
")",
":",
"(",
"year",
",",
"quarter",
",",
"curriculum_abbr",
",",
"course_number",
",",
"section_id",
")",
"=",
"course_sis_id",
".",
"split",
"(",
"'-'",
",",
"4",
")",
"return",
"get_subject_guide_for_section_params",
"(",
"year",
",",
"quarter",
",",
"curriculum_abbr",
",",
"course_number",
",",
"section_id",
")"
] | Returns a SubjectGuide model for the passed Canvas course SIS ID. | [
"Returns",
"a",
"SubjectGuide",
"model",
"for",
"the",
"passed",
"Canvas",
"course",
"SIS",
"ID",
"."
] | 2fa2e38be4516d7853c2802e2f23b17fbf4bac3d | https://github.com/uw-it-aca/uw-restclients-libraries/blob/2fa2e38be4516d7853c2802e2f23b17fbf4bac3d/uw_libraries/subject_guides.py#L53-L60 |
250,317 | FujiMakoto/IPS-Vagrant | ips_vagrant/common/progress.py | Label.update | def update(self, pbar):
"""
Handle progress bar updates
@type pbar: ProgressBar
@rtype: str
"""
if pbar.label != self._label:
self.label = pbar.label
return self.label | python | def update(self, pbar):
"""
Handle progress bar updates
@type pbar: ProgressBar
@rtype: str
"""
if pbar.label != self._label:
self.label = pbar.label
return self.label | [
"def",
"update",
"(",
"self",
",",
"pbar",
")",
":",
"if",
"pbar",
".",
"label",
"!=",
"self",
".",
"_label",
":",
"self",
".",
"label",
"=",
"pbar",
".",
"label",
"return",
"self",
".",
"label"
] | Handle progress bar updates
@type pbar: ProgressBar
@rtype: str | [
"Handle",
"progress",
"bar",
"updates"
] | 7b1d6d095034dd8befb026d9315ecc6494d52269 | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/progress.py#L88-L97 |
250,318 | FujiMakoto/IPS-Vagrant | ips_vagrant/common/progress.py | Label.label | def label(self, value):
"""
Set the label and generate the formatted value
@type value: str
"""
# Fixed width label formatting
value = value[:self.pad_size] if self.pad_size else value
try:
padding = ' ' * (self.pad_size - len(value)) if self.pad_size else ''
except TypeError:
padding = ''
self._formatted = ' {v}{p} '.format(v=value, p=padding) | python | def label(self, value):
"""
Set the label and generate the formatted value
@type value: str
"""
# Fixed width label formatting
value = value[:self.pad_size] if self.pad_size else value
try:
padding = ' ' * (self.pad_size - len(value)) if self.pad_size else ''
except TypeError:
padding = ''
self._formatted = ' {v}{p} '.format(v=value, p=padding) | [
"def",
"label",
"(",
"self",
",",
"value",
")",
":",
"# Fixed width label formatting",
"value",
"=",
"value",
"[",
":",
"self",
".",
"pad_size",
"]",
"if",
"self",
".",
"pad_size",
"else",
"value",
"try",
":",
"padding",
"=",
"' '",
"*",
"(",
"self",
".",
"pad_size",
"-",
"len",
"(",
"value",
")",
")",
"if",
"self",
".",
"pad_size",
"else",
"''",
"except",
"TypeError",
":",
"padding",
"=",
"''",
"self",
".",
"_formatted",
"=",
"' {v}{p} '",
".",
"format",
"(",
"v",
"=",
"value",
",",
"p",
"=",
"padding",
")"
] | Set the label and generate the formatted value
@type value: str | [
"Set",
"the",
"label",
"and",
"generate",
"the",
"formatted",
"value"
] | 7b1d6d095034dd8befb026d9315ecc6494d52269 | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/progress.py#L111-L123 |
250,319 | FujiMakoto/IPS-Vagrant | ips_vagrant/common/progress.py | MarkerProgressBar.finish | def finish(self):
"""
Update widgets on finish
"""
os.system('setterm -cursor on')
if self.nl:
Echo(self.label).done() | python | def finish(self):
"""
Update widgets on finish
"""
os.system('setterm -cursor on')
if self.nl:
Echo(self.label).done() | [
"def",
"finish",
"(",
"self",
")",
":",
"os",
".",
"system",
"(",
"'setterm -cursor on'",
")",
"if",
"self",
".",
"nl",
":",
"Echo",
"(",
"self",
".",
"label",
")",
".",
"done",
"(",
")"
] | Update widgets on finish | [
"Update",
"widgets",
"on",
"finish"
] | 7b1d6d095034dd8befb026d9315ecc6494d52269 | https://github.com/FujiMakoto/IPS-Vagrant/blob/7b1d6d095034dd8befb026d9315ecc6494d52269/ips_vagrant/common/progress.py#L155-L161 |
250,320 | wooyek/django-powerbank | src/django_powerbank/views/mixins.py | ReturnUrlMx.dispatch | def dispatch(self, request, *args, **kwargs):
"""
Does request processing for return_url query parameter and redirects with it's missing
We can't do that in the get method, as it does not exist in the View base class
and child mixins implementing get do not call super().get
"""
self.return_url = request.GET.get('return_url', None)
referrer = request.META.get('HTTP_REFERER', None)
# leave alone POST and ajax requests and if return_url is explicitly left empty
if (request.method != "GET" or
request.is_ajax() or
self.return_url or
referrer is None or
self.return_url is None and 'return_url' in request.GET):
return super().dispatch(request, *args, **kwargs)
if not self.return_url:
url = request.get_full_path()
if url.find("?") < 0:
url = "?return_url=".join((url, referrer))
else:
url = "&return_url=".join((url, referrer))
return HttpResponseRedirect(url) | python | def dispatch(self, request, *args, **kwargs):
"""
Does request processing for return_url query parameter and redirects with it's missing
We can't do that in the get method, as it does not exist in the View base class
and child mixins implementing get do not call super().get
"""
self.return_url = request.GET.get('return_url', None)
referrer = request.META.get('HTTP_REFERER', None)
# leave alone POST and ajax requests and if return_url is explicitly left empty
if (request.method != "GET" or
request.is_ajax() or
self.return_url or
referrer is None or
self.return_url is None and 'return_url' in request.GET):
return super().dispatch(request, *args, **kwargs)
if not self.return_url:
url = request.get_full_path()
if url.find("?") < 0:
url = "?return_url=".join((url, referrer))
else:
url = "&return_url=".join((url, referrer))
return HttpResponseRedirect(url) | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"return_url",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'return_url'",
",",
"None",
")",
"referrer",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_REFERER'",
",",
"None",
")",
"# leave alone POST and ajax requests and if return_url is explicitly left empty",
"if",
"(",
"request",
".",
"method",
"!=",
"\"GET\"",
"or",
"request",
".",
"is_ajax",
"(",
")",
"or",
"self",
".",
"return_url",
"or",
"referrer",
"is",
"None",
"or",
"self",
".",
"return_url",
"is",
"None",
"and",
"'return_url'",
"in",
"request",
".",
"GET",
")",
":",
"return",
"super",
"(",
")",
".",
"dispatch",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"self",
".",
"return_url",
":",
"url",
"=",
"request",
".",
"get_full_path",
"(",
")",
"if",
"url",
".",
"find",
"(",
"\"?\"",
")",
"<",
"0",
":",
"url",
"=",
"\"?return_url=\"",
".",
"join",
"(",
"(",
"url",
",",
"referrer",
")",
")",
"else",
":",
"url",
"=",
"\"&return_url=\"",
".",
"join",
"(",
"(",
"url",
",",
"referrer",
")",
")",
"return",
"HttpResponseRedirect",
"(",
"url",
")"
] | Does request processing for return_url query parameter and redirects with it's missing
We can't do that in the get method, as it does not exist in the View base class
and child mixins implementing get do not call super().get | [
"Does",
"request",
"processing",
"for",
"return_url",
"query",
"parameter",
"and",
"redirects",
"with",
"it",
"s",
"missing"
] | df91189f2ac18bacc545ccf3c81c4465fb993949 | https://github.com/wooyek/django-powerbank/blob/df91189f2ac18bacc545ccf3c81c4465fb993949/src/django_powerbank/views/mixins.py#L25-L50 |
250,321 | opinkerfi/nago | nago/extensions/info.py | get | def get(security_token=None, key=None):
""" Get information about this node """
if security_token is None:
security_token = nago.core.get_my_info()['host_name']
data = node_data.get(security_token, {})
if not key:
return data
else:
return data.get(key) | python | def get(security_token=None, key=None):
""" Get information about this node """
if security_token is None:
security_token = nago.core.get_my_info()['host_name']
data = node_data.get(security_token, {})
if not key:
return data
else:
return data.get(key) | [
"def",
"get",
"(",
"security_token",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"security_token",
"is",
"None",
":",
"security_token",
"=",
"nago",
".",
"core",
".",
"get_my_info",
"(",
")",
"[",
"'host_name'",
"]",
"data",
"=",
"node_data",
".",
"get",
"(",
"security_token",
",",
"{",
"}",
")",
"if",
"not",
"key",
":",
"return",
"data",
"else",
":",
"return",
"data",
".",
"get",
"(",
"key",
")"
] | Get information about this node | [
"Get",
"information",
"about",
"this",
"node"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/info.py#L15-L23 |
250,322 | opinkerfi/nago | nago/extensions/info.py | post | def post(node_name, key, **kwargs):
""" Give the server information about this node
Arguments:
node -- node_name or token for the node this data belongs to
key -- identifiable key, that you use later to retrieve that piece of data
kwargs -- the data you need to store
"""
node = nago.core.get_node(node_name)
if not node:
raise ValueError("Node named %s not found" % node_name)
token = node.token
node_data[token] = node_data[token] or {}
node_data[token][key] = kwargs
return "thanks!" | python | def post(node_name, key, **kwargs):
""" Give the server information about this node
Arguments:
node -- node_name or token for the node this data belongs to
key -- identifiable key, that you use later to retrieve that piece of data
kwargs -- the data you need to store
"""
node = nago.core.get_node(node_name)
if not node:
raise ValueError("Node named %s not found" % node_name)
token = node.token
node_data[token] = node_data[token] or {}
node_data[token][key] = kwargs
return "thanks!" | [
"def",
"post",
"(",
"node_name",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"node_name",
")",
"if",
"not",
"node",
":",
"raise",
"ValueError",
"(",
"\"Node named %s not found\"",
"%",
"node_name",
")",
"token",
"=",
"node",
".",
"token",
"node_data",
"[",
"token",
"]",
"=",
"node_data",
"[",
"token",
"]",
"or",
"{",
"}",
"node_data",
"[",
"token",
"]",
"[",
"key",
"]",
"=",
"kwargs",
"return",
"\"thanks!\""
] | Give the server information about this node
Arguments:
node -- node_name or token for the node this data belongs to
key -- identifiable key, that you use later to retrieve that piece of data
kwargs -- the data you need to store | [
"Give",
"the",
"server",
"information",
"about",
"this",
"node"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/info.py#L33-L47 |
250,323 | opinkerfi/nago | nago/extensions/info.py | send | def send(node_name):
""" Send our information to a remote nago instance
Arguments:
node -- node_name or token for the node this data belongs to
"""
my_data = nago.core.get_my_info()
if not node_name:
node_name = nago.settings.get('server')
node = nago.core.get_node(node_name)
json_params = {}
json_params['node_name'] = node_name
json_params['key'] = "node_info"
for k, v in my_data.items():
nago.core.log("sending %s to %s" % (k, node['host_name']), level="notice")
json_params[k] = v
return node.send_command('info', 'post', node_name=node.token, key="node_info", **my_data) | python | def send(node_name):
""" Send our information to a remote nago instance
Arguments:
node -- node_name or token for the node this data belongs to
"""
my_data = nago.core.get_my_info()
if not node_name:
node_name = nago.settings.get('server')
node = nago.core.get_node(node_name)
json_params = {}
json_params['node_name'] = node_name
json_params['key'] = "node_info"
for k, v in my_data.items():
nago.core.log("sending %s to %s" % (k, node['host_name']), level="notice")
json_params[k] = v
return node.send_command('info', 'post', node_name=node.token, key="node_info", **my_data) | [
"def",
"send",
"(",
"node_name",
")",
":",
"my_data",
"=",
"nago",
".",
"core",
".",
"get_my_info",
"(",
")",
"if",
"not",
"node_name",
":",
"node_name",
"=",
"nago",
".",
"settings",
".",
"get",
"(",
"'server'",
")",
"node",
"=",
"nago",
".",
"core",
".",
"get_node",
"(",
"node_name",
")",
"json_params",
"=",
"{",
"}",
"json_params",
"[",
"'node_name'",
"]",
"=",
"node_name",
"json_params",
"[",
"'key'",
"]",
"=",
"\"node_info\"",
"for",
"k",
",",
"v",
"in",
"my_data",
".",
"items",
"(",
")",
":",
"nago",
".",
"core",
".",
"log",
"(",
"\"sending %s to %s\"",
"%",
"(",
"k",
",",
"node",
"[",
"'host_name'",
"]",
")",
",",
"level",
"=",
"\"notice\"",
")",
"json_params",
"[",
"k",
"]",
"=",
"v",
"return",
"node",
".",
"send_command",
"(",
"'info'",
",",
"'post'",
",",
"node_name",
"=",
"node",
".",
"token",
",",
"key",
"=",
"\"node_info\"",
",",
"*",
"*",
"my_data",
")"
] | Send our information to a remote nago instance
Arguments:
node -- node_name or token for the node this data belongs to | [
"Send",
"our",
"information",
"to",
"a",
"remote",
"nago",
"instance"
] | 85e1bdd1de0122f56868a483e7599e1b36a439b0 | https://github.com/opinkerfi/nago/blob/85e1bdd1de0122f56868a483e7599e1b36a439b0/nago/extensions/info.py#L50-L66 |
250,324 | sandwichcloud/ingredients.tasks | ingredients_tasks/vmware.py | VMWareClient.get_obj | def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned
"""
obj = None
content = self.service_instance.RetrieveContent()
if folder is None:
folder = content.rootFolder
container = content.viewManager.CreateContainerView(folder, [vimtype], True)
for c in container.view:
if c.name == name:
obj = c
break
container.Destroy()
return obj | python | def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned
"""
obj = None
content = self.service_instance.RetrieveContent()
if folder is None:
folder = content.rootFolder
container = content.viewManager.CreateContainerView(folder, [vimtype], True)
for c in container.view:
if c.name == name:
obj = c
break
container.Destroy()
return obj | [
"def",
"get_obj",
"(",
"self",
",",
"vimtype",
",",
"name",
",",
"folder",
"=",
"None",
")",
":",
"obj",
"=",
"None",
"content",
"=",
"self",
".",
"service_instance",
".",
"RetrieveContent",
"(",
")",
"if",
"folder",
"is",
"None",
":",
"folder",
"=",
"content",
".",
"rootFolder",
"container",
"=",
"content",
".",
"viewManager",
".",
"CreateContainerView",
"(",
"folder",
",",
"[",
"vimtype",
"]",
",",
"True",
")",
"for",
"c",
"in",
"container",
".",
"view",
":",
"if",
"c",
".",
"name",
"==",
"name",
":",
"obj",
"=",
"c",
"break",
"container",
".",
"Destroy",
"(",
")",
"return",
"obj"
] | Return an object by name, if name is None the
first found object is returned | [
"Return",
"an",
"object",
"by",
"name",
"if",
"name",
"is",
"None",
"the",
"first",
"found",
"object",
"is",
"returned"
] | 23d2772536f07aa5e4787b7ee67dee2f1faedb08 | https://github.com/sandwichcloud/ingredients.tasks/blob/23d2772536f07aa5e4787b7ee67dee2f1faedb08/ingredients_tasks/vmware.py#L220-L238 |
250,325 | Deathnerd/pyterp | pyterp/__init__.py | Brainfuck._increment_current_byte | def _increment_current_byte(self):
"""
Increments the value of the current byte at the pointer. If the result is over 255,
then it will overflow to 0
"""
# If the current byte is uninitialized, then incrementing it will make it 1
if self.tape[self.pointer] is None:
self.tape[self.pointer] = 1
elif self.tape[self.pointer] == self.MAX_CELL_SIZE: # If the current byte is already at the max, then overflow
self.tape[self.pointer] = self.MIN_CELL_SIZE
else: # increment it
self.tape[self.pointer] += 1 | python | def _increment_current_byte(self):
"""
Increments the value of the current byte at the pointer. If the result is over 255,
then it will overflow to 0
"""
# If the current byte is uninitialized, then incrementing it will make it 1
if self.tape[self.pointer] is None:
self.tape[self.pointer] = 1
elif self.tape[self.pointer] == self.MAX_CELL_SIZE: # If the current byte is already at the max, then overflow
self.tape[self.pointer] = self.MIN_CELL_SIZE
else: # increment it
self.tape[self.pointer] += 1 | [
"def",
"_increment_current_byte",
"(",
"self",
")",
":",
"# If the current byte is uninitialized, then incrementing it will make it 1",
"if",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"is",
"None",
":",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"=",
"1",
"elif",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"==",
"self",
".",
"MAX_CELL_SIZE",
":",
"# If the current byte is already at the max, then overflow",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"=",
"self",
".",
"MIN_CELL_SIZE",
"else",
":",
"# increment it",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"+=",
"1"
] | Increments the value of the current byte at the pointer. If the result is over 255,
then it will overflow to 0 | [
"Increments",
"the",
"value",
"of",
"the",
"current",
"byte",
"at",
"the",
"pointer",
".",
"If",
"the",
"result",
"is",
"over",
"255",
"then",
"it",
"will",
"overflow",
"to",
"0"
] | baf2957263685f03873f368226f5752da4e51f08 | https://github.com/Deathnerd/pyterp/blob/baf2957263685f03873f368226f5752da4e51f08/pyterp/__init__.py#L154-L165 |
250,326 | Deathnerd/pyterp | pyterp/__init__.py | Brainfuck._decrement_current_byte | def _decrement_current_byte(self):
"""
Decrements the value of the current byte at the pointer. If the result is below 0,
then it will overflow to 255
"""
# If the current byte is uninitialized, then decrementing it will make it the max cell size
# Otherwise, if it's already at the minimum cell size, then it will also make it the max cell size
if self.tape[self.pointer] is None or self.tape[self.pointer] == self.MIN_CELL_SIZE:
self.tape[self.pointer] = self.MAX_CELL_SIZE
else: # decrement it
self.tape[self.pointer] -= 1 | python | def _decrement_current_byte(self):
"""
Decrements the value of the current byte at the pointer. If the result is below 0,
then it will overflow to 255
"""
# If the current byte is uninitialized, then decrementing it will make it the max cell size
# Otherwise, if it's already at the minimum cell size, then it will also make it the max cell size
if self.tape[self.pointer] is None or self.tape[self.pointer] == self.MIN_CELL_SIZE:
self.tape[self.pointer] = self.MAX_CELL_SIZE
else: # decrement it
self.tape[self.pointer] -= 1 | [
"def",
"_decrement_current_byte",
"(",
"self",
")",
":",
"# If the current byte is uninitialized, then decrementing it will make it the max cell size",
"# Otherwise, if it's already at the minimum cell size, then it will also make it the max cell size",
"if",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"is",
"None",
"or",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"==",
"self",
".",
"MIN_CELL_SIZE",
":",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"=",
"self",
".",
"MAX_CELL_SIZE",
"else",
":",
"# decrement it",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"-=",
"1"
] | Decrements the value of the current byte at the pointer. If the result is below 0,
then it will overflow to 255 | [
"Decrements",
"the",
"value",
"of",
"the",
"current",
"byte",
"at",
"the",
"pointer",
".",
"If",
"the",
"result",
"is",
"below",
"0",
"then",
"it",
"will",
"overflow",
"to",
"255"
] | baf2957263685f03873f368226f5752da4e51f08 | https://github.com/Deathnerd/pyterp/blob/baf2957263685f03873f368226f5752da4e51f08/pyterp/__init__.py#L167-L177 |
250,327 | Deathnerd/pyterp | pyterp/__init__.py | Brainfuck._output_current_byte | def _output_current_byte(self):
"""
Prints out the ASCII value of the current byte
"""
if self.tape[self.pointer] is None:
print "{}".format(chr(0)),
else:
print "{}".format(chr(int(self.tape[self.pointer]))), | python | def _output_current_byte(self):
"""
Prints out the ASCII value of the current byte
"""
if self.tape[self.pointer] is None:
print "{}".format(chr(0)),
else:
print "{}".format(chr(int(self.tape[self.pointer]))), | [
"def",
"_output_current_byte",
"(",
"self",
")",
":",
"if",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"is",
"None",
":",
"print",
"\"{}\"",
".",
"format",
"(",
"chr",
"(",
"0",
")",
")",
",",
"else",
":",
"print",
"\"{}\"",
".",
"format",
"(",
"chr",
"(",
"int",
"(",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
")",
")",
")",
","
] | Prints out the ASCII value of the current byte | [
"Prints",
"out",
"the",
"ASCII",
"value",
"of",
"the",
"current",
"byte"
] | baf2957263685f03873f368226f5752da4e51f08 | https://github.com/Deathnerd/pyterp/blob/baf2957263685f03873f368226f5752da4e51f08/pyterp/__init__.py#L179-L186 |
250,328 | Deathnerd/pyterp | pyterp/__init__.py | Brainfuck._read_byte | def _read_byte(self):
"""
Read a single byte from the user without waiting for the \n character
"""
from .getch import _Getch
try:
g = _Getch()
self.tape[self.pointer] = ord(g())
except TypeError as e:
print "Here's what _Getch() is giving me {}".format(g()) | python | def _read_byte(self):
"""
Read a single byte from the user without waiting for the \n character
"""
from .getch import _Getch
try:
g = _Getch()
self.tape[self.pointer] = ord(g())
except TypeError as e:
print "Here's what _Getch() is giving me {}".format(g()) | [
"def",
"_read_byte",
"(",
"self",
")",
":",
"from",
".",
"getch",
"import",
"_Getch",
"try",
":",
"g",
"=",
"_Getch",
"(",
")",
"self",
".",
"tape",
"[",
"self",
".",
"pointer",
"]",
"=",
"ord",
"(",
"g",
"(",
")",
")",
"except",
"TypeError",
"as",
"e",
":",
"print",
"\"Here's what _Getch() is giving me {}\"",
".",
"format",
"(",
"g",
"(",
")",
")"
] | Read a single byte from the user without waiting for the \n character | [
"Read",
"a",
"single",
"byte",
"from",
"the",
"user",
"without",
"waiting",
"for",
"the",
"\\",
"n",
"character"
] | baf2957263685f03873f368226f5752da4e51f08 | https://github.com/Deathnerd/pyterp/blob/baf2957263685f03873f368226f5752da4e51f08/pyterp/__init__.py#L188-L197 |
250,329 | minhhoit/yacms | yacms/generic/forms.py | KeywordsWidget.decompress | def decompress(self, value):
"""
Takes the sequence of ``AssignedKeyword`` instances and splits
them into lists of keyword IDs and titles each mapping to one
of the form field widgets.
"""
if hasattr(value, "select_related"):
keywords = [a.keyword for a in value.select_related("keyword")]
if keywords:
keywords = [(str(k.id), k.title) for k in keywords]
self._ids, words = list(zip(*keywords))
return (",".join(self._ids), ", ".join(words))
return ("", "") | python | def decompress(self, value):
"""
Takes the sequence of ``AssignedKeyword`` instances and splits
them into lists of keyword IDs and titles each mapping to one
of the form field widgets.
"""
if hasattr(value, "select_related"):
keywords = [a.keyword for a in value.select_related("keyword")]
if keywords:
keywords = [(str(k.id), k.title) for k in keywords]
self._ids, words = list(zip(*keywords))
return (",".join(self._ids), ", ".join(words))
return ("", "") | [
"def",
"decompress",
"(",
"self",
",",
"value",
")",
":",
"if",
"hasattr",
"(",
"value",
",",
"\"select_related\"",
")",
":",
"keywords",
"=",
"[",
"a",
".",
"keyword",
"for",
"a",
"in",
"value",
".",
"select_related",
"(",
"\"keyword\"",
")",
"]",
"if",
"keywords",
":",
"keywords",
"=",
"[",
"(",
"str",
"(",
"k",
".",
"id",
")",
",",
"k",
".",
"title",
")",
"for",
"k",
"in",
"keywords",
"]",
"self",
".",
"_ids",
",",
"words",
"=",
"list",
"(",
"zip",
"(",
"*",
"keywords",
")",
")",
"return",
"(",
"\",\"",
".",
"join",
"(",
"self",
".",
"_ids",
")",
",",
"\", \"",
".",
"join",
"(",
"words",
")",
")",
"return",
"(",
"\"\"",
",",
"\"\"",
")"
] | Takes the sequence of ``AssignedKeyword`` instances and splits
them into lists of keyword IDs and titles each mapping to one
of the form field widgets. | [
"Takes",
"the",
"sequence",
"of",
"AssignedKeyword",
"instances",
"and",
"splits",
"them",
"into",
"lists",
"of",
"keyword",
"IDs",
"and",
"titles",
"each",
"mapping",
"to",
"one",
"of",
"the",
"form",
"field",
"widgets",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/forms.py#L48-L60 |
250,330 | minhhoit/yacms | yacms/generic/forms.py | KeywordsWidget.format_output | def format_output(self, rendered_widgets):
"""
Wraps the output HTML with a list of all available ``Keyword``
instances that can be clicked on to toggle a keyword.
"""
rendered = super(KeywordsWidget, self).format_output(rendered_widgets)
links = ""
for keyword in Keyword.objects.all().order_by("title"):
prefix = "+" if str(keyword.id) not in self._ids else "-"
links += ("<a href='#'>%s%s</a>" % (prefix, str(keyword)))
rendered += mark_safe("<p class='keywords-field'>%s</p>" % links)
return rendered | python | def format_output(self, rendered_widgets):
"""
Wraps the output HTML with a list of all available ``Keyword``
instances that can be clicked on to toggle a keyword.
"""
rendered = super(KeywordsWidget, self).format_output(rendered_widgets)
links = ""
for keyword in Keyword.objects.all().order_by("title"):
prefix = "+" if str(keyword.id) not in self._ids else "-"
links += ("<a href='#'>%s%s</a>" % (prefix, str(keyword)))
rendered += mark_safe("<p class='keywords-field'>%s</p>" % links)
return rendered | [
"def",
"format_output",
"(",
"self",
",",
"rendered_widgets",
")",
":",
"rendered",
"=",
"super",
"(",
"KeywordsWidget",
",",
"self",
")",
".",
"format_output",
"(",
"rendered_widgets",
")",
"links",
"=",
"\"\"",
"for",
"keyword",
"in",
"Keyword",
".",
"objects",
".",
"all",
"(",
")",
".",
"order_by",
"(",
"\"title\"",
")",
":",
"prefix",
"=",
"\"+\"",
"if",
"str",
"(",
"keyword",
".",
"id",
")",
"not",
"in",
"self",
".",
"_ids",
"else",
"\"-\"",
"links",
"+=",
"(",
"\"<a href='#'>%s%s</a>\"",
"%",
"(",
"prefix",
",",
"str",
"(",
"keyword",
")",
")",
")",
"rendered",
"+=",
"mark_safe",
"(",
"\"<p class='keywords-field'>%s</p>\"",
"%",
"links",
")",
"return",
"rendered"
] | Wraps the output HTML with a list of all available ``Keyword``
instances that can be clicked on to toggle a keyword. | [
"Wraps",
"the",
"output",
"HTML",
"with",
"a",
"list",
"of",
"all",
"available",
"Keyword",
"instances",
"that",
"can",
"be",
"clicked",
"on",
"to",
"toggle",
"a",
"keyword",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/forms.py#L62-L73 |
250,331 | minhhoit/yacms | yacms/generic/forms.py | ThreadedCommentForm.save | def save(self, request):
"""
Saves a new comment and sends any notification emails.
"""
comment = self.get_comment_object()
obj = comment.content_object
if request.user.is_authenticated():
comment.user = request.user
comment.by_author = request.user == getattr(obj, "user", None)
comment.ip_address = ip_for_request(request)
comment.replied_to_id = self.data.get("replied_to")
# YaCms's duplicate check that also checks `replied_to_id`.
lookup = {
"content_type": comment.content_type,
"object_pk": comment.object_pk,
"user_name": comment.user_name,
"user_email": comment.user_email,
"user_url": comment.user_url,
"replied_to_id": comment.replied_to_id,
}
for duplicate in self.get_comment_model().objects.filter(**lookup):
if (duplicate.submit_date.date() == comment.submit_date.date() and
duplicate.comment == comment.comment):
return duplicate
comment.save()
comment_was_posted.send(sender=comment.__class__, comment=comment,
request=request)
notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
if notify_emails:
subject = ugettext("New comment for: ") + str(obj)
context = {
"comment": comment,
"comment_url": add_cache_bypass(comment.get_absolute_url()),
"request": request,
"obj": obj,
}
send_mail_template(subject, "email/comment_notification",
settings.DEFAULT_FROM_EMAIL, notify_emails,
context)
return comment | python | def save(self, request):
"""
Saves a new comment and sends any notification emails.
"""
comment = self.get_comment_object()
obj = comment.content_object
if request.user.is_authenticated():
comment.user = request.user
comment.by_author = request.user == getattr(obj, "user", None)
comment.ip_address = ip_for_request(request)
comment.replied_to_id = self.data.get("replied_to")
# YaCms's duplicate check that also checks `replied_to_id`.
lookup = {
"content_type": comment.content_type,
"object_pk": comment.object_pk,
"user_name": comment.user_name,
"user_email": comment.user_email,
"user_url": comment.user_url,
"replied_to_id": comment.replied_to_id,
}
for duplicate in self.get_comment_model().objects.filter(**lookup):
if (duplicate.submit_date.date() == comment.submit_date.date() and
duplicate.comment == comment.comment):
return duplicate
comment.save()
comment_was_posted.send(sender=comment.__class__, comment=comment,
request=request)
notify_emails = split_addresses(settings.COMMENTS_NOTIFICATION_EMAILS)
if notify_emails:
subject = ugettext("New comment for: ") + str(obj)
context = {
"comment": comment,
"comment_url": add_cache_bypass(comment.get_absolute_url()),
"request": request,
"obj": obj,
}
send_mail_template(subject, "email/comment_notification",
settings.DEFAULT_FROM_EMAIL, notify_emails,
context)
return comment | [
"def",
"save",
"(",
"self",
",",
"request",
")",
":",
"comment",
"=",
"self",
".",
"get_comment_object",
"(",
")",
"obj",
"=",
"comment",
".",
"content_object",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"comment",
".",
"user",
"=",
"request",
".",
"user",
"comment",
".",
"by_author",
"=",
"request",
".",
"user",
"==",
"getattr",
"(",
"obj",
",",
"\"user\"",
",",
"None",
")",
"comment",
".",
"ip_address",
"=",
"ip_for_request",
"(",
"request",
")",
"comment",
".",
"replied_to_id",
"=",
"self",
".",
"data",
".",
"get",
"(",
"\"replied_to\"",
")",
"# YaCms's duplicate check that also checks `replied_to_id`.",
"lookup",
"=",
"{",
"\"content_type\"",
":",
"comment",
".",
"content_type",
",",
"\"object_pk\"",
":",
"comment",
".",
"object_pk",
",",
"\"user_name\"",
":",
"comment",
".",
"user_name",
",",
"\"user_email\"",
":",
"comment",
".",
"user_email",
",",
"\"user_url\"",
":",
"comment",
".",
"user_url",
",",
"\"replied_to_id\"",
":",
"comment",
".",
"replied_to_id",
",",
"}",
"for",
"duplicate",
"in",
"self",
".",
"get_comment_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"*",
"*",
"lookup",
")",
":",
"if",
"(",
"duplicate",
".",
"submit_date",
".",
"date",
"(",
")",
"==",
"comment",
".",
"submit_date",
".",
"date",
"(",
")",
"and",
"duplicate",
".",
"comment",
"==",
"comment",
".",
"comment",
")",
":",
"return",
"duplicate",
"comment",
".",
"save",
"(",
")",
"comment_was_posted",
".",
"send",
"(",
"sender",
"=",
"comment",
".",
"__class__",
",",
"comment",
"=",
"comment",
",",
"request",
"=",
"request",
")",
"notify_emails",
"=",
"split_addresses",
"(",
"settings",
".",
"COMMENTS_NOTIFICATION_EMAILS",
")",
"if",
"notify_emails",
":",
"subject",
"=",
"ugettext",
"(",
"\"New comment for: \"",
")",
"+",
"str",
"(",
"obj",
")",
"context",
"=",
"{",
"\"comment\"",
":",
"comment",
",",
"\"comment_url\"",
":",
"add_cache_bypass",
"(",
"comment",
".",
"get_absolute_url",
"(",
")",
")",
",",
"\"request\"",
":",
"request",
",",
"\"obj\"",
":",
"obj",
",",
"}",
"send_mail_template",
"(",
"subject",
",",
"\"email/comment_notification\"",
",",
"settings",
".",
"DEFAULT_FROM_EMAIL",
",",
"notify_emails",
",",
"context",
")",
"return",
"comment"
] | Saves a new comment and sends any notification emails. | [
"Saves",
"a",
"new",
"comment",
"and",
"sends",
"any",
"notification",
"emails",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/forms.py#L131-L172 |
250,332 | minhhoit/yacms | yacms/generic/forms.py | RatingForm.clean | def clean(self):
"""
Check unauthenticated user's cookie as a light check to
prevent duplicate votes.
"""
bits = (self.data["content_type"], self.data["object_pk"])
request = self.request
self.current = "%s.%s" % bits
self.previous = request.COOKIES.get("yacms-rating", "").split(",")
already_rated = self.current in self.previous
if already_rated and not self.request.user.is_authenticated():
raise forms.ValidationError(ugettext("Already rated."))
return self.cleaned_data | python | def clean(self):
"""
Check unauthenticated user's cookie as a light check to
prevent duplicate votes.
"""
bits = (self.data["content_type"], self.data["object_pk"])
request = self.request
self.current = "%s.%s" % bits
self.previous = request.COOKIES.get("yacms-rating", "").split(",")
already_rated = self.current in self.previous
if already_rated and not self.request.user.is_authenticated():
raise forms.ValidationError(ugettext("Already rated."))
return self.cleaned_data | [
"def",
"clean",
"(",
"self",
")",
":",
"bits",
"=",
"(",
"self",
".",
"data",
"[",
"\"content_type\"",
"]",
",",
"self",
".",
"data",
"[",
"\"object_pk\"",
"]",
")",
"request",
"=",
"self",
".",
"request",
"self",
".",
"current",
"=",
"\"%s.%s\"",
"%",
"bits",
"self",
".",
"previous",
"=",
"request",
".",
"COOKIES",
".",
"get",
"(",
"\"yacms-rating\"",
",",
"\"\"",
")",
".",
"split",
"(",
"\",\"",
")",
"already_rated",
"=",
"self",
".",
"current",
"in",
"self",
".",
"previous",
"if",
"already_rated",
"and",
"not",
"self",
".",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"ugettext",
"(",
"\"Already rated.\"",
")",
")",
"return",
"self",
".",
"cleaned_data"
] | Check unauthenticated user's cookie as a light check to
prevent duplicate votes. | [
"Check",
"unauthenticated",
"user",
"s",
"cookie",
"as",
"a",
"light",
"check",
"to",
"prevent",
"duplicate",
"votes",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/forms.py#L197-L209 |
250,333 | minhhoit/yacms | yacms/generic/forms.py | RatingForm.save | def save(self):
"""
Saves a new rating - authenticated users can update the
value if they've previously rated.
"""
user = self.request.user
self.undoing = False
rating_value = self.cleaned_data["value"]
manager = self.rating_manager
if user.is_authenticated():
rating_instance, created = manager.get_or_create(user=user,
defaults={'value': rating_value})
if not created:
if rating_instance.value == int(rating_value):
# User submitted the same rating as previously,
# which we treat as undoing the rating (like a toggle).
rating_instance.delete()
self.undoing = True
else:
rating_instance.value = rating_value
rating_instance.save()
else:
rating_instance = manager.create(value=rating_value)
return rating_instance | python | def save(self):
"""
Saves a new rating - authenticated users can update the
value if they've previously rated.
"""
user = self.request.user
self.undoing = False
rating_value = self.cleaned_data["value"]
manager = self.rating_manager
if user.is_authenticated():
rating_instance, created = manager.get_or_create(user=user,
defaults={'value': rating_value})
if not created:
if rating_instance.value == int(rating_value):
# User submitted the same rating as previously,
# which we treat as undoing the rating (like a toggle).
rating_instance.delete()
self.undoing = True
else:
rating_instance.value = rating_value
rating_instance.save()
else:
rating_instance = manager.create(value=rating_value)
return rating_instance | [
"def",
"save",
"(",
"self",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"self",
".",
"undoing",
"=",
"False",
"rating_value",
"=",
"self",
".",
"cleaned_data",
"[",
"\"value\"",
"]",
"manager",
"=",
"self",
".",
"rating_manager",
"if",
"user",
".",
"is_authenticated",
"(",
")",
":",
"rating_instance",
",",
"created",
"=",
"manager",
".",
"get_or_create",
"(",
"user",
"=",
"user",
",",
"defaults",
"=",
"{",
"'value'",
":",
"rating_value",
"}",
")",
"if",
"not",
"created",
":",
"if",
"rating_instance",
".",
"value",
"==",
"int",
"(",
"rating_value",
")",
":",
"# User submitted the same rating as previously,",
"# which we treat as undoing the rating (like a toggle).",
"rating_instance",
".",
"delete",
"(",
")",
"self",
".",
"undoing",
"=",
"True",
"else",
":",
"rating_instance",
".",
"value",
"=",
"rating_value",
"rating_instance",
".",
"save",
"(",
")",
"else",
":",
"rating_instance",
"=",
"manager",
".",
"create",
"(",
"value",
"=",
"rating_value",
")",
"return",
"rating_instance"
] | Saves a new rating - authenticated users can update the
value if they've previously rated. | [
"Saves",
"a",
"new",
"rating",
"-",
"authenticated",
"users",
"can",
"update",
"the",
"value",
"if",
"they",
"ve",
"previously",
"rated",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/generic/forms.py#L211-L235 |
250,334 | veltzer/pylogconf | pylogconf/core.py | setup_exceptions | def setup_exceptions():
""" Only print the heart of the exception and not the stack trace """
# first set up the variables needed by the _excepthook function
global _print_traceback, _drill
local_print_traceback = os.getenv("PYLOGCONF_PRINT_TRACEBACK")
if local_print_traceback is not None:
_print_traceback = _str2bool(local_print_traceback)
local_drill = os.getenv("PYLOGCONF_DRILL")
if local_drill is not None:
_drill = _str2bool(local_drill)
# now that everything is ready attach the hook
sys.excepthook = _excepthook | python | def setup_exceptions():
""" Only print the heart of the exception and not the stack trace """
# first set up the variables needed by the _excepthook function
global _print_traceback, _drill
local_print_traceback = os.getenv("PYLOGCONF_PRINT_TRACEBACK")
if local_print_traceback is not None:
_print_traceback = _str2bool(local_print_traceback)
local_drill = os.getenv("PYLOGCONF_DRILL")
if local_drill is not None:
_drill = _str2bool(local_drill)
# now that everything is ready attach the hook
sys.excepthook = _excepthook | [
"def",
"setup_exceptions",
"(",
")",
":",
"# first set up the variables needed by the _excepthook function",
"global",
"_print_traceback",
",",
"_drill",
"local_print_traceback",
"=",
"os",
".",
"getenv",
"(",
"\"PYLOGCONF_PRINT_TRACEBACK\"",
")",
"if",
"local_print_traceback",
"is",
"not",
"None",
":",
"_print_traceback",
"=",
"_str2bool",
"(",
"local_print_traceback",
")",
"local_drill",
"=",
"os",
".",
"getenv",
"(",
"\"PYLOGCONF_DRILL\"",
")",
"if",
"local_drill",
"is",
"not",
"None",
":",
"_drill",
"=",
"_str2bool",
"(",
"local_drill",
")",
"# now that everything is ready attach the hook",
"sys",
".",
"excepthook",
"=",
"_excepthook"
] | Only print the heart of the exception and not the stack trace | [
"Only",
"print",
"the",
"heart",
"of",
"the",
"exception",
"and",
"not",
"the",
"stack",
"trace"
] | a3e230a073380b43b5d5096f40bb37ae28f3e430 | https://github.com/veltzer/pylogconf/blob/a3e230a073380b43b5d5096f40bb37ae28f3e430/pylogconf/core.py#L73-L84 |
250,335 | veltzer/pylogconf | pylogconf/core.py | setup_logging | def setup_logging():
""" setup the logging system """
default_path_yaml = os.path.expanduser('~/.pylogconf.yaml')
default_path_conf = os.path.expanduser('~/.pylogconf.conf')
# this matches the default logging level of the logging
# library and makes sense...
default_level = logging.WARNING
dbg = os.getenv("PYLOGCONF_DEBUG", False)
""" try YAML config file first """
value = os.getenv('PYLOGCONF_YAML', None)
if value is None:
path = default_path_yaml
else:
path = value
if os.path.isfile(path):
_debug('found logging configuration file [{0}]...'.format(path), dbg)
with open(path) as f:
config = yaml.load(f.read())
logging.config.dictConfig(config)
return
""" Now try regular config file """
value = os.getenv('PYLOGCONF_CONF', None)
if value is None:
path = default_path_conf
else:
path = value
if os.path.isfile(path):
_debug('found logging configuration file [{0}]...'.format(path), dbg)
logging.config.fileConfig(path)
return
_debug('logging with level [{0}]...'.format(default_level), dbg)
logging.basicConfig(level=default_level) | python | def setup_logging():
""" setup the logging system """
default_path_yaml = os.path.expanduser('~/.pylogconf.yaml')
default_path_conf = os.path.expanduser('~/.pylogconf.conf')
# this matches the default logging level of the logging
# library and makes sense...
default_level = logging.WARNING
dbg = os.getenv("PYLOGCONF_DEBUG", False)
""" try YAML config file first """
value = os.getenv('PYLOGCONF_YAML', None)
if value is None:
path = default_path_yaml
else:
path = value
if os.path.isfile(path):
_debug('found logging configuration file [{0}]...'.format(path), dbg)
with open(path) as f:
config = yaml.load(f.read())
logging.config.dictConfig(config)
return
""" Now try regular config file """
value = os.getenv('PYLOGCONF_CONF', None)
if value is None:
path = default_path_conf
else:
path = value
if os.path.isfile(path):
_debug('found logging configuration file [{0}]...'.format(path), dbg)
logging.config.fileConfig(path)
return
_debug('logging with level [{0}]...'.format(default_level), dbg)
logging.basicConfig(level=default_level) | [
"def",
"setup_logging",
"(",
")",
":",
"default_path_yaml",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.pylogconf.yaml'",
")",
"default_path_conf",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.pylogconf.conf'",
")",
"# this matches the default logging level of the logging",
"# library and makes sense...",
"default_level",
"=",
"logging",
".",
"WARNING",
"dbg",
"=",
"os",
".",
"getenv",
"(",
"\"PYLOGCONF_DEBUG\"",
",",
"False",
")",
"\"\"\" try YAML config file first \"\"\"",
"value",
"=",
"os",
".",
"getenv",
"(",
"'PYLOGCONF_YAML'",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"path",
"=",
"default_path_yaml",
"else",
":",
"path",
"=",
"value",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_debug",
"(",
"'found logging configuration file [{0}]...'",
".",
"format",
"(",
"path",
")",
",",
"dbg",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"config",
"=",
"yaml",
".",
"load",
"(",
"f",
".",
"read",
"(",
")",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"config",
")",
"return",
"\"\"\" Now try regular config file \"\"\"",
"value",
"=",
"os",
".",
"getenv",
"(",
"'PYLOGCONF_CONF'",
",",
"None",
")",
"if",
"value",
"is",
"None",
":",
"path",
"=",
"default_path_conf",
"else",
":",
"path",
"=",
"value",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"_debug",
"(",
"'found logging configuration file [{0}]...'",
".",
"format",
"(",
"path",
")",
",",
"dbg",
")",
"logging",
".",
"config",
".",
"fileConfig",
"(",
"path",
")",
"return",
"_debug",
"(",
"'logging with level [{0}]...'",
".",
"format",
"(",
"default_level",
")",
",",
"dbg",
")",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"default_level",
")"
] | setup the logging system | [
"setup",
"the",
"logging",
"system"
] | a3e230a073380b43b5d5096f40bb37ae28f3e430 | https://github.com/veltzer/pylogconf/blob/a3e230a073380b43b5d5096f40bb37ae28f3e430/pylogconf/core.py#L87-L122 |
250,336 | awacha/credolib | credolib/procedures.py | _merge_two_curves | def _merge_two_curves(curve1: Curve, curve2: Curve, qmin, qmax, qsep, use_additive_constant=False):
"""Merge two scattering curves
:param curve1: the first curve (longer distance)
:type curve1: sastool.classes.curve.GeneralCurve
:param curve2: the second curve (shorter distance)
:type curve2: sastool.classes.curve.GeneralCurve
:param qmin: lower bound of the interval for determining the scaling factor
:type qmin: float
:param qmax: upper bound of the interval for determining the scaling factor
:type qmax: float
:param qsep: separating (tailoring) point for the merge
:type qsep: float
:return: merged_curve, factor, background, stat
:rtype tuple of a sastool.classes2.curve.Curve and a float
"""
curve1=curve1.sanitize()
curve2=curve2.sanitize()
if len(curve1.trim(qmin, qmax)) > len(curve2.trim(qmin, qmax)):
curve2_interp = curve2.trim(qmin, qmax)
curve1_interp = curve1.interpolate(curve2_interp.q)
else:
curve1_interp = curve1.trim(qmin, qmax)
curve2_interp = curve2.interpolate(curve1_interp.q)
if use_additive_constant:
bg_init = 0
else:
bg_init = FixedParameter(0)
factor, bg, stat = nonlinear_odr(curve2_interp.Intensity, curve1_interp.Intensity,
curve2_interp.Error, curve1_interp.Error,
lambda x, factor, bg: x * factor + bg, [1.0, bg_init])
return Curve.merge(curve1 - bg, curve2 * factor, qsep), factor, bg, stat | python | def _merge_two_curves(curve1: Curve, curve2: Curve, qmin, qmax, qsep, use_additive_constant=False):
"""Merge two scattering curves
:param curve1: the first curve (longer distance)
:type curve1: sastool.classes.curve.GeneralCurve
:param curve2: the second curve (shorter distance)
:type curve2: sastool.classes.curve.GeneralCurve
:param qmin: lower bound of the interval for determining the scaling factor
:type qmin: float
:param qmax: upper bound of the interval for determining the scaling factor
:type qmax: float
:param qsep: separating (tailoring) point for the merge
:type qsep: float
:return: merged_curve, factor, background, stat
:rtype tuple of a sastool.classes2.curve.Curve and a float
"""
curve1=curve1.sanitize()
curve2=curve2.sanitize()
if len(curve1.trim(qmin, qmax)) > len(curve2.trim(qmin, qmax)):
curve2_interp = curve2.trim(qmin, qmax)
curve1_interp = curve1.interpolate(curve2_interp.q)
else:
curve1_interp = curve1.trim(qmin, qmax)
curve2_interp = curve2.interpolate(curve1_interp.q)
if use_additive_constant:
bg_init = 0
else:
bg_init = FixedParameter(0)
factor, bg, stat = nonlinear_odr(curve2_interp.Intensity, curve1_interp.Intensity,
curve2_interp.Error, curve1_interp.Error,
lambda x, factor, bg: x * factor + bg, [1.0, bg_init])
return Curve.merge(curve1 - bg, curve2 * factor, qsep), factor, bg, stat | [
"def",
"_merge_two_curves",
"(",
"curve1",
":",
"Curve",
",",
"curve2",
":",
"Curve",
",",
"qmin",
",",
"qmax",
",",
"qsep",
",",
"use_additive_constant",
"=",
"False",
")",
":",
"curve1",
"=",
"curve1",
".",
"sanitize",
"(",
")",
"curve2",
"=",
"curve2",
".",
"sanitize",
"(",
")",
"if",
"len",
"(",
"curve1",
".",
"trim",
"(",
"qmin",
",",
"qmax",
")",
")",
">",
"len",
"(",
"curve2",
".",
"trim",
"(",
"qmin",
",",
"qmax",
")",
")",
":",
"curve2_interp",
"=",
"curve2",
".",
"trim",
"(",
"qmin",
",",
"qmax",
")",
"curve1_interp",
"=",
"curve1",
".",
"interpolate",
"(",
"curve2_interp",
".",
"q",
")",
"else",
":",
"curve1_interp",
"=",
"curve1",
".",
"trim",
"(",
"qmin",
",",
"qmax",
")",
"curve2_interp",
"=",
"curve2",
".",
"interpolate",
"(",
"curve1_interp",
".",
"q",
")",
"if",
"use_additive_constant",
":",
"bg_init",
"=",
"0",
"else",
":",
"bg_init",
"=",
"FixedParameter",
"(",
"0",
")",
"factor",
",",
"bg",
",",
"stat",
"=",
"nonlinear_odr",
"(",
"curve2_interp",
".",
"Intensity",
",",
"curve1_interp",
".",
"Intensity",
",",
"curve2_interp",
".",
"Error",
",",
"curve1_interp",
".",
"Error",
",",
"lambda",
"x",
",",
"factor",
",",
"bg",
":",
"x",
"*",
"factor",
"+",
"bg",
",",
"[",
"1.0",
",",
"bg_init",
"]",
")",
"return",
"Curve",
".",
"merge",
"(",
"curve1",
"-",
"bg",
",",
"curve2",
"*",
"factor",
",",
"qsep",
")",
",",
"factor",
",",
"bg",
",",
"stat"
] | Merge two scattering curves
:param curve1: the first curve (longer distance)
:type curve1: sastool.classes.curve.GeneralCurve
:param curve2: the second curve (shorter distance)
:type curve2: sastool.classes.curve.GeneralCurve
:param qmin: lower bound of the interval for determining the scaling factor
:type qmin: float
:param qmax: upper bound of the interval for determining the scaling factor
:type qmax: float
:param qsep: separating (tailoring) point for the merge
:type qsep: float
:return: merged_curve, factor, background, stat
:rtype tuple of a sastool.classes2.curve.Curve and a float | [
"Merge",
"two",
"scattering",
"curves"
] | 11c0be3eea7257d3d6e13697d3e76ce538f2f1b2 | https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/procedures.py#L370-L401 |
250,337 | tylerbutler/propane | propane/filetools.py | calc_sha | def calc_sha(obj):
"""Calculates the base64-encoded SHA hash of a file."""
try:
pathfile = Path(obj)
except UnicodeDecodeError:
pathfile = None
sha = hashlib.sha256()
try:
if pathfile and pathfile.exists():
return base64.b64encode(pathfile.read_hash('SHA256'))
except TypeError:
# likely a bytestring
if isinstance(obj, string_types):
pass
else:
raise
if isinstance(obj, string_types):
sha.update(obj)
elif hasattr(obj, 'read'):
while True:
d = obj.read(8192)
if not d:
break
sha.update(d)
else:
return None
r = sha.digest()
r = base64.b64encode(r)
return r | python | def calc_sha(obj):
"""Calculates the base64-encoded SHA hash of a file."""
try:
pathfile = Path(obj)
except UnicodeDecodeError:
pathfile = None
sha = hashlib.sha256()
try:
if pathfile and pathfile.exists():
return base64.b64encode(pathfile.read_hash('SHA256'))
except TypeError:
# likely a bytestring
if isinstance(obj, string_types):
pass
else:
raise
if isinstance(obj, string_types):
sha.update(obj)
elif hasattr(obj, 'read'):
while True:
d = obj.read(8192)
if not d:
break
sha.update(d)
else:
return None
r = sha.digest()
r = base64.b64encode(r)
return r | [
"def",
"calc_sha",
"(",
"obj",
")",
":",
"try",
":",
"pathfile",
"=",
"Path",
"(",
"obj",
")",
"except",
"UnicodeDecodeError",
":",
"pathfile",
"=",
"None",
"sha",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"try",
":",
"if",
"pathfile",
"and",
"pathfile",
".",
"exists",
"(",
")",
":",
"return",
"base64",
".",
"b64encode",
"(",
"pathfile",
".",
"read_hash",
"(",
"'SHA256'",
")",
")",
"except",
"TypeError",
":",
"# likely a bytestring",
"if",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"pass",
"else",
":",
"raise",
"if",
"isinstance",
"(",
"obj",
",",
"string_types",
")",
":",
"sha",
".",
"update",
"(",
"obj",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'read'",
")",
":",
"while",
"True",
":",
"d",
"=",
"obj",
".",
"read",
"(",
"8192",
")",
"if",
"not",
"d",
":",
"break",
"sha",
".",
"update",
"(",
"d",
")",
"else",
":",
"return",
"None",
"r",
"=",
"sha",
".",
"digest",
"(",
")",
"r",
"=",
"base64",
".",
"b64encode",
"(",
"r",
")",
"return",
"r"
] | Calculates the base64-encoded SHA hash of a file. | [
"Calculates",
"the",
"base64",
"-",
"encoded",
"SHA",
"hash",
"of",
"a",
"file",
"."
] | 6c404285ab8d78865b7175a5c8adf8fae12d6be5 | https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/filetools.py#L13-L44 |
250,338 | minhhoit/yacms | yacms/blog/templatetags/blog_tags.py | blog_months | def blog_months(*args):
"""
Put a list of dates for blog posts into the template context.
"""
dates = BlogPost.objects.published().values_list("publish_date", flat=True)
date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates]
month_dicts = []
for date_dict in date_dicts:
if date_dict not in month_dicts:
month_dicts.append(date_dict)
for i, date_dict in enumerate(month_dicts):
month_dicts[i]["post_count"] = date_dicts.count(date_dict)
return month_dicts | python | def blog_months(*args):
"""
Put a list of dates for blog posts into the template context.
"""
dates = BlogPost.objects.published().values_list("publish_date", flat=True)
date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates]
month_dicts = []
for date_dict in date_dicts:
if date_dict not in month_dicts:
month_dicts.append(date_dict)
for i, date_dict in enumerate(month_dicts):
month_dicts[i]["post_count"] = date_dicts.count(date_dict)
return month_dicts | [
"def",
"blog_months",
"(",
"*",
"args",
")",
":",
"dates",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
".",
"values_list",
"(",
"\"publish_date\"",
",",
"flat",
"=",
"True",
")",
"date_dicts",
"=",
"[",
"{",
"\"date\"",
":",
"datetime",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"1",
")",
"}",
"for",
"d",
"in",
"dates",
"]",
"month_dicts",
"=",
"[",
"]",
"for",
"date_dict",
"in",
"date_dicts",
":",
"if",
"date_dict",
"not",
"in",
"month_dicts",
":",
"month_dicts",
".",
"append",
"(",
"date_dict",
")",
"for",
"i",
",",
"date_dict",
"in",
"enumerate",
"(",
"month_dicts",
")",
":",
"month_dicts",
"[",
"i",
"]",
"[",
"\"post_count\"",
"]",
"=",
"date_dicts",
".",
"count",
"(",
"date_dict",
")",
"return",
"month_dicts"
] | Put a list of dates for blog posts into the template context. | [
"Put",
"a",
"list",
"of",
"dates",
"for",
"blog",
"posts",
"into",
"the",
"template",
"context",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/templatetags/blog_tags.py#L18-L30 |
250,339 | minhhoit/yacms | yacms/blog/templatetags/blog_tags.py | blog_categories | def blog_categories(*args):
"""
Put a list of categories for blog posts into the template context.
"""
posts = BlogPost.objects.published()
categories = BlogCategory.objects.filter(blogposts__in=posts)
return list(categories.annotate(post_count=Count("blogposts"))) | python | def blog_categories(*args):
"""
Put a list of categories for blog posts into the template context.
"""
posts = BlogPost.objects.published()
categories = BlogCategory.objects.filter(blogposts__in=posts)
return list(categories.annotate(post_count=Count("blogposts"))) | [
"def",
"blog_categories",
"(",
"*",
"args",
")",
":",
"posts",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
"categories",
"=",
"BlogCategory",
".",
"objects",
".",
"filter",
"(",
"blogposts__in",
"=",
"posts",
")",
"return",
"list",
"(",
"categories",
".",
"annotate",
"(",
"post_count",
"=",
"Count",
"(",
"\"blogposts\"",
")",
")",
")"
] | Put a list of categories for blog posts into the template context. | [
"Put",
"a",
"list",
"of",
"categories",
"for",
"blog",
"posts",
"into",
"the",
"template",
"context",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/templatetags/blog_tags.py#L34-L40 |
250,340 | minhhoit/yacms | yacms/blog/templatetags/blog_tags.py | blog_recent_posts | def blog_recent_posts(limit=5, tag=None, username=None, category=None):
"""
Put a list of recently published blog posts into the template
context. A tag title or slug, category title or slug or author's
username can also be specified to filter the recent posts returned.
Usage::
{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %}
"""
blog_posts = BlogPost.objects.published().select_related("user")
title_or_slug = lambda s: Q(title=s) | Q(slug=s)
if tag is not None:
try:
tag = Keyword.objects.get(title_or_slug(tag))
blog_posts = blog_posts.filter(keywords__keyword=tag)
except Keyword.DoesNotExist:
return []
if category is not None:
try:
category = BlogCategory.objects.get(title_or_slug(category))
blog_posts = blog_posts.filter(categories=category)
except BlogCategory.DoesNotExist:
return []
if username is not None:
try:
author = User.objects.get(username=username)
blog_posts = blog_posts.filter(user=author)
except User.DoesNotExist:
return []
return list(blog_posts[:limit]) | python | def blog_recent_posts(limit=5, tag=None, username=None, category=None):
"""
Put a list of recently published blog posts into the template
context. A tag title or slug, category title or slug or author's
username can also be specified to filter the recent posts returned.
Usage::
{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %}
"""
blog_posts = BlogPost.objects.published().select_related("user")
title_or_slug = lambda s: Q(title=s) | Q(slug=s)
if tag is not None:
try:
tag = Keyword.objects.get(title_or_slug(tag))
blog_posts = blog_posts.filter(keywords__keyword=tag)
except Keyword.DoesNotExist:
return []
if category is not None:
try:
category = BlogCategory.objects.get(title_or_slug(category))
blog_posts = blog_posts.filter(categories=category)
except BlogCategory.DoesNotExist:
return []
if username is not None:
try:
author = User.objects.get(username=username)
blog_posts = blog_posts.filter(user=author)
except User.DoesNotExist:
return []
return list(blog_posts[:limit]) | [
"def",
"blog_recent_posts",
"(",
"limit",
"=",
"5",
",",
"tag",
"=",
"None",
",",
"username",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"blog_posts",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
".",
"select_related",
"(",
"\"user\"",
")",
"title_or_slug",
"=",
"lambda",
"s",
":",
"Q",
"(",
"title",
"=",
"s",
")",
"|",
"Q",
"(",
"slug",
"=",
"s",
")",
"if",
"tag",
"is",
"not",
"None",
":",
"try",
":",
"tag",
"=",
"Keyword",
".",
"objects",
".",
"get",
"(",
"title_or_slug",
"(",
"tag",
")",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"keywords__keyword",
"=",
"tag",
")",
"except",
"Keyword",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"if",
"category",
"is",
"not",
"None",
":",
"try",
":",
"category",
"=",
"BlogCategory",
".",
"objects",
".",
"get",
"(",
"title_or_slug",
"(",
"category",
")",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"categories",
"=",
"category",
")",
"except",
"BlogCategory",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"if",
"username",
"is",
"not",
"None",
":",
"try",
":",
"author",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"user",
"=",
"author",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"return",
"list",
"(",
"blog_posts",
"[",
":",
"limit",
"]",
")"
] | Put a list of recently published blog posts into the template
context. A tag title or slug, category title or slug or author's
username can also be specified to filter the recent posts returned.
Usage::
{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %} | [
"Put",
"a",
"list",
"of",
"recently",
"published",
"blog",
"posts",
"into",
"the",
"template",
"context",
".",
"A",
"tag",
"title",
"or",
"slug",
"category",
"title",
"or",
"slug",
"or",
"author",
"s",
"username",
"can",
"also",
"be",
"specified",
"to",
"filter",
"the",
"recent",
"posts",
"returned",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/templatetags/blog_tags.py#L54-L88 |
250,341 | soasme/rio-client | rio_client/contrib/flask.py | Rio.emit | def emit(self, action, payload, level=Level.INSTANT):
"""Emit action."""
if level == self.Level.INSTANT:
return self.emit_instantly(action, payload)
elif level == self.Level.CONTEXTUAL:
return self.emit_contextually(action, payload)
elif level == self.Level.DELAY:
return self.emit_delayed(action, payload)
else:
raise Exception('InvalidEmitLevel: %s' % level) | python | def emit(self, action, payload, level=Level.INSTANT):
"""Emit action."""
if level == self.Level.INSTANT:
return self.emit_instantly(action, payload)
elif level == self.Level.CONTEXTUAL:
return self.emit_contextually(action, payload)
elif level == self.Level.DELAY:
return self.emit_delayed(action, payload)
else:
raise Exception('InvalidEmitLevel: %s' % level) | [
"def",
"emit",
"(",
"self",
",",
"action",
",",
"payload",
",",
"level",
"=",
"Level",
".",
"INSTANT",
")",
":",
"if",
"level",
"==",
"self",
".",
"Level",
".",
"INSTANT",
":",
"return",
"self",
".",
"emit_instantly",
"(",
"action",
",",
"payload",
")",
"elif",
"level",
"==",
"self",
".",
"Level",
".",
"CONTEXTUAL",
":",
"return",
"self",
".",
"emit_contextually",
"(",
"action",
",",
"payload",
")",
"elif",
"level",
"==",
"self",
".",
"Level",
".",
"DELAY",
":",
"return",
"self",
".",
"emit_delayed",
"(",
"action",
",",
"payload",
")",
"else",
":",
"raise",
"Exception",
"(",
"'InvalidEmitLevel: %s'",
"%",
"level",
")"
] | Emit action. | [
"Emit",
"action",
"."
] | c6d684c6f9deea5b43f2b05bcaf40714c48b5619 | https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/contrib/flask.py#L66-L75 |
250,342 | soasme/rio-client | rio_client/contrib/flask.py | Rio.emit_contextually | def emit_contextually(self, action, payload):
""" Emit on exiting request context."""
self.dump(action, payload)
return g.rio_client_contextual.append((action, payload, )) | python | def emit_contextually(self, action, payload):
""" Emit on exiting request context."""
self.dump(action, payload)
return g.rio_client_contextual.append((action, payload, )) | [
"def",
"emit_contextually",
"(",
"self",
",",
"action",
",",
"payload",
")",
":",
"self",
".",
"dump",
"(",
"action",
",",
"payload",
")",
"return",
"g",
".",
"rio_client_contextual",
".",
"append",
"(",
"(",
"action",
",",
"payload",
",",
")",
")"
] | Emit on exiting request context. | [
"Emit",
"on",
"exiting",
"request",
"context",
"."
] | c6d684c6f9deea5b43f2b05bcaf40714c48b5619 | https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/contrib/flask.py#L81-L84 |
250,343 | soasme/rio-client | rio_client/contrib/flask.py | Rio.current | def current(self):
"""A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request.get_json())
"""
event = request.headers.get('X-RIO-EVENT')
data = dict([elem.split('=') for elem in event.split(',')])
return Current(**data) | python | def current(self):
"""A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request.get_json())
"""
event = request.headers.get('X-RIO-EVENT')
data = dict([elem.split('=') for elem in event.split(',')])
return Current(**data) | [
"def",
"current",
"(",
"self",
")",
":",
"event",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"'X-RIO-EVENT'",
")",
"data",
"=",
"dict",
"(",
"[",
"elem",
".",
"split",
"(",
"'='",
")",
"for",
"elem",
"in",
"event",
".",
"split",
"(",
"','",
")",
"]",
")",
"return",
"Current",
"(",
"*",
"*",
"data",
")"
] | A namedtuple contains `uuid`, `project`, `action`.
Example::
@app.route('/webhook/broadcast-news')
def broadcast_news():
if rio.current.action.startswith('news-'):
broadcast(request.get_json()) | [
"A",
"namedtuple",
"contains",
"uuid",
"project",
"action",
"."
] | c6d684c6f9deea5b43f2b05bcaf40714c48b5619 | https://github.com/soasme/rio-client/blob/c6d684c6f9deea5b43f2b05bcaf40714c48b5619/rio_client/contrib/flask.py#L111-L123 |
250,344 | jkenlooper/chill | src/chill/script.py | init | def init():
"Initialize the current directory with base starting files and database."
if not os.path.exists('site.cfg'):
f = open('site.cfg', 'w')
f.write(SITECFG)
f.close()
try:
os.mkdir('queries')
except OSError:
pass
try:
os.mkdir('templates')
except OSError:
pass
htmlfile = os.path.join('templates', 'homepage.html')
if not os.path.exists(htmlfile):
f = open(htmlfile, 'w')
f.write("""
<!doctype html>
<html>
<head>
<title>Chill</title>
</head>
<body>
<p>{{ homepage_content }}</p>
</body>
</html>
""")
f.close()
app = make_app(config='site.cfg', DEBUG=True)
with app.app_context():
app.logger.info("initializing database")
init_db()
homepage = insert_node(name='homepage', value=None)
insert_route(path='/', node_id=homepage)
insert_query(name='select_link_node_from_node.sql', node_id=homepage)
add_template_for_node('homepage.html', homepage)
homepage_content = insert_node(name='homepage_content', value="Cascading, Highly Irrelevant, Lost Llamas")
insert_node_node(node_id=homepage, target_node_id=homepage_content) | python | def init():
"Initialize the current directory with base starting files and database."
if not os.path.exists('site.cfg'):
f = open('site.cfg', 'w')
f.write(SITECFG)
f.close()
try:
os.mkdir('queries')
except OSError:
pass
try:
os.mkdir('templates')
except OSError:
pass
htmlfile = os.path.join('templates', 'homepage.html')
if not os.path.exists(htmlfile):
f = open(htmlfile, 'w')
f.write("""
<!doctype html>
<html>
<head>
<title>Chill</title>
</head>
<body>
<p>{{ homepage_content }}</p>
</body>
</html>
""")
f.close()
app = make_app(config='site.cfg', DEBUG=True)
with app.app_context():
app.logger.info("initializing database")
init_db()
homepage = insert_node(name='homepage', value=None)
insert_route(path='/', node_id=homepage)
insert_query(name='select_link_node_from_node.sql', node_id=homepage)
add_template_for_node('homepage.html', homepage)
homepage_content = insert_node(name='homepage_content', value="Cascading, Highly Irrelevant, Lost Llamas")
insert_node_node(node_id=homepage, target_node_id=homepage_content) | [
"def",
"init",
"(",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"'site.cfg'",
")",
":",
"f",
"=",
"open",
"(",
"'site.cfg'",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"SITECFG",
")",
"f",
".",
"close",
"(",
")",
"try",
":",
"os",
".",
"mkdir",
"(",
"'queries'",
")",
"except",
"OSError",
":",
"pass",
"try",
":",
"os",
".",
"mkdir",
"(",
"'templates'",
")",
"except",
"OSError",
":",
"pass",
"htmlfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'templates'",
",",
"'homepage.html'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"htmlfile",
")",
":",
"f",
"=",
"open",
"(",
"htmlfile",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"\"\"\"\n<!doctype html>\n<html>\n <head>\n <title>Chill</title>\n </head>\n <body>\n <p>{{ homepage_content }}</p>\n </body>\n</html>\n \"\"\"",
")",
"f",
".",
"close",
"(",
")",
"app",
"=",
"make_app",
"(",
"config",
"=",
"'site.cfg'",
",",
"DEBUG",
"=",
"True",
")",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"app",
".",
"logger",
".",
"info",
"(",
"\"initializing database\"",
")",
"init_db",
"(",
")",
"homepage",
"=",
"insert_node",
"(",
"name",
"=",
"'homepage'",
",",
"value",
"=",
"None",
")",
"insert_route",
"(",
"path",
"=",
"'/'",
",",
"node_id",
"=",
"homepage",
")",
"insert_query",
"(",
"name",
"=",
"'select_link_node_from_node.sql'",
",",
"node_id",
"=",
"homepage",
")",
"add_template_for_node",
"(",
"'homepage.html'",
",",
"homepage",
")",
"homepage_content",
"=",
"insert_node",
"(",
"name",
"=",
"'homepage_content'",
",",
"value",
"=",
"\"Cascading, Highly Irrelevant, Lost Llamas\"",
")",
"insert_node_node",
"(",
"node_id",
"=",
"homepage",
",",
"target_node_id",
"=",
"homepage_content",
")"
] | Initialize the current directory with base starting files and database. | [
"Initialize",
"the",
"current",
"directory",
"with",
"base",
"starting",
"files",
"and",
"database",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/script.py#L170-L217 |
250,345 | jkenlooper/chill | src/chill/script.py | operate | def operate(config):
"Interface to do simple operations on the database."
app = make_app(config=config)
print "Operate Mode"
with app.app_context():
operate_menu() | python | def operate(config):
"Interface to do simple operations on the database."
app = make_app(config=config)
print "Operate Mode"
with app.app_context():
operate_menu() | [
"def",
"operate",
"(",
"config",
")",
":",
"app",
"=",
"make_app",
"(",
"config",
"=",
"config",
")",
"print",
"\"Operate Mode\"",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"operate_menu",
"(",
")"
] | Interface to do simple operations on the database. | [
"Interface",
"to",
"do",
"simple",
"operations",
"on",
"the",
"database",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/script.py#L219-L226 |
250,346 | jkenlooper/chill | src/chill/script.py | run | def run(config):
"Start the web server in the foreground. Don't use for production."
app = make_app(config=config)
app.run(
host=app.config.get("HOST", '127.0.0.1'),
port=app.config.get("PORT", 5000),
use_reloader=True,
) | python | def run(config):
"Start the web server in the foreground. Don't use for production."
app = make_app(config=config)
app.run(
host=app.config.get("HOST", '127.0.0.1'),
port=app.config.get("PORT", 5000),
use_reloader=True,
) | [
"def",
"run",
"(",
"config",
")",
":",
"app",
"=",
"make_app",
"(",
"config",
"=",
"config",
")",
"app",
".",
"run",
"(",
"host",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"HOST\"",
",",
"'127.0.0.1'",
")",
",",
"port",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"PORT\"",
",",
"5000",
")",
",",
"use_reloader",
"=",
"True",
",",
")"
] | Start the web server in the foreground. Don't use for production. | [
"Start",
"the",
"web",
"server",
"in",
"the",
"foreground",
".",
"Don",
"t",
"use",
"for",
"production",
"."
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/script.py#L237-L245 |
250,347 | jkenlooper/chill | src/chill/script.py | serve | def serve(config):
"Serve the app with Gevent"
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get("HOST", '127.0.0.1')
port = app.config.get("PORT", 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() | python | def serve(config):
"Serve the app with Gevent"
from gevent.pywsgi import WSGIServer
app = make_app(config=config)
host = app.config.get("HOST", '127.0.0.1')
port = app.config.get("PORT", 5000)
http_server = WSGIServer((host, port), app)
http_server.serve_forever() | [
"def",
"serve",
"(",
"config",
")",
":",
"from",
"gevent",
".",
"pywsgi",
"import",
"WSGIServer",
"app",
"=",
"make_app",
"(",
"config",
"=",
"config",
")",
"host",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"HOST\"",
",",
"'127.0.0.1'",
")",
"port",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"PORT\"",
",",
"5000",
")",
"http_server",
"=",
"WSGIServer",
"(",
"(",
"host",
",",
"port",
")",
",",
"app",
")",
"http_server",
".",
"serve_forever",
"(",
")"
] | Serve the app with Gevent | [
"Serve",
"the",
"app",
"with",
"Gevent"
] | 35360c17c2a3b769ecb5406c6dabcf4cc70bd76f | https://github.com/jkenlooper/chill/blob/35360c17c2a3b769ecb5406c6dabcf4cc70bd76f/src/chill/script.py#L248-L257 |
250,348 | ulf1/oxyba | oxyba/clean_german_date.py | clean_german_date | def clean_german_date(x):
"""Convert a string with a German date 'DD.MM.YYYY' to Datetime objects
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a German formated date,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A datetime object or array of datetime objects.
Example
-------
The function aims to convert a string as follows
'23.09.2012' => datetime(2012, 9, 23, 0, 0)
Code Example
------------
print(clean_german_date('23.09.2012'))
Behavior
--------
- If it is not a string with date format 'DD.MM.YYYY' then None is returned
"""
import numpy as np
import pandas as pd
from datetime import datetime
def proc_elem(e):
try:
return datetime.strptime(e, '%d.%m.%Y')
except Exception as e:
print(e)
return None
def proc_list(x):
return [proc_elem(e) for e in x]
def proc_ndarray(x):
tmp = proc_list(list(x.reshape((x.size,))))
return np.array(tmp).reshape(x.shape)
# transform string, list/tuple, numpy array, pandas dataframe
if isinstance(x, str):
return proc_elem(x)
elif isinstance(x, (list, tuple)):
return proc_list(x)
elif isinstance(x, np.ndarray):
return proc_ndarray(x)
elif isinstance(x, pd.DataFrame):
return pd.DataFrame(proc_ndarray(x.values),
columns=x.columns,
index=x.index)
else:
return None | python | def clean_german_date(x):
"""Convert a string with a German date 'DD.MM.YYYY' to Datetime objects
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a German formated date,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A datetime object or array of datetime objects.
Example
-------
The function aims to convert a string as follows
'23.09.2012' => datetime(2012, 9, 23, 0, 0)
Code Example
------------
print(clean_german_date('23.09.2012'))
Behavior
--------
- If it is not a string with date format 'DD.MM.YYYY' then None is returned
"""
import numpy as np
import pandas as pd
from datetime import datetime
def proc_elem(e):
try:
return datetime.strptime(e, '%d.%m.%Y')
except Exception as e:
print(e)
return None
def proc_list(x):
return [proc_elem(e) for e in x]
def proc_ndarray(x):
tmp = proc_list(list(x.reshape((x.size,))))
return np.array(tmp).reshape(x.shape)
# transform string, list/tuple, numpy array, pandas dataframe
if isinstance(x, str):
return proc_elem(x)
elif isinstance(x, (list, tuple)):
return proc_list(x)
elif isinstance(x, np.ndarray):
return proc_ndarray(x)
elif isinstance(x, pd.DataFrame):
return pd.DataFrame(proc_ndarray(x.values),
columns=x.columns,
index=x.index)
else:
return None | [
"def",
"clean_german_date",
"(",
"x",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"pandas",
"as",
"pd",
"from",
"datetime",
"import",
"datetime",
"def",
"proc_elem",
"(",
"e",
")",
":",
"try",
":",
"return",
"datetime",
".",
"strptime",
"(",
"e",
",",
"'%d.%m.%Y'",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"None",
"def",
"proc_list",
"(",
"x",
")",
":",
"return",
"[",
"proc_elem",
"(",
"e",
")",
"for",
"e",
"in",
"x",
"]",
"def",
"proc_ndarray",
"(",
"x",
")",
":",
"tmp",
"=",
"proc_list",
"(",
"list",
"(",
"x",
".",
"reshape",
"(",
"(",
"x",
".",
"size",
",",
")",
")",
")",
")",
"return",
"np",
".",
"array",
"(",
"tmp",
")",
".",
"reshape",
"(",
"x",
".",
"shape",
")",
"# transform string, list/tuple, numpy array, pandas dataframe",
"if",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"return",
"proc_elem",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"proc_list",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"proc_ndarray",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"pd",
".",
"DataFrame",
")",
":",
"return",
"pd",
".",
"DataFrame",
"(",
"proc_ndarray",
"(",
"x",
".",
"values",
")",
",",
"columns",
"=",
"x",
".",
"columns",
",",
"index",
"=",
"x",
".",
"index",
")",
"else",
":",
"return",
"None"
] | Convert a string with a German date 'DD.MM.YYYY' to Datetime objects
Parameters
----------
x : str, list, tuple, numpy.ndarray, pandas.DataFrame
A string with a German formated date,
or an array of these strings, e.g. list, ndarray, df.
Returns
-------
y : str, list, tuple, numpy.ndarray, pandas.DataFrame
A datetime object or array of datetime objects.
Example
-------
The function aims to convert a string as follows
'23.09.2012' => datetime(2012, 9, 23, 0, 0)
Code Example
------------
print(clean_german_date('23.09.2012'))
Behavior
--------
- If it is not a string with date format 'DD.MM.YYYY' then None is returned | [
"Convert",
"a",
"string",
"with",
"a",
"German",
"date",
"DD",
".",
"MM",
".",
"YYYY",
"to",
"Datetime",
"objects"
] | b3043116050de275124365cb11e7df91fb40169d | https://github.com/ulf1/oxyba/blob/b3043116050de275124365cb11e7df91fb40169d/oxyba/clean_german_date.py#L2-L61 |
250,349 | shaypal5/utilp | utilp/classes/classes.py | mro | def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
Another way of looking at this, if you pass a single class K, this will
return the linearization of K (the MRO of K, *including* itself).
Found at:
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
"""
seqs = [list(C.__mro__) for C in bases] + [list(bases)]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
# Nothing left to process, we're done.
return tuple(res)
for seq in non_empty: # Find merge candidates among seq heads.
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
# Reject the candidate.
candidate = None
else:
break
if not candidate:
raise TypeError("inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
# Remove candidate.
if seq[0] == candidate:
del seq[0] | python | def mro(*bases):
"""Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
Another way of looking at this, if you pass a single class K, this will
return the linearization of K (the MRO of K, *including* itself).
Found at:
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/
"""
seqs = [list(C.__mro__) for C in bases] + [list(bases)]
res = []
while True:
non_empty = list(filter(None, seqs))
if not non_empty:
# Nothing left to process, we're done.
return tuple(res)
for seq in non_empty: # Find merge candidates among seq heads.
candidate = seq[0]
not_head = [s for s in non_empty if candidate in s[1:]]
if not_head:
# Reject the candidate.
candidate = None
else:
break
if not candidate:
raise TypeError("inconsistent hierarchy, no C3 MRO is possible")
res.append(candidate)
for seq in non_empty:
# Remove candidate.
if seq[0] == candidate:
del seq[0] | [
"def",
"mro",
"(",
"*",
"bases",
")",
":",
"seqs",
"=",
"[",
"list",
"(",
"C",
".",
"__mro__",
")",
"for",
"C",
"in",
"bases",
"]",
"+",
"[",
"list",
"(",
"bases",
")",
"]",
"res",
"=",
"[",
"]",
"while",
"True",
":",
"non_empty",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"seqs",
")",
")",
"if",
"not",
"non_empty",
":",
"# Nothing left to process, we're done.",
"return",
"tuple",
"(",
"res",
")",
"for",
"seq",
"in",
"non_empty",
":",
"# Find merge candidates among seq heads.",
"candidate",
"=",
"seq",
"[",
"0",
"]",
"not_head",
"=",
"[",
"s",
"for",
"s",
"in",
"non_empty",
"if",
"candidate",
"in",
"s",
"[",
"1",
":",
"]",
"]",
"if",
"not_head",
":",
"# Reject the candidate.",
"candidate",
"=",
"None",
"else",
":",
"break",
"if",
"not",
"candidate",
":",
"raise",
"TypeError",
"(",
"\"inconsistent hierarchy, no C3 MRO is possible\"",
")",
"res",
".",
"append",
"(",
"candidate",
")",
"for",
"seq",
"in",
"non_empty",
":",
"# Remove candidate.",
"if",
"seq",
"[",
"0",
"]",
"==",
"candidate",
":",
"del",
"seq",
"[",
"0",
"]"
] | Calculate the Method Resolution Order of bases using the C3 algorithm.
Suppose you intended creating a class K with the given base classes. This
function returns the MRO which K would have, *excluding* K itself (since
it doesn't yet exist), as if you had actually created the class.
Another way of looking at this, if you pass a single class K, this will
return the linearization of K (the MRO of K, *including* itself).
Found at:
http://code.activestate.com/recipes/577748-calculate-the-mro-of-a-class/ | [
"Calculate",
"the",
"Method",
"Resolution",
"Order",
"of",
"bases",
"using",
"the",
"C3",
"algorithm",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/classes/classes.py#L81-L115 |
250,350 | shaypal5/utilp | utilp/classes/classes.py | PrintLogger.printlog | def printlog(self, string, verbose=None, flush=False):
"""Prints the given string to a logfile if logging is on, and to
screen if verbosity is on."""
if self.writelog:
self.logger.info(string)
if verbose or (self.verbose and verbose is None):
print(string, flush=flush) | python | def printlog(self, string, verbose=None, flush=False):
"""Prints the given string to a logfile if logging is on, and to
screen if verbosity is on."""
if self.writelog:
self.logger.info(string)
if verbose or (self.verbose and verbose is None):
print(string, flush=flush) | [
"def",
"printlog",
"(",
"self",
",",
"string",
",",
"verbose",
"=",
"None",
",",
"flush",
"=",
"False",
")",
":",
"if",
"self",
".",
"writelog",
":",
"self",
".",
"logger",
".",
"info",
"(",
"string",
")",
"if",
"verbose",
"or",
"(",
"self",
".",
"verbose",
"and",
"verbose",
"is",
"None",
")",
":",
"print",
"(",
"string",
",",
"flush",
"=",
"flush",
")"
] | Prints the given string to a logfile if logging is on, and to
screen if verbosity is on. | [
"Prints",
"the",
"given",
"string",
"to",
"a",
"logfile",
"if",
"logging",
"is",
"on",
"and",
"to",
"screen",
"if",
"verbosity",
"is",
"on",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/classes/classes.py#L249-L255 |
250,351 | shaypal5/utilp | utilp/classes/classes.py | PrintLogger.exception | def exception(self, exception):
"""Prints the stacktrace of the given exception."""
if self.writelog:
self.logger.exception(exception)
if self.verbose:
for line in traceback.format_exception(
None, exception, exception.__traceback__):
print(line, end='', file=sys.stderr, flush=True) | python | def exception(self, exception):
"""Prints the stacktrace of the given exception."""
if self.writelog:
self.logger.exception(exception)
if self.verbose:
for line in traceback.format_exception(
None, exception, exception.__traceback__):
print(line, end='', file=sys.stderr, flush=True) | [
"def",
"exception",
"(",
"self",
",",
"exception",
")",
":",
"if",
"self",
".",
"writelog",
":",
"self",
".",
"logger",
".",
"exception",
"(",
"exception",
")",
"if",
"self",
".",
"verbose",
":",
"for",
"line",
"in",
"traceback",
".",
"format_exception",
"(",
"None",
",",
"exception",
",",
"exception",
".",
"__traceback__",
")",
":",
"print",
"(",
"line",
",",
"end",
"=",
"''",
",",
"file",
"=",
"sys",
".",
"stderr",
",",
"flush",
"=",
"True",
")"
] | Prints the stacktrace of the given exception. | [
"Prints",
"the",
"stacktrace",
"of",
"the",
"given",
"exception",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/classes/classes.py#L257-L264 |
250,352 | shaypal5/utilp | utilp/classes/classes.py | PrintLogger.tqdm | def tqdm(self, iterable, **kwargs):
"""Wraps the given iterable with a tqdm progress bar if this logger is
set to verbose. Otherwise, returns the iterable unchanged."""
if 'disable' in kwargs:
kwargs.pop('disable')
return tqdm(iterable, disable=not self.verbose, **kwargs) | python | def tqdm(self, iterable, **kwargs):
"""Wraps the given iterable with a tqdm progress bar if this logger is
set to verbose. Otherwise, returns the iterable unchanged."""
if 'disable' in kwargs:
kwargs.pop('disable')
return tqdm(iterable, disable=not self.verbose, **kwargs) | [
"def",
"tqdm",
"(",
"self",
",",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'disable'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'disable'",
")",
"return",
"tqdm",
"(",
"iterable",
",",
"disable",
"=",
"not",
"self",
".",
"verbose",
",",
"*",
"*",
"kwargs",
")"
] | Wraps the given iterable with a tqdm progress bar if this logger is
set to verbose. Otherwise, returns the iterable unchanged. | [
"Wraps",
"the",
"given",
"iterable",
"with",
"a",
"tqdm",
"progress",
"bar",
"if",
"this",
"logger",
"is",
"set",
"to",
"verbose",
".",
"Otherwise",
"returns",
"the",
"iterable",
"unchanged",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/classes/classes.py#L273-L278 |
250,353 | 20c/xbahn | xbahn/connection/tcp.py | Handler.respond | def respond(self, data):
"""
Respond to the connection accepted in this object
"""
self.push("%s%s" % (data, TERMINATOR))
if self.temporary:
self.close_when_done() | python | def respond(self, data):
"""
Respond to the connection accepted in this object
"""
self.push("%s%s" % (data, TERMINATOR))
if self.temporary:
self.close_when_done() | [
"def",
"respond",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"push",
"(",
"\"%s%s\"",
"%",
"(",
"data",
",",
"TERMINATOR",
")",
")",
"if",
"self",
".",
"temporary",
":",
"self",
".",
"close_when_done",
"(",
")"
] | Respond to the connection accepted in this object | [
"Respond",
"to",
"the",
"connection",
"accepted",
"in",
"this",
"object"
] | afb27b0576841338a366d7cac0200a782bd84be6 | https://github.com/20c/xbahn/blob/afb27b0576841338a366d7cac0200a782bd84be6/xbahn/connection/tcp.py#L98-L105 |
250,354 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/workspacefolder.py | WorkspaceFolder.participant_policy | def participant_policy(self, value):
""" Changing participation policy fires a
"ParticipationPolicyChanged" event
"""
old_policy = self.participant_policy
new_policy = value
self._participant_policy = new_policy
notify(ParticipationPolicyChangedEvent(self, old_policy, new_policy)) | python | def participant_policy(self, value):
""" Changing participation policy fires a
"ParticipationPolicyChanged" event
"""
old_policy = self.participant_policy
new_policy = value
self._participant_policy = new_policy
notify(ParticipationPolicyChangedEvent(self, old_policy, new_policy)) | [
"def",
"participant_policy",
"(",
"self",
",",
"value",
")",
":",
"old_policy",
"=",
"self",
".",
"participant_policy",
"new_policy",
"=",
"value",
"self",
".",
"_participant_policy",
"=",
"new_policy",
"notify",
"(",
"ParticipationPolicyChangedEvent",
"(",
"self",
",",
"old_policy",
",",
"new_policy",
")",
")"
] | Changing participation policy fires a
"ParticipationPolicyChanged" event | [
"Changing",
"participation",
"policy",
"fires",
"a",
"ParticipationPolicyChanged",
"event"
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/workspacefolder.py#L74-L81 |
250,355 | nejucomo/concon | concon.py | define_constrained_subtype | def define_constrained_subtype(prefix, base, blockednames, clsdict=None):
"""
Define a subtype which blocks a list of methods.
@param prefix: The subtype name prefix. This is prepended to the
base type name. This convention is baked in for
API consistency.
@param base: The base type to derive from.
@param blockednames: A list of method name strings. All of these
will be blocked.
@param clsdict: None or a dict which will be modified to become the
subtype class dict.
@return: The new subtype.
@raise: OverwriteError - If clsdict contains an entry in blockednames.
"""
name = prefix + base.__name__
clsdict = clsdict or {}
doc = clsdict.get('__doc__', '')
doc = 'An {} extension of {}.\n{}'.format(prefix, base.__name__, doc)
clsdict['__doc__'] = doc
setitem_without_overwrite(
clsdict,
'get_blocked_method_names',
lambda self: iter(blockednames),
)
for bname in blockednames:
setitem_without_overwrite(
clsdict,
bname,
ConstraintError.block(getattr(base, bname)),
)
return type(name, (base,), clsdict) | python | def define_constrained_subtype(prefix, base, blockednames, clsdict=None):
"""
Define a subtype which blocks a list of methods.
@param prefix: The subtype name prefix. This is prepended to the
base type name. This convention is baked in for
API consistency.
@param base: The base type to derive from.
@param blockednames: A list of method name strings. All of these
will be blocked.
@param clsdict: None or a dict which will be modified to become the
subtype class dict.
@return: The new subtype.
@raise: OverwriteError - If clsdict contains an entry in blockednames.
"""
name = prefix + base.__name__
clsdict = clsdict or {}
doc = clsdict.get('__doc__', '')
doc = 'An {} extension of {}.\n{}'.format(prefix, base.__name__, doc)
clsdict['__doc__'] = doc
setitem_without_overwrite(
clsdict,
'get_blocked_method_names',
lambda self: iter(blockednames),
)
for bname in blockednames:
setitem_without_overwrite(
clsdict,
bname,
ConstraintError.block(getattr(base, bname)),
)
return type(name, (base,), clsdict) | [
"def",
"define_constrained_subtype",
"(",
"prefix",
",",
"base",
",",
"blockednames",
",",
"clsdict",
"=",
"None",
")",
":",
"name",
"=",
"prefix",
"+",
"base",
".",
"__name__",
"clsdict",
"=",
"clsdict",
"or",
"{",
"}",
"doc",
"=",
"clsdict",
".",
"get",
"(",
"'__doc__'",
",",
"''",
")",
"doc",
"=",
"'An {} extension of {}.\\n{}'",
".",
"format",
"(",
"prefix",
",",
"base",
".",
"__name__",
",",
"doc",
")",
"clsdict",
"[",
"'__doc__'",
"]",
"=",
"doc",
"setitem_without_overwrite",
"(",
"clsdict",
",",
"'get_blocked_method_names'",
",",
"lambda",
"self",
":",
"iter",
"(",
"blockednames",
")",
",",
")",
"for",
"bname",
"in",
"blockednames",
":",
"setitem_without_overwrite",
"(",
"clsdict",
",",
"bname",
",",
"ConstraintError",
".",
"block",
"(",
"getattr",
"(",
"base",
",",
"bname",
")",
")",
",",
")",
"return",
"type",
"(",
"name",
",",
"(",
"base",
",",
")",
",",
"clsdict",
")"
] | Define a subtype which blocks a list of methods.
@param prefix: The subtype name prefix. This is prepended to the
base type name. This convention is baked in for
API consistency.
@param base: The base type to derive from.
@param blockednames: A list of method name strings. All of these
will be blocked.
@param clsdict: None or a dict which will be modified to become the
subtype class dict.
@return: The new subtype.
@raise: OverwriteError - If clsdict contains an entry in blockednames. | [
"Define",
"a",
"subtype",
"which",
"blocks",
"a",
"list",
"of",
"methods",
"."
] | 0302475a86d25c53cd6ef50b0e4f6279ea73090d | https://github.com/nejucomo/concon/blob/0302475a86d25c53cd6ef50b0e4f6279ea73090d/concon.py#L42-L83 |
250,356 | nejucomo/concon | concon.py | update_without_overwrite | def update_without_overwrite(d, *args, **kwds):
"""
This has the same interface as dict.update except it uses
setitem_without_overwrite for all updates.
Note: The implementation is derived from
collections.MutableMapping.update.
"""
if args:
assert len(args) == 1, \
'At most one positional parameter is allowed: {0!r}'.format(args)
(other,) = args
if isinstance(other, Mapping):
for key in other:
setitem_without_overwrite(d, key, other[key])
elif hasattr(other, "keys"):
for key in other.keys():
setitem_without_overwrite(d, key, other[key])
else:
for key, value in other:
setitem_without_overwrite(d, key, value)
for key, value in kwds.items():
setitem_without_overwrite(d, key, value) | python | def update_without_overwrite(d, *args, **kwds):
"""
This has the same interface as dict.update except it uses
setitem_without_overwrite for all updates.
Note: The implementation is derived from
collections.MutableMapping.update.
"""
if args:
assert len(args) == 1, \
'At most one positional parameter is allowed: {0!r}'.format(args)
(other,) = args
if isinstance(other, Mapping):
for key in other:
setitem_without_overwrite(d, key, other[key])
elif hasattr(other, "keys"):
for key in other.keys():
setitem_without_overwrite(d, key, other[key])
else:
for key, value in other:
setitem_without_overwrite(d, key, value)
for key, value in kwds.items():
setitem_without_overwrite(d, key, value) | [
"def",
"update_without_overwrite",
"(",
"d",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"args",
":",
"assert",
"len",
"(",
"args",
")",
"==",
"1",
",",
"'At most one positional parameter is allowed: {0!r}'",
".",
"format",
"(",
"args",
")",
"(",
"other",
",",
")",
"=",
"args",
"if",
"isinstance",
"(",
"other",
",",
"Mapping",
")",
":",
"for",
"key",
"in",
"other",
":",
"setitem_without_overwrite",
"(",
"d",
",",
"key",
",",
"other",
"[",
"key",
"]",
")",
"elif",
"hasattr",
"(",
"other",
",",
"\"keys\"",
")",
":",
"for",
"key",
"in",
"other",
".",
"keys",
"(",
")",
":",
"setitem_without_overwrite",
"(",
"d",
",",
"key",
",",
"other",
"[",
"key",
"]",
")",
"else",
":",
"for",
"key",
",",
"value",
"in",
"other",
":",
"setitem_without_overwrite",
"(",
"d",
",",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"kwds",
".",
"items",
"(",
")",
":",
"setitem_without_overwrite",
"(",
"d",
",",
"key",
",",
"value",
")"
] | This has the same interface as dict.update except it uses
setitem_without_overwrite for all updates.
Note: The implementation is derived from
collections.MutableMapping.update. | [
"This",
"has",
"the",
"same",
"interface",
"as",
"dict",
".",
"update",
"except",
"it",
"uses",
"setitem_without_overwrite",
"for",
"all",
"updates",
"."
] | 0302475a86d25c53cd6ef50b0e4f6279ea73090d | https://github.com/nejucomo/concon/blob/0302475a86d25c53cd6ef50b0e4f6279ea73090d/concon.py#L117-L141 |
250,357 | kervi/kervi-core | kervi/hal/__init__.py | ChannelPollingThread._step | def _step(self):
"""Private method do not call it directly or override it."""
try:
new_value = self._device.get(self._channel)
if new_value != self._value:
self._callback(new_value)
self._value = new_value
time.sleep(self._polling_time)
except:
self.spine.log.exception("_PollingThread") | python | def _step(self):
"""Private method do not call it directly or override it."""
try:
new_value = self._device.get(self._channel)
if new_value != self._value:
self._callback(new_value)
self._value = new_value
time.sleep(self._polling_time)
except:
self.spine.log.exception("_PollingThread") | [
"def",
"_step",
"(",
"self",
")",
":",
"try",
":",
"new_value",
"=",
"self",
".",
"_device",
".",
"get",
"(",
"self",
".",
"_channel",
")",
"if",
"new_value",
"!=",
"self",
".",
"_value",
":",
"self",
".",
"_callback",
"(",
"new_value",
")",
"self",
".",
"_value",
"=",
"new_value",
"time",
".",
"sleep",
"(",
"self",
".",
"_polling_time",
")",
"except",
":",
"self",
".",
"spine",
".",
"log",
".",
"exception",
"(",
"\"_PollingThread\"",
")"
] | Private method do not call it directly or override it. | [
"Private",
"method",
"do",
"not",
"call",
"it",
"directly",
"or",
"override",
"it",
"."
] | 3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23 | https://github.com/kervi/kervi-core/blob/3c1e3c8a17a7b4d085d8a28b99180ff2a96b0e23/kervi/hal/__init__.py#L218-L227 |
250,358 | minhhoit/yacms | yacms/blog/management/base.py | BaseImporterCommand.add_post | def add_post(self, title=None, content=None, old_url=None, pub_date=None,
tags=None, categories=None, comments=None):
"""
Adds a post to the post list for processing.
- ``title`` and ``content`` are strings for the post.
- ``old_url`` is a string that a redirect will be created for.
- ``pub_date`` is assumed to be a ``datetime`` object.
- ``tags`` and ``categories`` are sequences of strings.
- ``comments`` is a sequence of dicts - each dict should be the
return value of ``add_comment``.
"""
if not title:
title = strip_tags(content).split(". ")[0]
title = decode_entities(title)
if categories is None:
categories = []
if tags is None:
tags = []
if comments is None:
comments = []
self.posts.append({
"title": force_text(title),
"publish_date": pub_date,
"content": force_text(content),
"categories": categories,
"tags": tags,
"comments": comments,
"old_url": old_url,
})
return self.posts[-1] | python | def add_post(self, title=None, content=None, old_url=None, pub_date=None,
tags=None, categories=None, comments=None):
"""
Adds a post to the post list for processing.
- ``title`` and ``content`` are strings for the post.
- ``old_url`` is a string that a redirect will be created for.
- ``pub_date`` is assumed to be a ``datetime`` object.
- ``tags`` and ``categories`` are sequences of strings.
- ``comments`` is a sequence of dicts - each dict should be the
return value of ``add_comment``.
"""
if not title:
title = strip_tags(content).split(". ")[0]
title = decode_entities(title)
if categories is None:
categories = []
if tags is None:
tags = []
if comments is None:
comments = []
self.posts.append({
"title": force_text(title),
"publish_date": pub_date,
"content": force_text(content),
"categories": categories,
"tags": tags,
"comments": comments,
"old_url": old_url,
})
return self.posts[-1] | [
"def",
"add_post",
"(",
"self",
",",
"title",
"=",
"None",
",",
"content",
"=",
"None",
",",
"old_url",
"=",
"None",
",",
"pub_date",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"categories",
"=",
"None",
",",
"comments",
"=",
"None",
")",
":",
"if",
"not",
"title",
":",
"title",
"=",
"strip_tags",
"(",
"content",
")",
".",
"split",
"(",
"\". \"",
")",
"[",
"0",
"]",
"title",
"=",
"decode_entities",
"(",
"title",
")",
"if",
"categories",
"is",
"None",
":",
"categories",
"=",
"[",
"]",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"if",
"comments",
"is",
"None",
":",
"comments",
"=",
"[",
"]",
"self",
".",
"posts",
".",
"append",
"(",
"{",
"\"title\"",
":",
"force_text",
"(",
"title",
")",
",",
"\"publish_date\"",
":",
"pub_date",
",",
"\"content\"",
":",
"force_text",
"(",
"content",
")",
",",
"\"categories\"",
":",
"categories",
",",
"\"tags\"",
":",
"tags",
",",
"\"comments\"",
":",
"comments",
",",
"\"old_url\"",
":",
"old_url",
",",
"}",
")",
"return",
"self",
".",
"posts",
"[",
"-",
"1",
"]"
] | Adds a post to the post list for processing.
- ``title`` and ``content`` are strings for the post.
- ``old_url`` is a string that a redirect will be created for.
- ``pub_date`` is assumed to be a ``datetime`` object.
- ``tags`` and ``categories`` are sequences of strings.
- ``comments`` is a sequence of dicts - each dict should be the
return value of ``add_comment``. | [
"Adds",
"a",
"post",
"to",
"the",
"post",
"list",
"for",
"processing",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/base.py#L54-L84 |
250,359 | minhhoit/yacms | yacms/blog/management/base.py | BaseImporterCommand.add_page | def add_page(self, title=None, content=None, old_url=None,
tags=None, old_id=None, old_parent_id=None):
"""
Adds a page to the list of pages to be imported - used by the
Wordpress importer.
"""
if not title:
text = decode_entities(strip_tags(content)).replace("\n", " ")
title = text.split(". ")[0]
if tags is None:
tags = []
self.pages.append({
"title": title,
"content": content,
"tags": tags,
"old_url": old_url,
"old_id": old_id,
"old_parent_id": old_parent_id,
}) | python | def add_page(self, title=None, content=None, old_url=None,
tags=None, old_id=None, old_parent_id=None):
"""
Adds a page to the list of pages to be imported - used by the
Wordpress importer.
"""
if not title:
text = decode_entities(strip_tags(content)).replace("\n", " ")
title = text.split(". ")[0]
if tags is None:
tags = []
self.pages.append({
"title": title,
"content": content,
"tags": tags,
"old_url": old_url,
"old_id": old_id,
"old_parent_id": old_parent_id,
}) | [
"def",
"add_page",
"(",
"self",
",",
"title",
"=",
"None",
",",
"content",
"=",
"None",
",",
"old_url",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"old_id",
"=",
"None",
",",
"old_parent_id",
"=",
"None",
")",
":",
"if",
"not",
"title",
":",
"text",
"=",
"decode_entities",
"(",
"strip_tags",
"(",
"content",
")",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\" \"",
")",
"title",
"=",
"text",
".",
"split",
"(",
"\". \"",
")",
"[",
"0",
"]",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"self",
".",
"pages",
".",
"append",
"(",
"{",
"\"title\"",
":",
"title",
",",
"\"content\"",
":",
"content",
",",
"\"tags\"",
":",
"tags",
",",
"\"old_url\"",
":",
"old_url",
",",
"\"old_id\"",
":",
"old_id",
",",
"\"old_parent_id\"",
":",
"old_parent_id",
",",
"}",
")"
] | Adds a page to the list of pages to be imported - used by the
Wordpress importer. | [
"Adds",
"a",
"page",
"to",
"the",
"list",
"of",
"pages",
"to",
"be",
"imported",
"-",
"used",
"by",
"the",
"Wordpress",
"importer",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/base.py#L86-L104 |
250,360 | minhhoit/yacms | yacms/blog/management/base.py | BaseImporterCommand.add_comment | def add_comment(self, post=None, name=None, email=None, pub_date=None,
website=None, body=None):
"""
Adds a comment to the post provided.
"""
if post is None:
if not self.posts:
raise CommandError("Cannot add comments without posts")
post = self.posts[-1]
post["comments"].append({
"user_name": name,
"user_email": email,
"submit_date": pub_date,
"user_url": website,
"comment": body,
}) | python | def add_comment(self, post=None, name=None, email=None, pub_date=None,
website=None, body=None):
"""
Adds a comment to the post provided.
"""
if post is None:
if not self.posts:
raise CommandError("Cannot add comments without posts")
post = self.posts[-1]
post["comments"].append({
"user_name": name,
"user_email": email,
"submit_date": pub_date,
"user_url": website,
"comment": body,
}) | [
"def",
"add_comment",
"(",
"self",
",",
"post",
"=",
"None",
",",
"name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"pub_date",
"=",
"None",
",",
"website",
"=",
"None",
",",
"body",
"=",
"None",
")",
":",
"if",
"post",
"is",
"None",
":",
"if",
"not",
"self",
".",
"posts",
":",
"raise",
"CommandError",
"(",
"\"Cannot add comments without posts\"",
")",
"post",
"=",
"self",
".",
"posts",
"[",
"-",
"1",
"]",
"post",
"[",
"\"comments\"",
"]",
".",
"append",
"(",
"{",
"\"user_name\"",
":",
"name",
",",
"\"user_email\"",
":",
"email",
",",
"\"submit_date\"",
":",
"pub_date",
",",
"\"user_url\"",
":",
"website",
",",
"\"comment\"",
":",
"body",
",",
"}",
")"
] | Adds a comment to the post provided. | [
"Adds",
"a",
"comment",
"to",
"the",
"post",
"provided",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/base.py#L106-L121 |
250,361 | minhhoit/yacms | yacms/blog/management/base.py | BaseImporterCommand.trunc | def trunc(self, model, prompt, **fields):
"""
Truncates fields values for the given model. Prompts for a new
value if truncation occurs.
"""
for field_name, value in fields.items():
field = model._meta.get_field(field_name)
max_length = getattr(field, "max_length", None)
if not max_length:
continue
elif not prompt:
fields[field_name] = value[:max_length]
continue
while len(value) > max_length:
encoded_value = value.encode("utf-8")
new_value = input("The value for the field %s.%s exceeds "
"its maximum length of %s chars: %s\n\nEnter a new value "
"for it, or press return to have it truncated: " %
(model.__name__, field_name, max_length, encoded_value))
value = new_value if new_value else value[:max_length]
fields[field_name] = value
return fields | python | def trunc(self, model, prompt, **fields):
"""
Truncates fields values for the given model. Prompts for a new
value if truncation occurs.
"""
for field_name, value in fields.items():
field = model._meta.get_field(field_name)
max_length = getattr(field, "max_length", None)
if not max_length:
continue
elif not prompt:
fields[field_name] = value[:max_length]
continue
while len(value) > max_length:
encoded_value = value.encode("utf-8")
new_value = input("The value for the field %s.%s exceeds "
"its maximum length of %s chars: %s\n\nEnter a new value "
"for it, or press return to have it truncated: " %
(model.__name__, field_name, max_length, encoded_value))
value = new_value if new_value else value[:max_length]
fields[field_name] = value
return fields | [
"def",
"trunc",
"(",
"self",
",",
"model",
",",
"prompt",
",",
"*",
"*",
"fields",
")",
":",
"for",
"field_name",
",",
"value",
"in",
"fields",
".",
"items",
"(",
")",
":",
"field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"max_length",
"=",
"getattr",
"(",
"field",
",",
"\"max_length\"",
",",
"None",
")",
"if",
"not",
"max_length",
":",
"continue",
"elif",
"not",
"prompt",
":",
"fields",
"[",
"field_name",
"]",
"=",
"value",
"[",
":",
"max_length",
"]",
"continue",
"while",
"len",
"(",
"value",
")",
">",
"max_length",
":",
"encoded_value",
"=",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
"new_value",
"=",
"input",
"(",
"\"The value for the field %s.%s exceeds \"",
"\"its maximum length of %s chars: %s\\n\\nEnter a new value \"",
"\"for it, or press return to have it truncated: \"",
"%",
"(",
"model",
".",
"__name__",
",",
"field_name",
",",
"max_length",
",",
"encoded_value",
")",
")",
"value",
"=",
"new_value",
"if",
"new_value",
"else",
"value",
"[",
":",
"max_length",
"]",
"fields",
"[",
"field_name",
"]",
"=",
"value",
"return",
"fields"
] | Truncates fields values for the given model. Prompts for a new
value if truncation occurs. | [
"Truncates",
"fields",
"values",
"for",
"the",
"given",
"model",
".",
"Prompts",
"for",
"a",
"new",
"value",
"if",
"truncation",
"occurs",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/base.py#L123-L144 |
250,362 | minhhoit/yacms | yacms/blog/management/base.py | BaseImporterCommand.add_meta | def add_meta(self, obj, tags, prompt, verbosity, old_url=None):
"""
Adds tags and a redirect for the given obj, which is a blog
post or a page.
"""
for tag in tags:
keyword = self.trunc(Keyword, prompt, title=tag)
keyword, created = Keyword.objects.get_or_create_iexact(**keyword)
obj.keywords.create(keyword=keyword)
if created and verbosity >= 1:
print("Imported tag: %s" % keyword)
if old_url is not None:
old_path = urlparse(old_url).path
if not old_path.strip("/"):
return
redirect = self.trunc(Redirect, prompt, old_path=old_path)
redirect['site'] = Site.objects.get_current()
redirect, created = Redirect.objects.get_or_create(**redirect)
redirect.new_path = obj.get_absolute_url()
redirect.save()
if created and verbosity >= 1:
print("Created redirect for: %s" % old_url) | python | def add_meta(self, obj, tags, prompt, verbosity, old_url=None):
"""
Adds tags and a redirect for the given obj, which is a blog
post or a page.
"""
for tag in tags:
keyword = self.trunc(Keyword, prompt, title=tag)
keyword, created = Keyword.objects.get_or_create_iexact(**keyword)
obj.keywords.create(keyword=keyword)
if created and verbosity >= 1:
print("Imported tag: %s" % keyword)
if old_url is not None:
old_path = urlparse(old_url).path
if not old_path.strip("/"):
return
redirect = self.trunc(Redirect, prompt, old_path=old_path)
redirect['site'] = Site.objects.get_current()
redirect, created = Redirect.objects.get_or_create(**redirect)
redirect.new_path = obj.get_absolute_url()
redirect.save()
if created and verbosity >= 1:
print("Created redirect for: %s" % old_url) | [
"def",
"add_meta",
"(",
"self",
",",
"obj",
",",
"tags",
",",
"prompt",
",",
"verbosity",
",",
"old_url",
"=",
"None",
")",
":",
"for",
"tag",
"in",
"tags",
":",
"keyword",
"=",
"self",
".",
"trunc",
"(",
"Keyword",
",",
"prompt",
",",
"title",
"=",
"tag",
")",
"keyword",
",",
"created",
"=",
"Keyword",
".",
"objects",
".",
"get_or_create_iexact",
"(",
"*",
"*",
"keyword",
")",
"obj",
".",
"keywords",
".",
"create",
"(",
"keyword",
"=",
"keyword",
")",
"if",
"created",
"and",
"verbosity",
">=",
"1",
":",
"print",
"(",
"\"Imported tag: %s\"",
"%",
"keyword",
")",
"if",
"old_url",
"is",
"not",
"None",
":",
"old_path",
"=",
"urlparse",
"(",
"old_url",
")",
".",
"path",
"if",
"not",
"old_path",
".",
"strip",
"(",
"\"/\"",
")",
":",
"return",
"redirect",
"=",
"self",
".",
"trunc",
"(",
"Redirect",
",",
"prompt",
",",
"old_path",
"=",
"old_path",
")",
"redirect",
"[",
"'site'",
"]",
"=",
"Site",
".",
"objects",
".",
"get_current",
"(",
")",
"redirect",
",",
"created",
"=",
"Redirect",
".",
"objects",
".",
"get_or_create",
"(",
"*",
"*",
"redirect",
")",
"redirect",
".",
"new_path",
"=",
"obj",
".",
"get_absolute_url",
"(",
")",
"redirect",
".",
"save",
"(",
")",
"if",
"created",
"and",
"verbosity",
">=",
"1",
":",
"print",
"(",
"\"Created redirect for: %s\"",
"%",
"old_url",
")"
] | Adds tags and a redirect for the given obj, which is a blog
post or a page. | [
"Adds",
"tags",
"and",
"a",
"redirect",
"for",
"the",
"given",
"obj",
"which",
"is",
"a",
"blog",
"post",
"or",
"a",
"page",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/blog/management/base.py#L242-L263 |
250,363 | tylerbutler/propane | propane/django/modeltools.py | smart_content_type_for_model | def smart_content_type_for_model(model):
"""
Returns the Django ContentType for a given model. If model is a proxy model, the proxy model's ContentType will
be returned. This differs from Django's standard behavior - the default behavior is to return the parent
ContentType for proxy models.
"""
try:
# noinspection PyPackageRequirements,PyUnresolvedReferences
from django.contrib.contenttypes.models import ContentType
except ImportError:
print("Django is required but cannot be imported.")
raise
if model._meta.proxy:
return ContentType.objects.get(app_label=model._meta.app_label,
model=model._meta.object_name.lower())
else:
return ContentType.objects.get_for_model(model) | python | def smart_content_type_for_model(model):
"""
Returns the Django ContentType for a given model. If model is a proxy model, the proxy model's ContentType will
be returned. This differs from Django's standard behavior - the default behavior is to return the parent
ContentType for proxy models.
"""
try:
# noinspection PyPackageRequirements,PyUnresolvedReferences
from django.contrib.contenttypes.models import ContentType
except ImportError:
print("Django is required but cannot be imported.")
raise
if model._meta.proxy:
return ContentType.objects.get(app_label=model._meta.app_label,
model=model._meta.object_name.lower())
else:
return ContentType.objects.get_for_model(model) | [
"def",
"smart_content_type_for_model",
"(",
"model",
")",
":",
"try",
":",
"# noinspection PyPackageRequirements,PyUnresolvedReferences",
"from",
"django",
".",
"contrib",
".",
"contenttypes",
".",
"models",
"import",
"ContentType",
"except",
"ImportError",
":",
"print",
"(",
"\"Django is required but cannot be imported.\"",
")",
"raise",
"if",
"model",
".",
"_meta",
".",
"proxy",
":",
"return",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"model",
".",
"_meta",
".",
"app_label",
",",
"model",
"=",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
")",
"else",
":",
"return",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")"
] | Returns the Django ContentType for a given model. If model is a proxy model, the proxy model's ContentType will
be returned. This differs from Django's standard behavior - the default behavior is to return the parent
ContentType for proxy models. | [
"Returns",
"the",
"Django",
"ContentType",
"for",
"a",
"given",
"model",
".",
"If",
"model",
"is",
"a",
"proxy",
"model",
"the",
"proxy",
"model",
"s",
"ContentType",
"will",
"be",
"returned",
".",
"This",
"differs",
"from",
"Django",
"s",
"standard",
"behavior",
"-",
"the",
"default",
"behavior",
"is",
"to",
"return",
"the",
"parent",
"ContentType",
"for",
"proxy",
"models",
"."
] | 6c404285ab8d78865b7175a5c8adf8fae12d6be5 | https://github.com/tylerbutler/propane/blob/6c404285ab8d78865b7175a5c8adf8fae12d6be5/propane/django/modeltools.py#L8-L25 |
250,364 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/utils.py | get_first_content | def get_first_content(el_list, alt=None, strip=True):
"""
Return content of the first element in `el_list` or `alt`. Also return `alt`
if the content string of first element is blank.
Args:
el_list (list): List of HTMLElement objects.
alt (default None): Value returner when list or content is blank.
strip (bool, default True): Call .strip() to content.
Returns:
str or alt: String representation of the content of the first element \
or `alt` if not found.
"""
if not el_list:
return alt
content = el_list[0].getContent()
if strip:
content = content.strip()
if not content:
return alt
return content | python | def get_first_content(el_list, alt=None, strip=True):
"""
Return content of the first element in `el_list` or `alt`. Also return `alt`
if the content string of first element is blank.
Args:
el_list (list): List of HTMLElement objects.
alt (default None): Value returner when list or content is blank.
strip (bool, default True): Call .strip() to content.
Returns:
str or alt: String representation of the content of the first element \
or `alt` if not found.
"""
if not el_list:
return alt
content = el_list[0].getContent()
if strip:
content = content.strip()
if not content:
return alt
return content | [
"def",
"get_first_content",
"(",
"el_list",
",",
"alt",
"=",
"None",
",",
"strip",
"=",
"True",
")",
":",
"if",
"not",
"el_list",
":",
"return",
"alt",
"content",
"=",
"el_list",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
"if",
"strip",
":",
"content",
"=",
"content",
".",
"strip",
"(",
")",
"if",
"not",
"content",
":",
"return",
"alt",
"return",
"content"
] | Return content of the first element in `el_list` or `alt`. Also return `alt`
if the content string of first element is blank.
Args:
el_list (list): List of HTMLElement objects.
alt (default None): Value returner when list or content is blank.
strip (bool, default True): Call .strip() to content.
Returns:
str or alt: String representation of the content of the first element \
or `alt` if not found. | [
"Return",
"content",
"of",
"the",
"first",
"element",
"in",
"el_list",
"or",
"alt",
".",
"Also",
"return",
"alt",
"if",
"the",
"content",
"string",
"of",
"first",
"element",
"is",
"blank",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L62-L87 |
250,365 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/utils.py | normalize_url | def normalize_url(base_url, rel_url):
"""
Normalize the `url` - from relative, create absolute URL.
Args:
base_url (str): Domain with ``protocol://`` string
rel_url (str): Relative or absolute url.
Returns:
str/None: Normalized URL or None if `url` is blank.
"""
if not rel_url:
return None
if not is_absolute_url(rel_url):
rel_url = rel_url.replace("../", "/")
if (not base_url.endswith("/")) and (not rel_url.startswith("/")):
return base_url + "/" + rel_url.replace("../", "/")
return base_url + rel_url.replace("../", "/")
return rel_url | python | def normalize_url(base_url, rel_url):
"""
Normalize the `url` - from relative, create absolute URL.
Args:
base_url (str): Domain with ``protocol://`` string
rel_url (str): Relative or absolute url.
Returns:
str/None: Normalized URL or None if `url` is blank.
"""
if not rel_url:
return None
if not is_absolute_url(rel_url):
rel_url = rel_url.replace("../", "/")
if (not base_url.endswith("/")) and (not rel_url.startswith("/")):
return base_url + "/" + rel_url.replace("../", "/")
return base_url + rel_url.replace("../", "/")
return rel_url | [
"def",
"normalize_url",
"(",
"base_url",
",",
"rel_url",
")",
":",
"if",
"not",
"rel_url",
":",
"return",
"None",
"if",
"not",
"is_absolute_url",
"(",
"rel_url",
")",
":",
"rel_url",
"=",
"rel_url",
".",
"replace",
"(",
"\"../\"",
",",
"\"/\"",
")",
"if",
"(",
"not",
"base_url",
".",
"endswith",
"(",
"\"/\"",
")",
")",
"and",
"(",
"not",
"rel_url",
".",
"startswith",
"(",
"\"/\"",
")",
")",
":",
"return",
"base_url",
"+",
"\"/\"",
"+",
"rel_url",
".",
"replace",
"(",
"\"../\"",
",",
"\"/\"",
")",
"return",
"base_url",
"+",
"rel_url",
".",
"replace",
"(",
"\"../\"",
",",
"\"/\"",
")",
"return",
"rel_url"
] | Normalize the `url` - from relative, create absolute URL.
Args:
base_url (str): Domain with ``protocol://`` string
rel_url (str): Relative or absolute url.
Returns:
str/None: Normalized URL or None if `url` is blank. | [
"Normalize",
"the",
"url",
"-",
"from",
"relative",
"create",
"absolute",
"URL",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L114-L136 |
250,366 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/utils.py | has_param | def has_param(param):
"""
Generate function, which will check `param` is in html element.
This function can be used as parameter for .find() method in HTMLElement.
"""
def has_param_closure(element):
"""
Look for `param` in `element`.
"""
if element.params.get(param, "").strip():
return True
return False
return has_param_closure | python | def has_param(param):
"""
Generate function, which will check `param` is in html element.
This function can be used as parameter for .find() method in HTMLElement.
"""
def has_param_closure(element):
"""
Look for `param` in `element`.
"""
if element.params.get(param, "").strip():
return True
return False
return has_param_closure | [
"def",
"has_param",
"(",
"param",
")",
":",
"def",
"has_param_closure",
"(",
"element",
")",
":",
"\"\"\"\n Look for `param` in `element`.\n \"\"\"",
"if",
"element",
".",
"params",
".",
"get",
"(",
"param",
",",
"\"\"",
")",
".",
"strip",
"(",
")",
":",
"return",
"True",
"return",
"False",
"return",
"has_param_closure"
] | Generate function, which will check `param` is in html element.
This function can be used as parameter for .find() method in HTMLElement. | [
"Generate",
"function",
"which",
"will",
"check",
"param",
"is",
"in",
"html",
"element",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L139-L154 |
250,367 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/utils.py | must_contain | def must_contain(tag_name, tag_content, container_tag_name):
"""
Generate function, which checks if given element contains `tag_name` with
string content `tag_content` and also another tag named
`container_tag_name`.
This function can be used as parameter for .find() method in HTMLElement.
"""
def must_contain_closure(element):
# containing in first level of childs <tag_name> tag
matching_tags = element.match(tag_name, absolute=True)
if not matching_tags:
return False
# which's content match `tag_content`
if matching_tags[0].getContent() != tag_content:
return False
# and also contains <container_tag_name> tag
if container_tag_name and \
not element.match(container_tag_name, absolute=True):
return False
return True
return must_contain_closure | python | def must_contain(tag_name, tag_content, container_tag_name):
"""
Generate function, which checks if given element contains `tag_name` with
string content `tag_content` and also another tag named
`container_tag_name`.
This function can be used as parameter for .find() method in HTMLElement.
"""
def must_contain_closure(element):
# containing in first level of childs <tag_name> tag
matching_tags = element.match(tag_name, absolute=True)
if not matching_tags:
return False
# which's content match `tag_content`
if matching_tags[0].getContent() != tag_content:
return False
# and also contains <container_tag_name> tag
if container_tag_name and \
not element.match(container_tag_name, absolute=True):
return False
return True
return must_contain_closure | [
"def",
"must_contain",
"(",
"tag_name",
",",
"tag_content",
",",
"container_tag_name",
")",
":",
"def",
"must_contain_closure",
"(",
"element",
")",
":",
"# containing in first level of childs <tag_name> tag",
"matching_tags",
"=",
"element",
".",
"match",
"(",
"tag_name",
",",
"absolute",
"=",
"True",
")",
"if",
"not",
"matching_tags",
":",
"return",
"False",
"# which's content match `tag_content`",
"if",
"matching_tags",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
"!=",
"tag_content",
":",
"return",
"False",
"# and also contains <container_tag_name> tag",
"if",
"container_tag_name",
"and",
"not",
"element",
".",
"match",
"(",
"container_tag_name",
",",
"absolute",
"=",
"True",
")",
":",
"return",
"False",
"return",
"True",
"return",
"must_contain_closure"
] | Generate function, which checks if given element contains `tag_name` with
string content `tag_content` and also another tag named
`container_tag_name`.
This function can be used as parameter for .find() method in HTMLElement. | [
"Generate",
"function",
"which",
"checks",
"if",
"given",
"element",
"contains",
"tag_name",
"with",
"string",
"content",
"tag_content",
"and",
"also",
"another",
"tag",
"named",
"container_tag_name",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L157-L182 |
250,368 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/scrappers/utils.py | content_matchs | def content_matchs(tag_content, content_transformer=None):
"""
Generate function, which checks whether the content of the tag matchs
`tag_content`.
Args:
tag_content (str): Content of the tag which will be matched thru whole
DOM.
content_transformer (fn, default None): Function used to transform all
tags before matching.
This function can be used as parameter for .find() method in HTMLElement.
"""
def content_matchs_closure(element):
if not element.isTag():
return False
cont = element.getContent()
if content_transformer:
cont = content_transformer(cont)
return tag_content == cont
return content_matchs_closure | python | def content_matchs(tag_content, content_transformer=None):
"""
Generate function, which checks whether the content of the tag matchs
`tag_content`.
Args:
tag_content (str): Content of the tag which will be matched thru whole
DOM.
content_transformer (fn, default None): Function used to transform all
tags before matching.
This function can be used as parameter for .find() method in HTMLElement.
"""
def content_matchs_closure(element):
if not element.isTag():
return False
cont = element.getContent()
if content_transformer:
cont = content_transformer(cont)
return tag_content == cont
return content_matchs_closure | [
"def",
"content_matchs",
"(",
"tag_content",
",",
"content_transformer",
"=",
"None",
")",
":",
"def",
"content_matchs_closure",
"(",
"element",
")",
":",
"if",
"not",
"element",
".",
"isTag",
"(",
")",
":",
"return",
"False",
"cont",
"=",
"element",
".",
"getContent",
"(",
")",
"if",
"content_transformer",
":",
"cont",
"=",
"content_transformer",
"(",
"cont",
")",
"return",
"tag_content",
"==",
"cont",
"return",
"content_matchs_closure"
] | Generate function, which checks whether the content of the tag matchs
`tag_content`.
Args:
tag_content (str): Content of the tag which will be matched thru whole
DOM.
content_transformer (fn, default None): Function used to transform all
tags before matching.
This function can be used as parameter for .find() method in HTMLElement. | [
"Generate",
"function",
"which",
"checks",
"whether",
"the",
"content",
"of",
"the",
"tag",
"matchs",
"tag_content",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/utils.py#L185-L208 |
250,369 | edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | _removeSpecialCharacters | def _removeSpecialCharacters(epub):
"""
Remove most of the unnecessary interpunction from epublication, which can
break unimark if not used properly.
"""
special_chars = "/:,- "
epub_dict = epub._asdict()
for key in epub_dict.keys():
if isinstance(epub_dict[key], basestring):
epub_dict[key] = epub_dict[key].strip(special_chars)
elif type(epub_dict[key]) in [tuple, list]:
out = []
for item in epub_dict[key]:
if not isinstance(item, Author):
out.append(item)
continue
new_item = item._asdict()
for key in new_item.keys():
new_item[key] = new_item[key].strip(special_chars)
out.append(Author(**new_item))
epub_dict[key] = out
return EPublication(**epub_dict) | python | def _removeSpecialCharacters(epub):
"""
Remove most of the unnecessary interpunction from epublication, which can
break unimark if not used properly.
"""
special_chars = "/:,- "
epub_dict = epub._asdict()
for key in epub_dict.keys():
if isinstance(epub_dict[key], basestring):
epub_dict[key] = epub_dict[key].strip(special_chars)
elif type(epub_dict[key]) in [tuple, list]:
out = []
for item in epub_dict[key]:
if not isinstance(item, Author):
out.append(item)
continue
new_item = item._asdict()
for key in new_item.keys():
new_item[key] = new_item[key].strip(special_chars)
out.append(Author(**new_item))
epub_dict[key] = out
return EPublication(**epub_dict) | [
"def",
"_removeSpecialCharacters",
"(",
"epub",
")",
":",
"special_chars",
"=",
"\"/:,- \"",
"epub_dict",
"=",
"epub",
".",
"_asdict",
"(",
")",
"for",
"key",
"in",
"epub_dict",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"epub_dict",
"[",
"key",
"]",
",",
"basestring",
")",
":",
"epub_dict",
"[",
"key",
"]",
"=",
"epub_dict",
"[",
"key",
"]",
".",
"strip",
"(",
"special_chars",
")",
"elif",
"type",
"(",
"epub_dict",
"[",
"key",
"]",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
":",
"out",
"=",
"[",
"]",
"for",
"item",
"in",
"epub_dict",
"[",
"key",
"]",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"Author",
")",
":",
"out",
".",
"append",
"(",
"item",
")",
"continue",
"new_item",
"=",
"item",
".",
"_asdict",
"(",
")",
"for",
"key",
"in",
"new_item",
".",
"keys",
"(",
")",
":",
"new_item",
"[",
"key",
"]",
"=",
"new_item",
"[",
"key",
"]",
".",
"strip",
"(",
"special_chars",
")",
"out",
".",
"append",
"(",
"Author",
"(",
"*",
"*",
"new_item",
")",
")",
"epub_dict",
"[",
"key",
"]",
"=",
"out",
"return",
"EPublication",
"(",
"*",
"*",
"epub_dict",
")"
] | Remove most of the unnecessary interpunction from epublication, which can
break unimark if not used properly. | [
"Remove",
"most",
"of",
"the",
"unnecessary",
"interpunction",
"from",
"epublication",
"which",
"can",
"break",
"unimark",
"if",
"not",
"used",
"properly",
"."
] | 360342c0504d5daa2344e864762cdf938d4149c7 | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L346-L375 |
250,370 | edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | PostData._import_epublication | def _import_epublication(self, epub):
"""
Fill internal property ._POST dictionary with data from EPublication.
"""
# mrs. Svobodová requires that annotation exported by us have this
# prefix
prefixed_annotation = ANNOTATION_PREFIX + epub.anotace
self._POST["P0501010__a"] = epub.ISBN
self._POST["P07012001_a"] = epub.nazev
self._POST["P07032001_e"] = epub.podnazev
self._POST["P0502010__b"] = epub.vazba
self._POST["P0504010__d"] = epub.cena
self._POST["P07042001_h"] = epub.castDil
self._POST["P07052001_i"] = epub.nazevCasti
self._POST["P0902210__c"] = epub.nakladatelVydavatel
self._POST["P0903210__d"] = epub.datumVydani
self._POST["P0801205__a"] = epub.poradiVydani
self._POST["P1502IST1_b"] = epub.zpracovatelZaznamu
self._POST["P0503010__x"] = epub.format
self._POST["P110185640u"] = epub.url or ""
self._POST["P0901210__a"] = epub.mistoVydani
self._POST["P0601010__a"] = epub.ISBNSouboruPublikaci
self._POST["P1801URL__u"] = epub.internal_url
self._POST["P1001330__a"] = prefixed_annotation if epub.anotace else ""
if len(epub.autori) > 3:
epub.autori[2] = ", ".join(epub.autori[2:])
epub.autori = epub.autori[:3]
# check whether the autors have required type (string)
for author in epub.autori:
error_msg = "Bad type of author (%s) (str is required)."
assert isinstance(author, basestring), (error_msg % type(author))
authors_fields = ("P1301ZAK__b", "P1302ZAK__c", "P1303ZAK__c")
self._POST.update(dict(zip(authors_fields, epub.autori))) | python | def _import_epublication(self, epub):
"""
Fill internal property ._POST dictionary with data from EPublication.
"""
# mrs. Svobodová requires that annotation exported by us have this
# prefix
prefixed_annotation = ANNOTATION_PREFIX + epub.anotace
self._POST["P0501010__a"] = epub.ISBN
self._POST["P07012001_a"] = epub.nazev
self._POST["P07032001_e"] = epub.podnazev
self._POST["P0502010__b"] = epub.vazba
self._POST["P0504010__d"] = epub.cena
self._POST["P07042001_h"] = epub.castDil
self._POST["P07052001_i"] = epub.nazevCasti
self._POST["P0902210__c"] = epub.nakladatelVydavatel
self._POST["P0903210__d"] = epub.datumVydani
self._POST["P0801205__a"] = epub.poradiVydani
self._POST["P1502IST1_b"] = epub.zpracovatelZaznamu
self._POST["P0503010__x"] = epub.format
self._POST["P110185640u"] = epub.url or ""
self._POST["P0901210__a"] = epub.mistoVydani
self._POST["P0601010__a"] = epub.ISBNSouboruPublikaci
self._POST["P1801URL__u"] = epub.internal_url
self._POST["P1001330__a"] = prefixed_annotation if epub.anotace else ""
if len(epub.autori) > 3:
epub.autori[2] = ", ".join(epub.autori[2:])
epub.autori = epub.autori[:3]
# check whether the autors have required type (string)
for author in epub.autori:
error_msg = "Bad type of author (%s) (str is required)."
assert isinstance(author, basestring), (error_msg % type(author))
authors_fields = ("P1301ZAK__b", "P1302ZAK__c", "P1303ZAK__c")
self._POST.update(dict(zip(authors_fields, epub.autori))) | [
"def",
"_import_epublication",
"(",
"self",
",",
"epub",
")",
":",
"# mrs. Svobodová requires that annotation exported by us have this",
"# prefix",
"prefixed_annotation",
"=",
"ANNOTATION_PREFIX",
"+",
"epub",
".",
"anotace",
"self",
".",
"_POST",
"[",
"\"P0501010__a\"",
"]",
"=",
"epub",
".",
"ISBN",
"self",
".",
"_POST",
"[",
"\"P07012001_a\"",
"]",
"=",
"epub",
".",
"nazev",
"self",
".",
"_POST",
"[",
"\"P07032001_e\"",
"]",
"=",
"epub",
".",
"podnazev",
"self",
".",
"_POST",
"[",
"\"P0502010__b\"",
"]",
"=",
"epub",
".",
"vazba",
"self",
".",
"_POST",
"[",
"\"P0504010__d\"",
"]",
"=",
"epub",
".",
"cena",
"self",
".",
"_POST",
"[",
"\"P07042001_h\"",
"]",
"=",
"epub",
".",
"castDil",
"self",
".",
"_POST",
"[",
"\"P07052001_i\"",
"]",
"=",
"epub",
".",
"nazevCasti",
"self",
".",
"_POST",
"[",
"\"P0902210__c\"",
"]",
"=",
"epub",
".",
"nakladatelVydavatel",
"self",
".",
"_POST",
"[",
"\"P0903210__d\"",
"]",
"=",
"epub",
".",
"datumVydani",
"self",
".",
"_POST",
"[",
"\"P0801205__a\"",
"]",
"=",
"epub",
".",
"poradiVydani",
"self",
".",
"_POST",
"[",
"\"P1502IST1_b\"",
"]",
"=",
"epub",
".",
"zpracovatelZaznamu",
"self",
".",
"_POST",
"[",
"\"P0503010__x\"",
"]",
"=",
"epub",
".",
"format",
"self",
".",
"_POST",
"[",
"\"P110185640u\"",
"]",
"=",
"epub",
".",
"url",
"or",
"\"\"",
"self",
".",
"_POST",
"[",
"\"P0901210__a\"",
"]",
"=",
"epub",
".",
"mistoVydani",
"self",
".",
"_POST",
"[",
"\"P0601010__a\"",
"]",
"=",
"epub",
".",
"ISBNSouboruPublikaci",
"self",
".",
"_POST",
"[",
"\"P1801URL__u\"",
"]",
"=",
"epub",
".",
"internal_url",
"self",
".",
"_POST",
"[",
"\"P1001330__a\"",
"]",
"=",
"prefixed_annotation",
"if",
"epub",
".",
"anotace",
"else",
"\"\"",
"if",
"len",
"(",
"epub",
".",
"autori",
")",
">",
"3",
":",
"epub",
".",
"autori",
"[",
"2",
"]",
"=",
"\", \"",
".",
"join",
"(",
"epub",
".",
"autori",
"[",
"2",
":",
"]",
")",
"epub",
".",
"autori",
"=",
"epub",
".",
"autori",
"[",
":",
"3",
"]",
"# check whether the autors have required type (string)",
"for",
"author",
"in",
"epub",
".",
"autori",
":",
"error_msg",
"=",
"\"Bad type of author (%s) (str is required).\"",
"assert",
"isinstance",
"(",
"author",
",",
"basestring",
")",
",",
"(",
"error_msg",
"%",
"type",
"(",
"author",
")",
")",
"authors_fields",
"=",
"(",
"\"P1301ZAK__b\"",
",",
"\"P1302ZAK__c\"",
",",
"\"P1303ZAK__c\"",
")",
"self",
".",
"_POST",
".",
"update",
"(",
"dict",
"(",
"zip",
"(",
"authors_fields",
",",
"epub",
".",
"autori",
")",
")",
")"
] | Fill internal property ._POST dictionary with data from EPublication. | [
"Fill",
"internal",
"property",
".",
"_POST",
"dictionary",
"with",
"data",
"from",
"EPublication",
"."
] | 360342c0504d5daa2344e864762cdf938d4149c7 | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L162-L198 |
250,371 | edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | PostData._apply_mapping | def _apply_mapping(self, mapping):
"""
Map some case specific data to the fields in internal dictionary.
"""
self._POST["P0100LDR__"] = mapping[0]
self._POST["P0200FMT__"] = mapping[1]
self._POST["P0300BAS__a"] = mapping[2]
self._POST["P07022001_b"] = mapping[3]
self._POST["P1501IST1_a"] = mapping[4] | python | def _apply_mapping(self, mapping):
"""
Map some case specific data to the fields in internal dictionary.
"""
self._POST["P0100LDR__"] = mapping[0]
self._POST["P0200FMT__"] = mapping[1]
self._POST["P0300BAS__a"] = mapping[2]
self._POST["P07022001_b"] = mapping[3]
self._POST["P1501IST1_a"] = mapping[4] | [
"def",
"_apply_mapping",
"(",
"self",
",",
"mapping",
")",
":",
"self",
".",
"_POST",
"[",
"\"P0100LDR__\"",
"]",
"=",
"mapping",
"[",
"0",
"]",
"self",
".",
"_POST",
"[",
"\"P0200FMT__\"",
"]",
"=",
"mapping",
"[",
"1",
"]",
"self",
".",
"_POST",
"[",
"\"P0300BAS__a\"",
"]",
"=",
"mapping",
"[",
"2",
"]",
"self",
".",
"_POST",
"[",
"\"P07022001_b\"",
"]",
"=",
"mapping",
"[",
"3",
"]",
"self",
".",
"_POST",
"[",
"\"P1501IST1_a\"",
"]",
"=",
"mapping",
"[",
"4",
"]"
] | Map some case specific data to the fields in internal dictionary. | [
"Map",
"some",
"case",
"specific",
"data",
"to",
"the",
"fields",
"in",
"internal",
"dictionary",
"."
] | 360342c0504d5daa2344e864762cdf938d4149c7 | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L200-L208 |
250,372 | edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | PostData._postprocess | def _postprocess(self):
"""
Move data between internal fields, validate them and make sure, that
everything is as it should be.
"""
# validate series ISBN
self._POST["P0601010__a"] = self._validate_isbn(
self._POST["P0601010__a"],
accept_blank=True
)
if self._POST["P0601010__a"] != "":
self._POST["P0601010__b"] = "soubor : " + self._POST["P0601010__a"]
# validate ISBN of the book
self._POST["P0501010__a"] = self._validate_isbn(
self._POST["P0501010__a"],
accept_blank=False
)
self._POST["P1601ISB__a"] = self._POST["P0501010__a"] | python | def _postprocess(self):
"""
Move data between internal fields, validate them and make sure, that
everything is as it should be.
"""
# validate series ISBN
self._POST["P0601010__a"] = self._validate_isbn(
self._POST["P0601010__a"],
accept_blank=True
)
if self._POST["P0601010__a"] != "":
self._POST["P0601010__b"] = "soubor : " + self._POST["P0601010__a"]
# validate ISBN of the book
self._POST["P0501010__a"] = self._validate_isbn(
self._POST["P0501010__a"],
accept_blank=False
)
self._POST["P1601ISB__a"] = self._POST["P0501010__a"] | [
"def",
"_postprocess",
"(",
"self",
")",
":",
"# validate series ISBN",
"self",
".",
"_POST",
"[",
"\"P0601010__a\"",
"]",
"=",
"self",
".",
"_validate_isbn",
"(",
"self",
".",
"_POST",
"[",
"\"P0601010__a\"",
"]",
",",
"accept_blank",
"=",
"True",
")",
"if",
"self",
".",
"_POST",
"[",
"\"P0601010__a\"",
"]",
"!=",
"\"\"",
":",
"self",
".",
"_POST",
"[",
"\"P0601010__b\"",
"]",
"=",
"\"soubor : \"",
"+",
"self",
".",
"_POST",
"[",
"\"P0601010__a\"",
"]",
"# validate ISBN of the book",
"self",
".",
"_POST",
"[",
"\"P0501010__a\"",
"]",
"=",
"self",
".",
"_validate_isbn",
"(",
"self",
".",
"_POST",
"[",
"\"P0501010__a\"",
"]",
",",
"accept_blank",
"=",
"False",
")",
"self",
".",
"_POST",
"[",
"\"P1601ISB__a\"",
"]",
"=",
"self",
".",
"_POST",
"[",
"\"P0501010__a\"",
"]"
] | Move data between internal fields, validate them and make sure, that
everything is as it should be. | [
"Move",
"data",
"between",
"internal",
"fields",
"validate",
"them",
"and",
"make",
"sure",
"that",
"everything",
"is",
"as",
"it",
"should",
"be",
"."
] | 360342c0504d5daa2344e864762cdf938d4149c7 | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L227-L245 |
250,373 | edeposit/edeposit.amqp.aleph | src/edeposit/amqp/aleph/export.py | PostData._check_required_fields | def _check_required_fields(self):
"""
Make sure, that internal dictionary contains all fields, which are
required by the webform.
"""
assert self._POST["P0501010__a"] != "", "ISBN is required!"
# export script accepts only czech ISBNs
for isbn_field_name in ("P0501010__a", "P1601ISB__a"):
check = PostData._czech_isbn_check(self._POST[isbn_field_name])
assert check, "Only czech ISBN is accepted!"
assert self._POST["P1601ISB__a"] != "", "Hidden ISBN field is required!"
assert self._POST["P07012001_a"] != "", "Nazev is required!"
assert self._POST["P0901210__a"] != "", "Místo vydání is required!"
assert self._POST["P0903210__d"] != "", "Datum vydání is required!"
assert self._POST["P0801205__a"] != "", "Pořadí vydání is required!"
# Zpracovatel záznamu
assert self._POST["P1501IST1_a"] != "", "Zpracovatel is required! (H)"
assert self._POST["P1502IST1_b"] != "", "Zpracovatel is required! (V)"
# vazba/forma
assert self._POST["P0502010__b"] != "", "Vazba/forma is required!"
# assert self._POST["P110185640u"] != "", "URL is required!"
# Formát (pouze pro epublikace)
if self._POST["P0502010__b"] == FormatEnum.ONLINE:
assert self._POST["P0503010__x"] != "", "Format is required!"
assert self._POST["P0902210__c"] != "", "Nakladatel is required!"
def to_unicode(inp):
try:
return unicode(inp)
except UnicodeDecodeError:
return unicode(inp, "utf-8")
# check lenght of annotation field - try to convert string to unicode,
# to count characters, not combination bytes
annotation_length = len(to_unicode(self._POST["P1001330__a"]))
annotation_length -= len(to_unicode(ANNOTATION_PREFIX))
assert annotation_length <= 500, "Annotation is too long (> 500)." | python | def _check_required_fields(self):
"""
Make sure, that internal dictionary contains all fields, which are
required by the webform.
"""
assert self._POST["P0501010__a"] != "", "ISBN is required!"
# export script accepts only czech ISBNs
for isbn_field_name in ("P0501010__a", "P1601ISB__a"):
check = PostData._czech_isbn_check(self._POST[isbn_field_name])
assert check, "Only czech ISBN is accepted!"
assert self._POST["P1601ISB__a"] != "", "Hidden ISBN field is required!"
assert self._POST["P07012001_a"] != "", "Nazev is required!"
assert self._POST["P0901210__a"] != "", "Místo vydání is required!"
assert self._POST["P0903210__d"] != "", "Datum vydání is required!"
assert self._POST["P0801205__a"] != "", "Pořadí vydání is required!"
# Zpracovatel záznamu
assert self._POST["P1501IST1_a"] != "", "Zpracovatel is required! (H)"
assert self._POST["P1502IST1_b"] != "", "Zpracovatel is required! (V)"
# vazba/forma
assert self._POST["P0502010__b"] != "", "Vazba/forma is required!"
# assert self._POST["P110185640u"] != "", "URL is required!"
# Formát (pouze pro epublikace)
if self._POST["P0502010__b"] == FormatEnum.ONLINE:
assert self._POST["P0503010__x"] != "", "Format is required!"
assert self._POST["P0902210__c"] != "", "Nakladatel is required!"
def to_unicode(inp):
try:
return unicode(inp)
except UnicodeDecodeError:
return unicode(inp, "utf-8")
# check lenght of annotation field - try to convert string to unicode,
# to count characters, not combination bytes
annotation_length = len(to_unicode(self._POST["P1001330__a"]))
annotation_length -= len(to_unicode(ANNOTATION_PREFIX))
assert annotation_length <= 500, "Annotation is too long (> 500)." | [
"def",
"_check_required_fields",
"(",
"self",
")",
":",
"assert",
"self",
".",
"_POST",
"[",
"\"P0501010__a\"",
"]",
"!=",
"\"\"",
",",
"\"ISBN is required!\"",
"# export script accepts only czech ISBNs",
"for",
"isbn_field_name",
"in",
"(",
"\"P0501010__a\"",
",",
"\"P1601ISB__a\"",
")",
":",
"check",
"=",
"PostData",
".",
"_czech_isbn_check",
"(",
"self",
".",
"_POST",
"[",
"isbn_field_name",
"]",
")",
"assert",
"check",
",",
"\"Only czech ISBN is accepted!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P1601ISB__a\"",
"]",
"!=",
"\"\"",
",",
"\"Hidden ISBN field is required!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P07012001_a\"",
"]",
"!=",
"\"\"",
",",
"\"Nazev is required!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P0901210__a\"",
"]",
"!=",
"\"\"",
",",
"\"Místo vydání is required!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P0903210__d\"",
"]",
"!=",
"\"\"",
",",
"\"Datum vydání is required!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P0801205__a\"",
"]",
"!=",
"\"\"",
",",
"\"Pořadí vydání is required!\"",
"# Zpracovatel záznamu",
"assert",
"self",
".",
"_POST",
"[",
"\"P1501IST1_a\"",
"]",
"!=",
"\"\"",
",",
"\"Zpracovatel is required! (H)\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P1502IST1_b\"",
"]",
"!=",
"\"\"",
",",
"\"Zpracovatel is required! (V)\"",
"# vazba/forma",
"assert",
"self",
".",
"_POST",
"[",
"\"P0502010__b\"",
"]",
"!=",
"\"\"",
",",
"\"Vazba/forma is required!\"",
"# assert self._POST[\"P110185640u\"] != \"\", \"URL is required!\"",
"# Formát (pouze pro epublikace)",
"if",
"self",
".",
"_POST",
"[",
"\"P0502010__b\"",
"]",
"==",
"FormatEnum",
".",
"ONLINE",
":",
"assert",
"self",
".",
"_POST",
"[",
"\"P0503010__x\"",
"]",
"!=",
"\"\"",
",",
"\"Format is required!\"",
"assert",
"self",
".",
"_POST",
"[",
"\"P0902210__c\"",
"]",
"!=",
"\"\"",
",",
"\"Nakladatel is required!\"",
"def",
"to_unicode",
"(",
"inp",
")",
":",
"try",
":",
"return",
"unicode",
"(",
"inp",
")",
"except",
"UnicodeDecodeError",
":",
"return",
"unicode",
"(",
"inp",
",",
"\"utf-8\"",
")",
"# check lenght of annotation field - try to convert string to unicode,",
"# to count characters, not combination bytes",
"annotation_length",
"=",
"len",
"(",
"to_unicode",
"(",
"self",
".",
"_POST",
"[",
"\"P1001330__a\"",
"]",
")",
")",
"annotation_length",
"-=",
"len",
"(",
"to_unicode",
"(",
"ANNOTATION_PREFIX",
")",
")",
"assert",
"annotation_length",
"<=",
"500",
",",
"\"Annotation is too long (> 500).\""
] | Make sure, that internal dictionary contains all fields, which are
required by the webform. | [
"Make",
"sure",
"that",
"internal",
"dictionary",
"contains",
"all",
"fields",
"which",
"are",
"required",
"by",
"the",
"webform",
"."
] | 360342c0504d5daa2344e864762cdf938d4149c7 | https://github.com/edeposit/edeposit.amqp.aleph/blob/360342c0504d5daa2344e864762cdf938d4149c7/src/edeposit/amqp/aleph/export.py#L256-L301 |
250,374 | paetzke/consolor | consolor/consolor.py | print_line | def print_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None, end='\n'):
"""
Prints a string with the given formatting.
"""
s = get_line(s, bold=bold, underline=underline,
blinking=blinking, color=color, bgcolor=bgcolor)
print(s, end=end) | python | def print_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None, end='\n'):
"""
Prints a string with the given formatting.
"""
s = get_line(s, bold=bold, underline=underline,
blinking=blinking, color=color, bgcolor=bgcolor)
print(s, end=end) | [
"def",
"print_line",
"(",
"s",
",",
"bold",
"=",
"False",
",",
"underline",
"=",
"False",
",",
"blinking",
"=",
"False",
",",
"color",
"=",
"None",
",",
"bgcolor",
"=",
"None",
",",
"end",
"=",
"'\\n'",
")",
":",
"s",
"=",
"get_line",
"(",
"s",
",",
"bold",
"=",
"bold",
",",
"underline",
"=",
"underline",
",",
"blinking",
"=",
"blinking",
",",
"color",
"=",
"color",
",",
"bgcolor",
"=",
"bgcolor",
")",
"print",
"(",
"s",
",",
"end",
"=",
"end",
")"
] | Prints a string with the given formatting. | [
"Prints",
"a",
"string",
"with",
"the",
"given",
"formatting",
"."
] | 2d6b6063c181095ae9ec805cc4571ad1f960e5fd | https://github.com/paetzke/consolor/blob/2d6b6063c181095ae9ec805cc4571ad1f960e5fd/consolor/consolor.py#L51-L58 |
250,375 | paetzke/consolor | consolor/consolor.py | get_line | def get_line(s, bold=False, underline=False, blinking=False, color=None,
bgcolor=None, update_line=False):
"""
Returns a string with the given formatting.
"""
parts = []
if update_line:
parts.append(_UPDATE_LINE)
for val in [color, bgcolor]:
if val:
parts.append(val)
if bold:
parts.append(_TURN_BOLD_MODE_ON)
if underline:
parts.append(_TURN_UNDERLINE_MODE_ON)
if blinking:
parts.append(_TURN_BLINKING_MODE_ON)
parts.append(s)
parts.append(_TURN_OFF_CHARACTER_ATTS)
result = ''.join(parts)
return result | python | def get_line(s, bold=False, underline=False, blinking=False, color=None,
bgcolor=None, update_line=False):
"""
Returns a string with the given formatting.
"""
parts = []
if update_line:
parts.append(_UPDATE_LINE)
for val in [color, bgcolor]:
if val:
parts.append(val)
if bold:
parts.append(_TURN_BOLD_MODE_ON)
if underline:
parts.append(_TURN_UNDERLINE_MODE_ON)
if blinking:
parts.append(_TURN_BLINKING_MODE_ON)
parts.append(s)
parts.append(_TURN_OFF_CHARACTER_ATTS)
result = ''.join(parts)
return result | [
"def",
"get_line",
"(",
"s",
",",
"bold",
"=",
"False",
",",
"underline",
"=",
"False",
",",
"blinking",
"=",
"False",
",",
"color",
"=",
"None",
",",
"bgcolor",
"=",
"None",
",",
"update_line",
"=",
"False",
")",
":",
"parts",
"=",
"[",
"]",
"if",
"update_line",
":",
"parts",
".",
"append",
"(",
"_UPDATE_LINE",
")",
"for",
"val",
"in",
"[",
"color",
",",
"bgcolor",
"]",
":",
"if",
"val",
":",
"parts",
".",
"append",
"(",
"val",
")",
"if",
"bold",
":",
"parts",
".",
"append",
"(",
"_TURN_BOLD_MODE_ON",
")",
"if",
"underline",
":",
"parts",
".",
"append",
"(",
"_TURN_UNDERLINE_MODE_ON",
")",
"if",
"blinking",
":",
"parts",
".",
"append",
"(",
"_TURN_BLINKING_MODE_ON",
")",
"parts",
".",
"append",
"(",
"s",
")",
"parts",
".",
"append",
"(",
"_TURN_OFF_CHARACTER_ATTS",
")",
"result",
"=",
"''",
".",
"join",
"(",
"parts",
")",
"return",
"result"
] | Returns a string with the given formatting. | [
"Returns",
"a",
"string",
"with",
"the",
"given",
"formatting",
"."
] | 2d6b6063c181095ae9ec805cc4571ad1f960e5fd | https://github.com/paetzke/consolor/blob/2d6b6063c181095ae9ec805cc4571ad1f960e5fd/consolor/consolor.py#L61-L87 |
250,376 | paetzke/consolor | consolor/consolor.py | update_line | def update_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None):
"""
Overwrites the output of the current line and prints s on the same line
without a new line.
"""
s = get_line(s, bold=bold, underline=underline, blinking=blinking,
color=color, bgcolor=bgcolor, update_line=True)
print(s, end='') | python | def update_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None):
"""
Overwrites the output of the current line and prints s on the same line
without a new line.
"""
s = get_line(s, bold=bold, underline=underline, blinking=blinking,
color=color, bgcolor=bgcolor, update_line=True)
print(s, end='') | [
"def",
"update_line",
"(",
"s",
",",
"bold",
"=",
"False",
",",
"underline",
"=",
"False",
",",
"blinking",
"=",
"False",
",",
"color",
"=",
"None",
",",
"bgcolor",
"=",
"None",
")",
":",
"s",
"=",
"get_line",
"(",
"s",
",",
"bold",
"=",
"bold",
",",
"underline",
"=",
"underline",
",",
"blinking",
"=",
"blinking",
",",
"color",
"=",
"color",
",",
"bgcolor",
"=",
"bgcolor",
",",
"update_line",
"=",
"True",
")",
"print",
"(",
"s",
",",
"end",
"=",
"''",
")"
] | Overwrites the output of the current line and prints s on the same line
without a new line. | [
"Overwrites",
"the",
"output",
"of",
"the",
"current",
"line",
"and",
"prints",
"s",
"on",
"the",
"same",
"line",
"without",
"a",
"new",
"line",
"."
] | 2d6b6063c181095ae9ec805cc4571ad1f960e5fd | https://github.com/paetzke/consolor/blob/2d6b6063c181095ae9ec805cc4571ad1f960e5fd/consolor/consolor.py#L90-L98 |
250,377 | mixmastamyk/env | env.py | Entry.path_list | def path_list(self, sep=os.pathsep):
''' Return list of Path objects. '''
from pathlib import Path
return [ Path(pathstr) for pathstr in self.split(sep) ] | python | def path_list(self, sep=os.pathsep):
''' Return list of Path objects. '''
from pathlib import Path
return [ Path(pathstr) for pathstr in self.split(sep) ] | [
"def",
"path_list",
"(",
"self",
",",
"sep",
"=",
"os",
".",
"pathsep",
")",
":",
"from",
"pathlib",
"import",
"Path",
"return",
"[",
"Path",
"(",
"pathstr",
")",
"for",
"pathstr",
"in",
"self",
".",
"split",
"(",
"sep",
")",
"]"
] | Return list of Path objects. | [
"Return",
"list",
"of",
"Path",
"objects",
"."
] | 63ed6b914bd5189986972b338b86453e42890fa0 | https://github.com/mixmastamyk/env/blob/63ed6b914bd5189986972b338b86453e42890fa0/env.py#L87-L90 |
250,378 | b3j0f/conf | b3j0f/conf/configurable/log.py | _filehandler | def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') | python | def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') | [
"def",
"_filehandler",
"(",
"configurable",
")",
":",
"filename",
"=",
"configurable",
".",
"log_name",
".",
"replace",
"(",
"'.'",
",",
"sep",
")",
"path",
"=",
"join",
"(",
"configurable",
".",
"log_path",
",",
"'{0}.log'",
".",
"format",
"(",
"filename",
")",
")",
"return",
"FileHandler",
"(",
"path",
",",
"mode",
"=",
"'a+'",
")"
] | Default logging file handler. | [
"Default",
"logging",
"file",
"handler",
"."
] | 18dd6d5d6560f9b202793739e2330a2181163511 | https://github.com/b3j0f/conf/blob/18dd6d5d6560f9b202793739e2330a2181163511/b3j0f/conf/configurable/log.py#L51-L57 |
250,379 | globocom/globomap-loader-api-client | globomap_loader_api_client/update.py | Update.post | def post(self, document):
"""Send to API a document or a list of document.
:param document: a document or a list of document.
:type document: dict or list
:return: Message with location of job
:rtype: dict
:raises ValidationError: if API returns status 400
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status
"""
if type(document) is dict:
document = [document]
return self.make_request(method='POST', uri='updates/', data=document) | python | def post(self, document):
"""Send to API a document or a list of document.
:param document: a document or a list of document.
:type document: dict or list
:return: Message with location of job
:rtype: dict
:raises ValidationError: if API returns status 400
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status
"""
if type(document) is dict:
document = [document]
return self.make_request(method='POST', uri='updates/', data=document) | [
"def",
"post",
"(",
"self",
",",
"document",
")",
":",
"if",
"type",
"(",
"document",
")",
"is",
"dict",
":",
"document",
"=",
"[",
"document",
"]",
"return",
"self",
".",
"make_request",
"(",
"method",
"=",
"'POST'",
",",
"uri",
"=",
"'updates/'",
",",
"data",
"=",
"document",
")"
] | Send to API a document or a list of document.
:param document: a document or a list of document.
:type document: dict or list
:return: Message with location of job
:rtype: dict
:raises ValidationError: if API returns status 400
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status | [
"Send",
"to",
"API",
"a",
"document",
"or",
"a",
"list",
"of",
"document",
"."
] | b12347ca77d245de1abd604d1b694162156570e6 | https://github.com/globocom/globomap-loader-api-client/blob/b12347ca77d245de1abd604d1b694162156570e6/globomap_loader_api_client/update.py#L21-L38 |
250,380 | globocom/globomap-loader-api-client | globomap_loader_api_client/update.py | Update.get | def get(self, key):
"""Return the status from a job.
:param key: id of job
:type document: dict or list
:return: message with location of job
:rtype: dict
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status
"""
uri = 'updates/job/{}'.format(key)
return self.make_request(method='GET', uri=uri) | python | def get(self, key):
"""Return the status from a job.
:param key: id of job
:type document: dict or list
:return: message with location of job
:rtype: dict
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status
"""
uri = 'updates/job/{}'.format(key)
return self.make_request(method='GET', uri=uri) | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"uri",
"=",
"'updates/job/{}'",
".",
"format",
"(",
"key",
")",
"return",
"self",
".",
"make_request",
"(",
"method",
"=",
"'GET'",
",",
"uri",
"=",
"uri",
")"
] | Return the status from a job.
:param key: id of job
:type document: dict or list
:return: message with location of job
:rtype: dict
:raises Unauthorized: if API returns status 401
:raises Forbidden: if API returns status 403
:raises NotFound: if API returns status 404
:raises ApiError: if API returns other status | [
"Return",
"the",
"status",
"from",
"a",
"job",
"."
] | b12347ca77d245de1abd604d1b694162156570e6 | https://github.com/globocom/globomap-loader-api-client/blob/b12347ca77d245de1abd604d1b694162156570e6/globomap_loader_api_client/update.py#L40-L54 |
250,381 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/inventory/expand_hosts.py | detect_range | def detect_range(line = None):
'''
A helper function that checks a given host line to see if it contains
a range pattern descibed in the docstring above.
Returnes True if the given line contains a pattern, else False.
'''
if (not line.startswith("[") and
line.find("[") != -1 and
line.find(":") != -1 and
line.find("]") != -1 and
line.index("[") < line.index(":") < line.index("]")):
return True
else:
return False | python | def detect_range(line = None):
'''
A helper function that checks a given host line to see if it contains
a range pattern descibed in the docstring above.
Returnes True if the given line contains a pattern, else False.
'''
if (not line.startswith("[") and
line.find("[") != -1 and
line.find(":") != -1 and
line.find("]") != -1 and
line.index("[") < line.index(":") < line.index("]")):
return True
else:
return False | [
"def",
"detect_range",
"(",
"line",
"=",
"None",
")",
":",
"if",
"(",
"not",
"line",
".",
"startswith",
"(",
"\"[\"",
")",
"and",
"line",
".",
"find",
"(",
"\"[\"",
")",
"!=",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"\":\"",
")",
"!=",
"-",
"1",
"and",
"line",
".",
"find",
"(",
"\"]\"",
")",
"!=",
"-",
"1",
"and",
"line",
".",
"index",
"(",
"\"[\"",
")",
"<",
"line",
".",
"index",
"(",
"\":\"",
")",
"<",
"line",
".",
"index",
"(",
"\"]\"",
")",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | A helper function that checks a given host line to see if it contains
a range pattern descibed in the docstring above.
Returnes True if the given line contains a pattern, else False. | [
"A",
"helper",
"function",
"that",
"checks",
"a",
"given",
"host",
"line",
"to",
"see",
"if",
"it",
"contains",
"a",
"range",
"pattern",
"descibed",
"in",
"the",
"docstring",
"above",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/expand_hosts.py#L37-L51 |
250,382 | cirruscluster/cirruscluster | cirruscluster/ext/ansible/inventory/expand_hosts.py | expand_hostname_range | def expand_hostname_range(line = None):
'''
A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in this function with '|' to ease
string splitting.
References: http://ansible.github.com/patterns.html#hosts-and-groups
'''
all_hosts = []
if line:
# A hostname such as db[1:6]-node is considered to consists
# three parts:
# head: 'db'
# nrange: [1:6]; range() is a built-in. Can't use the name
# tail: '-node'
(head, nrange, tail) = line.replace('[','|').replace(']','|').split('|')
bounds = nrange.split(":")
if len(bounds) != 2:
raise errors.AnsibleError("host range incorrectly specified")
beg = bounds[0]
end = bounds[1]
if not beg:
beg = "0"
if not end:
raise errors.AnsibleError("host range end value missing")
if beg[0] == '0' and len(beg) > 1:
rlen = len(beg) # range length formatting hint
if rlen != len(end):
raise errors.AnsibleError("host range format incorrectly specified!")
fill = lambda _: str(_).zfill(rlen) # range sequence
else:
fill = str
try:
i_beg = string.ascii_letters.index(beg)
i_end = string.ascii_letters.index(end)
if i_beg > i_end:
raise errors.AnsibleError("host range format incorrectly specified!")
seq = string.ascii_letters[i_beg:i_end+1]
except ValueError: # not a alpha range
seq = range(int(beg), int(end)+1)
for rseq in seq:
hname = ''.join((head, fill(rseq), tail))
all_hosts.append(hname)
return all_hosts | python | def expand_hostname_range(line = None):
'''
A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in this function with '|' to ease
string splitting.
References: http://ansible.github.com/patterns.html#hosts-and-groups
'''
all_hosts = []
if line:
# A hostname such as db[1:6]-node is considered to consists
# three parts:
# head: 'db'
# nrange: [1:6]; range() is a built-in. Can't use the name
# tail: '-node'
(head, nrange, tail) = line.replace('[','|').replace(']','|').split('|')
bounds = nrange.split(":")
if len(bounds) != 2:
raise errors.AnsibleError("host range incorrectly specified")
beg = bounds[0]
end = bounds[1]
if not beg:
beg = "0"
if not end:
raise errors.AnsibleError("host range end value missing")
if beg[0] == '0' and len(beg) > 1:
rlen = len(beg) # range length formatting hint
if rlen != len(end):
raise errors.AnsibleError("host range format incorrectly specified!")
fill = lambda _: str(_).zfill(rlen) # range sequence
else:
fill = str
try:
i_beg = string.ascii_letters.index(beg)
i_end = string.ascii_letters.index(end)
if i_beg > i_end:
raise errors.AnsibleError("host range format incorrectly specified!")
seq = string.ascii_letters[i_beg:i_end+1]
except ValueError: # not a alpha range
seq = range(int(beg), int(end)+1)
for rseq in seq:
hname = ''.join((head, fill(rseq), tail))
all_hosts.append(hname)
return all_hosts | [
"def",
"expand_hostname_range",
"(",
"line",
"=",
"None",
")",
":",
"all_hosts",
"=",
"[",
"]",
"if",
"line",
":",
"# A hostname such as db[1:6]-node is considered to consists",
"# three parts:",
"# head: 'db'",
"# nrange: [1:6]; range() is a built-in. Can't use the name",
"# tail: '-node'",
"(",
"head",
",",
"nrange",
",",
"tail",
")",
"=",
"line",
".",
"replace",
"(",
"'['",
",",
"'|'",
")",
".",
"replace",
"(",
"']'",
",",
"'|'",
")",
".",
"split",
"(",
"'|'",
")",
"bounds",
"=",
"nrange",
".",
"split",
"(",
"\":\"",
")",
"if",
"len",
"(",
"bounds",
")",
"!=",
"2",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"host range incorrectly specified\"",
")",
"beg",
"=",
"bounds",
"[",
"0",
"]",
"end",
"=",
"bounds",
"[",
"1",
"]",
"if",
"not",
"beg",
":",
"beg",
"=",
"\"0\"",
"if",
"not",
"end",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"host range end value missing\"",
")",
"if",
"beg",
"[",
"0",
"]",
"==",
"'0'",
"and",
"len",
"(",
"beg",
")",
">",
"1",
":",
"rlen",
"=",
"len",
"(",
"beg",
")",
"# range length formatting hint",
"if",
"rlen",
"!=",
"len",
"(",
"end",
")",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"host range format incorrectly specified!\"",
")",
"fill",
"=",
"lambda",
"_",
":",
"str",
"(",
"_",
")",
".",
"zfill",
"(",
"rlen",
")",
"# range sequence",
"else",
":",
"fill",
"=",
"str",
"try",
":",
"i_beg",
"=",
"string",
".",
"ascii_letters",
".",
"index",
"(",
"beg",
")",
"i_end",
"=",
"string",
".",
"ascii_letters",
".",
"index",
"(",
"end",
")",
"if",
"i_beg",
">",
"i_end",
":",
"raise",
"errors",
".",
"AnsibleError",
"(",
"\"host range format incorrectly specified!\"",
")",
"seq",
"=",
"string",
".",
"ascii_letters",
"[",
"i_beg",
":",
"i_end",
"+",
"1",
"]",
"except",
"ValueError",
":",
"# not a alpha range",
"seq",
"=",
"range",
"(",
"int",
"(",
"beg",
")",
",",
"int",
"(",
"end",
")",
"+",
"1",
")",
"for",
"rseq",
"in",
"seq",
":",
"hname",
"=",
"''",
".",
"join",
"(",
"(",
"head",
",",
"fill",
"(",
"rseq",
")",
",",
"tail",
")",
")",
"all_hosts",
".",
"append",
"(",
"hname",
")",
"return",
"all_hosts"
] | A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in this function with '|' to ease
string splitting.
References: http://ansible.github.com/patterns.html#hosts-and-groups | [
"A",
"helper",
"function",
"that",
"expands",
"a",
"given",
"line",
"that",
"contains",
"a",
"pattern",
"specified",
"in",
"top",
"docstring",
"and",
"returns",
"a",
"list",
"that",
"consists",
"of",
"the",
"expanded",
"version",
"."
] | 977409929dd81322d886425cdced10608117d5d7 | https://github.com/cirruscluster/cirruscluster/blob/977409929dd81322d886425cdced10608117d5d7/cirruscluster/ext/ansible/inventory/expand_hosts.py#L53-L104 |
250,383 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/add_content.py | AddContent.create | def create(self, image=None):
"""Create content and return url. In case of images add the image."""
container = self.context
new = api.content.create(
container=container,
type=self.portal_type,
title=self.title,
safe_id=True,
)
if image:
namedblobimage = NamedBlobImage(
data=image.read(),
filename=safe_unicode(image.filename))
new.image = namedblobimage
if new:
new.description = safe_unicode(self.description)
return new.absolute_url() | python | def create(self, image=None):
"""Create content and return url. In case of images add the image."""
container = self.context
new = api.content.create(
container=container,
type=self.portal_type,
title=self.title,
safe_id=True,
)
if image:
namedblobimage = NamedBlobImage(
data=image.read(),
filename=safe_unicode(image.filename))
new.image = namedblobimage
if new:
new.description = safe_unicode(self.description)
return new.absolute_url() | [
"def",
"create",
"(",
"self",
",",
"image",
"=",
"None",
")",
":",
"container",
"=",
"self",
".",
"context",
"new",
"=",
"api",
".",
"content",
".",
"create",
"(",
"container",
"=",
"container",
",",
"type",
"=",
"self",
".",
"portal_type",
",",
"title",
"=",
"self",
".",
"title",
",",
"safe_id",
"=",
"True",
",",
")",
"if",
"image",
":",
"namedblobimage",
"=",
"NamedBlobImage",
"(",
"data",
"=",
"image",
".",
"read",
"(",
")",
",",
"filename",
"=",
"safe_unicode",
"(",
"image",
".",
"filename",
")",
")",
"new",
".",
"image",
"=",
"namedblobimage",
"if",
"new",
":",
"new",
".",
"description",
"=",
"safe_unicode",
"(",
"self",
".",
"description",
")",
"return",
"new",
".",
"absolute_url",
"(",
")"
] | Create content and return url. In case of images add the image. | [
"Create",
"content",
"and",
"return",
"url",
".",
"In",
"case",
"of",
"images",
"add",
"the",
"image",
"."
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/add_content.py#L32-L49 |
250,384 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/add_content.py | AddContent.redirect | def redirect(self, url):
"""Has its own method to allow overriding"""
url = '{}/view'.format(url)
return self.request.response.redirect(url) | python | def redirect(self, url):
"""Has its own method to allow overriding"""
url = '{}/view'.format(url)
return self.request.response.redirect(url) | [
"def",
"redirect",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"'{}/view'",
".",
"format",
"(",
"url",
")",
"return",
"self",
".",
"request",
".",
"response",
".",
"redirect",
"(",
"url",
")"
] | Has its own method to allow overriding | [
"Has",
"its",
"own",
"method",
"to",
"allow",
"overriding"
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/add_content.py#L51-L54 |
250,385 | ploneintranet/ploneintranet.workspace | src/ploneintranet/workspace/browser/roster.py | EditRoster.update_users | def update_users(self, entries):
"""Update user properties on the roster """
ws = IWorkspace(self.context)
members = ws.members
# check user permissions against join policy
join_policy = self.context.join_policy
if (join_policy == "admin"
and not checkPermission(
"collective.workspace: Manage roster",
self.context)):
raise Unauthorized("You are not allowed to add users here")
for entry in entries:
id = entry.get('id')
is_member = bool(entry.get('member'))
is_admin = bool(entry.get('admin'))
# Existing members
if id in members:
member = members[id]
if not is_member:
if checkPermission(
"ploneintranet.workspace: Manage workspace",
self.context):
ws.membership_factory(ws, member).remove_from_team()
else:
raise Unauthorized(
"Only team managers can remove members")
elif not is_admin:
ws.membership_factory(ws, member).groups -= {'Admins'}
else:
ws.membership_factory(ws, member).groups |= {'Admins'}
# New members
elif id not in members and (is_member or is_admin):
groups = set()
if is_admin:
groups.add('Admins')
ws.add_to_team(user=id, groups=groups) | python | def update_users(self, entries):
"""Update user properties on the roster """
ws = IWorkspace(self.context)
members = ws.members
# check user permissions against join policy
join_policy = self.context.join_policy
if (join_policy == "admin"
and not checkPermission(
"collective.workspace: Manage roster",
self.context)):
raise Unauthorized("You are not allowed to add users here")
for entry in entries:
id = entry.get('id')
is_member = bool(entry.get('member'))
is_admin = bool(entry.get('admin'))
# Existing members
if id in members:
member = members[id]
if not is_member:
if checkPermission(
"ploneintranet.workspace: Manage workspace",
self.context):
ws.membership_factory(ws, member).remove_from_team()
else:
raise Unauthorized(
"Only team managers can remove members")
elif not is_admin:
ws.membership_factory(ws, member).groups -= {'Admins'}
else:
ws.membership_factory(ws, member).groups |= {'Admins'}
# New members
elif id not in members and (is_member or is_admin):
groups = set()
if is_admin:
groups.add('Admins')
ws.add_to_team(user=id, groups=groups) | [
"def",
"update_users",
"(",
"self",
",",
"entries",
")",
":",
"ws",
"=",
"IWorkspace",
"(",
"self",
".",
"context",
")",
"members",
"=",
"ws",
".",
"members",
"# check user permissions against join policy",
"join_policy",
"=",
"self",
".",
"context",
".",
"join_policy",
"if",
"(",
"join_policy",
"==",
"\"admin\"",
"and",
"not",
"checkPermission",
"(",
"\"collective.workspace: Manage roster\"",
",",
"self",
".",
"context",
")",
")",
":",
"raise",
"Unauthorized",
"(",
"\"You are not allowed to add users here\"",
")",
"for",
"entry",
"in",
"entries",
":",
"id",
"=",
"entry",
".",
"get",
"(",
"'id'",
")",
"is_member",
"=",
"bool",
"(",
"entry",
".",
"get",
"(",
"'member'",
")",
")",
"is_admin",
"=",
"bool",
"(",
"entry",
".",
"get",
"(",
"'admin'",
")",
")",
"# Existing members",
"if",
"id",
"in",
"members",
":",
"member",
"=",
"members",
"[",
"id",
"]",
"if",
"not",
"is_member",
":",
"if",
"checkPermission",
"(",
"\"ploneintranet.workspace: Manage workspace\"",
",",
"self",
".",
"context",
")",
":",
"ws",
".",
"membership_factory",
"(",
"ws",
",",
"member",
")",
".",
"remove_from_team",
"(",
")",
"else",
":",
"raise",
"Unauthorized",
"(",
"\"Only team managers can remove members\"",
")",
"elif",
"not",
"is_admin",
":",
"ws",
".",
"membership_factory",
"(",
"ws",
",",
"member",
")",
".",
"groups",
"-=",
"{",
"'Admins'",
"}",
"else",
":",
"ws",
".",
"membership_factory",
"(",
"ws",
",",
"member",
")",
".",
"groups",
"|=",
"{",
"'Admins'",
"}",
"# New members",
"elif",
"id",
"not",
"in",
"members",
"and",
"(",
"is_member",
"or",
"is_admin",
")",
":",
"groups",
"=",
"set",
"(",
")",
"if",
"is_admin",
":",
"groups",
".",
"add",
"(",
"'Admins'",
")",
"ws",
".",
"add_to_team",
"(",
"user",
"=",
"id",
",",
"groups",
"=",
"groups",
")"
] | Update user properties on the roster | [
"Update",
"user",
"properties",
"on",
"the",
"roster"
] | a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba | https://github.com/ploneintranet/ploneintranet.workspace/blob/a4fc7a5c61f9c6d4d4ad25478ff5250f342ffbba/src/ploneintranet/workspace/browser/roster.py#L43-L82 |
250,386 | spookey/photon | photon/tools/git.py | Git._get_remote | def _get_remote(self, cached=True):
'''
Helper function to determine remote
:param cached:
Use cached values or query remotes
'''
return self.m(
'getting current remote',
cmdd=dict(
cmd='git remote show %s' % ('-n' if cached else ''),
cwd=self.local
),
verbose=False
) | python | def _get_remote(self, cached=True):
'''
Helper function to determine remote
:param cached:
Use cached values or query remotes
'''
return self.m(
'getting current remote',
cmdd=dict(
cmd='git remote show %s' % ('-n' if cached else ''),
cwd=self.local
),
verbose=False
) | [
"def",
"_get_remote",
"(",
"self",
",",
"cached",
"=",
"True",
")",
":",
"return",
"self",
".",
"m",
"(",
"'getting current remote'",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git remote show %s'",
"%",
"(",
"'-n'",
"if",
"cached",
"else",
"''",
")",
",",
"cwd",
"=",
"self",
".",
"local",
")",
",",
"verbose",
"=",
"False",
")"
] | Helper function to determine remote
:param cached:
Use cached values or query remotes | [
"Helper",
"function",
"to",
"determine",
"remote"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/git.py#L350-L365 |
250,387 | spookey/photon | photon/tools/git.py | Git._log | def _log(self, num=None, format=None):
'''
Helper function to receive git log
:param num:
Number of entries
:param format:
Use formatted output with specified format string
'''
num = '-n %s' % (num) if num else ''
format = '--format="%s"' % (format) if format else ''
return self.m(
'getting git log',
cmdd=dict(cmd='git log %s %s' % (num, format), cwd=self.local),
verbose=False
) | python | def _log(self, num=None, format=None):
'''
Helper function to receive git log
:param num:
Number of entries
:param format:
Use formatted output with specified format string
'''
num = '-n %s' % (num) if num else ''
format = '--format="%s"' % (format) if format else ''
return self.m(
'getting git log',
cmdd=dict(cmd='git log %s %s' % (num, format), cwd=self.local),
verbose=False
) | [
"def",
"_log",
"(",
"self",
",",
"num",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"num",
"=",
"'-n %s'",
"%",
"(",
"num",
")",
"if",
"num",
"else",
"''",
"format",
"=",
"'--format=\"%s\"'",
"%",
"(",
"format",
")",
"if",
"format",
"else",
"''",
"return",
"self",
".",
"m",
"(",
"'getting git log'",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git log %s %s'",
"%",
"(",
"num",
",",
"format",
")",
",",
"cwd",
"=",
"self",
".",
"local",
")",
",",
"verbose",
"=",
"False",
")"
] | Helper function to receive git log
:param num:
Number of entries
:param format:
Use formatted output with specified format string | [
"Helper",
"function",
"to",
"receive",
"git",
"log"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/git.py#L367-L383 |
250,388 | spookey/photon | photon/tools/git.py | Git._get_branch | def _get_branch(self, remotes=False):
'''
Helper function to determine current branch
:param remotes:
List the remote-tracking branches
'''
return self.m(
'getting git branch information',
cmdd=dict(
cmd='git branch %s' % ('-r' if remotes else ''),
cwd=self.local
),
verbose=False
) | python | def _get_branch(self, remotes=False):
'''
Helper function to determine current branch
:param remotes:
List the remote-tracking branches
'''
return self.m(
'getting git branch information',
cmdd=dict(
cmd='git branch %s' % ('-r' if remotes else ''),
cwd=self.local
),
verbose=False
) | [
"def",
"_get_branch",
"(",
"self",
",",
"remotes",
"=",
"False",
")",
":",
"return",
"self",
".",
"m",
"(",
"'getting git branch information'",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git branch %s'",
"%",
"(",
"'-r'",
"if",
"remotes",
"else",
"''",
")",
",",
"cwd",
"=",
"self",
".",
"local",
")",
",",
"verbose",
"=",
"False",
")"
] | Helper function to determine current branch
:param remotes:
List the remote-tracking branches | [
"Helper",
"function",
"to",
"determine",
"current",
"branch"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/git.py#L385-L400 |
250,389 | spookey/photon | photon/tools/git.py | Git._checkout | def _checkout(self, treeish):
'''
Helper function to checkout something
:param treeish:
String for '`tag`', '`branch`', or remote tracking '-B `banch`'
'''
return self.m(
'checking out "%s"' % (treeish),
cmdd=dict(cmd='git checkout %s' % (treeish), cwd=self.local),
verbose=False
) | python | def _checkout(self, treeish):
'''
Helper function to checkout something
:param treeish:
String for '`tag`', '`branch`', or remote tracking '-B `banch`'
'''
return self.m(
'checking out "%s"' % (treeish),
cmdd=dict(cmd='git checkout %s' % (treeish), cwd=self.local),
verbose=False
) | [
"def",
"_checkout",
"(",
"self",
",",
"treeish",
")",
":",
"return",
"self",
".",
"m",
"(",
"'checking out \"%s\"'",
"%",
"(",
"treeish",
")",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git checkout %s'",
"%",
"(",
"treeish",
")",
",",
"cwd",
"=",
"self",
".",
"local",
")",
",",
"verbose",
"=",
"False",
")"
] | Helper function to checkout something
:param treeish:
String for '`tag`', '`branch`', or remote tracking '-B `banch`' | [
"Helper",
"function",
"to",
"checkout",
"something"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/git.py#L402-L414 |
250,390 | spookey/photon | photon/tools/git.py | Git._pull | def _pull(self):
'''
Helper function to pull from remote
'''
pull = self.m(
'pulling remote changes',
cmdd=dict(cmd='git pull --tags', cwd=self.local),
critical=False
)
if 'CONFLICT' in pull.get('out'):
self.m(
'Congratulations! You have merge conflicts in the repository!',
state=True,
more=pull
)
return pull | python | def _pull(self):
'''
Helper function to pull from remote
'''
pull = self.m(
'pulling remote changes',
cmdd=dict(cmd='git pull --tags', cwd=self.local),
critical=False
)
if 'CONFLICT' in pull.get('out'):
self.m(
'Congratulations! You have merge conflicts in the repository!',
state=True,
more=pull
)
return pull | [
"def",
"_pull",
"(",
"self",
")",
":",
"pull",
"=",
"self",
".",
"m",
"(",
"'pulling remote changes'",
",",
"cmdd",
"=",
"dict",
"(",
"cmd",
"=",
"'git pull --tags'",
",",
"cwd",
"=",
"self",
".",
"local",
")",
",",
"critical",
"=",
"False",
")",
"if",
"'CONFLICT'",
"in",
"pull",
".",
"get",
"(",
"'out'",
")",
":",
"self",
".",
"m",
"(",
"'Congratulations! You have merge conflicts in the repository!'",
",",
"state",
"=",
"True",
",",
"more",
"=",
"pull",
")",
"return",
"pull"
] | Helper function to pull from remote | [
"Helper",
"function",
"to",
"pull",
"from",
"remote"
] | 57212a26ce713ab7723910ee49e3d0ba1697799f | https://github.com/spookey/photon/blob/57212a26ce713ab7723910ee49e3d0ba1697799f/photon/tools/git.py#L416-L432 |
250,391 | jenanwise/codequality | codequality/scmhandlers.py | _temp_filename | def _temp_filename(contents):
"""
Make a temporary file with `contents`.
The file will be cleaned up on exit.
"""
fp = tempfile.NamedTemporaryFile(
prefix='codequalitytmp', delete=False)
name = fp.name
fp.write(contents)
fp.close()
_files_to_cleanup.append(name)
return name | python | def _temp_filename(contents):
"""
Make a temporary file with `contents`.
The file will be cleaned up on exit.
"""
fp = tempfile.NamedTemporaryFile(
prefix='codequalitytmp', delete=False)
name = fp.name
fp.write(contents)
fp.close()
_files_to_cleanup.append(name)
return name | [
"def",
"_temp_filename",
"(",
"contents",
")",
":",
"fp",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"'codequalitytmp'",
",",
"delete",
"=",
"False",
")",
"name",
"=",
"fp",
".",
"name",
"fp",
".",
"write",
"(",
"contents",
")",
"fp",
".",
"close",
"(",
")",
"_files_to_cleanup",
".",
"append",
"(",
"name",
")",
"return",
"name"
] | Make a temporary file with `contents`.
The file will be cleaned up on exit. | [
"Make",
"a",
"temporary",
"file",
"with",
"contents",
"."
] | 8a2bd767fd73091c49a5318fdbfb2b4fff77533d | https://github.com/jenanwise/codequality/blob/8a2bd767fd73091c49a5318fdbfb2b4fff77533d/codequality/scmhandlers.py#L212-L224 |
250,392 | abe-winter/pg13-py | pg13/pg.py | set_options | def set_options(pool_or_cursor,row_instance):
"for connection-level options that need to be set on Row instances"
# todo: move around an Options object instead
for option in ('JSON_READ',): setattr(row_instance,option,getattr(pool_or_cursor,option,None))
return row_instance | python | def set_options(pool_or_cursor,row_instance):
"for connection-level options that need to be set on Row instances"
# todo: move around an Options object instead
for option in ('JSON_READ',): setattr(row_instance,option,getattr(pool_or_cursor,option,None))
return row_instance | [
"def",
"set_options",
"(",
"pool_or_cursor",
",",
"row_instance",
")",
":",
"# todo: move around an Options object instead\r",
"for",
"option",
"in",
"(",
"'JSON_READ'",
",",
")",
":",
"setattr",
"(",
"row_instance",
",",
"option",
",",
"getattr",
"(",
"pool_or_cursor",
",",
"option",
",",
"None",
")",
")",
"return",
"row_instance"
] | for connection-level options that need to be set on Row instances | [
"for",
"connection",
"-",
"level",
"options",
"that",
"need",
"to",
"be",
"set",
"on",
"Row",
"instances"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L53-L57 |
250,393 | abe-winter/pg13-py | pg13/pg.py | transform_specialfield | def transform_specialfield(jsonify,f,v):
"helper for serialize_row"
raw = f.ser(v) if is_serdes(f) else v
return ujson.dumps(raw) if not isinstance(f,basestring) and jsonify else raw | python | def transform_specialfield(jsonify,f,v):
"helper for serialize_row"
raw = f.ser(v) if is_serdes(f) else v
return ujson.dumps(raw) if not isinstance(f,basestring) and jsonify else raw | [
"def",
"transform_specialfield",
"(",
"jsonify",
",",
"f",
",",
"v",
")",
":",
"raw",
"=",
"f",
".",
"ser",
"(",
"v",
")",
"if",
"is_serdes",
"(",
"f",
")",
"else",
"v",
"return",
"ujson",
".",
"dumps",
"(",
"raw",
")",
"if",
"not",
"isinstance",
"(",
"f",
",",
"basestring",
")",
"and",
"jsonify",
"else",
"raw"
] | helper for serialize_row | [
"helper",
"for",
"serialize_row"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L59-L62 |
250,394 | abe-winter/pg13-py | pg13/pg.py | dirty | def dirty(field,ttl=None):
"decorator to cache the result of a function until a field changes"
if ttl is not None: raise NotImplementedError('pg.dirty ttl feature')
def decorator(f):
@functools.wraps(f)
def wrapper(self,*args,**kwargs):
# warning: not reentrant
d=self.dirty_cache[field] if field in self.dirty_cache else self.dirty_cache.setdefault(field,{})
return d[f.__name__] if f.__name__ in d else d.setdefault(f.__name__,f(self,*args,**kwargs))
return wrapper
return decorator | python | def dirty(field,ttl=None):
"decorator to cache the result of a function until a field changes"
if ttl is not None: raise NotImplementedError('pg.dirty ttl feature')
def decorator(f):
@functools.wraps(f)
def wrapper(self,*args,**kwargs):
# warning: not reentrant
d=self.dirty_cache[field] if field in self.dirty_cache else self.dirty_cache.setdefault(field,{})
return d[f.__name__] if f.__name__ in d else d.setdefault(f.__name__,f(self,*args,**kwargs))
return wrapper
return decorator | [
"def",
"dirty",
"(",
"field",
",",
"ttl",
"=",
"None",
")",
":",
"if",
"ttl",
"is",
"not",
"None",
":",
"raise",
"NotImplementedError",
"(",
"'pg.dirty ttl feature'",
")",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# warning: not reentrant\r",
"d",
"=",
"self",
".",
"dirty_cache",
"[",
"field",
"]",
"if",
"field",
"in",
"self",
".",
"dirty_cache",
"else",
"self",
".",
"dirty_cache",
".",
"setdefault",
"(",
"field",
",",
"{",
"}",
")",
"return",
"d",
"[",
"f",
".",
"__name__",
"]",
"if",
"f",
".",
"__name__",
"in",
"d",
"else",
"d",
".",
"setdefault",
"(",
"f",
".",
"__name__",
",",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")",
"return",
"wrapper",
"return",
"decorator"
] | decorator to cache the result of a function until a field changes | [
"decorator",
"to",
"cache",
"the",
"result",
"of",
"a",
"function",
"until",
"a",
"field",
"changes"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L64-L74 |
250,395 | abe-winter/pg13-py | pg13/pg.py | Row.create_table | def create_table(clas,pool_or_cursor):
"uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model"
def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb')
fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS)))
base = 'create table if not exists %s (%s'%(clas.TABLE,fields)
if clas.PKEY: base += ',primary key (%s)'%clas.PKEY
base += ')'
commit_or_execute(pool_or_cursor,base)
clas.create_indexes(pool_or_cursor) | python | def create_table(clas,pool_or_cursor):
"uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model"
def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb')
fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS)))
base = 'create table if not exists %s (%s'%(clas.TABLE,fields)
if clas.PKEY: base += ',primary key (%s)'%clas.PKEY
base += ')'
commit_or_execute(pool_or_cursor,base)
clas.create_indexes(pool_or_cursor) | [
"def",
"create_table",
"(",
"clas",
",",
"pool_or_cursor",
")",
":",
"def",
"mkfield",
"(",
"(",
"name",
",",
"tp",
")",
")",
":",
"return",
"name",
",",
"(",
"tp",
"if",
"isinstance",
"(",
"tp",
",",
"basestring",
")",
"else",
"'jsonb'",
")",
"fields",
"=",
"','",
".",
"join",
"(",
"map",
"(",
"' '",
".",
"join",
",",
"map",
"(",
"mkfield",
",",
"clas",
".",
"FIELDS",
")",
")",
")",
"base",
"=",
"'create table if not exists %s (%s'",
"%",
"(",
"clas",
".",
"TABLE",
",",
"fields",
")",
"if",
"clas",
".",
"PKEY",
":",
"base",
"+=",
"',primary key (%s)'",
"%",
"clas",
".",
"PKEY",
"base",
"+=",
"')'",
"commit_or_execute",
"(",
"pool_or_cursor",
",",
"base",
")",
"clas",
".",
"create_indexes",
"(",
"pool_or_cursor",
")"
] | uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model | [
"uses",
"FIELDS",
"PKEY",
"INDEXES",
"and",
"TABLE",
"members",
"to",
"create",
"a",
"sql",
"table",
"for",
"the",
"model"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L111-L119 |
250,396 | abe-winter/pg13-py | pg13/pg.py | Row.pkey_get | def pkey_get(clas,pool_or_cursor,*vals):
"lookup by primary keys in order"
pkey = clas.PKEY.split(',')
if len(vals)!=len(pkey): raise ValueError("%i args != %i-len primary key for %s"%(len(vals),len(pkey),clas.TABLE))
rows = list(clas.select(pool_or_cursor,**dict(zip(pkey,vals))))
if not rows: raise Missing
return set_options(pool_or_cursor,clas(*rows[0])) | python | def pkey_get(clas,pool_or_cursor,*vals):
"lookup by primary keys in order"
pkey = clas.PKEY.split(',')
if len(vals)!=len(pkey): raise ValueError("%i args != %i-len primary key for %s"%(len(vals),len(pkey),clas.TABLE))
rows = list(clas.select(pool_or_cursor,**dict(zip(pkey,vals))))
if not rows: raise Missing
return set_options(pool_or_cursor,clas(*rows[0])) | [
"def",
"pkey_get",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"vals",
")",
":",
"pkey",
"=",
"clas",
".",
"PKEY",
".",
"split",
"(",
"','",
")",
"if",
"len",
"(",
"vals",
")",
"!=",
"len",
"(",
"pkey",
")",
":",
"raise",
"ValueError",
"(",
"\"%i args != %i-len primary key for %s\"",
"%",
"(",
"len",
"(",
"vals",
")",
",",
"len",
"(",
"pkey",
")",
",",
"clas",
".",
"TABLE",
")",
")",
"rows",
"=",
"list",
"(",
"clas",
".",
"select",
"(",
"pool_or_cursor",
",",
"*",
"*",
"dict",
"(",
"zip",
"(",
"pkey",
",",
"vals",
")",
")",
")",
")",
"if",
"not",
"rows",
":",
"raise",
"Missing",
"return",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"rows",
"[",
"0",
"]",
")",
")"
] | lookup by primary keys in order | [
"lookup",
"by",
"primary",
"keys",
"in",
"order"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L143-L149 |
250,397 | abe-winter/pg13-py | pg13/pg.py | Row.select_models | def select_models(clas,pool_or_cursor,**kwargs):
"returns generator yielding instances of the class"
if 'columns' in kwargs: raise ValueError("don't pass 'columns' to select_models")
return (set_options(pool_or_cursor,clas(*row)) for row in clas.select(pool_or_cursor,**kwargs)) | python | def select_models(clas,pool_or_cursor,**kwargs):
"returns generator yielding instances of the class"
if 'columns' in kwargs: raise ValueError("don't pass 'columns' to select_models")
return (set_options(pool_or_cursor,clas(*row)) for row in clas.select(pool_or_cursor,**kwargs)) | [
"def",
"select_models",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'columns'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"don't pass 'columns' to select_models\"",
")",
"return",
"(",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"row",
")",
")",
"for",
"row",
"in",
"clas",
".",
"select",
"(",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
")"
] | returns generator yielding instances of the class | [
"returns",
"generator",
"yielding",
"instances",
"of",
"the",
"class"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L165-L168 |
250,398 | abe-winter/pg13-py | pg13/pg.py | Row.kwinsert | def kwinsert(clas,pool_or_cursor,**kwargs):
"kwargs version of insert"
returning = kwargs.pop('returning',None)
fields,vals = zip(*kwargs.items())
# note: don't do SpecialField resolution here; clas.insert takes care of it
return clas.insert(pool_or_cursor,fields,vals,returning=returning) | python | def kwinsert(clas,pool_or_cursor,**kwargs):
"kwargs version of insert"
returning = kwargs.pop('returning',None)
fields,vals = zip(*kwargs.items())
# note: don't do SpecialField resolution here; clas.insert takes care of it
return clas.insert(pool_or_cursor,fields,vals,returning=returning) | [
"def",
"kwinsert",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"returning",
"=",
"kwargs",
".",
"pop",
"(",
"'returning'",
",",
"None",
")",
"fields",
",",
"vals",
"=",
"zip",
"(",
"*",
"kwargs",
".",
"items",
"(",
")",
")",
"# note: don't do SpecialField resolution here; clas.insert takes care of it\r",
"return",
"clas",
".",
"insert",
"(",
"pool_or_cursor",
",",
"fields",
",",
"vals",
",",
"returning",
"=",
"returning",
")"
] | kwargs version of insert | [
"kwargs",
"version",
"of",
"insert"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L208-L213 |
250,399 | abe-winter/pg13-py | pg13/pg.py | Row.kwinsert_mk | def kwinsert_mk(clas,pool_or_cursor,**kwargs):
"wrapper for kwinsert that returns a constructed class. use this over kwinsert in most cases"
if 'returning' in kwargs: raise ValueError("don't call kwinsert_mk with 'returning'")
return set_options(
pool_or_cursor,
clas(*clas.kwinsert(pool_or_cursor,returning='*',**kwargs))
) | python | def kwinsert_mk(clas,pool_or_cursor,**kwargs):
"wrapper for kwinsert that returns a constructed class. use this over kwinsert in most cases"
if 'returning' in kwargs: raise ValueError("don't call kwinsert_mk with 'returning'")
return set_options(
pool_or_cursor,
clas(*clas.kwinsert(pool_or_cursor,returning='*',**kwargs))
) | [
"def",
"kwinsert_mk",
"(",
"clas",
",",
"pool_or_cursor",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'returning'",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"don't call kwinsert_mk with 'returning'\"",
")",
"return",
"set_options",
"(",
"pool_or_cursor",
",",
"clas",
"(",
"*",
"clas",
".",
"kwinsert",
"(",
"pool_or_cursor",
",",
"returning",
"=",
"'*'",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | wrapper for kwinsert that returns a constructed class. use this over kwinsert in most cases | [
"wrapper",
"for",
"kwinsert",
"that",
"returns",
"a",
"constructed",
"class",
".",
"use",
"this",
"over",
"kwinsert",
"in",
"most",
"cases"
] | c78806f99f35541a8756987e86edca3438aa97f5 | https://github.com/abe-winter/pg13-py/blob/c78806f99f35541a8756987e86edca3438aa97f5/pg13/pg.py#L215-L221 |
Subsets and Splits