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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
LLNL/certipy
certipy/certipy.py
Certipy.sign
def sign(self, req, issuer_cert_key, validity_period, digest="sha256", extensions=None, serial=0): """ Generate a certificate given a certificate request. Arguments: req - Certificate request to use issuer_cert - The certificate of the issuer issuer_key - The private key of the issuer not_before - Timestamp (relative to now) when the certificate starts being valid not_after - Timestamp (relative to now) when the certificate stops being valid digest - Digest method to use for signing, default is sha256 Returns: The signed certificate in an X509 object """ issuer_cert, issuer_key = issuer_cert_key not_before, not_after = validity_period cert = crypto.X509() cert.set_serial_number(serial) cert.gmtime_adj_notBefore(not_before) cert.gmtime_adj_notAfter(not_after) cert.set_issuer(issuer_cert.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) if extensions: for ext in extensions: if callable(ext): ext = ext(cert) cert.add_extensions([ext]) cert.sign(issuer_key, digest) return cert
python
def sign(self, req, issuer_cert_key, validity_period, digest="sha256", extensions=None, serial=0): """ Generate a certificate given a certificate request. Arguments: req - Certificate request to use issuer_cert - The certificate of the issuer issuer_key - The private key of the issuer not_before - Timestamp (relative to now) when the certificate starts being valid not_after - Timestamp (relative to now) when the certificate stops being valid digest - Digest method to use for signing, default is sha256 Returns: The signed certificate in an X509 object """ issuer_cert, issuer_key = issuer_cert_key not_before, not_after = validity_period cert = crypto.X509() cert.set_serial_number(serial) cert.gmtime_adj_notBefore(not_before) cert.gmtime_adj_notAfter(not_after) cert.set_issuer(issuer_cert.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) if extensions: for ext in extensions: if callable(ext): ext = ext(cert) cert.add_extensions([ext]) cert.sign(issuer_key, digest) return cert
[ "def", "sign", "(", "self", ",", "req", ",", "issuer_cert_key", ",", "validity_period", ",", "digest", "=", "\"sha256\"", ",", "extensions", "=", "None", ",", "serial", "=", "0", ")", ":", "issuer_cert", ",", "issuer_key", "=", "issuer_cert_key", "not_before...
Generate a certificate given a certificate request. Arguments: req - Certificate request to use issuer_cert - The certificate of the issuer issuer_key - The private key of the issuer not_before - Timestamp (relative to now) when the certificate starts being valid not_after - Timestamp (relative to now) when the certificate stops being valid digest - Digest method to use for signing, default is sha256 Returns: The signed certificate in an X509 object
[ "Generate", "a", "certificate", "given", "a", "certificate", "request", "." ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L487-L522
train
46,900
LLNL/certipy
certipy/certipy.py
Certipy.create_ca_bundle_for_names
def create_ca_bundle_for_names(self, bundle_name, names): """Create a CA bundle to trust only certs defined in names """ records = [rec for name, rec in self.store.store.items() if name in names] return self.create_bundle( bundle_name, names=[r['parent_ca'] for r in records])
python
def create_ca_bundle_for_names(self, bundle_name, names): """Create a CA bundle to trust only certs defined in names """ records = [rec for name, rec in self.store.store.items() if name in names] return self.create_bundle( bundle_name, names=[r['parent_ca'] for r in records])
[ "def", "create_ca_bundle_for_names", "(", "self", ",", "bundle_name", ",", "names", ")", ":", "records", "=", "[", "rec", "for", "name", ",", "rec", "in", "self", ".", "store", ".", "store", ".", "items", "(", ")", "if", "name", "in", "names", "]", "...
Create a CA bundle to trust only certs defined in names
[ "Create", "a", "CA", "bundle", "to", "trust", "only", "certs", "defined", "in", "names" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L524-L531
train
46,901
LLNL/certipy
certipy/certipy.py
Certipy.create_bundle
def create_bundle(self, bundle_name, names=None, ca_only=True): """Create a bundle of public certs for trust distribution This will create a bundle of both CAs and/or regular certificates. Arguments: names - The names of certs to include in the bundle bundle_name - The name of the bundle file to output Returns: Path to the bundle file """ if not names: if ca_only: names = [] for name, record in self.store.store.items(): if record['is_ca']: names.append(name) else: names = self.store.store.keys() out_file_path = os.path.join(self.store.containing_dir, bundle_name) with open(out_file_path, 'w') as fh: for name in names: bundle = self.store.get_files(name) bundle.cert.load() fh.write(str(bundle.cert)) return out_file_path
python
def create_bundle(self, bundle_name, names=None, ca_only=True): """Create a bundle of public certs for trust distribution This will create a bundle of both CAs and/or regular certificates. Arguments: names - The names of certs to include in the bundle bundle_name - The name of the bundle file to output Returns: Path to the bundle file """ if not names: if ca_only: names = [] for name, record in self.store.store.items(): if record['is_ca']: names.append(name) else: names = self.store.store.keys() out_file_path = os.path.join(self.store.containing_dir, bundle_name) with open(out_file_path, 'w') as fh: for name in names: bundle = self.store.get_files(name) bundle.cert.load() fh.write(str(bundle.cert)) return out_file_path
[ "def", "create_bundle", "(", "self", ",", "bundle_name", ",", "names", "=", "None", ",", "ca_only", "=", "True", ")", ":", "if", "not", "names", ":", "if", "ca_only", ":", "names", "=", "[", "]", "for", "name", ",", "record", "in", "self", ".", "st...
Create a bundle of public certs for trust distribution This will create a bundle of both CAs and/or regular certificates. Arguments: names - The names of certs to include in the bundle bundle_name - The name of the bundle file to output Returns: Path to the bundle file
[ "Create", "a", "bundle", "of", "public", "certs", "for", "trust", "distribution" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L545-L569
train
46,902
LLNL/certipy
certipy/certipy.py
Certipy.trust_from_graph
def trust_from_graph(self, graph): """Create a set of trust bundles from a relationship graph. Components in this sense are defined by unique CAs. This method assists in setting up complicated trust between various components that need to do TLS auth. Arguments: graph - dict component:list(components) Returns: dict component:trust bundle file path """ # Ensure there are CAs backing all graph components def distinct_components(graph): """Return a set of components from the provided graph.""" components = set(graph.keys()) for trusts in graph.values(): components |= set(trusts) return components # Default to creating a CA (incapable of signing intermediaries) to # identify a component not known to Certipy for component in distinct_components(graph): try: self.store.get_record(component) except CertNotFoundError: self.create_ca(component) # Build bundles from the graph trust_files = {} for component, trusts in graph.items(): file_name = component + '_trust.crt' trust_files[component] = self.create_bundle( file_name, names=trusts, ca_only=False) return trust_files
python
def trust_from_graph(self, graph): """Create a set of trust bundles from a relationship graph. Components in this sense are defined by unique CAs. This method assists in setting up complicated trust between various components that need to do TLS auth. Arguments: graph - dict component:list(components) Returns: dict component:trust bundle file path """ # Ensure there are CAs backing all graph components def distinct_components(graph): """Return a set of components from the provided graph.""" components = set(graph.keys()) for trusts in graph.values(): components |= set(trusts) return components # Default to creating a CA (incapable of signing intermediaries) to # identify a component not known to Certipy for component in distinct_components(graph): try: self.store.get_record(component) except CertNotFoundError: self.create_ca(component) # Build bundles from the graph trust_files = {} for component, trusts in graph.items(): file_name = component + '_trust.crt' trust_files[component] = self.create_bundle( file_name, names=trusts, ca_only=False) return trust_files
[ "def", "trust_from_graph", "(", "self", ",", "graph", ")", ":", "# Ensure there are CAs backing all graph components", "def", "distinct_components", "(", "graph", ")", ":", "\"\"\"Return a set of components from the provided graph.\"\"\"", "components", "=", "set", "(", "grap...
Create a set of trust bundles from a relationship graph. Components in this sense are defined by unique CAs. This method assists in setting up complicated trust between various components that need to do TLS auth. Arguments: graph - dict component:list(components) Returns: dict component:trust bundle file path
[ "Create", "a", "set", "of", "trust", "bundles", "from", "a", "relationship", "graph", "." ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L571-L604
train
46,903
LLNL/certipy
certipy/certipy.py
Certipy.create_ca
def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048, alt_names=None, years=5, serial=0, pathlen=0, overwrite=False): """ Create a certificate authority Arguments: name - The name of the CA cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new CA """ cakey = self.create_key_pair(cert_type, bits) req = self.create_request(cakey, CN=name) signing_key = cakey signing_cert = req parent_ca = '' if ca_name: ca_bundle = self.store.get_files(ca_name) signing_key = ca_bundle.key.load() signing_cert = ca_bundle.cert.load() parent_ca = ca_bundle.cert.file_path basicConstraints = "CA:true" # If pathlen is exactly 0, this CA cannot sign intermediaries. # A negative value leaves this out entirely and allows arbitrary # numbers of intermediates. if pathlen >=0: basicConstraints += ', pathlen:' + str(pathlen) extensions = [ crypto.X509Extension( b"basicConstraints", True, basicConstraints.encode()), crypto.X509Extension( b"keyUsage", True, b"keyCertSign, cRLSign"), crypto.X509Extension( b"extendedKeyUsage", True, b"serverAuth, clientAuth"), lambda cert: crypto.X509Extension( b"subjectKeyIdentifier", False, b"hash", subject=cert), lambda cert: crypto.X509Extension( b"authorityKeyIdentifier", False, b"keyid:always", issuer=cert), ] if alt_names: extensions.append( crypto.X509Extension(b"subjectAltName", False, ",".join(alt_names).encode()) ) # TODO: start time before today for clock skew? cacert = self.sign( req, (signing_cert, signing_key), (0, 60*60*24*365*years), extensions=extensions) x509s = {'key': cakey, 'cert': cacert, 'ca': cacert} self.store.add_files(name, x509s, overwrite=overwrite, parent_ca=parent_ca, is_ca=True) if ca_name: self.store.add_sign_link(ca_name, name) return self.store.get_record(name)
python
def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048, alt_names=None, years=5, serial=0, pathlen=0, overwrite=False): """ Create a certificate authority Arguments: name - The name of the CA cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new CA """ cakey = self.create_key_pair(cert_type, bits) req = self.create_request(cakey, CN=name) signing_key = cakey signing_cert = req parent_ca = '' if ca_name: ca_bundle = self.store.get_files(ca_name) signing_key = ca_bundle.key.load() signing_cert = ca_bundle.cert.load() parent_ca = ca_bundle.cert.file_path basicConstraints = "CA:true" # If pathlen is exactly 0, this CA cannot sign intermediaries. # A negative value leaves this out entirely and allows arbitrary # numbers of intermediates. if pathlen >=0: basicConstraints += ', pathlen:' + str(pathlen) extensions = [ crypto.X509Extension( b"basicConstraints", True, basicConstraints.encode()), crypto.X509Extension( b"keyUsage", True, b"keyCertSign, cRLSign"), crypto.X509Extension( b"extendedKeyUsage", True, b"serverAuth, clientAuth"), lambda cert: crypto.X509Extension( b"subjectKeyIdentifier", False, b"hash", subject=cert), lambda cert: crypto.X509Extension( b"authorityKeyIdentifier", False, b"keyid:always", issuer=cert), ] if alt_names: extensions.append( crypto.X509Extension(b"subjectAltName", False, ",".join(alt_names).encode()) ) # TODO: start time before today for clock skew? cacert = self.sign( req, (signing_cert, signing_key), (0, 60*60*24*365*years), extensions=extensions) x509s = {'key': cakey, 'cert': cacert, 'ca': cacert} self.store.add_files(name, x509s, overwrite=overwrite, parent_ca=parent_ca, is_ca=True) if ca_name: self.store.add_sign_link(ca_name, name) return self.store.get_record(name)
[ "def", "create_ca", "(", "self", ",", "name", ",", "ca_name", "=", "''", ",", "cert_type", "=", "crypto", ".", "TYPE_RSA", ",", "bits", "=", "2048", ",", "alt_names", "=", "None", ",", "years", "=", "5", ",", "serial", "=", "0", ",", "pathlen", "="...
Create a certificate authority Arguments: name - The name of the CA cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new CA
[ "Create", "a", "certificate", "authority" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L606-L669
train
46,904
LLNL/certipy
certipy/certipy.py
Certipy.create_signed_pair
def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA, bits=2048, years=5, alt_names=None, serial=0, overwrite=False): """ Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name - The name of the CA to sign this cert cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new signed pair """ key = self.create_key_pair(cert_type, bits) req = self.create_request(key, CN=name) extensions = [ crypto.X509Extension( b"extendedKeyUsage", True, b"serverAuth, clientAuth"), ] if alt_names: extensions.append( crypto.X509Extension(b"subjectAltName", False, ",".join(alt_names).encode()) ) ca_bundle = self.store.get_files(ca_name) cacert = ca_bundle.cert.load() cakey = ca_bundle.key.load() cert = self.sign(req, (cacert, cakey), (0, 60*60*24*365*years), extensions=extensions) x509s = {'key': key, 'cert': cert, 'ca': None} self.store.add_files(name, x509s, parent_ca=ca_name, overwrite=overwrite) # Relate these certs as being parent and child self.store.add_sign_link(ca_name, name) return self.store.get_record(name)
python
def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA, bits=2048, years=5, alt_names=None, serial=0, overwrite=False): """ Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name - The name of the CA to sign this cert cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new signed pair """ key = self.create_key_pair(cert_type, bits) req = self.create_request(key, CN=name) extensions = [ crypto.X509Extension( b"extendedKeyUsage", True, b"serverAuth, clientAuth"), ] if alt_names: extensions.append( crypto.X509Extension(b"subjectAltName", False, ",".join(alt_names).encode()) ) ca_bundle = self.store.get_files(ca_name) cacert = ca_bundle.cert.load() cakey = ca_bundle.key.load() cert = self.sign(req, (cacert, cakey), (0, 60*60*24*365*years), extensions=extensions) x509s = {'key': key, 'cert': cert, 'ca': None} self.store.add_files(name, x509s, parent_ca=ca_name, overwrite=overwrite) # Relate these certs as being parent and child self.store.add_sign_link(ca_name, name) return self.store.get_record(name)
[ "def", "create_signed_pair", "(", "self", ",", "name", ",", "ca_name", ",", "cert_type", "=", "crypto", ".", "TYPE_RSA", ",", "bits", "=", "2048", ",", "years", "=", "5", ",", "alt_names", "=", "None", ",", "serial", "=", "0", ",", "overwrite", "=", ...
Create a key-cert pair Arguments: name - The name of the key-cert pair ca_name - The name of the CA to sign this cert cert_type - The type of the cert. TYPE_RSA or TYPE_DSA bits - The number of bits to use alt_names - An array of alternative names in the format: IP:address, DNS:address Returns: KeyCertPair for the new signed pair
[ "Create", "a", "key", "-", "cert", "pair" ]
8705a8ba32655e12021d2893cf1c3c98c697edd7
https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L671-L712
train
46,905
marten-de-vries/Flask-WebSub
flask_websub/hub/tasks.py
send_change_notification
def send_change_notification(hub, topic_url, updated_content=None): """7. Content Distribution""" if updated_content: body = base64.b64decode(updated_content['content']) else: body, updated_content = get_new_content(hub.config, topic_url) b64_body = updated_content['content'] headers = updated_content['headers'] link_header = headers.get('Link', '') if 'rel="hub"' not in link_header or 'rel="self"' not in link_header: raise NotificationError(INVALID_LINK) for callback_url, secret in hub.storage.get_callbacks(topic_url): schedule_request(hub, topic_url, callback_url, secret, body, b64_body, headers)
python
def send_change_notification(hub, topic_url, updated_content=None): """7. Content Distribution""" if updated_content: body = base64.b64decode(updated_content['content']) else: body, updated_content = get_new_content(hub.config, topic_url) b64_body = updated_content['content'] headers = updated_content['headers'] link_header = headers.get('Link', '') if 'rel="hub"' not in link_header or 'rel="self"' not in link_header: raise NotificationError(INVALID_LINK) for callback_url, secret in hub.storage.get_callbacks(topic_url): schedule_request(hub, topic_url, callback_url, secret, body, b64_body, headers)
[ "def", "send_change_notification", "(", "hub", ",", "topic_url", ",", "updated_content", "=", "None", ")", ":", "if", "updated_content", ":", "body", "=", "base64", ".", "b64decode", "(", "updated_content", "[", "'content'", "]", ")", "else", ":", "body", ",...
7. Content Distribution
[ "7", ".", "Content", "Distribution" ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L18-L34
train
46,906
marten-de-vries/Flask-WebSub
flask_websub/hub/tasks.py
subscribe
def subscribe(hub, callback_url, topic_url, lease_seconds, secret, endpoint_hook_data): """5.2 Subscription Validation""" for validate in hub.validators: error = validate(callback_url, topic_url, lease_seconds, secret, endpoint_hook_data) if error: send_denied(hub, callback_url, topic_url, error) return if intent_verified(hub, callback_url, 'subscribe', topic_url, lease_seconds): hub.storage[topic_url, callback_url] = { 'lease_seconds': lease_seconds, 'secret': secret, }
python
def subscribe(hub, callback_url, topic_url, lease_seconds, secret, endpoint_hook_data): """5.2 Subscription Validation""" for validate in hub.validators: error = validate(callback_url, topic_url, lease_seconds, secret, endpoint_hook_data) if error: send_denied(hub, callback_url, topic_url, error) return if intent_verified(hub, callback_url, 'subscribe', topic_url, lease_seconds): hub.storage[topic_url, callback_url] = { 'lease_seconds': lease_seconds, 'secret': secret, }
[ "def", "subscribe", "(", "hub", ",", "callback_url", ",", "topic_url", ",", "lease_seconds", ",", "secret", ",", "endpoint_hook_data", ")", ":", "for", "validate", "in", "hub", ".", "validators", ":", "error", "=", "validate", "(", "callback_url", ",", "topi...
5.2 Subscription Validation
[ "5", ".", "2", "Subscription", "Validation" ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L87-L103
train
46,907
marten-de-vries/Flask-WebSub
flask_websub/hub/tasks.py
intent_verified
def intent_verified(hub, callback_url, mode, topic_url, lease_seconds): """ 5.3 Hub Verifies Intent of the Subscriber""" challenge = uuid4() params = { 'hub.mode': mode, 'hub.topic': topic_url, 'hub.challenge': challenge, 'hub.lease_seconds': lease_seconds, } try: response = request_url(hub.config, 'GET', callback_url, params=params) assert response.status_code == 200 and response.text == challenge except requests.exceptions.RequestException as e: warn("Cannot verify subscriber intent", e) except AssertionError as e: warn(INTENT_UNVERIFIED % (response.status_code, response.content), e) else: return True return False
python
def intent_verified(hub, callback_url, mode, topic_url, lease_seconds): """ 5.3 Hub Verifies Intent of the Subscriber""" challenge = uuid4() params = { 'hub.mode': mode, 'hub.topic': topic_url, 'hub.challenge': challenge, 'hub.lease_seconds': lease_seconds, } try: response = request_url(hub.config, 'GET', callback_url, params=params) assert response.status_code == 200 and response.text == challenge except requests.exceptions.RequestException as e: warn("Cannot verify subscriber intent", e) except AssertionError as e: warn(INTENT_UNVERIFIED % (response.status_code, response.content), e) else: return True return False
[ "def", "intent_verified", "(", "hub", ",", "callback_url", ",", "mode", ",", "topic_url", ",", "lease_seconds", ")", ":", "challenge", "=", "uuid4", "(", ")", "params", "=", "{", "'hub.mode'", ":", "mode", ",", "'hub.topic'", ":", "topic_url", ",", "'hub.c...
5.3 Hub Verifies Intent of the Subscriber
[ "5", ".", "3", "Hub", "Verifies", "Intent", "of", "the", "Subscriber" ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L117-L136
train
46,908
marten-de-vries/Flask-WebSub
flask_websub/hub/__init__.py
Hub.init_celery
def init_celery(self, celery): """Registers the celery tasks on the hub object.""" count = next(self.counter) def task_with_hub(f, **opts): @functools.wraps(f) def wrapper(*args, **kwargs): return f(self, *args, **kwargs) # Make sure newer instances don't overwride older ones. wrapper.__name__ = wrapper.__name__ + '_' + str(count) return celery.task(**opts)(wrapper) # tasks for internal use: self.subscribe = task_with_hub(subscribe) self.unsubscribe = task_with_hub(unsubscribe) max_attempts = self.config.get('MAX_ATTEMPTS', 10) make_req = task_with_hub(make_request_retrying, bind=True, max_retries=max_attempts) self.make_request_retrying = make_req # user facing tasks # wrapped by send_change_notification: self.send_change = task_with_hub(send_change_notification) # wrapped by cleanup_expired_subscriptions @task_with_hub def cleanup(hub): self.storage.cleanup_expired_subscriptions() self.cleanup = cleanup # wrapped by schedule_cleanup def schedule(every_x_seconds=A_DAY): celery.add_periodic_task(every_x_seconds, self.cleanup_expired_subscriptions.s()) self.schedule = schedule
python
def init_celery(self, celery): """Registers the celery tasks on the hub object.""" count = next(self.counter) def task_with_hub(f, **opts): @functools.wraps(f) def wrapper(*args, **kwargs): return f(self, *args, **kwargs) # Make sure newer instances don't overwride older ones. wrapper.__name__ = wrapper.__name__ + '_' + str(count) return celery.task(**opts)(wrapper) # tasks for internal use: self.subscribe = task_with_hub(subscribe) self.unsubscribe = task_with_hub(unsubscribe) max_attempts = self.config.get('MAX_ATTEMPTS', 10) make_req = task_with_hub(make_request_retrying, bind=True, max_retries=max_attempts) self.make_request_retrying = make_req # user facing tasks # wrapped by send_change_notification: self.send_change = task_with_hub(send_change_notification) # wrapped by cleanup_expired_subscriptions @task_with_hub def cleanup(hub): self.storage.cleanup_expired_subscriptions() self.cleanup = cleanup # wrapped by schedule_cleanup def schedule(every_x_seconds=A_DAY): celery.add_periodic_task(every_x_seconds, self.cleanup_expired_subscriptions.s()) self.schedule = schedule
[ "def", "init_celery", "(", "self", ",", "celery", ")", ":", "count", "=", "next", "(", "self", ".", "counter", ")", "def", "task_with_hub", "(", "f", ",", "*", "*", "opts", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", ...
Registers the celery tasks on the hub object.
[ "Registers", "the", "celery", "tasks", "on", "the", "hub", "object", "." ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/__init__.py#L66-L103
train
46,909
marten-de-vries/Flask-WebSub
flask_websub/publisher.py
init_publisher
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url, 'websub_self_link': stack.top.websub_self_link, 'websub_hub_link': stack.top.websub_hub_link, }
python
def init_publisher(app): """Calling this with your flask app as argument is required for the publisher decorator to work. """ @app.context_processor def inject_links(): return { 'websub_self_url': stack.top.websub_self_url, 'websub_hub_url': stack.top.websub_hub_url, 'websub_self_link': stack.top.websub_self_link, 'websub_hub_link': stack.top.websub_hub_link, }
[ "def", "init_publisher", "(", "app", ")", ":", "@", "app", ".", "context_processor", "def", "inject_links", "(", ")", ":", "return", "{", "'websub_self_url'", ":", "stack", ".", "top", ".", "websub_self_url", ",", "'websub_hub_url'", ":", "stack", ".", "top"...
Calling this with your flask app as argument is required for the publisher decorator to work.
[ "Calling", "this", "with", "your", "flask", "app", "as", "argument", "is", "required", "for", "the", "publisher", "decorator", "to", "work", "." ]
422d5b597245554c47e881483f99cae7c57a81ba
https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/publisher.py#L15-L27
train
46,910
openspending/babbage
babbage/query/__init__.py
count_results
def count_results(cube, q): """ Get the count of records matching the query. """ q = select(columns=[func.count(True)], from_obj=q.alias()) return cube.engine.execute(q).scalar()
python
def count_results(cube, q): """ Get the count of records matching the query. """ q = select(columns=[func.count(True)], from_obj=q.alias()) return cube.engine.execute(q).scalar()
[ "def", "count_results", "(", "cube", ",", "q", ")", ":", "q", "=", "select", "(", "columns", "=", "[", "func", ".", "count", "(", "True", ")", "]", ",", "from_obj", "=", "q", ".", "alias", "(", ")", ")", "return", "cube", ".", "engine", ".", "e...
Get the count of records matching the query.
[ "Get", "the", "count", "of", "records", "matching", "the", "query", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/__init__.py#L12-L15
train
46,911
openspending/babbage
babbage/query/__init__.py
generate_results
def generate_results(cube, q): """ Generate the resulting records for this query, applying pagination. Values will be returned by their reference. """ if q._limit is not None and q._limit < 1: return rp = cube.engine.execute(q) while True: row = rp.fetchone() if row is None: return yield dict(row.items())
python
def generate_results(cube, q): """ Generate the resulting records for this query, applying pagination. Values will be returned by their reference. """ if q._limit is not None and q._limit < 1: return rp = cube.engine.execute(q) while True: row = rp.fetchone() if row is None: return yield dict(row.items())
[ "def", "generate_results", "(", "cube", ",", "q", ")", ":", "if", "q", ".", "_limit", "is", "not", "None", "and", "q", ".", "_limit", "<", "1", ":", "return", "rp", "=", "cube", ".", "engine", ".", "execute", "(", "q", ")", "while", "True", ":", ...
Generate the resulting records for this query, applying pagination. Values will be returned by their reference.
[ "Generate", "the", "resulting", "records", "for", "this", "query", "applying", "pagination", ".", "Values", "will", "be", "returned", "by", "their", "reference", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/__init__.py#L18-L28
train
46,912
bodylabs/lace
lace/mesh.py
Mesh.concatenate
def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. """ nargs = len(args) if nargs == 1: return args[0] vs = [a.v for a in args if a.v is not None] vcs = [a.vc for a in args if a.vc is not None] fs = [a.f for a in args if a.f is not None] if vs and len(vs) != nargs: raise ValueError('Expected `v` for all args or none.') if vcs and len(vcs) != nargs: raise ValueError('Expected `vc` for all args or none.') if fs and len(fs) != nargs: raise ValueError('Expected `f` for all args or none.') # Offset face indices by the cumulative vertex count. face_offsets = np.cumsum([v.shape[0] for v in vs[:-1]]) for offset, f in zip(face_offsets, fs[1:]): # https://bitbucket.org/logilab/pylint/issues/603/operator-generates-false-positive-unused pylint: disable=unused-variable f += offset return Mesh( v=np.vstack(vs) if vs else None, vc=np.vstack(vcs) if vcs else None, f=np.vstack(fs) if fs else None, )
python
def concatenate(cls, *args): """Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces. """ nargs = len(args) if nargs == 1: return args[0] vs = [a.v for a in args if a.v is not None] vcs = [a.vc for a in args if a.vc is not None] fs = [a.f for a in args if a.f is not None] if vs and len(vs) != nargs: raise ValueError('Expected `v` for all args or none.') if vcs and len(vcs) != nargs: raise ValueError('Expected `vc` for all args or none.') if fs and len(fs) != nargs: raise ValueError('Expected `f` for all args or none.') # Offset face indices by the cumulative vertex count. face_offsets = np.cumsum([v.shape[0] for v in vs[:-1]]) for offset, f in zip(face_offsets, fs[1:]): # https://bitbucket.org/logilab/pylint/issues/603/operator-generates-false-positive-unused pylint: disable=unused-variable f += offset return Mesh( v=np.vstack(vs) if vs else None, vc=np.vstack(vcs) if vcs else None, f=np.vstack(fs) if fs else None, )
[ "def", "concatenate", "(", "cls", ",", "*", "args", ")", ":", "nargs", "=", "len", "(", "args", ")", "if", "nargs", "==", "1", ":", "return", "args", "[", "0", "]", "vs", "=", "[", "a", ".", "v", "for", "a", "in", "args", "if", "a", ".", "v...
Concatenates an arbitrary number of meshes. Currently supports vertices, vertex colors, and faces.
[ "Concatenates", "an", "arbitrary", "number", "of", "meshes", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/mesh.py#L215-L244
train
46,913
nerdynick/PySQLPool
src/PySQLPool/__init__.py
getNewConnection
def getNewConnection(*args, **kargs): """ Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to connect on @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support """ kargs = dict(kargs) if len(args) > 0: if len(args) >= 1: kargs['host'] = args[0] if len(args) >= 2: kargs['user'] = args[1] if len(args) >= 3: kargs['passwd'] = args[2] if len(args) >= 4: kargs['db'] = args[3] if len(args) >= 5: kargs['port'] = args[4] if len(args) >= 6: kargs['commitOnEnd'] = args[5] return connection.Connection(*args, **kargs)
python
def getNewConnection(*args, **kargs): """ Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to connect on @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support """ kargs = dict(kargs) if len(args) > 0: if len(args) >= 1: kargs['host'] = args[0] if len(args) >= 2: kargs['user'] = args[1] if len(args) >= 3: kargs['passwd'] = args[2] if len(args) >= 4: kargs['db'] = args[3] if len(args) >= 5: kargs['port'] = args[4] if len(args) >= 6: kargs['commitOnEnd'] = args[5] return connection.Connection(*args, **kargs)
[ "def", "getNewConnection", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "kargs", "=", "dict", "(", "kargs", ")", "if", "len", "(", "args", ")", ">", "0", ":", "if", "len", "(", "args", ")", ">=", "1", ":", "kargs", "[", "'host'", "]", ...
Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to connect on @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support
[ "Quickly", "Create", "a", "new", "PySQLConnection", "class" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/__init__.py#L15-L43
train
46,914
nerdynick/PySQLPool
src/PySQLPool/__init__.py
getNewQuery
def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs): """ Create a new PySQLQuery Class @param PySQLConnectionObj: Connection Object representing your connection string @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support """ if connection is None: return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd) else: #Updated 7/24/08 to include commitOnEnd here #-Chandler Prall return query.PySQLQuery(connection, commitOnEnd = commitOnEnd)
python
def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs): """ Create a new PySQLQuery Class @param PySQLConnectionObj: Connection Object representing your connection string @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support """ if connection is None: return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd) else: #Updated 7/24/08 to include commitOnEnd here #-Chandler Prall return query.PySQLQuery(connection, commitOnEnd = commitOnEnd)
[ "def", "getNewQuery", "(", "connection", "=", "None", ",", "commitOnEnd", "=", "False", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "connection", "is", "None", ":", "return", "query", ".", "PySQLQuery", "(", "getNewConnection", "(", "*", ...
Create a new PySQLQuery Class @param PySQLConnectionObj: Connection Object representing your connection string @param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit @author: Nick Verbeck @since: 5/12/2008 @updated: 7/19/2008 - Added commitOnEnd support
[ "Create", "a", "new", "PySQLQuery", "Class" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/__init__.py#L46-L61
train
46,915
mandeep/Travis-Encrypt
travis/cli.py
cli
def cli(username, repository, path, password, deploy, env, clipboard, env_file): """Encrypt passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the password that needs to be encrypted. The given password will then be encrypted via the PKCS1v15 padding scheme and printed to standard output. If the path to a .travis.yml file is given as an argument, the encrypted password is added to the .travis.yml file. """ key = retrieve_public_key('{}/{}' .format(username, repository)) if env_file: if path: config = load_travis_configuration(path) for env_var, value in dotenv_values(env_file).items(): encrypted_env = encrypt_key(key, value.encode()) config.setdefault('env', {}).setdefault('global', {})[env_var] = {'secure': encrypted_env} dump_travis_configuration(config, path) print('Encrypted variables from {} added to {}'.format(env_file, path)) else: print('\nPlease add the following to your .travis.yml:') for env_var, value in dotenv_values(env_file).items(): encrypted_env = encrypt_key(key, value.encode()) print("{}:\n secure: {}".format(env_var, encrypted_env)) else: encrypted_password = encrypt_key(key, password.encode()) if path: config = load_travis_configuration(path) if config is None: config = OrderedDict() if deploy: config.setdefault('deploy', {}).setdefault('password', {})['secure'] = encrypted_password elif env: try: config.setdefault('env', {}).setdefault('global', {})['secure'] = encrypted_password except TypeError: for item in config['env']['global']: if isinstance(item, dict) and 'secure' in item: item['secure'] = encrypted_password else: config.setdefault('password', {})['secure'] = encrypted_password dump_travis_configuration(config, path) print('Encrypted password added to {}' .format(path)) elif clipboard: pyperclip.copy(encrypted_password) print('\nThe encrypted password has been copied to your clipboard.') else: print('\nPlease add the following to your .travis.yml:\nsecure: {}' .format(encrypted_password))
python
def cli(username, repository, path, password, deploy, env, clipboard, env_file): """Encrypt passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the password that needs to be encrypted. The given password will then be encrypted via the PKCS1v15 padding scheme and printed to standard output. If the path to a .travis.yml file is given as an argument, the encrypted password is added to the .travis.yml file. """ key = retrieve_public_key('{}/{}' .format(username, repository)) if env_file: if path: config = load_travis_configuration(path) for env_var, value in dotenv_values(env_file).items(): encrypted_env = encrypt_key(key, value.encode()) config.setdefault('env', {}).setdefault('global', {})[env_var] = {'secure': encrypted_env} dump_travis_configuration(config, path) print('Encrypted variables from {} added to {}'.format(env_file, path)) else: print('\nPlease add the following to your .travis.yml:') for env_var, value in dotenv_values(env_file).items(): encrypted_env = encrypt_key(key, value.encode()) print("{}:\n secure: {}".format(env_var, encrypted_env)) else: encrypted_password = encrypt_key(key, password.encode()) if path: config = load_travis_configuration(path) if config is None: config = OrderedDict() if deploy: config.setdefault('deploy', {}).setdefault('password', {})['secure'] = encrypted_password elif env: try: config.setdefault('env', {}).setdefault('global', {})['secure'] = encrypted_password except TypeError: for item in config['env']['global']: if isinstance(item, dict) and 'secure' in item: item['secure'] = encrypted_password else: config.setdefault('password', {})['secure'] = encrypted_password dump_travis_configuration(config, path) print('Encrypted password added to {}' .format(path)) elif clipboard: pyperclip.copy(encrypted_password) print('\nThe encrypted password has been copied to your clipboard.') else: print('\nPlease add the following to your .travis.yml:\nsecure: {}' .format(encrypted_password))
[ "def", "cli", "(", "username", ",", "repository", ",", "path", ",", "password", ",", "deploy", ",", "env", ",", "clipboard", ",", "env_file", ")", ":", "key", "=", "retrieve_public_key", "(", "'{}/{}'", ".", "format", "(", "username", ",", "repository", ...
Encrypt passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the password that needs to be encrypted. The given password will then be encrypted via the PKCS1v15 padding scheme and printed to standard output. If the path to a .travis.yml file is given as an argument, the encrypted password is added to the .travis.yml file.
[ "Encrypt", "passwords", "and", "environment", "variables", "for", "use", "with", "Travis", "CI", "." ]
0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/cli.py#L53-L107
train
46,916
openspending/babbage
babbage/query/fields.py
Fields.apply
def apply(self, q, bindings, fields, distinct=False): """ Define a set of fields to return for a non-aggregated query. """ info = [] group_by = None for field in self.parse(fields): for concept in self.cube.model.match(field): info.append(concept.ref) table, column = concept.bind(self.cube) bindings.append(Binding(table, concept.ref)) if distinct: if group_by is None: q = q.group_by(column) group_by = column else: min_column = func.max(column) min_column = min_column.label(column.name) column = min_column q = q.column(column) if not len(self.results): # If no fields are requested, return all available fields. for concept in list(self.cube.model.attributes) + \ list(self.cube.model.measures): info.append(concept.ref) table, column = concept.bind(self.cube) bindings.append(Binding(table, concept.ref)) q = q.column(column) return info, q, bindings
python
def apply(self, q, bindings, fields, distinct=False): """ Define a set of fields to return for a non-aggregated query. """ info = [] group_by = None for field in self.parse(fields): for concept in self.cube.model.match(field): info.append(concept.ref) table, column = concept.bind(self.cube) bindings.append(Binding(table, concept.ref)) if distinct: if group_by is None: q = q.group_by(column) group_by = column else: min_column = func.max(column) min_column = min_column.label(column.name) column = min_column q = q.column(column) if not len(self.results): # If no fields are requested, return all available fields. for concept in list(self.cube.model.attributes) + \ list(self.cube.model.measures): info.append(concept.ref) table, column = concept.bind(self.cube) bindings.append(Binding(table, concept.ref)) q = q.column(column) return info, q, bindings
[ "def", "apply", "(", "self", ",", "q", ",", "bindings", ",", "fields", ",", "distinct", "=", "False", ")", ":", "info", "=", "[", "]", "group_by", "=", "None", "for", "field", "in", "self", ".", "parse", "(", "fields", ")", ":", "for", "concept", ...
Define a set of fields to return for a non-aggregated query.
[ "Define", "a", "set", "of", "fields", "to", "return", "for", "a", "non", "-", "aggregated", "query", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/fields.py#L21-L51
train
46,917
nschloe/meshplex
meshplex/mesh_line.py
MeshLine.create_cell_volumes
def create_cell_volumes(self): """Computes the volumes of the "cells" in the mesh. """ self.cell_volumes = numpy.array( [ abs( self.node_coords[cell["nodes"]][1] - self.node_coords[cell["nodes"]][0] ) for cell in self.cells ] ) return
python
def create_cell_volumes(self): """Computes the volumes of the "cells" in the mesh. """ self.cell_volumes = numpy.array( [ abs( self.node_coords[cell["nodes"]][1] - self.node_coords[cell["nodes"]][0] ) for cell in self.cells ] ) return
[ "def", "create_cell_volumes", "(", "self", ")", ":", "self", ".", "cell_volumes", "=", "numpy", ".", "array", "(", "[", "abs", "(", "self", ".", "node_coords", "[", "cell", "[", "\"nodes\"", "]", "]", "[", "1", "]", "-", "self", ".", "node_coords", "...
Computes the volumes of the "cells" in the mesh.
[ "Computes", "the", "volumes", "of", "the", "cells", "in", "the", "mesh", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_line.py#L21-L33
train
46,918
bodylabs/lace
lace/shapes.py
create_rectangular_prism
def create_rectangular_prism(origin, size): ''' Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array. ''' from lace.topology import quads_to_tris lower_base_plane = np.array([ # Lower base plane origin, origin + np.array([size[0], 0, 0]), origin + np.array([size[0], 0, size[2]]), origin + np.array([0, 0, size[2]]), ]) upper_base_plane = lower_base_plane + np.array([0, size[1], 0]) vertices = np.vstack([lower_base_plane, upper_base_plane]) faces = quads_to_tris(np.array([ [0, 1, 2, 3], # lower base (-y) [7, 6, 5, 4], # upper base (+y) [4, 5, 1, 0], # +z face [5, 6, 2, 1], # +x face [6, 7, 3, 2], # -z face [3, 7, 4, 0], # -x face ])) return Mesh(v=vertices, f=faces)
python
def create_rectangular_prism(origin, size): ''' Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array. ''' from lace.topology import quads_to_tris lower_base_plane = np.array([ # Lower base plane origin, origin + np.array([size[0], 0, 0]), origin + np.array([size[0], 0, size[2]]), origin + np.array([0, 0, size[2]]), ]) upper_base_plane = lower_base_plane + np.array([0, size[1], 0]) vertices = np.vstack([lower_base_plane, upper_base_plane]) faces = quads_to_tris(np.array([ [0, 1, 2, 3], # lower base (-y) [7, 6, 5, 4], # upper base (+y) [4, 5, 1, 0], # +z face [5, 6, 2, 1], # +x face [6, 7, 3, 2], # -z face [3, 7, 4, 0], # -x face ])) return Mesh(v=vertices, f=faces)
[ "def", "create_rectangular_prism", "(", "origin", ",", "size", ")", ":", "from", "lace", ".", "topology", "import", "quads_to_tris", "lower_base_plane", "=", "np", ".", "array", "(", "[", "# Lower base plane", "origin", ",", "origin", "+", "np", ".", "array", ...
Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array.
[ "Return", "a", "Mesh", "which", "is", "an", "axis", "-", "aligned", "rectangular", "prism", ".", "One", "vertex", "is", "origin", ";", "the", "diametrically", "opposite", "vertex", "is", "origin", "+", "size", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L6-L36
train
46,919
bodylabs/lace
lace/shapes.py
create_triangular_prism
def create_triangular_prism(p1, p2, p3, height): ''' Return a Mesh which is a triangular prism whose base is the triangle p1, p2, p3. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. ''' from blmath.geometry import Plane base_plane = Plane.from_points(p1, p2, p3) lower_base_to_upper_base = height * -base_plane.normal # pylint: disable=invalid-unary-operand-type vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base)) faces = np.array([ [0, 1, 2], # base [0, 3, 4], [0, 4, 1], # side 0, 3, 4, 1 [1, 4, 5], [1, 5, 2], # side 1, 4, 5, 2 [2, 5, 3], [2, 3, 0], # side 2, 5, 3, 0 [5, 4, 3], # base ]) return Mesh(v=vertices, f=faces)
python
def create_triangular_prism(p1, p2, p3, height): ''' Return a Mesh which is a triangular prism whose base is the triangle p1, p2, p3. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. ''' from blmath.geometry import Plane base_plane = Plane.from_points(p1, p2, p3) lower_base_to_upper_base = height * -base_plane.normal # pylint: disable=invalid-unary-operand-type vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base)) faces = np.array([ [0, 1, 2], # base [0, 3, 4], [0, 4, 1], # side 0, 3, 4, 1 [1, 4, 5], [1, 5, 2], # side 1, 4, 5, 2 [2, 5, 3], [2, 3, 0], # side 2, 5, 3, 0 [5, 4, 3], # base ]) return Mesh(v=vertices, f=faces)
[ "def", "create_triangular_prism", "(", "p1", ",", "p2", ",", "p3", ",", "height", ")", ":", "from", "blmath", ".", "geometry", "import", "Plane", "base_plane", "=", "Plane", ".", "from_points", "(", "p1", ",", "p2", ",", "p3", ")", "lower_base_to_upper_bas...
Return a Mesh which is a triangular prism whose base is the triangle p1, p2, p3. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them.
[ "Return", "a", "Mesh", "which", "is", "a", "triangular", "prism", "whose", "base", "is", "the", "triangle", "p1", "p2", "p3", ".", "If", "the", "vertices", "are", "oriented", "in", "a", "counterclockwise", "direction", "the", "prism", "extends", "from", "b...
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L50-L71
train
46,920
bodylabs/lace
lace/shapes.py
create_horizontal_plane
def create_horizontal_plane(): ''' Creates a horizontal plane. ''' v = np.array([ [1., 0., 0.], [-1., 0., 0.], [0., 0., 1.], [0., 0., -1.] ]) f = [[0, 1, 2], [3, 1, 0]] return Mesh(v=v, f=f)
python
def create_horizontal_plane(): ''' Creates a horizontal plane. ''' v = np.array([ [1., 0., 0.], [-1., 0., 0.], [0., 0., 1.], [0., 0., -1.] ]) f = [[0, 1, 2], [3, 1, 0]] return Mesh(v=v, f=f)
[ "def", "create_horizontal_plane", "(", ")", ":", "v", "=", "np", ".", "array", "(", "[", "[", "1.", ",", "0.", ",", "0.", "]", ",", "[", "-", "1.", ",", "0.", ",", "0.", "]", ",", "[", "0.", ",", "0.", ",", "1.", "]", ",", "[", "0.", ",",...
Creates a horizontal plane.
[ "Creates", "a", "horizontal", "plane", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L74-L85
train
46,921
openspending/babbage
babbage/model/concept.py
Concept.match_ref
def match_ref(self, ref): """ Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label. """ if ref in self.refs: self._matched_ref = ref return True return False
python
def match_ref(self, ref): """ Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label. """ if ref in self.refs: self._matched_ref = ref return True return False
[ "def", "match_ref", "(", "self", ",", "ref", ")", ":", "if", "ref", "in", "self", ".", "refs", ":", "self", ".", "_matched_ref", "=", "ref", "return", "True", "return", "False" ]
Check if the ref matches one the concept's aliases. If so, mark the matched ref so that we use it as the column label.
[ "Check", "if", "the", "ref", "matches", "one", "the", "concept", "s", "aliases", ".", "If", "so", "mark", "the", "matched", "ref", "so", "that", "we", "use", "it", "as", "the", "column", "label", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/concept.py#L40-L47
train
46,922
openspending/babbage
babbage/model/concept.py
Concept.bind
def bind(self, cube): """ Map a model reference to an physical column in the database. """ table, column = self._physical_column(cube, self.column_name) column = column.label(self.matched_ref) column.quote = True return table, column
python
def bind(self, cube): """ Map a model reference to an physical column in the database. """ table, column = self._physical_column(cube, self.column_name) column = column.label(self.matched_ref) column.quote = True return table, column
[ "def", "bind", "(", "self", ",", "cube", ")", ":", "table", ",", "column", "=", "self", ".", "_physical_column", "(", "cube", ",", "self", ".", "column_name", ")", "column", "=", "column", ".", "label", "(", "self", ".", "matched_ref", ")", "column", ...
Map a model reference to an physical column in the database.
[ "Map", "a", "model", "reference", "to", "an", "physical", "column", "in", "the", "database", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/concept.py#L63-L68
train
46,923
ArabellaTech/aa-stripe
aa_stripe/models.py
StripeCoupon.update_from_stripe_data
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True): """ Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if commit is False. """ fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or []) update_data = {key: stripe_coupon[key] for key in fields_to_update} for field in ["created", "redeem_by"]: if update_data.get(field): update_data[field] = timestamp_to_timezone_aware_date(update_data[field]) if update_data.get("amount_off"): update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100 # also make sure the object is up to date (without the need to call database) for key, value in six.iteritems(update_data): setattr(self, key, value) if commit: return StripeCoupon.objects.filter(pk=self.pk).update(**update_data)
python
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True): """ Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if commit is False. """ fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or []) update_data = {key: stripe_coupon[key] for key in fields_to_update} for field in ["created", "redeem_by"]: if update_data.get(field): update_data[field] = timestamp_to_timezone_aware_date(update_data[field]) if update_data.get("amount_off"): update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100 # also make sure the object is up to date (without the need to call database) for key, value in six.iteritems(update_data): setattr(self, key, value) if commit: return StripeCoupon.objects.filter(pk=self.pk).update(**update_data)
[ "def", "update_from_stripe_data", "(", "self", ",", "stripe_coupon", ",", "exclude_fields", "=", "None", ",", "commit", "=", "True", ")", ":", "fields_to_update", "=", "self", ".", "STRIPE_FIELDS", "-", "set", "(", "exclude_fields", "or", "[", "]", ")", "upd...
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve. To only update the object, set the commit param to False. Returns the number of rows altered or None if commit is False.
[ "Update", "StripeCoupon", "object", "with", "data", "from", "stripe", ".", "Coupon", "without", "calling", "stripe", ".", "Coupon", ".", "retrieve", "." ]
bda97c233a7513a69947c30f524a6050f984088b
https://github.com/ArabellaTech/aa-stripe/blob/bda97c233a7513a69947c30f524a6050f984088b/aa_stripe/models.py#L239-L260
train
46,924
ArabellaTech/aa-stripe
aa_stripe/models.py
StripeCoupon.save
def save(self, force_retrieve=False, *args, **kwargs): """ Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe API or update the local object with data fetched from Stripe. """ stripe.api_key = stripe_settings.API_KEY if self._previous_is_deleted != self.is_deleted and self.is_deleted: try: stripe_coupon = stripe.Coupon.retrieve(self.coupon_id) # make sure to delete correct coupon if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]): stripe_coupon.delete() except stripe.error.InvalidRequestError: # means that the coupon has already been removed from stripe pass return super(StripeCoupon, self).save(*args, **kwargs) if self.pk or force_retrieve: try: stripe_coupon = stripe.Coupon.retrieve(self.coupon_id) if not force_retrieve: stripe_coupon.metadata = self.metadata stripe_coupon.save() if force_retrieve: # make sure we are not creating a duplicate coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id) if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists(): raise StripeCouponAlreadyExists # all old coupons should be deleted for coupon in coupon_qs: coupon.is_deleted = True super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals # update all fields in the local object in case someone tried to change them self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else []) self.stripe_response = stripe_coupon except stripe.error.InvalidRequestError: if force_retrieve: raise self.is_deleted = True else: self.stripe_response = stripe.Coupon.create( id=self.coupon_id, duration=self.duration, amount_off=int(self.amount_off * 100) if self.amount_off else None, currency=self.currency, duration_in_months=self.duration_in_months, max_redemptions=self.max_redemptions, metadata=self.metadata, percent_off=self.percent_off, redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None ) # stripe will generate coupon_id if none was specified in the request if not self.coupon_id: self.coupon_id = self.stripe_response["id"] self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"]) # for future self.is_created_at_stripe = True return super(StripeCoupon, self).save(*args, **kwargs)
python
def save(self, force_retrieve=False, *args, **kwargs): """ Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe API or update the local object with data fetched from Stripe. """ stripe.api_key = stripe_settings.API_KEY if self._previous_is_deleted != self.is_deleted and self.is_deleted: try: stripe_coupon = stripe.Coupon.retrieve(self.coupon_id) # make sure to delete correct coupon if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]): stripe_coupon.delete() except stripe.error.InvalidRequestError: # means that the coupon has already been removed from stripe pass return super(StripeCoupon, self).save(*args, **kwargs) if self.pk or force_retrieve: try: stripe_coupon = stripe.Coupon.retrieve(self.coupon_id) if not force_retrieve: stripe_coupon.metadata = self.metadata stripe_coupon.save() if force_retrieve: # make sure we are not creating a duplicate coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id) if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists(): raise StripeCouponAlreadyExists # all old coupons should be deleted for coupon in coupon_qs: coupon.is_deleted = True super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals # update all fields in the local object in case someone tried to change them self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else []) self.stripe_response = stripe_coupon except stripe.error.InvalidRequestError: if force_retrieve: raise self.is_deleted = True else: self.stripe_response = stripe.Coupon.create( id=self.coupon_id, duration=self.duration, amount_off=int(self.amount_off * 100) if self.amount_off else None, currency=self.currency, duration_in_months=self.duration_in_months, max_redemptions=self.max_redemptions, metadata=self.metadata, percent_off=self.percent_off, redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None ) # stripe will generate coupon_id if none was specified in the request if not self.coupon_id: self.coupon_id = self.stripe_response["id"] self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"]) # for future self.is_created_at_stripe = True return super(StripeCoupon, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "force_retrieve", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "stripe", ".", "api_key", "=", "stripe_settings", ".", "API_KEY", "if", "self", ".", "_previous_is_deleted", "!=", "self", ".", "is_dele...
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe API or update the local object with data fetched from Stripe.
[ "Use", "the", "force_retrieve", "parameter", "to", "create", "a", "new", "StripeCoupon", "object", "from", "an", "existing", "coupon", "created", "at", "Stripe" ]
bda97c233a7513a69947c30f524a6050f984088b
https://github.com/ArabellaTech/aa-stripe/blob/bda97c233a7513a69947c30f524a6050f984088b/aa_stripe/models.py#L262-L325
train
46,925
nschloe/meshplex
meshplex/helpers.py
get_signed_simplex_volumes
def get_signed_simplex_volumes(cells, pts): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1) return numpy.linalg.det(p) / math.factorial(n)
python
def get_signed_simplex_volumes(cells, pts): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1) return numpy.linalg.det(p) / math.factorial(n)
[ "def", "get_signed_simplex_volumes", "(", "cells", ",", "pts", ")", ":", "n", "=", "pts", ".", "shape", "[", "1", "]", "assert", "cells", ".", "shape", "[", "1", "]", "==", "n", "+", "1", "p", "=", "pts", "[", "cells", "]", "p", "=", "numpy", "...
Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n.
[ "Signed", "volume", "of", "a", "simplex", "in", "nD", ".", "Note", "that", "signing", "only", "makes", "sense", "for", "n", "-", "simplices", "in", "R^n", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/helpers.py#L8-L17
train
46,926
nschloe/meshplex
meshplex/base.py
compute_triangle_circumcenters
def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej): """Computes the circumcenters of all given triangles. """ # The input argument are the dot products # # <e1, e2> # <e2, e0> # <e0, e1> # # of the edges # # e0: x1->x2, # e1: x2->x0, # e2: x0->x1. # # Note that edge e_i is opposite of node i and the edges add up to 0. # The trilinear coordinates of the circumcenter are # # cos(alpha0) : cos(alpha1) : cos(alpha2) # # where alpha_k is the angle at point k, opposite of edge k. The Cartesian # coordinates are (see # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>) # # C = sum_i ||e_i|| * cos(alpha_i)/beta * P_i # # with # # beta = sum ||e_i||*cos(alpha_i) # # Incidentally, the cosines are # # cos(alpha0) = <e1, e2> / ||e1|| / ||e2||, # # so in total # # C = <e_0, e0> <e1, e2> / sum_i (<e_i, e_i> <e{i+1}, e{i+2}>) P0 # + ... P1 # + ... P2. # # An even nicer formula is given on # <https://en.wikipedia.org/wiki/Circumscribed_circle#Barycentric_coordinates>: The # barycentric coordinates of the circumcenter are # # a^2 (b^2 + c^2 - a^2) : b^2 (c^2 + a^2 - b^2) : c^2 (a^2 + b^2 - c^2). # # This is only using the squared edge lengths, too! # alpha = ei_dot_ei * ei_dot_ej alpha_sum = alpha[0] + alpha[1] + alpha[2] beta = alpha / alpha_sum[None] a = X * beta[..., None] cc = a[0] + a[1] + a[2] # alpha = numpy.array([ # ei_dot_ei[0] * (ei_dot_ei[1] + ei_dot_ei[2] - ei_dot_ei[0]), # ei_dot_ei[1] * (ei_dot_ei[2] + ei_dot_ei[0] - ei_dot_ei[1]), # ei_dot_ei[2] * (ei_dot_ei[0] + ei_dot_ei[1] - ei_dot_ei[2]), # ]) # alpha /= numpy.sum(alpha, axis=0) # cc = (X[0].T * alpha[0] + X[1].T * alpha[1] + X[2].T * alpha[2]).T return cc
python
def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej): """Computes the circumcenters of all given triangles. """ # The input argument are the dot products # # <e1, e2> # <e2, e0> # <e0, e1> # # of the edges # # e0: x1->x2, # e1: x2->x0, # e2: x0->x1. # # Note that edge e_i is opposite of node i and the edges add up to 0. # The trilinear coordinates of the circumcenter are # # cos(alpha0) : cos(alpha1) : cos(alpha2) # # where alpha_k is the angle at point k, opposite of edge k. The Cartesian # coordinates are (see # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>) # # C = sum_i ||e_i|| * cos(alpha_i)/beta * P_i # # with # # beta = sum ||e_i||*cos(alpha_i) # # Incidentally, the cosines are # # cos(alpha0) = <e1, e2> / ||e1|| / ||e2||, # # so in total # # C = <e_0, e0> <e1, e2> / sum_i (<e_i, e_i> <e{i+1}, e{i+2}>) P0 # + ... P1 # + ... P2. # # An even nicer formula is given on # <https://en.wikipedia.org/wiki/Circumscribed_circle#Barycentric_coordinates>: The # barycentric coordinates of the circumcenter are # # a^2 (b^2 + c^2 - a^2) : b^2 (c^2 + a^2 - b^2) : c^2 (a^2 + b^2 - c^2). # # This is only using the squared edge lengths, too! # alpha = ei_dot_ei * ei_dot_ej alpha_sum = alpha[0] + alpha[1] + alpha[2] beta = alpha / alpha_sum[None] a = X * beta[..., None] cc = a[0] + a[1] + a[2] # alpha = numpy.array([ # ei_dot_ei[0] * (ei_dot_ei[1] + ei_dot_ei[2] - ei_dot_ei[0]), # ei_dot_ei[1] * (ei_dot_ei[2] + ei_dot_ei[0] - ei_dot_ei[1]), # ei_dot_ei[2] * (ei_dot_ei[0] + ei_dot_ei[1] - ei_dot_ei[2]), # ]) # alpha /= numpy.sum(alpha, axis=0) # cc = (X[0].T * alpha[0] + X[1].T * alpha[1] + X[2].T * alpha[2]).T return cc
[ "def", "compute_triangle_circumcenters", "(", "X", ",", "ei_dot_ei", ",", "ei_dot_ej", ")", ":", "# The input argument are the dot products", "#", "# <e1, e2>", "# <e2, e0>", "# <e0, e1>", "#", "# of the edges", "#", "# e0: x1->x2,", "# e1: x2->x0,", "# e2: x0->x1...
Computes the circumcenters of all given triangles.
[ "Computes", "the", "circumcenters", "of", "all", "given", "triangles", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L86-L148
train
46,927
mandeep/Travis-Encrypt
travis/orderer.py
ordered_dump
def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds): """Dump a yaml configuration as an OrderedDict.""" class OrderedDumper(Dumper): pass def dict_representer(dumper, data): return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds)
python
def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds): """Dump a yaml configuration as an OrderedDict.""" class OrderedDumper(Dumper): pass def dict_representer(dumper, data): return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items()) OrderedDumper.add_representer(OrderedDict, dict_representer) return yaml.dump(data, stream, OrderedDumper, **kwds)
[ "def", "ordered_dump", "(", "data", ",", "stream", "=", "None", ",", "Dumper", "=", "yaml", ".", "SafeDumper", ",", "*", "*", "kwds", ")", ":", "class", "OrderedDumper", "(", "Dumper", ")", ":", "pass", "def", "dict_representer", "(", "dumper", ",", "d...
Dump a yaml configuration as an OrderedDict.
[ "Dump", "a", "yaml", "configuration", "as", "an", "OrderedDict", "." ]
0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/orderer.py#L27-L37
train
46,928
openspending/babbage
babbage/query/cuts.py
Cuts._check_type
def _check_type(self, ref, value): """ Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if it doesn't match """ if isinstance(value, list): return [self._check_type(ref, val) for val in value] model_type = self.cube.model[ref].datatype if model_type is None: return query_type = self._api_type(value) if query_type == model_type: return else: raise QueryException("Invalid value %r parsed as type '%s' " "for cut %s of type '%s'" % (value, query_type, ref, model_type))
python
def _check_type(self, ref, value): """ Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if it doesn't match """ if isinstance(value, list): return [self._check_type(ref, val) for val in value] model_type = self.cube.model[ref].datatype if model_type is None: return query_type = self._api_type(value) if query_type == model_type: return else: raise QueryException("Invalid value %r parsed as type '%s' " "for cut %s of type '%s'" % (value, query_type, ref, model_type))
[ "def", "_check_type", "(", "self", ",", "ref", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "return", "[", "self", ".", "_check_type", "(", "ref", ",", "val", ")", "for", "val", "in", "value", "]", "model_type", ...
Checks whether the type of the cut value matches the type of the concept being cut, and raises a QueryException if it doesn't match
[ "Checks", "whether", "the", "type", "of", "the", "cut", "value", "matches", "the", "type", "of", "the", "concept", "being", "cut", "and", "raises", "a", "QueryException", "if", "it", "doesn", "t", "match" ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/cuts.py#L24-L41
train
46,929
openspending/babbage
babbage/query/cuts.py
Cuts._api_type
def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types): return 'integer' elif type(value) is datetime.datetime: return 'date'
python
def _api_type(self, value): """ Returns the API type of the given value based on its python type. """ if isinstance(value, six.string_types): return 'string' elif isinstance(value, six.integer_types): return 'integer' elif type(value) is datetime.datetime: return 'date'
[ "def", "_api_type", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "'string'", "elif", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", ":", "return", "'intege...
Returns the API type of the given value based on its python type.
[ "Returns", "the", "API", "type", "of", "the", "given", "value", "based", "on", "its", "python", "type", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/cuts.py#L43-L53
train
46,930
bodylabs/lace
lace/color.py
MeshMixin.color_by_height
def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument ''' Color each vertex by its height above the floor point. axis: The axis to use. 0 means x, 1 means y, 2 means z. threshold: The top of the range. Points at and above this height will be the same color. ''' import numpy as np heights = self.v[:, axis] - self.floor_point[axis] if threshold: # height == 0 -> saturation = 0. # height == threshold -> saturation = 1. color_weights = np.minimum(heights / threshold, 1.) color_weights = color_weights * color_weights self.set_vertex_colors_from_weights(color_weights, scale_to_range_1=False) else: self.set_vertex_colors_from_weights(heights)
python
def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument ''' Color each vertex by its height above the floor point. axis: The axis to use. 0 means x, 1 means y, 2 means z. threshold: The top of the range. Points at and above this height will be the same color. ''' import numpy as np heights = self.v[:, axis] - self.floor_point[axis] if threshold: # height == 0 -> saturation = 0. # height == threshold -> saturation = 1. color_weights = np.minimum(heights / threshold, 1.) color_weights = color_weights * color_weights self.set_vertex_colors_from_weights(color_weights, scale_to_range_1=False) else: self.set_vertex_colors_from_weights(heights)
[ "def", "color_by_height", "(", "self", ",", "axis", "=", "1", ",", "threshold", "=", "None", ",", "color", "=", "DEFAULT_COLORMAP", ")", ":", "# pylint: disable=unused-argument", "import", "numpy", "as", "np", "heights", "=", "self", ".", "v", "[", ":", ",...
Color each vertex by its height above the floor point. axis: The axis to use. 0 means x, 1 means y, 2 means z. threshold: The top of the range. Points at and above this height will be the same color.
[ "Color", "each", "vertex", "by", "its", "height", "above", "the", "floor", "point", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/color.py#L85-L105
train
46,931
bodylabs/lace
lace/topology.py
quads_to_tris
def quads_to_tris(quads): ''' Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array. ''' import numpy as np tris = np.empty((2 * len(quads), 3)) tris[0::2, :] = quads[:, [0, 1, 2]] tris[1::2, :] = quads[:, [0, 2, 3]] return tris
python
def quads_to_tris(quads): ''' Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array. ''' import numpy as np tris = np.empty((2 * len(quads), 3)) tris[0::2, :] = quads[:, [0, 1, 2]] tris[1::2, :] = quads[:, [0, 2, 3]] return tris
[ "def", "quads_to_tris", "(", "quads", ")", ":", "import", "numpy", "as", "np", "tris", "=", "np", ".", "empty", "(", "(", "2", "*", "len", "(", "quads", ")", ",", "3", ")", ")", "tris", "[", "0", ":", ":", "2", ",", ":", "]", "=", "quads", ...
Convert quad faces to triangular faces. quads: An nx4 array. Return a 2nx3 array.
[ "Convert", "quad", "faces", "to", "triangular", "faces", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L4-L17
train
46,932
bodylabs/lace
lace/topology.py
MeshMixin.vertex_indices_in_segments
def vertex_indices_in_segments(self, segments, ret_face_indices=False): ''' Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns face indices ''' import numpy as np import warnings face_indices = np.array([]) vertex_indices = np.array([]) if self.segm is not None: try: segments = [self.segm[name] for name in segments] except KeyError as e: raise ValueError('Unknown segments {}. Consier using Mesh.clean_segments on segments'.format(e.args[0])) face_indices = np.unique(np.concatenate(segments)) vertex_indices = np.unique(np.ravel(self.f[face_indices])) else: warnings.warn('self.segm is None, will return empty array') if ret_face_indices: return vertex_indices, face_indices else: return vertex_indices
python
def vertex_indices_in_segments(self, segments, ret_face_indices=False): ''' Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns face indices ''' import numpy as np import warnings face_indices = np.array([]) vertex_indices = np.array([]) if self.segm is not None: try: segments = [self.segm[name] for name in segments] except KeyError as e: raise ValueError('Unknown segments {}. Consier using Mesh.clean_segments on segments'.format(e.args[0])) face_indices = np.unique(np.concatenate(segments)) vertex_indices = np.unique(np.ravel(self.f[face_indices])) else: warnings.warn('self.segm is None, will return empty array') if ret_face_indices: return vertex_indices, face_indices else: return vertex_indices
[ "def", "vertex_indices_in_segments", "(", "self", ",", "segments", ",", "ret_face_indices", "=", "False", ")", ":", "import", "numpy", "as", "np", "import", "warnings", "face_indices", "=", "np", ".", "array", "(", "[", "]", ")", "vertex_indices", "=", "np",...
Given a list of segment names, return an array of vertex indices for all the vertices in those faces. Args: segments: a list of segment names, ret_face_indices: if it is `True`, returns face indices
[ "Given", "a", "list", "of", "segment", "names", "return", "an", "array", "of", "vertex", "indices", "for", "all", "the", "vertices", "in", "those", "faces", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L76-L103
train
46,933
bodylabs/lace
lace/topology.py
MeshMixin.keep_segments
def keep_segments(self, segments_to_keep, preserve_segmentation=True): ''' Keep the faces and vertices for given segments, discarding all others. When preserve_segmentation is false self.segm is discarded for speed. ''' v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True) self.segm = {name: self.segm[name] for name in segments_to_keep} if not preserve_segmentation: self.segm = None self.f = self.f[f_ind] if self.ft is not None: self.ft = self.ft[f_ind] self.keep_vertices(v_ind)
python
def keep_segments(self, segments_to_keep, preserve_segmentation=True): ''' Keep the faces and vertices for given segments, discarding all others. When preserve_segmentation is false self.segm is discarded for speed. ''' v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True) self.segm = {name: self.segm[name] for name in segments_to_keep} if not preserve_segmentation: self.segm = None self.f = self.f[f_ind] if self.ft is not None: self.ft = self.ft[f_ind] self.keep_vertices(v_ind)
[ "def", "keep_segments", "(", "self", ",", "segments_to_keep", ",", "preserve_segmentation", "=", "True", ")", ":", "v_ind", ",", "f_ind", "=", "self", ".", "vertex_indices_in_segments", "(", "segments_to_keep", ",", "ret_face_indices", "=", "True", ")", "self", ...
Keep the faces and vertices for given segments, discarding all others. When preserve_segmentation is false self.segm is discarded for speed.
[ "Keep", "the", "faces", "and", "vertices", "for", "given", "segments", "discarding", "all", "others", ".", "When", "preserve_segmentation", "is", "false", "self", ".", "segm", "is", "discarded", "for", "speed", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L110-L124
train
46,934
bodylabs/lace
lace/topology.py
MeshMixin.remove_segments
def remove_segments(self, segments_to_remove): ''' Remove the faces and vertices for given segments, keeping all others. Args: segments_to_remove: a list of segnments whose vertices will be removed ''' v_ind = self.vertex_indices_in_segments(segments_to_remove) self.segm = {name: faces for name, faces in self.segm.iteritems() if name not in segments_to_remove} self.remove_vertices(v_ind)
python
def remove_segments(self, segments_to_remove): ''' Remove the faces and vertices for given segments, keeping all others. Args: segments_to_remove: a list of segnments whose vertices will be removed ''' v_ind = self.vertex_indices_in_segments(segments_to_remove) self.segm = {name: faces for name, faces in self.segm.iteritems() if name not in segments_to_remove} self.remove_vertices(v_ind)
[ "def", "remove_segments", "(", "self", ",", "segments_to_remove", ")", ":", "v_ind", "=", "self", ".", "vertex_indices_in_segments", "(", "segments_to_remove", ")", "self", ".", "segm", "=", "{", "name", ":", "faces", "for", "name", ",", "faces", "in", "self...
Remove the faces and vertices for given segments, keeping all others. Args: segments_to_remove: a list of segnments whose vertices will be removed
[ "Remove", "the", "faces", "and", "vertices", "for", "given", "segments", "keeping", "all", "others", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L126-L134
train
46,935
bodylabs/lace
lace/topology.py
MeshMixin.verts_in_common
def verts_in_common(self, segments): """ returns array of all vertex indices common to each segment in segments""" verts_by_segm = self.verts_by_segm return sorted(reduce(lambda s0, s1: s0.intersection(s1), [set(verts_by_segm[segm]) for segm in segments]))
python
def verts_in_common(self, segments): """ returns array of all vertex indices common to each segment in segments""" verts_by_segm = self.verts_by_segm return sorted(reduce(lambda s0, s1: s0.intersection(s1), [set(verts_by_segm[segm]) for segm in segments]))
[ "def", "verts_in_common", "(", "self", ",", "segments", ")", ":", "verts_by_segm", "=", "self", ".", "verts_by_segm", "return", "sorted", "(", "reduce", "(", "lambda", "s0", ",", "s1", ":", "s0", ".", "intersection", "(", "s1", ")", ",", "[", "set", "(...
returns array of all vertex indices common to each segment in segments
[ "returns", "array", "of", "all", "vertex", "indices", "common", "to", "each", "segment", "in", "segments" ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L147-L152
train
46,936
bodylabs/lace
lace/topology.py
MeshMixin.uniquified_mesh
def uniquified_mesh(self): """This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face, and hence has only one texture""" import numpy as np from lace.mesh import Mesh new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3)) if self.vn is None: self.reset_normals() new_mesh.vn = self.vn[self.f.flatten()] if self.vt is not None: new_mesh.vt = self.vt[self.ft.flatten()] new_mesh.ft = new_mesh.f.copy() return new_mesh
python
def uniquified_mesh(self): """This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face, and hence has only one texture""" import numpy as np from lace.mesh import Mesh new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3)) if self.vn is None: self.reset_normals() new_mesh.vn = self.vn[self.f.flatten()] if self.vt is not None: new_mesh.vt = self.vt[self.ft.flatten()] new_mesh.ft = new_mesh.f.copy() return new_mesh
[ "def", "uniquified_mesh", "(", "self", ")", ":", "import", "numpy", "as", "np", "from", "lace", ".", "mesh", "import", "Mesh", "new_mesh", "=", "Mesh", "(", "v", "=", "self", ".", "v", "[", "self", ".", "f", ".", "flatten", "(", ")", "]", ",", "f...
This function returns a copy of the mesh in which vertices are copied such that each vertex appears in only one face, and hence has only one texture
[ "This", "function", "returns", "a", "copy", "of", "the", "mesh", "in", "which", "vertices", "are", "copied", "such", "that", "each", "vertex", "appears", "in", "only", "one", "face", "and", "hence", "has", "only", "one", "texture" ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L179-L193
train
46,937
bodylabs/lace
lace/topology.py
MeshMixin.downsampled_mesh
def downsampled_mesh(self, step): """Returns a downsampled copy of this mesh. Args: step: the step size for the sampling Returns: a new, downsampled Mesh object. Raises: ValueError if this Mesh has faces. """ from lace.mesh import Mesh if self.f is not None: raise ValueError( 'Function `downsampled_mesh` does not support faces.') low = Mesh() if self.v is not None: low.v = self.v[::step] if self.vc is not None: low.vc = self.vc[::step] return low
python
def downsampled_mesh(self, step): """Returns a downsampled copy of this mesh. Args: step: the step size for the sampling Returns: a new, downsampled Mesh object. Raises: ValueError if this Mesh has faces. """ from lace.mesh import Mesh if self.f is not None: raise ValueError( 'Function `downsampled_mesh` does not support faces.') low = Mesh() if self.v is not None: low.v = self.v[::step] if self.vc is not None: low.vc = self.vc[::step] return low
[ "def", "downsampled_mesh", "(", "self", ",", "step", ")", ":", "from", "lace", ".", "mesh", "import", "Mesh", "if", "self", ".", "f", "is", "not", "None", ":", "raise", "ValueError", "(", "'Function `downsampled_mesh` does not support faces.'", ")", "low", "="...
Returns a downsampled copy of this mesh. Args: step: the step size for the sampling Returns: a new, downsampled Mesh object. Raises: ValueError if this Mesh has faces.
[ "Returns", "a", "downsampled", "copy", "of", "this", "mesh", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L195-L218
train
46,938
bodylabs/lace
lace/topology.py
MeshMixin.keep_vertices
def keep_vertices(self, indices_to_keep, ret_kept_faces=False): ''' Keep the given vertices and discard the others, and any faces to which they may belong. If `ret_kept_faces` is `True`, return the original indices of the kept faces. Otherwise return `self` for chaining. ''' import numpy as np if self.v is None: return indices_to_keep = np.array(indices_to_keep, dtype=np.uint32) initial_num_verts = self.v.shape[0] if self.f is not None: initial_num_faces = self.f.shape[0] f_indices_to_keep = self.all_faces_with_verts(indices_to_keep, as_boolean=True) # Why do we test this? Don't know. But we do need to test it before we # mutate self.v. vn_should_update = self.vn is not None and self.vn.shape[0] == initial_num_verts vc_should_update = self.vc is not None and self.vc.shape[0] == initial_num_verts self.v = self.v[indices_to_keep] if vn_should_update: self.vn = self.vn[indices_to_keep] if vc_should_update: self.vc = self.vc[indices_to_keep] if self.f is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) f_old_to_new = np.zeros(initial_num_faces, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.f = v_old_to_new[self.f[f_indices_to_keep]] f_old_to_new[f_indices_to_keep] = np.arange(self.f.shape[0], dtype=int) else: # Make the code below work, in case there is somehow degenerate # segm even though there are no faces. f_indices_to_keep = [] if self.segm is not None: new_segm = {} for segm_name, segm_faces in self.segm.items(): faces = np.array(segm_faces, dtype=int) valid_faces = faces[f_indices_to_keep[faces]] if len(valid_faces): new_segm[segm_name] = f_old_to_new[valid_faces] self.segm = new_segm if new_segm else None if hasattr(self, '_raw_landmarks') and self._raw_landmarks is not None: self.recompute_landmarks() return np.nonzero(f_indices_to_keep)[0] if ret_kept_faces else self
python
def keep_vertices(self, indices_to_keep, ret_kept_faces=False): ''' Keep the given vertices and discard the others, and any faces to which they may belong. If `ret_kept_faces` is `True`, return the original indices of the kept faces. Otherwise return `self` for chaining. ''' import numpy as np if self.v is None: return indices_to_keep = np.array(indices_to_keep, dtype=np.uint32) initial_num_verts = self.v.shape[0] if self.f is not None: initial_num_faces = self.f.shape[0] f_indices_to_keep = self.all_faces_with_verts(indices_to_keep, as_boolean=True) # Why do we test this? Don't know. But we do need to test it before we # mutate self.v. vn_should_update = self.vn is not None and self.vn.shape[0] == initial_num_verts vc_should_update = self.vc is not None and self.vc.shape[0] == initial_num_verts self.v = self.v[indices_to_keep] if vn_should_update: self.vn = self.vn[indices_to_keep] if vc_should_update: self.vc = self.vc[indices_to_keep] if self.f is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) f_old_to_new = np.zeros(initial_num_faces, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.f = v_old_to_new[self.f[f_indices_to_keep]] f_old_to_new[f_indices_to_keep] = np.arange(self.f.shape[0], dtype=int) else: # Make the code below work, in case there is somehow degenerate # segm even though there are no faces. f_indices_to_keep = [] if self.segm is not None: new_segm = {} for segm_name, segm_faces in self.segm.items(): faces = np.array(segm_faces, dtype=int) valid_faces = faces[f_indices_to_keep[faces]] if len(valid_faces): new_segm[segm_name] = f_old_to_new[valid_faces] self.segm = new_segm if new_segm else None if hasattr(self, '_raw_landmarks') and self._raw_landmarks is not None: self.recompute_landmarks() return np.nonzero(f_indices_to_keep)[0] if ret_kept_faces else self
[ "def", "keep_vertices", "(", "self", ",", "indices_to_keep", ",", "ret_kept_faces", "=", "False", ")", ":", "import", "numpy", "as", "np", "if", "self", ".", "v", "is", "None", ":", "return", "indices_to_keep", "=", "np", ".", "array", "(", "indices_to_kee...
Keep the given vertices and discard the others, and any faces to which they may belong. If `ret_kept_faces` is `True`, return the original indices of the kept faces. Otherwise return `self` for chaining.
[ "Keep", "the", "given", "vertices", "and", "discard", "the", "others", "and", "any", "faces", "to", "which", "they", "may", "belong", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L220-L279
train
46,939
bodylabs/lace
lace/topology.py
MeshMixin.create_from_mesh_and_lines
def create_from_mesh_and_lines(cls, mesh, lines): ''' Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or Lines objects. ''' mesh_with_lines = mesh.copy() mesh_with_lines.add_lines(lines) return mesh_with_lines
python
def create_from_mesh_and_lines(cls, mesh, lines): ''' Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or Lines objects. ''' mesh_with_lines = mesh.copy() mesh_with_lines.add_lines(lines) return mesh_with_lines
[ "def", "create_from_mesh_and_lines", "(", "cls", ",", "mesh", ",", "lines", ")", ":", "mesh_with_lines", "=", "mesh", ".", "copy", "(", ")", "mesh_with_lines", ".", "add_lines", "(", "lines", ")", "return", "mesh_with_lines" ]
Return a copy of mesh with line vertices and edges added. mesh: A Mesh lines: A list of Polyline or Lines objects.
[ "Return", "a", "copy", "of", "mesh", "with", "line", "vertices", "and", "edges", "added", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L367-L377
train
46,940
bodylabs/lace
lace/topology.py
MeshMixin.add_lines
def add_lines(self, lines): ''' Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects. ''' import numpy as np if not lines: return v_lines = np.vstack([l.v for l in lines]) v_index_offset = np.cumsum([0] + [len(l.v) for l in lines]) e_lines = np.vstack([l.e + v_index_offset[i] for i, l in enumerate(lines)]) num_body_verts = self.v.shape[0] self.v = np.vstack([self.v, v_lines]) self.e = e_lines + num_body_verts
python
def add_lines(self, lines): ''' Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects. ''' import numpy as np if not lines: return v_lines = np.vstack([l.v for l in lines]) v_index_offset = np.cumsum([0] + [len(l.v) for l in lines]) e_lines = np.vstack([l.e + v_index_offset[i] for i, l in enumerate(lines)]) num_body_verts = self.v.shape[0] self.v = np.vstack([self.v, v_lines]) self.e = e_lines + num_body_verts
[ "def", "add_lines", "(", "self", ",", "lines", ")", ":", "import", "numpy", "as", "np", "if", "not", "lines", ":", "return", "v_lines", "=", "np", ".", "vstack", "(", "[", "l", ".", "v", "for", "l", "in", "lines", "]", ")", "v_index_offset", "=", ...
Add line vertices and edges to the mesh. lines: A list of Polyline or Lines objects.
[ "Add", "line", "vertices", "and", "edges", "to", "the", "mesh", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L379-L395
train
46,941
bodylabs/lace
lace/topology.py
MeshMixin.faces_per_edge
def faces_per_edge(self): """Returns an Ex2 array of adjacencies between faces, where each element in the array is a face index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np import scipy.sparse as sp from blmath.numerics.matlab import col IS = np.repeat(np.arange(len(self.f)), 3) JS = self.f.ravel() data = np.ones(IS.size) f2v = sp.csc_matrix((data, (IS, JS)), shape=(len(self.f), np.max(self.f.ravel())+1)) f2f = f2v.dot(f2v.T) f2f = f2f.tocoo() f2f = np.hstack((col(f2f.row), col(f2f.col), col(f2f.data))) which = (f2f[:, 0] < f2f[:, 1]) & (f2f[:, 2] >= 2) return np.asarray(f2f[which, :2], np.uint32)
python
def faces_per_edge(self): """Returns an Ex2 array of adjacencies between faces, where each element in the array is a face index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np import scipy.sparse as sp from blmath.numerics.matlab import col IS = np.repeat(np.arange(len(self.f)), 3) JS = self.f.ravel() data = np.ones(IS.size) f2v = sp.csc_matrix((data, (IS, JS)), shape=(len(self.f), np.max(self.f.ravel())+1)) f2f = f2v.dot(f2v.T) f2f = f2f.tocoo() f2f = np.hstack((col(f2f.row), col(f2f.col), col(f2f.data))) which = (f2f[:, 0] < f2f[:, 1]) & (f2f[:, 2] >= 2) return np.asarray(f2f[which, :2], np.uint32)
[ "def", "faces_per_edge", "(", "self", ")", ":", "import", "numpy", "as", "np", "import", "scipy", ".", "sparse", "as", "sp", "from", "blmath", ".", "numerics", ".", "matlab", "import", "col", "IS", "=", "np", ".", "repeat", "(", "np", ".", "arange", ...
Returns an Ex2 array of adjacencies between faces, where each element in the array is a face index. Each edge is included only once. Edges that are not shared by 2 faces are not included.
[ "Returns", "an", "Ex2", "array", "of", "adjacencies", "between", "faces", "where", "each", "element", "in", "the", "array", "is", "a", "face", "index", ".", "Each", "edge", "is", "included", "only", "once", ".", "Edges", "that", "are", "not", "shared", "...
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L438-L453
train
46,942
bodylabs/lace
lace/topology.py
MeshMixin.vertices_per_edge
def vertices_per_edge(self): """Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]])
python
def vertices_per_edge(self): """Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. Edges that are not shared by 2 faces are not included.""" import numpy as np return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]])
[ "def", "vertices_per_edge", "(", "self", ")", ":", "import", "numpy", "as", "np", "return", "np", ".", "asarray", "(", "[", "vertices_in_common", "(", "e", "[", "0", "]", ",", "e", "[", "1", "]", ")", "for", "e", "in", "self", ".", "f", "[", "sel...
Returns an Ex2 array of adjacencies between vertices, where each element in the array is a vertex index. Each edge is included only once. Edges that are not shared by 2 faces are not included.
[ "Returns", "an", "Ex2", "array", "of", "adjacencies", "between", "vertices", "where", "each", "element", "in", "the", "array", "is", "a", "vertex", "index", ".", "Each", "edge", "is", "included", "only", "once", ".", "Edges", "that", "are", "not", "shared"...
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L456-L461
train
46,943
bodylabs/lace
lace/topology.py
MeshMixin.remove_redundant_verts
def remove_redundant_verts(self, eps=1e-10): """Given verts and faces, this remove colocated vertices""" import numpy as np from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module fshape = self.f.shape tree = cKDTree(self.v) close_pairs = list(tree.query_pairs(eps)) if close_pairs: close_pairs = np.sort(close_pairs, axis=1) # update faces to not refer to redundant vertices equivalent_verts = np.arange(self.v.shape[0]) for v1, v2 in close_pairs: if equivalent_verts[v2] > v1: equivalent_verts[v2] = v1 self.f = equivalent_verts[self.f.flatten()].reshape((-1, 3)) # get rid of unused verts, and update faces accordingly vertidxs_left = np.unique(self.f) repl = np.arange(np.max(self.f)+1) repl[vertidxs_left] = np.arange(len(vertidxs_left)) self.v = self.v[vertidxs_left] self.f = repl[self.f].reshape((-1, fshape[1]))
python
def remove_redundant_verts(self, eps=1e-10): """Given verts and faces, this remove colocated vertices""" import numpy as np from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module fshape = self.f.shape tree = cKDTree(self.v) close_pairs = list(tree.query_pairs(eps)) if close_pairs: close_pairs = np.sort(close_pairs, axis=1) # update faces to not refer to redundant vertices equivalent_verts = np.arange(self.v.shape[0]) for v1, v2 in close_pairs: if equivalent_verts[v2] > v1: equivalent_verts[v2] = v1 self.f = equivalent_verts[self.f.flatten()].reshape((-1, 3)) # get rid of unused verts, and update faces accordingly vertidxs_left = np.unique(self.f) repl = np.arange(np.max(self.f)+1) repl[vertidxs_left] = np.arange(len(vertidxs_left)) self.v = self.v[vertidxs_left] self.f = repl[self.f].reshape((-1, fshape[1]))
[ "def", "remove_redundant_verts", "(", "self", ",", "eps", "=", "1e-10", ")", ":", "import", "numpy", "as", "np", "from", "scipy", ".", "spatial", "import", "cKDTree", "# FIXME pylint: disable=no-name-in-module", "fshape", "=", "self", ".", "f", ".", "shape", "...
Given verts and faces, this remove colocated vertices
[ "Given", "verts", "and", "faces", "this", "remove", "colocated", "vertices" ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L498-L518
train
46,944
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.signed_cell_areas
def signed_cell_areas(self): """Signed area of a triangle in 2D. """ # http://mathworld.wolfram.com/TriangleArea.html assert ( self.node_coords.shape[1] == 2 ), "Signed areas only make sense for triangles in 2D." if self._signed_cell_areas is None: # One could make p contiguous by adding a copy(), but that's not # really worth it here. p = self.node_coords[self.cells["nodes"]].T # <https://stackoverflow.com/q/50411583/353337> self._signed_cell_areas = ( +p[0][2] * (p[1][0] - p[1][1]) + p[0][0] * (p[1][1] - p[1][2]) + p[0][1] * (p[1][2] - p[1][0]) ) / 2 return self._signed_cell_areas
python
def signed_cell_areas(self): """Signed area of a triangle in 2D. """ # http://mathworld.wolfram.com/TriangleArea.html assert ( self.node_coords.shape[1] == 2 ), "Signed areas only make sense for triangles in 2D." if self._signed_cell_areas is None: # One could make p contiguous by adding a copy(), but that's not # really worth it here. p = self.node_coords[self.cells["nodes"]].T # <https://stackoverflow.com/q/50411583/353337> self._signed_cell_areas = ( +p[0][2] * (p[1][0] - p[1][1]) + p[0][0] * (p[1][1] - p[1][2]) + p[0][1] * (p[1][2] - p[1][0]) ) / 2 return self._signed_cell_areas
[ "def", "signed_cell_areas", "(", "self", ")", ":", "# http://mathworld.wolfram.com/TriangleArea.html", "assert", "(", "self", ".", "node_coords", ".", "shape", "[", "1", "]", "==", "2", ")", ",", "\"Signed areas only make sense for triangles in 2D.\"", "if", "self", "...
Signed area of a triangle in 2D.
[ "Signed", "area", "of", "a", "triangle", "in", "2D", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L282-L300
train
46,945
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.create_edges
def create_edges(self): """Set up edge-node and edge-cell relations. """ # Reshape into individual edges. # Sort the columns to make it possible for `unique()` to identify # individual edges. s = self.idx_hierarchy.shape a = numpy.sort(self.idx_hierarchy.reshape(s[0], -1).T) a_unique, inv, cts = unique_rows(a) assert numpy.all( cts < 3 ), "No edge has more than 2 cells. Are cells listed twice?" self.is_boundary_edge = (cts[inv] == 1).reshape(s[1:]) self.is_boundary_edge_individual = cts == 1 self.edges = {"nodes": a_unique} # cell->edges relationship self.cells["edges"] = inv.reshape(3, -1).T self._edges_cells = None self._edge_gid_to_edge_list = None # Store an index {boundary,interior}_edge -> edge_gid self._edge_to_edge_gid = [ [], numpy.where(self.is_boundary_edge_individual)[0], numpy.where(~self.is_boundary_edge_individual)[0], ] return
python
def create_edges(self): """Set up edge-node and edge-cell relations. """ # Reshape into individual edges. # Sort the columns to make it possible for `unique()` to identify # individual edges. s = self.idx_hierarchy.shape a = numpy.sort(self.idx_hierarchy.reshape(s[0], -1).T) a_unique, inv, cts = unique_rows(a) assert numpy.all( cts < 3 ), "No edge has more than 2 cells. Are cells listed twice?" self.is_boundary_edge = (cts[inv] == 1).reshape(s[1:]) self.is_boundary_edge_individual = cts == 1 self.edges = {"nodes": a_unique} # cell->edges relationship self.cells["edges"] = inv.reshape(3, -1).T self._edges_cells = None self._edge_gid_to_edge_list = None # Store an index {boundary,interior}_edge -> edge_gid self._edge_to_edge_gid = [ [], numpy.where(self.is_boundary_edge_individual)[0], numpy.where(~self.is_boundary_edge_individual)[0], ] return
[ "def", "create_edges", "(", "self", ")", ":", "# Reshape into individual edges.", "# Sort the columns to make it possible for `unique()` to identify", "# individual edges.", "s", "=", "self", ".", "idx_hierarchy", ".", "shape", "a", "=", "numpy", ".", "sort", "(", "self",...
Set up edge-node and edge-cell relations.
[ "Set", "up", "edge", "-", "node", "and", "edge", "-", "cell", "relations", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L334-L366
train
46,946
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_edges_cells
def _compute_edges_cells(self): """This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy. """ if self.edges is None: self.create_edges() num_edges = len(self.edges["nodes"]) counts = numpy.zeros(num_edges, dtype=int) fastfunc.add.at( counts, self.cells["edges"], numpy.ones(self.cells["edges"].shape, dtype=int), ) # <https://stackoverflow.com/a/50395231/353337> edges_flat = self.cells["edges"].flat idx_sort = numpy.argsort(edges_flat) idx_start, count = grp_start_len(edges_flat[idx_sort]) res1 = idx_sort[idx_start[count == 1]][:, numpy.newaxis] idx = idx_start[count == 2] res2 = numpy.column_stack([idx_sort[idx], idx_sort[idx + 1]]) self._edges_cells = [ [], # no edges with zero adjacent cells res1 // 3, res2 // 3, ] # self._edges_local = [ # [], # no edges with zero adjacent cells # res1 % 3, # res2 % 3, # ] # For each edge, store the number of adjacent cells plus the index into # the respective edge array. self._edge_gid_to_edge_list = numpy.empty((num_edges, 2), dtype=int) self._edge_gid_to_edge_list[:, 0] = count c1 = count == 1 l1 = numpy.sum(c1) self._edge_gid_to_edge_list[c1, 1] = numpy.arange(l1) c2 = count == 2 l2 = numpy.sum(c2) self._edge_gid_to_edge_list[c2, 1] = numpy.arange(l2) assert l1 + l2 == len(count) return
python
def _compute_edges_cells(self): """This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy. """ if self.edges is None: self.create_edges() num_edges = len(self.edges["nodes"]) counts = numpy.zeros(num_edges, dtype=int) fastfunc.add.at( counts, self.cells["edges"], numpy.ones(self.cells["edges"].shape, dtype=int), ) # <https://stackoverflow.com/a/50395231/353337> edges_flat = self.cells["edges"].flat idx_sort = numpy.argsort(edges_flat) idx_start, count = grp_start_len(edges_flat[idx_sort]) res1 = idx_sort[idx_start[count == 1]][:, numpy.newaxis] idx = idx_start[count == 2] res2 = numpy.column_stack([idx_sort[idx], idx_sort[idx + 1]]) self._edges_cells = [ [], # no edges with zero adjacent cells res1 // 3, res2 // 3, ] # self._edges_local = [ # [], # no edges with zero adjacent cells # res1 % 3, # res2 % 3, # ] # For each edge, store the number of adjacent cells plus the index into # the respective edge array. self._edge_gid_to_edge_list = numpy.empty((num_edges, 2), dtype=int) self._edge_gid_to_edge_list[:, 0] = count c1 = count == 1 l1 = numpy.sum(c1) self._edge_gid_to_edge_list[c1, 1] = numpy.arange(l1) c2 = count == 2 l2 = numpy.sum(c2) self._edge_gid_to_edge_list[c2, 1] = numpy.arange(l2) assert l1 + l2 == len(count) return
[ "def", "_compute_edges_cells", "(", "self", ")", ":", "if", "self", ".", "edges", "is", "None", ":", "self", ".", "create_edges", "(", ")", "num_edges", "=", "len", "(", "self", ".", "edges", "[", "\"nodes\"", "]", ")", "counts", "=", "numpy", ".", "...
This creates interior edge->cells relations. While it's not necessary for many applications, it sometimes does come in handy.
[ "This", "creates", "interior", "edge", "-", ">", "cells", "relations", ".", "While", "it", "s", "not", "necessary", "for", "many", "applications", "it", "sometimes", "does", "come", "in", "handy", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L374-L420
train
46,947
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_integral_x
def _compute_integral_x(self): """Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by a node, an edge midpoint, and a circumcenter. """ # The integral of any linear function over a triangle is the average of # the values of the function in each of the three corners, times the # area of the triangle. right_triangle_vols = self.cell_partitions node_edges = self.idx_hierarchy corner = self.node_coords[node_edges] edge_midpoints = 0.5 * (corner[0] + corner[1]) cc = self.cell_circumcenters average = (corner + edge_midpoints[None] + cc[None, None]) / 3.0 contribs = right_triangle_vols[None, :, :, None] * average return node_edges, contribs
python
def _compute_integral_x(self): """Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by a node, an edge midpoint, and a circumcenter. """ # The integral of any linear function over a triangle is the average of # the values of the function in each of the three corners, times the # area of the triangle. right_triangle_vols = self.cell_partitions node_edges = self.idx_hierarchy corner = self.node_coords[node_edges] edge_midpoints = 0.5 * (corner[0] + corner[1]) cc = self.cell_circumcenters average = (corner + edge_midpoints[None] + cc[None, None]) / 3.0 contribs = right_triangle_vols[None, :, :, None] * average return node_edges, contribs
[ "def", "_compute_integral_x", "(", "self", ")", ":", "# The integral of any linear function over a triangle is the average of", "# the values of the function in each of the three corners, times the", "# area of the triangle.", "right_triangle_vols", "=", "self", ".", "cell_partitions", "...
Computes the integral of x, \\int_V x, over all atomic "triangles", i.e., areas cornered by a node, an edge midpoint, and a circumcenter.
[ "Computes", "the", "integral", "of", "x" ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L512-L535
train
46,948
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri._compute_surface_areas
def _compute_surface_areas(self, cell_ids): """For each edge, one half of the the edge goes to each of the end points. Used for Neumann boundary conditions if on the boundary of the mesh and transition conditions if in the interior. """ # Each of the three edges may contribute to the surface areas of all # three vertices. Here, only the two adjacent nodes receive a # contribution, but other approaches (e.g., the flat cell corrector), # may contribute to all three nodes. cn = self.cells["nodes"][cell_ids] ids = numpy.stack([cn, cn, cn], axis=1) half_el = 0.5 * self.edge_lengths[..., cell_ids] zero = numpy.zeros([half_el.shape[1]]) vals = numpy.stack( [ numpy.column_stack([zero, half_el[0], half_el[0]]), numpy.column_stack([half_el[1], zero, half_el[1]]), numpy.column_stack([half_el[2], half_el[2], zero]), ], axis=1, ) return ids, vals
python
def _compute_surface_areas(self, cell_ids): """For each edge, one half of the the edge goes to each of the end points. Used for Neumann boundary conditions if on the boundary of the mesh and transition conditions if in the interior. """ # Each of the three edges may contribute to the surface areas of all # three vertices. Here, only the two adjacent nodes receive a # contribution, but other approaches (e.g., the flat cell corrector), # may contribute to all three nodes. cn = self.cells["nodes"][cell_ids] ids = numpy.stack([cn, cn, cn], axis=1) half_el = 0.5 * self.edge_lengths[..., cell_ids] zero = numpy.zeros([half_el.shape[1]]) vals = numpy.stack( [ numpy.column_stack([zero, half_el[0], half_el[0]]), numpy.column_stack([half_el[1], zero, half_el[1]]), numpy.column_stack([half_el[2], half_el[2], zero]), ], axis=1, ) return ids, vals
[ "def", "_compute_surface_areas", "(", "self", ",", "cell_ids", ")", ":", "# Each of the three edges may contribute to the surface areas of all", "# three vertices. Here, only the two adjacent nodes receive a", "# contribution, but other approaches (e.g., the flat cell corrector),", "# may cont...
For each edge, one half of the the edge goes to each of the end points. Used for Neumann boundary conditions if on the boundary of the mesh and transition conditions if in the interior.
[ "For", "each", "edge", "one", "half", "of", "the", "the", "edge", "goes", "to", "each", "of", "the", "end", "points", ".", "Used", "for", "Neumann", "boundary", "conditions", "if", "on", "the", "boundary", "of", "the", "mesh", "and", "transition", "condi...
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L537-L560
train
46,949
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.compute_curl
def compute_curl(self, vector_field): """Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; see <https://en.wikipedia.org/wiki/Curl_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges. """ # Compute the projection of A on the edge at each edge midpoint. # Take the average of `vector_field` at the endpoints to get the # approximate value at the edge midpoint. A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0) # sum of <edge, A> for all three edges sum_edge_dot_A = numpy.einsum("ijk, ijk->j", self.half_edge_coords, A) # Get normalized vector orthogonal to triangle z = numpy.cross(self.half_edge_coords[0], self.half_edge_coords[1]) # Now compute # # curl = z / ||z|| * sum_edge_dot_A / |A|. # # Since ||z|| = 2*|A|, one can save a sqrt and do # # curl = z * sum_edge_dot_A * 0.5 / |A|^2. # curl = z * (0.5 * sum_edge_dot_A / self.cell_volumes ** 2)[..., None] return curl
python
def compute_curl(self, vector_field): """Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; see <https://en.wikipedia.org/wiki/Curl_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges. """ # Compute the projection of A on the edge at each edge midpoint. # Take the average of `vector_field` at the endpoints to get the # approximate value at the edge midpoint. A = 0.5 * numpy.sum(vector_field[self.idx_hierarchy], axis=0) # sum of <edge, A> for all three edges sum_edge_dot_A = numpy.einsum("ijk, ijk->j", self.half_edge_coords, A) # Get normalized vector orthogonal to triangle z = numpy.cross(self.half_edge_coords[0], self.half_edge_coords[1]) # Now compute # # curl = z / ||z|| * sum_edge_dot_A / |A|. # # Since ||z|| = 2*|A|, one can save a sqrt and do # # curl = z * sum_edge_dot_A * 0.5 / |A|^2. # curl = z * (0.5 * sum_edge_dot_A / self.cell_volumes ** 2)[..., None] return curl
[ "def", "compute_curl", "(", "self", ",", "vector_field", ")", ":", "# Compute the projection of A on the edge at each edge midpoint.", "# Take the average of `vector_field` at the endpoints to get the", "# approximate value at the edge midpoint.", "A", "=", "0.5", "*", "numpy", ".", ...
Computes the curl of a vector field over the mesh. While the vector field is point-based, the curl will be cell-based. The approximation is based on .. math:: n\\cdot curl(F) = \\lim_{A\\to 0} |A|^{-1} <\\int_{dGamma}, F> dr; see <https://en.wikipedia.org/wiki/Curl_(mathematics)>. Actually, to approximate the integral, one would only need the projection of the vector field onto the edges at the midpoint of the edges.
[ "Computes", "the", "curl", "of", "a", "vector", "field", "over", "the", "mesh", ".", "While", "the", "vector", "field", "is", "point", "-", "based", "the", "curl", "will", "be", "cell", "-", "based", ".", "The", "approximation", "is", "based", "on" ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L651-L682
train
46,950
nschloe/meshplex
meshplex/mesh_tri.py
MeshTri.show_vertex
def show_vertex(self, node_id, show_ce_ratio=True): """Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt fig = plt.figure() ax = fig.gca() plt.axis("equal") # Find the edges that contain the vertex edge_gids = numpy.where((self.edges["nodes"] == node_id).any(axis=1))[0] # ... and plot them for node_ids in self.edges["nodes"][edge_gids]: x = self.node_coords[node_ids] ax.plot(x[:, 0], x[:, 1], "k") # Highlight ce_ratios. if show_ce_ratio: if self.cell_circumcenters is None: X = self.node_coords[self.cells["nodes"]] self.cell_circumcenters = self.compute_triangle_circumcenters( X, self.ei_dot_ei, self.ei_dot_ej ) # Find the cells that contain the vertex cell_ids = numpy.where((self.cells["nodes"] == node_id).any(axis=1))[0] for cell_id in cell_ids: for edge_gid in self.cells["edges"][cell_id]: if node_id not in self.edges["nodes"][edge_gid]: continue node_ids = self.edges["nodes"][edge_gid] edge_midpoint = 0.5 * ( self.node_coords[node_ids[0]] + self.node_coords[node_ids[1]] ) p = _column_stack(self.cell_circumcenters[cell_id], edge_midpoint) q = numpy.column_stack( [ self.cell_circumcenters[cell_id], edge_midpoint, self.node_coords[node_id], ] ) ax.fill(q[0], q[1], color="0.5") ax.plot(p[0], p[1], color="0.7") return
python
def show_vertex(self, node_id, show_ce_ratio=True): """Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional """ # Importing matplotlib takes a while, so don't do that at the header. from matplotlib import pyplot as plt fig = plt.figure() ax = fig.gca() plt.axis("equal") # Find the edges that contain the vertex edge_gids = numpy.where((self.edges["nodes"] == node_id).any(axis=1))[0] # ... and plot them for node_ids in self.edges["nodes"][edge_gids]: x = self.node_coords[node_ids] ax.plot(x[:, 0], x[:, 1], "k") # Highlight ce_ratios. if show_ce_ratio: if self.cell_circumcenters is None: X = self.node_coords[self.cells["nodes"]] self.cell_circumcenters = self.compute_triangle_circumcenters( X, self.ei_dot_ei, self.ei_dot_ej ) # Find the cells that contain the vertex cell_ids = numpy.where((self.cells["nodes"] == node_id).any(axis=1))[0] for cell_id in cell_ids: for edge_gid in self.cells["edges"][cell_id]: if node_id not in self.edges["nodes"][edge_gid]: continue node_ids = self.edges["nodes"][edge_gid] edge_midpoint = 0.5 * ( self.node_coords[node_ids[0]] + self.node_coords[node_ids[1]] ) p = _column_stack(self.cell_circumcenters[cell_id], edge_midpoint) q = numpy.column_stack( [ self.cell_circumcenters[cell_id], edge_midpoint, self.node_coords[node_id], ] ) ax.fill(q[0], q[1], color="0.5") ax.plot(p[0], p[1], color="0.7") return
[ "def", "show_vertex", "(", "self", ",", "node_id", ",", "show_ce_ratio", "=", "True", ")", ":", "# Importing matplotlib takes a while, so don't do that at the header.", "from", "matplotlib", "import", "pyplot", "as", "plt", "fig", "=", "plt", ".", "figure", "(", ")"...
Plot the vicinity of a node and its ce_ratio. :param node_id: Node ID of the node to be shown. :type node_id: int :param show_ce_ratio: If true, shows the ce_ratio of the node, too. :type show_ce_ratio: bool, optional
[ "Plot", "the", "vicinity", "of", "a", "node", "and", "its", "ce_ratio", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L815-L867
train
46,951
bodylabs/lace
lace/serialization/dae.py
_dump
def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
python
def _dump(f, mesh): ''' Writes a mesh to collada file format. ''' dae = mesh_to_collada(mesh) dae.write(f.name)
[ "def", "_dump", "(", "f", ",", "mesh", ")", ":", "dae", "=", "mesh_to_collada", "(", "mesh", ")", "dae", ".", "write", "(", "f", ".", "name", ")" ]
Writes a mesh to collada file format.
[ "Writes", "a", "mesh", "to", "collada", "file", "format", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L7-L12
train
46,952
bodylabs/lace
lace/serialization/dae.py
dumps
def dumps(mesh): ''' Generates a UTF-8 XML string containing the mesh, in collada format. ''' from lxml import etree dae = mesh_to_collada(mesh) # Update the xmlnode. dae.save() return etree.tostring(dae.xmlnode, encoding='UTF-8')
python
def dumps(mesh): ''' Generates a UTF-8 XML string containing the mesh, in collada format. ''' from lxml import etree dae = mesh_to_collada(mesh) # Update the xmlnode. dae.save() return etree.tostring(dae.xmlnode, encoding='UTF-8')
[ "def", "dumps", "(", "mesh", ")", ":", "from", "lxml", "import", "etree", "dae", "=", "mesh_to_collada", "(", "mesh", ")", "# Update the xmlnode.", "dae", ".", "save", "(", ")", "return", "etree", ".", "tostring", "(", "dae", ".", "xmlnode", ",", "encodi...
Generates a UTF-8 XML string containing the mesh, in collada format.
[ "Generates", "a", "UTF", "-", "8", "XML", "string", "containing", "the", "mesh", "in", "collada", "format", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L14-L25
train
46,953
bodylabs/lace
lace/serialization/dae.py
mesh_to_collada
def mesh_to_collada(mesh): ''' Supports per-vertex color, but nothing else. ''' import numpy as np try: from collada import Collada, scene except ImportError: raise ImportError("lace.serialization.dae.mesh_to_collade requires package pycollada.") def create_material(dae): from collada import material, scene effect = material.Effect("effect0", [], "phong", diffuse=(1, 1, 1), specular=(0, 0, 0), double_sided=True) mat = material.Material("material0", "mymaterial", effect) dae.effects.append(effect) dae.materials.append(mat) return scene.MaterialNode("materialref", mat, inputs=[]) def geometry_from_mesh(dae, mesh): from collada import source, geometry srcs = [] # v srcs.append(source.FloatSource("verts-array", mesh.v, ('X', 'Y', 'Z'))) input_list = source.InputList() input_list.addInput(0, 'VERTEX', "#verts-array") # vc if mesh.vc is not None: input_list.addInput(len(srcs), 'COLOR', "#color-array") srcs.append(source.FloatSource("color-array", mesh.vc[mesh.f.ravel()], ('X', 'Y', 'Z'))) # f geom = geometry.Geometry(str(mesh), "geometry0", "mymesh", srcs) indices = np.dstack([mesh.f for _ in srcs]).ravel() triset = geom.createTriangleSet(indices, input_list, "materialref") geom.primitives.append(triset) # e if mesh.e is not None: indices = np.dstack([mesh.e for _ in srcs]).ravel() lineset = geom.createLineSet(indices, input_list, "materialref") geom.primitives.append(lineset) dae.geometries.append(geom) return geom dae = Collada() geom = geometry_from_mesh(dae, mesh) node = scene.Node("node0", children=[scene.GeometryNode(geom, [create_material(dae)])]) myscene = scene.Scene("myscene", [node]) dae.scenes.append(myscene) dae.scene = myscene return dae
python
def mesh_to_collada(mesh): ''' Supports per-vertex color, but nothing else. ''' import numpy as np try: from collada import Collada, scene except ImportError: raise ImportError("lace.serialization.dae.mesh_to_collade requires package pycollada.") def create_material(dae): from collada import material, scene effect = material.Effect("effect0", [], "phong", diffuse=(1, 1, 1), specular=(0, 0, 0), double_sided=True) mat = material.Material("material0", "mymaterial", effect) dae.effects.append(effect) dae.materials.append(mat) return scene.MaterialNode("materialref", mat, inputs=[]) def geometry_from_mesh(dae, mesh): from collada import source, geometry srcs = [] # v srcs.append(source.FloatSource("verts-array", mesh.v, ('X', 'Y', 'Z'))) input_list = source.InputList() input_list.addInput(0, 'VERTEX', "#verts-array") # vc if mesh.vc is not None: input_list.addInput(len(srcs), 'COLOR', "#color-array") srcs.append(source.FloatSource("color-array", mesh.vc[mesh.f.ravel()], ('X', 'Y', 'Z'))) # f geom = geometry.Geometry(str(mesh), "geometry0", "mymesh", srcs) indices = np.dstack([mesh.f for _ in srcs]).ravel() triset = geom.createTriangleSet(indices, input_list, "materialref") geom.primitives.append(triset) # e if mesh.e is not None: indices = np.dstack([mesh.e for _ in srcs]).ravel() lineset = geom.createLineSet(indices, input_list, "materialref") geom.primitives.append(lineset) dae.geometries.append(geom) return geom dae = Collada() geom = geometry_from_mesh(dae, mesh) node = scene.Node("node0", children=[scene.GeometryNode(geom, [create_material(dae)])]) myscene = scene.Scene("myscene", [node]) dae.scenes.append(myscene) dae.scene = myscene return dae
[ "def", "mesh_to_collada", "(", "mesh", ")", ":", "import", "numpy", "as", "np", "try", ":", "from", "collada", "import", "Collada", ",", "scene", "except", "ImportError", ":", "raise", "ImportError", "(", "\"lace.serialization.dae.mesh_to_collade requires package pyco...
Supports per-vertex color, but nothing else.
[ "Supports", "per", "-", "vertex", "color", "but", "nothing", "else", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/dae.py#L27-L76
train
46,954
bodylabs/lace
lace/geometry.py
MeshMixin.convert_units
def convert_units(self, from_units, to_units): ''' Convert the mesh from one set of units to another. These calls are equivalent: - mesh.convert_units(from_units='cm', to_units='m') - mesh.scale(.01) ''' from blmath import units factor = units.factor( from_units=from_units, to_units=to_units, units_class='length' ) self.scale(factor)
python
def convert_units(self, from_units, to_units): ''' Convert the mesh from one set of units to another. These calls are equivalent: - mesh.convert_units(from_units='cm', to_units='m') - mesh.scale(.01) ''' from blmath import units factor = units.factor( from_units=from_units, to_units=to_units, units_class='length' ) self.scale(factor)
[ "def", "convert_units", "(", "self", ",", "from_units", ",", "to_units", ")", ":", "from", "blmath", "import", "units", "factor", "=", "units", ".", "factor", "(", "from_units", "=", "from_units", ",", "to_units", "=", "to_units", ",", "units_class", "=", ...
Convert the mesh from one set of units to another. These calls are equivalent: - mesh.convert_units(from_units='cm', to_units='m') - mesh.scale(.01)
[ "Convert", "the", "mesh", "from", "one", "set", "of", "units", "to", "another", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L34-L50
train
46,955
bodylabs/lace
lace/geometry.py
MeshMixin.predict_body_units
def predict_body_units(self): ''' There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned ''' longest_dist = np.max(np.max(self.v, axis=0) - np.min(self.v, axis=0)) if round(longest_dist / 1000) > 0: return 'mm' if round(longest_dist / 100) > 0: return 'cm' if round(longest_dist / 10) > 0: return 'dm' return 'm'
python
def predict_body_units(self): ''' There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned ''' longest_dist = np.max(np.max(self.v, axis=0) - np.min(self.v, axis=0)) if round(longest_dist / 1000) > 0: return 'mm' if round(longest_dist / 100) > 0: return 'cm' if round(longest_dist / 10) > 0: return 'dm' return 'm'
[ "def", "predict_body_units", "(", "self", ")", ":", "longest_dist", "=", "np", ".", "max", "(", "np", ".", "max", "(", "self", ".", "v", ",", "axis", "=", "0", ")", "-", "np", ".", "min", "(", "self", ".", "v", ",", "axis", "=", "0", ")", ")"...
There is no prediction for united states unit system. This may fail when a mesh is not axis-aligned
[ "There", "is", "no", "prediction", "for", "united", "states", "unit", "system", ".", "This", "may", "fail", "when", "a", "mesh", "is", "not", "axis", "-", "aligned" ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L52-L64
train
46,956
bodylabs/lace
lace/geometry.py
MeshMixin.reorient
def reorient(self, up, look): ''' Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera). ''' from blmath.geometry.transform import rotation_from_up_and_look from blmath.numerics import as_numeric_array up = as_numeric_array(up, (3,)) look = as_numeric_array(look, (3,)) if self.v is not None: self.v = np.dot(rotation_from_up_and_look(up, look), self.v.T).T
python
def reorient(self, up, look): ''' Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera). ''' from blmath.geometry.transform import rotation_from_up_and_look from blmath.numerics import as_numeric_array up = as_numeric_array(up, (3,)) look = as_numeric_array(look, (3,)) if self.v is not None: self.v = np.dot(rotation_from_up_and_look(up, look), self.v.T).T
[ "def", "reorient", "(", "self", ",", "up", ",", "look", ")", ":", "from", "blmath", ".", "geometry", ".", "transform", "import", "rotation_from_up_and_look", "from", "blmath", ".", "numerics", "import", "as_numeric_array", "up", "=", "as_numeric_array", "(", "...
Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera).
[ "Reorient", "the", "mesh", "by", "specifying", "two", "vectors", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L80-L98
train
46,957
bodylabs/lace
lace/geometry.py
MeshMixin.centroid
def centroid(self): ''' Return the geometric center. ''' if self.v is None: raise ValueError('Mesh has no vertices; centroid is not defined') return np.mean(self.v, axis=0)
python
def centroid(self): ''' Return the geometric center. ''' if self.v is None: raise ValueError('Mesh has no vertices; centroid is not defined') return np.mean(self.v, axis=0)
[ "def", "centroid", "(", "self", ")", ":", "if", "self", ".", "v", "is", "None", ":", "raise", "ValueError", "(", "'Mesh has no vertices; centroid is not defined'", ")", "return", "np", ".", "mean", "(", "self", ".", "v", ",", "axis", "=", "0", ")" ]
Return the geometric center.
[ "Return", "the", "geometric", "center", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L119-L127
train
46,958
bodylabs/lace
lace/geometry.py
MeshMixin.floor_point
def floor_point(self): ''' Return the point on the floor that lies below the centroid. ''' floor_point = self.centroid # y to floor floor_point[1] = self.v[:, 1].min() return floor_point
python
def floor_point(self): ''' Return the point on the floor that lies below the centroid. ''' floor_point = self.centroid # y to floor floor_point[1] = self.v[:, 1].min() return floor_point
[ "def", "floor_point", "(", "self", ")", ":", "floor_point", "=", "self", ".", "centroid", "# y to floor", "floor_point", "[", "1", "]", "=", "self", ".", "v", "[", ":", ",", "1", "]", ".", "min", "(", ")", "return", "floor_point" ]
Return the point on the floor that lies below the centroid.
[ "Return", "the", "point", "on", "the", "floor", "that", "lies", "below", "the", "centroid", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L133-L141
train
46,959
bodylabs/lace
lace/geometry.py
MeshMixin.apex
def apex(self, axis): ''' Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array. ''' from blmath.geometry.apex import apex return apex(self.v, axis)
python
def apex(self, axis): ''' Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array. ''' from blmath.geometry.apex import apex return apex(self.v, axis)
[ "def", "apex", "(", "self", ",", "axis", ")", ":", "from", "blmath", ".", "geometry", ".", "apex", "import", "apex", "return", "apex", "(", "self", ".", "v", ",", "axis", ")" ]
Find the most extreme vertex in the direction of the axis provided. axis: A vector, which is an 3x1 np.array.
[ "Find", "the", "most", "extreme", "vertex", "in", "the", "direction", "of", "the", "axis", "provided", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L167-L175
train
46,960
bodylabs/lace
lace/geometry.py
MeshMixin.cut_across_axis
def cut_across_axis(self, dim, minval=None, maxval=None): ''' Cut the mesh by a plane, discarding vertices that lie behind that plane. Or cut the mesh by two parallel planes, discarding vertices that lie outside them. The region to keep is defined by an axis of perpendicularity, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices. ''' # vertex_mask keeps track of the vertices we want to keep. vertex_mask = np.ones((len(self.v),), dtype=bool) if minval is not None: predicate = self.v[:, dim] >= minval vertex_mask = np.logical_and(vertex_mask, predicate) if maxval is not None: predicate = self.v[:, dim] <= maxval vertex_mask = np.logical_and(vertex_mask, predicate) vertex_indices = np.flatnonzero(vertex_mask) self.keep_vertices(vertex_indices) return vertex_indices
python
def cut_across_axis(self, dim, minval=None, maxval=None): ''' Cut the mesh by a plane, discarding vertices that lie behind that plane. Or cut the mesh by two parallel planes, discarding vertices that lie outside them. The region to keep is defined by an axis of perpendicularity, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices. ''' # vertex_mask keeps track of the vertices we want to keep. vertex_mask = np.ones((len(self.v),), dtype=bool) if minval is not None: predicate = self.v[:, dim] >= minval vertex_mask = np.logical_and(vertex_mask, predicate) if maxval is not None: predicate = self.v[:, dim] <= maxval vertex_mask = np.logical_and(vertex_mask, predicate) vertex_indices = np.flatnonzero(vertex_mask) self.keep_vertices(vertex_indices) return vertex_indices
[ "def", "cut_across_axis", "(", "self", ",", "dim", ",", "minval", "=", "None", ",", "maxval", "=", "None", ")", ":", "# vertex_mask keeps track of the vertices we want to keep.", "vertex_mask", "=", "np", ".", "ones", "(", "(", "len", "(", "self", ".", "v", ...
Cut the mesh by a plane, discarding vertices that lie behind that plane. Or cut the mesh by two parallel planes, discarding vertices that lie outside them. The region to keep is defined by an axis of perpendicularity, specified by `dim`: 0 means x, 1 means y, 2 means z. `minval` and `maxval` indicate the portion of that axis to keep. Return the original indices of the kept vertices.
[ "Cut", "the", "mesh", "by", "a", "plane", "discarding", "vertices", "that", "lie", "behind", "that", "plane", ".", "Or", "cut", "the", "mesh", "by", "two", "parallel", "planes", "discarding", "vertices", "that", "lie", "outside", "them", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L206-L233
train
46,961
bodylabs/lace
lace/geometry.py
MeshMixin.surface_areas
def surface_areas(self): ''' returns the surface area of each face ''' e_1 = self.v[self.f[:, 1]] - self.v[self.f[:, 0]] e_2 = self.v[self.f[:, 2]] - self.v[self.f[:, 0]] cross_products = np.array([e_1[:, 1]*e_2[:, 2] - e_1[:, 2]*e_2[:, 1], e_1[:, 2]*e_2[:, 0] - e_1[:, 0]*e_2[:, 2], e_1[:, 0]*e_2[:, 1] - e_1[:, 1]*e_2[:, 0]]).T return (0.5)*((cross_products**2.).sum(axis=1)**0.5)
python
def surface_areas(self): ''' returns the surface area of each face ''' e_1 = self.v[self.f[:, 1]] - self.v[self.f[:, 0]] e_2 = self.v[self.f[:, 2]] - self.v[self.f[:, 0]] cross_products = np.array([e_1[:, 1]*e_2[:, 2] - e_1[:, 2]*e_2[:, 1], e_1[:, 2]*e_2[:, 0] - e_1[:, 0]*e_2[:, 2], e_1[:, 0]*e_2[:, 1] - e_1[:, 1]*e_2[:, 0]]).T return (0.5)*((cross_products**2.).sum(axis=1)**0.5)
[ "def", "surface_areas", "(", "self", ")", ":", "e_1", "=", "self", ".", "v", "[", "self", ".", "f", "[", ":", ",", "1", "]", "]", "-", "self", ".", "v", "[", "self", ".", "f", "[", ":", ",", "0", "]", "]", "e_2", "=", "self", ".", "v", ...
returns the surface area of each face
[ "returns", "the", "surface", "area", "of", "each", "face" ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/geometry.py#L279-L290
train
46,962
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
purge_items
def purge_items(app, env, docname): """ Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event. """ keys = list(env.traceability_all_items.keys()) for key in keys: if env.traceability_all_items[key]['docname'] == docname: del env.traceability_all_items[key]
python
def purge_items(app, env, docname): """ Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event. """ keys = list(env.traceability_all_items.keys()) for key in keys: if env.traceability_all_items[key]['docname'] == docname: del env.traceability_all_items[key]
[ "def", "purge_items", "(", "app", ",", "env", ",", "docname", ")", ":", "keys", "=", "list", "(", "env", ".", "traceability_all_items", ".", "keys", "(", ")", ")", "for", "key", "in", "keys", ":", "if", "env", ".", "traceability_all_items", "[", "key",...
Clean, if existing, ``item`` entries in ``traceability_all_items`` environment variable, for all the source docs being purged. This function should be triggered upon ``env-purge-doc`` event.
[ "Clean", "if", "existing", "item", "entries", "in", "traceability_all_items", "environment", "variable", "for", "all", "the", "source", "docs", "being", "purged", "." ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L212-L223
train
46,963
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
process_item_nodes
def process_item_nodes(app, doctree, fromdocname): """ This function should be triggered upon ``doctree-resolved event`` Replace all item_list nodes with a list of the collected items. Augment each item with a backlink to the original location. """ env = app.builder.env all_items = sorted(env.traceability_all_items, key=naturalsortkey) # Item matrix: # Create table with related items, printing their target references. # Only source and target items matching respective regexp shall be included for node in doctree.traverse(item_matrix): table = nodes.table() tgroup = nodes.tgroup() left_colspec = nodes.colspec(colwidth=5) right_colspec = nodes.colspec(colwidth=5) tgroup += [left_colspec, right_colspec] tgroup += nodes.thead('', nodes.row( '', nodes.entry('', nodes.paragraph('', 'Source')), nodes.entry('', nodes.paragraph('', 'Target')))) tbody = nodes.tbody() tgroup += tbody table += tgroup for source_item in all_items: if re.match(node['source'], source_item): row = nodes.row() left = nodes.entry() left += make_item_ref(app, env, fromdocname, env.traceability_all_items[source_item]) right = nodes.entry() for target_item in all_items: if (re.match(node['target'], target_item) and are_related( env, source_item, target_item, node['type'])): right += make_item_ref( app, env, fromdocname, env.traceability_all_items[target_item]) row += left row += right tbody += row node.replace_self(table) # Item list: # Create list with target references. Only items matching list regexp # shall be included for node in doctree.traverse(item_list): content = nodes.bullet_list() for item in all_items: if re.match(node['filter'], item): bullet_list_item = nodes.list_item() paragraph = nodes.paragraph() paragraph.append( make_item_ref(app, env, fromdocname, env.traceability_all_items[item])) bullet_list_item.append(paragraph) content.append(bullet_list_item) node.replace_self(content) # Resolve item cross references (from ``item`` role) for node in doctree.traverse(pending_item_xref): # Create a dummy reference to be used if target reference fails new_node = make_refnode(app.builder, fromdocname, fromdocname, 'ITEM_NOT_FOUND', node[0].deepcopy(), node['reftarget'] + '??') # If target exists, try to create the reference if node['reftarget'] in env.traceability_all_items: item_info = env.traceability_all_items[node['reftarget']] try: new_node = make_refnode(app.builder, fromdocname, item_info['docname'], item_info['target']['refid'], node[0].deepcopy(), node['reftarget']) except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass else: env.warn_node( 'Traceability: item %s not found' % node['reftarget'], node) node.replace_self(new_node)
python
def process_item_nodes(app, doctree, fromdocname): """ This function should be triggered upon ``doctree-resolved event`` Replace all item_list nodes with a list of the collected items. Augment each item with a backlink to the original location. """ env = app.builder.env all_items = sorted(env.traceability_all_items, key=naturalsortkey) # Item matrix: # Create table with related items, printing their target references. # Only source and target items matching respective regexp shall be included for node in doctree.traverse(item_matrix): table = nodes.table() tgroup = nodes.tgroup() left_colspec = nodes.colspec(colwidth=5) right_colspec = nodes.colspec(colwidth=5) tgroup += [left_colspec, right_colspec] tgroup += nodes.thead('', nodes.row( '', nodes.entry('', nodes.paragraph('', 'Source')), nodes.entry('', nodes.paragraph('', 'Target')))) tbody = nodes.tbody() tgroup += tbody table += tgroup for source_item in all_items: if re.match(node['source'], source_item): row = nodes.row() left = nodes.entry() left += make_item_ref(app, env, fromdocname, env.traceability_all_items[source_item]) right = nodes.entry() for target_item in all_items: if (re.match(node['target'], target_item) and are_related( env, source_item, target_item, node['type'])): right += make_item_ref( app, env, fromdocname, env.traceability_all_items[target_item]) row += left row += right tbody += row node.replace_self(table) # Item list: # Create list with target references. Only items matching list regexp # shall be included for node in doctree.traverse(item_list): content = nodes.bullet_list() for item in all_items: if re.match(node['filter'], item): bullet_list_item = nodes.list_item() paragraph = nodes.paragraph() paragraph.append( make_item_ref(app, env, fromdocname, env.traceability_all_items[item])) bullet_list_item.append(paragraph) content.append(bullet_list_item) node.replace_self(content) # Resolve item cross references (from ``item`` role) for node in doctree.traverse(pending_item_xref): # Create a dummy reference to be used if target reference fails new_node = make_refnode(app.builder, fromdocname, fromdocname, 'ITEM_NOT_FOUND', node[0].deepcopy(), node['reftarget'] + '??') # If target exists, try to create the reference if node['reftarget'] in env.traceability_all_items: item_info = env.traceability_all_items[node['reftarget']] try: new_node = make_refnode(app.builder, fromdocname, item_info['docname'], item_info['target']['refid'], node[0].deepcopy(), node['reftarget']) except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass else: env.warn_node( 'Traceability: item %s not found' % node['reftarget'], node) node.replace_self(new_node)
[ "def", "process_item_nodes", "(", "app", ",", "doctree", ",", "fromdocname", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "all_items", "=", "sorted", "(", "env", ".", "traceability_all_items", ",", "key", "=", "naturalsortkey", ")", "# Item matri...
This function should be triggered upon ``doctree-resolved event`` Replace all item_list nodes with a list of the collected items. Augment each item with a backlink to the original location.
[ "This", "function", "should", "be", "triggered", "upon", "doctree", "-", "resolved", "event" ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L226-L319
train
46,964
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
initialize_environment
def initialize_environment(app): """ Perform initializations needed before the build process starts. """ env = app.builder.env # Assure ``traceability_all_items`` will always be there. if not hasattr(env, 'traceability_all_items'): env.traceability_all_items = {} update_available_item_relationships(app)
python
def initialize_environment(app): """ Perform initializations needed before the build process starts. """ env = app.builder.env # Assure ``traceability_all_items`` will always be there. if not hasattr(env, 'traceability_all_items'): env.traceability_all_items = {} update_available_item_relationships(app)
[ "def", "initialize_environment", "(", "app", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "# Assure ``traceability_all_items`` will always be there.", "if", "not", "hasattr", "(", "env", ",", "'traceability_all_items'", ")", ":", "env", ".", "traceabilit...
Perform initializations needed before the build process starts.
[ "Perform", "initializations", "needed", "before", "the", "build", "process", "starts", "." ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L347-L357
train
46,965
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
make_item_ref
def make_item_ref(app, env, fromdocname, item_info): """ Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. """ id = item_info['target']['refid'] if item_info['caption'] != '': caption = ', ' + item_info['caption'] else: caption = '' para = nodes.paragraph() newnode = nodes.reference('', '') innernode = nodes.emphasis(id + caption, id + caption) newnode['refdocname'] = item_info['docname'] try: newnode['refuri'] = app.builder.get_relative_uri(fromdocname, item_info['docname']) newnode['refuri'] += '#' + id except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass newnode.append(innernode) para += newnode return para
python
def make_item_ref(app, env, fromdocname, item_info): """ Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists. """ id = item_info['target']['refid'] if item_info['caption'] != '': caption = ', ' + item_info['caption'] else: caption = '' para = nodes.paragraph() newnode = nodes.reference('', '') innernode = nodes.emphasis(id + caption, id + caption) newnode['refdocname'] = item_info['docname'] try: newnode['refuri'] = app.builder.get_relative_uri(fromdocname, item_info['docname']) newnode['refuri'] += '#' + id except NoUri: # ignore if no URI can be determined, e.g. for LaTeX output :( pass newnode.append(innernode) para += newnode return para
[ "def", "make_item_ref", "(", "app", ",", "env", ",", "fromdocname", ",", "item_info", ")", ":", "id", "=", "item_info", "[", "'target'", "]", "[", "'refid'", "]", "if", "item_info", "[", "'caption'", "]", "!=", "''", ":", "caption", "=", "', '", "+", ...
Creates a reference node for an item, embedded in a paragraph. Reference text adds also a caption if it exists.
[ "Creates", "a", "reference", "node", "for", "an", "item", "embedded", "in", "a", "paragraph", ".", "Reference", "text", "adds", "also", "a", "caption", "if", "it", "exists", "." ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L363-L390
train
46,966
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
naturalsortkey
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
python
def naturalsortkey(s): """Natural sort order""" return [int(part) if part.isdigit() else part for part in re.split('([0-9]+)', s)]
[ "def", "naturalsortkey", "(", "s", ")", ":", "return", "[", "int", "(", "part", ")", "if", "part", ".", "isdigit", "(", ")", "else", "part", "for", "part", "in", "re", ".", "split", "(", "'([0-9]+)'", ",", "s", ")", "]" ]
Natural sort order
[ "Natural", "sort", "order" ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L393-L396
train
46,967
ociu/sphinx-traceability-extension
sphinxcontrib/traceability.py
are_related
def are_related(env, source, target, relationships): """ Returns ``True`` if ``source`` and ``target`` items are related according a list, ``relationships``, of relationship types. ``False`` is returned otherwise If the list of relationship types is empty, all available relationship types are to be considered. """ if not relationships: relationships = list(env.relationships.keys()) for rel in relationships: if (target in env.traceability_all_items[source][rel] or source in env.traceability_all_items[target][env.relationships[rel]]): return True return False
python
def are_related(env, source, target, relationships): """ Returns ``True`` if ``source`` and ``target`` items are related according a list, ``relationships``, of relationship types. ``False`` is returned otherwise If the list of relationship types is empty, all available relationship types are to be considered. """ if not relationships: relationships = list(env.relationships.keys()) for rel in relationships: if (target in env.traceability_all_items[source][rel] or source in env.traceability_all_items[target][env.relationships[rel]]): return True return False
[ "def", "are_related", "(", "env", ",", "source", ",", "target", ",", "relationships", ")", ":", "if", "not", "relationships", ":", "relationships", "=", "list", "(", "env", ".", "relationships", ".", "keys", "(", ")", ")", "for", "rel", "in", "relationsh...
Returns ``True`` if ``source`` and ``target`` items are related according a list, ``relationships``, of relationship types. ``False`` is returned otherwise If the list of relationship types is empty, all available relationship types are to be considered.
[ "Returns", "True", "if", "source", "and", "target", "items", "are", "related", "according", "a", "list", "relationships", "of", "relationship", "types", ".", "False", "is", "returned", "otherwise" ]
85db6f496911938660397f5d8e1c856a18120f55
https://github.com/ociu/sphinx-traceability-extension/blob/85db6f496911938660397f5d8e1c856a18120f55/sphinxcontrib/traceability.py#L399-L418
train
46,968
bodylabs/lace
lace/meshviewer.py
MeshViewer
def MeshViewer( titlebar='Mesh Viewer', static_meshes=None, static_lines=None, uid=None, autorecenter=True, keepalive=False, window_width=1280, window_height=960, snapshot_camera=None ): """Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string printed in the window titlebar dynamic_meshes: list of Mesh objects to be displayed static_meshes: list of Mesh objects to be displayed dynamic_lines: list of Lines objects to be displayed static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=(1, 1), uid=uid, titlebar=titlebar, keepalive=keepalive, window_width=window_width, window_height=window_height ) result = mv.get_subwindows()[0][0] result.snapshot_camera = snapshot_camera if static_meshes: result.static_meshes = static_meshes if static_lines: result.static_lines = static_lines result.autorecenter = autorecenter return result
python
def MeshViewer( titlebar='Mesh Viewer', static_meshes=None, static_lines=None, uid=None, autorecenter=True, keepalive=False, window_width=1280, window_height=960, snapshot_camera=None ): """Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string printed in the window titlebar dynamic_meshes: list of Mesh objects to be displayed static_meshes: list of Mesh objects to be displayed dynamic_lines: list of Lines objects to be displayed static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=(1, 1), uid=uid, titlebar=titlebar, keepalive=keepalive, window_width=window_width, window_height=window_height ) result = mv.get_subwindows()[0][0] result.snapshot_camera = snapshot_camera if static_meshes: result.static_meshes = static_meshes if static_lines: result.static_lines = static_lines result.autorecenter = autorecenter return result
[ "def", "MeshViewer", "(", "titlebar", "=", "'Mesh Viewer'", ",", "static_meshes", "=", "None", ",", "static_lines", "=", "None", ",", "uid", "=", "None", ",", "autorecenter", "=", "True", ",", "keepalive", "=", "False", ",", "window_width", "=", "1280", ",...
Allows visual inspection of geometric primitives. Write-only Attributes: titlebar: string printed in the window titlebar dynamic_meshes: list of Mesh objects to be displayed static_meshes: list of Mesh objects to be displayed dynamic_lines: list of Lines objects to be displayed static_lines: list of Lines objects to be displayed Note: static_meshes is meant for Meshes that are updated infrequently, and dynamic_meshes is for Meshes that are updated frequently (same for dynamic_lines vs static_lines). They may be treated differently for performance reasons.
[ "Allows", "visual", "inspection", "of", "geometric", "primitives", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L87-L120
train
46,969
bodylabs/lace
lace/meshviewer.py
MeshViewers
def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepalive=False, window_width=1280, window_height=960 ): """Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns: a list of lists of MeshViewer objects: one per window requested. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive, window_width=window_width, window_height=window_height ) return mv.get_subwindows()
python
def MeshViewers( shape=(1, 1), titlebar="Mesh Viewers", keepalive=False, window_width=1280, window_height=960 ): """Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns: a list of lists of MeshViewer objects: one per window requested. """ if not test_for_opengl(): return Dummy() mv = MeshViewerLocal( shape=shape, titlebar=titlebar, uid=None, keepalive=keepalive, window_width=window_width, window_height=window_height ) return mv.get_subwindows()
[ "def", "MeshViewers", "(", "shape", "=", "(", "1", ",", "1", ")", ",", "titlebar", "=", "\"Mesh Viewers\"", ",", "keepalive", "=", "False", ",", "window_width", "=", "1280", ",", "window_height", "=", "960", ")", ":", "if", "not", "test_for_opengl", "(",...
Allows subplot-style inspection of primitives in multiple subwindows. Args: shape: a tuple indicating the number of vertical and horizontal windows requested Returns: a list of lists of MeshViewer objects: one per window requested.
[ "Allows", "subplot", "-", "style", "inspection", "of", "primitives", "in", "multiple", "subwindows", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L123-L140
train
46,970
bodylabs/lace
lace/meshviewer.py
MeshViewerRemote.on_click
def on_click(self, button, button_state, cursor_x, cursor_y): """ Mouse button clicked. Glut calls this function when a mouse button is clicked or released. """ self.isdragging = False if button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_UP: # Left button released self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One elif button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_DOWN: # Left button clicked down self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One self.isdragging = True # Prepare For Dragging mouse_pt = arcball.Point2fT(cursor_x, cursor_y) self.arcball.click(mouse_pt) # Update Start Vector And Prepare For Dragging elif button == glut.GLUT_RIGHT_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y) elif button == glut.GLUT_MIDDLE_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y, button='middle') glut.glutPostRedisplay()
python
def on_click(self, button, button_state, cursor_x, cursor_y): """ Mouse button clicked. Glut calls this function when a mouse button is clicked or released. """ self.isdragging = False if button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_UP: # Left button released self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One elif button == glut.GLUT_LEFT_BUTTON and button_state == glut.GLUT_DOWN: # Left button clicked down self.lastrot = copy.copy(self.thisrot) # Set Last Static Rotation To Last Dynamic One self.isdragging = True # Prepare For Dragging mouse_pt = arcball.Point2fT(cursor_x, cursor_y) self.arcball.click(mouse_pt) # Update Start Vector And Prepare For Dragging elif button == glut.GLUT_RIGHT_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y) elif button == glut.GLUT_MIDDLE_BUTTON and button_state == glut.GLUT_DOWN: # If a mouse click location was requested, return it to caller if hasattr(self, 'event_port'): self.mouseclick_port = self.event_port del self.event_port if hasattr(self, 'mouseclick_port'): self.send_mouseclick_to_caller(cursor_x, cursor_y, button='middle') glut.glutPostRedisplay()
[ "def", "on_click", "(", "self", ",", "button", ",", "button_state", ",", "cursor_x", ",", "cursor_y", ")", ":", "self", ".", "isdragging", "=", "False", "if", "button", "==", "glut", ".", "GLUT_LEFT_BUTTON", "and", "button_state", "==", "glut", ".", "GLUT_...
Mouse button clicked. Glut calls this function when a mouse button is clicked or released.
[ "Mouse", "button", "clicked", ".", "Glut", "calls", "this", "function", "when", "a", "mouse", "button", "is", "clicked", "or", "released", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/meshviewer.py#L840-L869
train
46,971
nschloe/meshplex
meshplex/mesh_tetra.py
MeshTetra._compute_cell_circumcenters
def _compute_cell_circumcenters(self): """Computes the center of the circumsphere of each cell. """ # Just like for triangular cells, tetrahedron circumcenters are most easily # computed with the quadrilateral coordinates available. # Luckily, we have the circumcenter-face distances (cfd): # # CC = ( # + cfd[0] * face_area[0] / sum(cfd*face_area) * X[0] # + cfd[1] * face_area[1] / sum(cfd*face_area) * X[1] # + cfd[2] * face_area[2] / sum(cfd*face_area) * X[2] # + cfd[3] * face_area[3] / sum(cfd*face_area) * X[3] # ) # # (Compare with # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>.) # Because of # # cfd = zeta / (24.0 * face_areas) / self.cell_volumes[None] # # we have # # CC = sum_k (zeta[k] / sum(zeta) * X[k]). # alpha = self._zeta / numpy.sum(self._zeta, axis=0) self._circumcenters = numpy.sum( alpha[None].T * self.node_coords[self.cells["nodes"]], axis=1 ) return
python
def _compute_cell_circumcenters(self): """Computes the center of the circumsphere of each cell. """ # Just like for triangular cells, tetrahedron circumcenters are most easily # computed with the quadrilateral coordinates available. # Luckily, we have the circumcenter-face distances (cfd): # # CC = ( # + cfd[0] * face_area[0] / sum(cfd*face_area) * X[0] # + cfd[1] * face_area[1] / sum(cfd*face_area) * X[1] # + cfd[2] * face_area[2] / sum(cfd*face_area) * X[2] # + cfd[3] * face_area[3] / sum(cfd*face_area) * X[3] # ) # # (Compare with # <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>.) # Because of # # cfd = zeta / (24.0 * face_areas) / self.cell_volumes[None] # # we have # # CC = sum_k (zeta[k] / sum(zeta) * X[k]). # alpha = self._zeta / numpy.sum(self._zeta, axis=0) self._circumcenters = numpy.sum( alpha[None].T * self.node_coords[self.cells["nodes"]], axis=1 ) return
[ "def", "_compute_cell_circumcenters", "(", "self", ")", ":", "# Just like for triangular cells, tetrahedron circumcenters are most easily", "# computed with the quadrilateral coordinates available.", "# Luckily, we have the circumcenter-face distances (cfd):", "#", "# CC = (", "# + cfd...
Computes the center of the circumsphere of each cell.
[ "Computes", "the", "center", "of", "the", "circumsphere", "of", "each", "cell", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tetra.py#L187-L216
train
46,972
nschloe/meshplex
meshplex/mesh_tetra.py
MeshTetra.show_edge
def show_edge(self, edge_id): """Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int """ # pylint: disable=unused-variable,relative-import from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt if "faces" not in self.cells: self.create_cell_face_relationships() if "edges" not in self.faces: self.create_face_edge_relationships() fig = plt.figure() ax = fig.gca(projection=Axes3D.name) plt.axis("equal") # find all faces with this edge adj_face_ids = numpy.where((self.faces["edges"] == edge_id).any(axis=1))[0] # find all cells with the faces # https://stackoverflow.com/a/38481969/353337 adj_cell_ids = numpy.where( numpy.in1d(self.cells["faces"], adj_face_ids) .reshape(self.cells["faces"].shape) .any(axis=1) )[0] # plot all those adjacent cells; first collect all edges adj_edge_ids = numpy.unique( [ adj_edge_id for adj_cell_id in adj_cell_ids for face_id in self.cells["faces"][adj_cell_id] for adj_edge_id in self.faces["edges"][face_id] ] ) col = "k" for adj_edge_id in adj_edge_ids: x = self.node_coords[self.edges["nodes"][adj_edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], col) # make clear which is edge_id x = self.node_coords[self.edges["nodes"][edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], color=col, linewidth=3.0) # connect the face circumcenters with the corresponding cell # circumcenters X = self.node_coords for cell_id in adj_cell_ids: cc = self._circumcenters[cell_id] # x = X[self.node_face_cells[..., [cell_id]]] face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei, self.ei_dot_ej) # draw the face circumcenters ax.plot( face_ccs[..., 0].flatten(), face_ccs[..., 1].flatten(), face_ccs[..., 2].flatten(), "go", ) # draw the connections # tet circumcenter---face circumcenter for face_cc in face_ccs: ax.plot( [cc[..., 0], face_cc[..., 0]], [cc[..., 1], face_cc[..., 1]], [cc[..., 2], face_cc[..., 2]], "b-", ) # draw the cell circumcenters cc = self._circumcenters[adj_cell_ids] ax.plot(cc[:, 0], cc[:, 1], cc[:, 2], "ro") return
python
def show_edge(self, edge_id): """Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int """ # pylint: disable=unused-variable,relative-import from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt if "faces" not in self.cells: self.create_cell_face_relationships() if "edges" not in self.faces: self.create_face_edge_relationships() fig = plt.figure() ax = fig.gca(projection=Axes3D.name) plt.axis("equal") # find all faces with this edge adj_face_ids = numpy.where((self.faces["edges"] == edge_id).any(axis=1))[0] # find all cells with the faces # https://stackoverflow.com/a/38481969/353337 adj_cell_ids = numpy.where( numpy.in1d(self.cells["faces"], adj_face_ids) .reshape(self.cells["faces"].shape) .any(axis=1) )[0] # plot all those adjacent cells; first collect all edges adj_edge_ids = numpy.unique( [ adj_edge_id for adj_cell_id in adj_cell_ids for face_id in self.cells["faces"][adj_cell_id] for adj_edge_id in self.faces["edges"][face_id] ] ) col = "k" for adj_edge_id in adj_edge_ids: x = self.node_coords[self.edges["nodes"][adj_edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], col) # make clear which is edge_id x = self.node_coords[self.edges["nodes"][edge_id]] ax.plot(x[:, 0], x[:, 1], x[:, 2], color=col, linewidth=3.0) # connect the face circumcenters with the corresponding cell # circumcenters X = self.node_coords for cell_id in adj_cell_ids: cc = self._circumcenters[cell_id] # x = X[self.node_face_cells[..., [cell_id]]] face_ccs = compute_triangle_circumcenters(x, self.ei_dot_ei, self.ei_dot_ej) # draw the face circumcenters ax.plot( face_ccs[..., 0].flatten(), face_ccs[..., 1].flatten(), face_ccs[..., 2].flatten(), "go", ) # draw the connections # tet circumcenter---face circumcenter for face_cc in face_ccs: ax.plot( [cc[..., 0], face_cc[..., 0]], [cc[..., 1], face_cc[..., 1]], [cc[..., 2], face_cc[..., 2]], "b-", ) # draw the cell circumcenters cc = self._circumcenters[adj_cell_ids] ax.plot(cc[:, 0], cc[:, 1], cc[:, 2], "ro") return
[ "def", "show_edge", "(", "self", ",", "edge_id", ")", ":", "# pylint: disable=unused-variable,relative-import", "from", "mpl_toolkits", ".", "mplot3d", "import", "Axes3D", "from", "matplotlib", "import", "pyplot", "as", "plt", "if", "\"faces\"", "not", "in", "self",...
Displays edge with ce_ratio. :param edge_id: Edge ID for which to show the ce_ratio. :type edge_id: int
[ "Displays", "edge", "with", "ce_ratio", "." ]
376cfe8ce7b9917e5398c5d60c87455ff5590913
https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tetra.py#L504-L579
train
46,973
openspending/babbage
babbage/util.py
parse_int
def parse_int(text, fallback=None): """ Try to extract an integer from a string, return the fallback if that's not possible. """ try: if isinstance(text, six.integer_types): return text elif isinstance(text, six.string_types): return int(text) else: return fallback except ValueError: return fallback
python
def parse_int(text, fallback=None): """ Try to extract an integer from a string, return the fallback if that's not possible. """ try: if isinstance(text, six.integer_types): return text elif isinstance(text, six.string_types): return int(text) else: return fallback except ValueError: return fallback
[ "def", "parse_int", "(", "text", ",", "fallback", "=", "None", ")", ":", "try", ":", "if", "isinstance", "(", "text", ",", "six", ".", "integer_types", ")", ":", "return", "text", "elif", "isinstance", "(", "text", ",", "six", ".", "string_types", ")",...
Try to extract an integer from a string, return the fallback if that's not possible.
[ "Try", "to", "extract", "an", "integer", "from", "a", "string", "return", "the", "fallback", "if", "that", "s", "not", "possible", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/util.py#L7-L18
train
46,974
openspending/babbage
babbage/cube.py
Cube._load_table
def _load_table(self, name): """ Reflect a given table from the database. """ table = self._tables.get(name, None) if table is not None: return table if not self.engine.has_table(name): raise BindingException('Table does not exist: %r' % name, table=name) table = Table(name, self.meta, autoload=True) self._tables[name] = table return table
python
def _load_table(self, name): """ Reflect a given table from the database. """ table = self._tables.get(name, None) if table is not None: return table if not self.engine.has_table(name): raise BindingException('Table does not exist: %r' % name, table=name) table = Table(name, self.meta, autoload=True) self._tables[name] = table return table
[ "def", "_load_table", "(", "self", ",", "name", ")", ":", "table", "=", "self", ".", "_tables", ".", "get", "(", "name", ",", "None", ")", "if", "table", "is", "not", "None", ":", "return", "table", "if", "not", "self", ".", "engine", ".", "has_tab...
Reflect a given table from the database.
[ "Reflect", "a", "given", "table", "from", "the", "database", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L30-L40
train
46,975
openspending/babbage
babbage/cube.py
Cube.fact_pk
def fact_pk(self): """ Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk. """ keys = [c for c in self.fact_table.columns if c.primary_key] return keys[0]
python
def fact_pk(self): """ Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk. """ keys = [c for c in self.fact_table.columns if c.primary_key] return keys[0]
[ "def", "fact_pk", "(", "self", ")", ":", "keys", "=", "[", "c", "for", "c", "in", "self", ".", "fact_table", ".", "columns", "if", "c", ".", "primary_key", "]", "return", "keys", "[", "0", "]" ]
Try to determine the primary key of the fact table for use in fact table counting. If more than one column exists, return the first column of the pk.
[ "Try", "to", "determine", "the", "primary", "key", "of", "the", "fact", "table", "for", "use", "in", "fact", "table", "counting", ".", "If", "more", "than", "one", "column", "exists", "return", "the", "first", "column", "of", "the", "pk", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L43-L49
train
46,976
openspending/babbage
babbage/cube.py
Cube.members
def members(self, ref, cuts=None, order=None, page=None, page_size=None): """ List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned. """ def prep(cuts, ref, order, columns=None): q = select(columns=columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) fields, q, bindings = \ Fields(self).apply(q, bindings, ref, distinct=True) ordering, q, bindings = \ Ordering(self).apply(q, bindings, order, distinct=fields[0]) q = self.restrict_joins(q, bindings) return q, bindings, cuts, fields, ordering # Count count = count_results(self, prep(cuts, ref, order, [1])[0]) # Member list q, bindings, cuts, fields, ordering = prep(cuts, ref, order) page, q = Pagination(self).apply(q, page, page_size) q = self.restrict_joins(q, bindings) return { 'total_member_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
python
def members(self, ref, cuts=None, order=None, page=None, page_size=None): """ List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned. """ def prep(cuts, ref, order, columns=None): q = select(columns=columns) bindings = [] cuts, q, bindings = Cuts(self).apply(q, bindings, cuts) fields, q, bindings = \ Fields(self).apply(q, bindings, ref, distinct=True) ordering, q, bindings = \ Ordering(self).apply(q, bindings, order, distinct=fields[0]) q = self.restrict_joins(q, bindings) return q, bindings, cuts, fields, ordering # Count count = count_results(self, prep(cuts, ref, order, [1])[0]) # Member list q, bindings, cuts, fields, ordering = prep(cuts, ref, order) page, q = Pagination(self).apply(q, page, page_size) q = self.restrict_joins(q, bindings) return { 'total_member_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
[ "def", "members", "(", "self", ",", "ref", ",", "cuts", "=", "None", ",", "order", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ")", ":", "def", "prep", "(", "cuts", ",", "ref", ",", "order", ",", "columns", "=", "None", ...
List all the distinct members of the given reference, filtered and paginated. If the reference describes a dimension, all attributes are returned.
[ "List", "all", "the", "distinct", "members", "of", "the", "given", "reference", "filtered", "and", "paginated", ".", "If", "the", "reference", "describes", "a", "dimension", "all", "attributes", "are", "returned", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L119-L149
train
46,977
openspending/babbage
babbage/cube.py
Cube.facts
def facts(self, fields=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """ List all facts in the cube, returning only the specified references if these are specified. """ def prep(cuts, columns=None): q = select(columns=columns).select_from(self.fact_table) bindings = [] _, q, bindings = Cuts(self).apply(q, bindings, cuts) q = self.restrict_joins(q, bindings) return q, bindings # Count count = count_results(self, prep(cuts, [1])[0]) # Facts q, bindings = prep(cuts) fields, q, bindings = Fields(self).apply(q, bindings, fields) ordering, q, bindings = Ordering(self).apply(q, bindings, order) page, q = Pagination(self).apply(q, page, page_size, page_max) q = self.restrict_joins(q, bindings) return { 'total_fact_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
python
def facts(self, fields=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """ List all facts in the cube, returning only the specified references if these are specified. """ def prep(cuts, columns=None): q = select(columns=columns).select_from(self.fact_table) bindings = [] _, q, bindings = Cuts(self).apply(q, bindings, cuts) q = self.restrict_joins(q, bindings) return q, bindings # Count count = count_results(self, prep(cuts, [1])[0]) # Facts q, bindings = prep(cuts) fields, q, bindings = Fields(self).apply(q, bindings, fields) ordering, q, bindings = Ordering(self).apply(q, bindings, order) page, q = Pagination(self).apply(q, page, page_size, page_max) q = self.restrict_joins(q, bindings) return { 'total_fact_count': count, 'data': list(generate_results(self, q)), 'cell': cuts, 'fields': fields, 'order': ordering, 'page': page['page'], 'page_size': page['page_size'] }
[ "def", "facts", "(", "self", ",", "fields", "=", "None", ",", "cuts", "=", "None", ",", "order", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "page_max", "=", "None", ")", ":", "def", "prep", "(", "cuts", ",", "colum...
List all facts in the cube, returning only the specified references if these are specified.
[ "List", "all", "facts", "in", "the", "cube", "returning", "only", "the", "specified", "references", "if", "these", "are", "specified", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L151-L180
train
46,978
openspending/babbage
babbage/cube.py
Cube.compute_cardinalities
def compute_cardinalities(self): """ This will count the number of distinct values for each dimension in the dataset and add that count to the model so that it can be used as a hint by UI components. """ for dimension in self.model.dimensions: result = self.members(dimension.ref, page_size=0) dimension.spec['cardinality'] = result.get('total_member_count')
python
def compute_cardinalities(self): """ This will count the number of distinct values for each dimension in the dataset and add that count to the model so that it can be used as a hint by UI components. """ for dimension in self.model.dimensions: result = self.members(dimension.ref, page_size=0) dimension.spec['cardinality'] = result.get('total_member_count')
[ "def", "compute_cardinalities", "(", "self", ")", ":", "for", "dimension", "in", "self", ".", "model", ".", "dimensions", ":", "result", "=", "self", ".", "members", "(", "dimension", ".", "ref", ",", "page_size", "=", "0", ")", "dimension", ".", "spec",...
This will count the number of distinct values for each dimension in the dataset and add that count to the model so that it can be used as a hint by UI components.
[ "This", "will", "count", "the", "number", "of", "distinct", "values", "for", "each", "dimension", "in", "the", "dataset", "and", "add", "that", "count", "to", "the", "model", "so", "that", "it", "can", "be", "used", "as", "a", "hint", "by", "UI", "comp...
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L182-L188
train
46,979
openspending/babbage
babbage/cube.py
Cube.restrict_joins
def restrict_joins(self, q, bindings): """ Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are referenced, this ensures their returned rows are connected via the fact table. """ if len(q.froms) == 1: return q else: for binding in bindings: if binding.table == self.fact_table: continue concept = self.model[binding.ref] if isinstance(concept, Dimension): dimension = concept else: dimension = concept.dimension dimension_table, key_col = dimension.key_attribute.bind(self) if binding.table != dimension_table: raise BindingException('Attributes must be of same table as ' 'as their dimension key') join_column_name = dimension.join_column_name if isinstance(join_column_name, string_types): try: join_column = self.fact_table.columns[join_column_name] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name, dimension)) else: if not isinstance(join_column_name, list) or len(join_column_name) != 2: raise BindingException("Join column '%s' for %r should be either a string or a 2-tuple." % (join_column_name, dimension)) try: join_column = self.fact_table.columns[join_column_name[0]] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name[0], dimension)) try: key_col = dimension_table.columns[join_column_name[1]] except KeyError: raise BindingException("Join column '%s' for %r not in dimension table." % (dimension.join_column_name[1], dimension)) q = q.where(join_column == key_col) return q
python
def restrict_joins(self, q, bindings): """ Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are referenced, this ensures their returned rows are connected via the fact table. """ if len(q.froms) == 1: return q else: for binding in bindings: if binding.table == self.fact_table: continue concept = self.model[binding.ref] if isinstance(concept, Dimension): dimension = concept else: dimension = concept.dimension dimension_table, key_col = dimension.key_attribute.bind(self) if binding.table != dimension_table: raise BindingException('Attributes must be of same table as ' 'as their dimension key') join_column_name = dimension.join_column_name if isinstance(join_column_name, string_types): try: join_column = self.fact_table.columns[join_column_name] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name, dimension)) else: if not isinstance(join_column_name, list) or len(join_column_name) != 2: raise BindingException("Join column '%s' for %r should be either a string or a 2-tuple." % (join_column_name, dimension)) try: join_column = self.fact_table.columns[join_column_name[0]] except KeyError: raise BindingException("Join column '%s' for %r not in fact table." % (dimension.join_column_name[0], dimension)) try: key_col = dimension_table.columns[join_column_name[1]] except KeyError: raise BindingException("Join column '%s' for %r not in dimension table." % (dimension.join_column_name[1], dimension)) q = q.where(join_column == key_col) return q
[ "def", "restrict_joins", "(", "self", ",", "q", ",", "bindings", ")", ":", "if", "len", "(", "q", ".", "froms", ")", "==", "1", ":", "return", "q", "else", ":", "for", "binding", "in", "bindings", ":", "if", "binding", ".", "table", "==", "self", ...
Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are referenced, this ensures their returned rows are connected via the fact table.
[ "Restrict", "the", "joins", "across", "all", "tables", "referenced", "in", "the", "database", "query", "to", "those", "specified", "in", "the", "model", "for", "the", "relevant", "dimensions", ".", "If", "a", "single", "table", "is", "used", "for", "the", ...
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/cube.py#L190-L237
train
46,980
pinax/pinax-cli
pinaxcli/utils.py
order_manually
def order_manually(sub_commands): """Order sub-commands for display""" order = [ "start", "projects", ] ordered = [] commands = dict(zip([cmd for cmd in sub_commands], sub_commands)) for k in order: ordered.append(commands.get(k, "")) if k in commands: del commands[k] # Add commands not present in `order` above for k in commands: ordered.append(commands[k]) return ordered
python
def order_manually(sub_commands): """Order sub-commands for display""" order = [ "start", "projects", ] ordered = [] commands = dict(zip([cmd for cmd in sub_commands], sub_commands)) for k in order: ordered.append(commands.get(k, "")) if k in commands: del commands[k] # Add commands not present in `order` above for k in commands: ordered.append(commands[k]) return ordered
[ "def", "order_manually", "(", "sub_commands", ")", ":", "order", "=", "[", "\"start\"", ",", "\"projects\"", ",", "]", "ordered", "=", "[", "]", "commands", "=", "dict", "(", "zip", "(", "[", "cmd", "for", "cmd", "in", "sub_commands", "]", ",", "sub_co...
Order sub-commands for display
[ "Order", "sub", "-", "commands", "for", "display" ]
7dac21907a2ac22a0efd06054ddea56f562efbaf
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/utils.py#L4-L21
train
46,981
openspending/babbage
babbage/model/model.py
Model.concepts
def concepts(self): """ Return all existing concepts, i.e. dimensions, measures and attributes within the model. """ for measure in self.measures: yield measure for aggregate in self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dimension.attributes: yield attribute
python
def concepts(self): """ Return all existing concepts, i.e. dimensions, measures and attributes within the model. """ for measure in self.measures: yield measure for aggregate in self.aggregates: yield aggregate for dimension in self.dimensions: yield dimension for attribute in dimension.attributes: yield attribute
[ "def", "concepts", "(", "self", ")", ":", "for", "measure", "in", "self", ".", "measures", ":", "yield", "measure", "for", "aggregate", "in", "self", ".", "aggregates", ":", "yield", "aggregate", "for", "dimension", "in", "self", ".", "dimensions", ":", ...
Return all existing concepts, i.e. dimensions, measures and attributes within the model.
[ "Return", "all", "existing", "concepts", "i", ".", "e", ".", "dimensions", "measures", "and", "attributes", "within", "the", "model", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/model.py#L60-L70
train
46,982
openspending/babbage
babbage/model/model.py
Model.match
def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in concept.attributes] except KeyError: return []
python
def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in concept.attributes] except KeyError: return []
[ "def", "match", "(", "self", ",", "ref", ")", ":", "try", ":", "concept", "=", "self", "[", "ref", "]", "if", "not", "isinstance", "(", "concept", ",", "Dimension", ")", ":", "return", "[", "concept", "]", "return", "[", "a", "for", "a", "in", "c...
Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself.
[ "Get", "all", "concepts", "matching", "this", "ref", ".", "For", "a", "dimension", "that", "is", "all", "its", "attributes", "but", "not", "the", "dimension", "itself", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/model.py#L72-L81
train
46,983
scopely-devops/details
details/costs.py
Costs.add
def add(self, lineitem): """ Add a line item record to this Costs object. """ # Check for a ProductName in the lineitem. # If its not there, it is a subtotal line and including it # will throw the total cost calculation off. So ignore it. if lineitem['ProductName']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: self._blended_cost += lineitem['BlendedCost'] if lineitem['UnBlendedCost']: self._unblended_cost += lineitem['UnBlendedCost']
python
def add(self, lineitem): """ Add a line item record to this Costs object. """ # Check for a ProductName in the lineitem. # If its not there, it is a subtotal line and including it # will throw the total cost calculation off. So ignore it. if lineitem['ProductName']: self._lineitems.append(lineitem) if lineitem['BlendedCost']: self._blended_cost += lineitem['BlendedCost'] if lineitem['UnBlendedCost']: self._unblended_cost += lineitem['UnBlendedCost']
[ "def", "add", "(", "self", ",", "lineitem", ")", ":", "# Check for a ProductName in the lineitem.", "# If its not there, it is a subtotal line and including it", "# will throw the total cost calculation off. So ignore it.", "if", "lineitem", "[", "'ProductName'", "]", ":", "self",...
Add a line item record to this Costs object.
[ "Add", "a", "line", "item", "record", "to", "this", "Costs", "object", "." ]
07f2fc7f27b29a6ddcda918abf6ae0882450319e
https://github.com/scopely-devops/details/blob/07f2fc7f27b29a6ddcda918abf6ae0882450319e/details/costs.py#L73-L85
train
46,984
scopely-devops/details
details/costs.py
Costs.filter
def filter(self, filters): """ Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the regular expression matches the value in that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``. """ subset = Costs(self._columns) filters = [(col, re.compile(regex)) for col, regex in filters] for lineitem in self._lineitems: for filter in filters: if filter[1].search(lineitem[filter[0]]) is None: continue subset.add(lineitem) return subset
python
def filter(self, filters): """ Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the regular expression matches the value in that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``. """ subset = Costs(self._columns) filters = [(col, re.compile(regex)) for col, regex in filters] for lineitem in self._lineitems: for filter in filters: if filter[1].search(lineitem[filter[0]]) is None: continue subset.add(lineitem) return subset
[ "def", "filter", "(", "self", ",", "filters", ")", ":", "subset", "=", "Costs", "(", "self", ".", "_columns", ")", "filters", "=", "[", "(", "col", ",", "re", ".", "compile", "(", "regex", ")", ")", "for", "col", ",", "regex", "in", "filters", "]...
Pass in a list of tuples where each tuple represents one filter. The first element of the tuple is the name of the column to filter on and the second value is a regular expression which each value in that column will be compared against. If the regular expression matches the value in that column, that lineitem will be included in the new Costs object returned. Example: filters=[('ProductName', '.*DynamoDB')] This filter would find all lineitems whose ``ProductName`` column contains values that end in the string ``DynamoDB``.
[ "Pass", "in", "a", "list", "of", "tuples", "where", "each", "tuple", "represents", "one", "filter", ".", "The", "first", "element", "of", "the", "tuple", "is", "the", "name", "of", "the", "column", "to", "filter", "on", "and", "the", "second", "value", ...
07f2fc7f27b29a6ddcda918abf6ae0882450319e
https://github.com/scopely-devops/details/blob/07f2fc7f27b29a6ddcda918abf6ae0882450319e/details/costs.py#L95-L118
train
46,985
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.query
def query(self, query, args=None): """ Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() log.logger.debug('Running query "%s" with args "%s"', query, args) self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.lastInsertID = self.conn.connection.insert_id() self.rowcount = cursor.rowcount log.logger.debug('Query Resulted in %s affected rows, %s rows returned, %s last insert id', self.affectedRows, self.lastInsertID, self.rowcount) self.record = cursor.fetchall() self.conn.updateCheckTime() except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
python
def query(self, query, args=None): """ Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() log.logger.debug('Running query "%s" with args "%s"', query, args) self.conn.query = query #Execute query and store results cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.lastInsertID = self.conn.connection.insert_id() self.rowcount = cursor.rowcount log.logger.debug('Query Resulted in %s affected rows, %s rows returned, %s last insert id', self.affectedRows, self.lastInsertID, self.rowcount) self.record = cursor.fetchall() self.conn.updateCheckTime() except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
[ "def", "query", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "self", ".", "affectedRows", "=", "None", "self", ".", "lastError", "=", "None", "cursor", "=", "None", "try", ":", "try", ":", "self", ".", "_GetConnection", "(", ")", ...
Execute the passed in query against the database @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008
[ "Execute", "the", "passed", "in", "query", "against", "the", "database" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L74-L114
train
46,986
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.queryOne
def queryOne(self, query, args=None): """ Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.conn.updateCheckTime() while 1: row = cursor.fetchone() if row is None: break else: self.record = row yield row self.rowcount = cursor.rowcount except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: raise StopIteration
python
def queryOne(self, query, args=None): """ Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008 """ self.affectedRows = None self.lastError = None cursor = None try: try: self._GetConnection() self.conn.query = query #Execute query cursor = self.conn.getCursor() self.affectedRows = cursor.execute(query, args) self.conn.updateCheckTime() while 1: row = cursor.fetchone() if row is None: break else: self.record = row yield row self.rowcount = cursor.rowcount except Exception, e: self.lastError = e self.affectedRows = None finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: raise StopIteration
[ "def", "queryOne", "(", "self", ",", "query", ",", "args", "=", "None", ")", ":", "self", ".", "affectedRows", "=", "None", "self", ".", "lastError", "=", "None", "cursor", "=", "None", "try", ":", "try", ":", "self", ".", "_GetConnection", "(", ")",...
Execute the passed in query against the database. Uses a Generator & fetchone to reduce your process memory size. @param query: MySQL Query to execute. %s or %(key)s will be replaced by parameter args sequence @param args: Sequence of value to replace in your query. A mapping may also be used but your query must use %(key)s @author: Nick Verbeck @since: 5/12/2008
[ "Execute", "the", "passed", "in", "query", "against", "the", "database", ".", "Uses", "a", "Generator", "&", "fetchone", "to", "reduce", "your", "process", "memory", "size", "." ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L117-L158
train
46,987
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery.queryMulti
def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execute query and store results cursor = self.conn.getCursor() for query in queries: self.conn.query = query if query.__class__ == [].__class__: self.affectedRows += cursor.execute(query[0], query[1]) else: self.affectedRows += cursor.execute(query) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
python
def queryMulti(self, queries): """ Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = 0 self.rowcount = None self.record = None cursor = None try: try: self._GetConnection() #Execute query and store results cursor = self.conn.getCursor() for query in queries: self.conn.query = query if query.__class__ == [].__class__: self.affectedRows += cursor.execute(query[0], query[1]) else: self.affectedRows += cursor.execute(query) self.conn.updateCheckTime() except Exception, e: self.lastError = e finally: if cursor is not None: cursor.close() self._ReturnConnection() if self.lastError is not None: raise self.lastError else: return self.affectedRows
[ "def", "queryMulti", "(", "self", ",", "queries", ")", ":", "self", ".", "lastError", "=", "None", "self", ".", "affectedRows", "=", "0", "self", ".", "rowcount", "=", "None", "self", ".", "record", "=", "None", "cursor", "=", "None", "try", ":", "tr...
Execute a series of Deletes,Inserts, & Updates in the Queires List @author: Nick Verbeck @since: 9/7/2008
[ "Execute", "a", "series", "of", "Deletes", "Inserts", "&", "Updates", "in", "the", "Queires", "List" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L197-L231
train
46,988
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery._GetConnection
def _GetConnection(self): """ Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008 """ #Attempt to get a connection. If all connections are in use and we have reached the max number of connections, #we wait 1 second and try again. #The Connection is returned locked to be thread safe while self.conn is None: self.conn = Pool().GetConnection(self.connInfo) if self.conn is not None: break else: time.sleep(1)
python
def _GetConnection(self): """ Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008 """ #Attempt to get a connection. If all connections are in use and we have reached the max number of connections, #we wait 1 second and try again. #The Connection is returned locked to be thread safe while self.conn is None: self.conn = Pool().GetConnection(self.connInfo) if self.conn is not None: break else: time.sleep(1)
[ "def", "_GetConnection", "(", "self", ")", ":", "#Attempt to get a connection. If all connections are in use and we have reached the max number of connections,", "#we wait 1 second and try again.", "#The Connection is returned locked to be thread safe", "while", "self", ".", "conn", "is", ...
Retieves a prelocked connection from the Pool @author: Nick Verbeck @since: 9/7/2008
[ "Retieves", "a", "prelocked", "connection", "from", "the", "Pool" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L234-L249
train
46,989
nerdynick/PySQLPool
src/PySQLPool/query.py
PySQLQuery._ReturnConnection
def _ReturnConnection(self): """ Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 """ if self.conn is not None: if self.connInfo.commitOnEnd is True or self.commitOnEnd is True: self.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
python
def _ReturnConnection(self): """ Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008 """ if self.conn is not None: if self.connInfo.commitOnEnd is True or self.commitOnEnd is True: self.conn.Commit() Pool().returnConnection(self.conn) self.conn = None
[ "def", "_ReturnConnection", "(", "self", ")", ":", "if", "self", ".", "conn", "is", "not", "None", ":", "if", "self", ".", "connInfo", ".", "commitOnEnd", "is", "True", "or", "self", ".", "commitOnEnd", "is", "True", ":", "self", ".", "conn", ".", "C...
Returns a connection back to the pool @author: Nick Verbeck @since: 9/7/2008
[ "Returns", "a", "connection", "back", "to", "the", "pool" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/query.py#L251-L263
train
46,990
openspending/babbage
babbage/model/aggregate.py
Aggregate.bind
def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation function: column = getattr(func, self.function)(column) column = column.label(self.ref) column.quote = True return table, column
python
def bind(self, cube): """ When one column needs to match, use the key. """ if self.measure: table, column = self.measure.bind(cube) else: table, column = cube.fact_table, cube.fact_pk # apply the SQL aggregation function: column = getattr(func, self.function)(column) column = column.label(self.ref) column.quote = True return table, column
[ "def", "bind", "(", "self", ",", "cube", ")", ":", "if", "self", ".", "measure", ":", "table", ",", "column", "=", "self", ".", "measure", ".", "bind", "(", "cube", ")", "else", ":", "table", ",", "column", "=", "cube", ".", "fact_table", ",", "c...
When one column needs to match, use the key.
[ "When", "one", "column", "needs", "to", "match", "use", "the", "key", "." ]
9e03efe62e0be0cceabafd4de2a09cb8ec794b92
https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/aggregate.py#L22-L32
train
46,991
mandeep/Travis-Encrypt
travis/encrypt.py
retrieve_public_key
def retrieve_public_key(user_repo): """Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being returned from the Travis API as PKCS8 encoded, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given """ url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.split('/') raise InvalidCredentialsError("Either the username: '{}' or the repository: '{}' does not exist. Please enter a valid username or repository name. The username and repository name are both case sensitive." .format(username, repository))
python
def retrieve_public_key(user_repo): """Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being returned from the Travis API as PKCS8 encoded, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given """ url = 'https://api.travis-ci.org/repos/{}/key' .format(user_repo) response = requests.get(url) try: return response.json()['key'].replace(' RSA ', ' ') except KeyError: username, repository = user_repo.split('/') raise InvalidCredentialsError("Either the username: '{}' or the repository: '{}' does not exist. Please enter a valid username or repository name. The username and repository name are both case sensitive." .format(username, repository))
[ "def", "retrieve_public_key", "(", "user_repo", ")", ":", "url", "=", "'https://api.travis-ci.org/repos/{}/key'", ".", "format", "(", "user_repo", ")", "response", "=", "requests", ".", "get", "(", "url", ")", "try", ":", "return", "response", ".", "json", "("...
Retrieve the public key from the Travis API. The Travis API response is accessed as JSON so that Travis-Encrypt can easily find the public key that is to be passed to cryptography's load_pem_public_key function. Due to issues with some public keys being returned from the Travis API as PKCS8 encoded, the key is returned with RSA removed from the header and footer. Parameters ---------- user_repo: str the repository in the format of 'username/repository' Returns ------- response: str the public RSA key of the username's repository Raises ------ InvalidCredentialsError raised when an invalid 'username/repository' is given
[ "Retrieve", "the", "public", "key", "from", "the", "Travis", "API", "." ]
0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L21-L52
train
46,992
mandeep/Travis-Encrypt
travis/encrypt.py
encrypt_key
def encrypt_key(key, password): """Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPublicKey. The encrypted password is then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None)) """ public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
python
def encrypt_key(key, password): """Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPublicKey. The encrypted password is then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None)) """ public_key = load_pem_public_key(key.encode(), default_backend()) encrypted_password = public_key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password).decode('ascii')
[ "def", "encrypt_key", "(", "key", ",", "password", ")", ":", "public_key", "=", "load_pem_public_key", "(", "key", ".", "encode", "(", ")", ",", "default_backend", "(", ")", ")", "encrypted_password", "=", "public_key", ".", "encrypt", "(", "password", ",", ...
Encrypt the password with the public key and return an ASCII representation. The public key retrieved from the Travis API is loaded as an RSAPublicKey object using Cryptography's default backend. Then the given password is encrypted with the encrypt() method of RSAPublicKey. The encrypted password is then encoded to base64 and decoded into ASCII in order to convert the bytes object into a string object. Parameters ---------- key: str Travis CI public RSA key that requires deserialization password: str the password to be encrypted Returns ------- encrypted_password: str the base64 encoded encrypted password decoded as ASCII Notes ----- Travis CI uses the PKCS1v15 padding scheme. While PKCS1v15 is secure, it is outdated and should be replaced with OAEP. Example: OAEP(mgf=MGF1(algorithm=SHA256()), algorithm=SHA256(), label=None))
[ "Encrypt", "the", "password", "with", "the", "public", "key", "and", "return", "an", "ASCII", "representation", "." ]
0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L55-L86
train
46,993
mandeep/Travis-Encrypt
travis/encrypt.py
dump_travis_configuration
def dump_travis_configuration(config, path): """Dump the travis configuration settings to the travis.yml file. The configuration settings from the travis.yml will be dumped with ordering preserved. Thus, when a password is added to the travis.yml file, a diff will show that only the password was added. Parameters ---------- config: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None """ with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
python
def dump_travis_configuration(config, path): """Dump the travis configuration settings to the travis.yml file. The configuration settings from the travis.yml will be dumped with ordering preserved. Thus, when a password is added to the travis.yml file, a diff will show that only the password was added. Parameters ---------- config: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None """ with open(path, 'w') as config_file: ordered_dump(config, config_file, default_flow_style=False)
[ "def", "dump_travis_configuration", "(", "config", ",", "path", ")", ":", "with", "open", "(", "path", ",", "'w'", ")", "as", "config_file", ":", "ordered_dump", "(", "config", ",", "config_file", ",", "default_flow_style", "=", "False", ")" ]
Dump the travis configuration settings to the travis.yml file. The configuration settings from the travis.yml will be dumped with ordering preserved. Thus, when a password is added to the travis.yml file, a diff will show that only the password was added. Parameters ---------- config: collections.OrderedDict The configuration settings to dump into the travis.yml file path: str The file path to the .travis.yml file Returns ------- None
[ "Dump", "the", "travis", "configuration", "settings", "to", "the", "travis", ".", "yml", "file", "." ]
0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41
https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/encrypt.py#L111-L130
train
46,994
pinax/pinax-cli
pinaxcli/cli.py
show_distribution_section
def show_distribution_section(config, title, section_name): """ Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". """ payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Release".rjust(7), title)) click.echo("------- ---------------") section = latest_distribution[section_name] names = sorted(section.keys()) for name in names: click.echo("{} {}".format(section[name].rjust(7), name))
python
def show_distribution_section(config, title, section_name): """ Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". """ payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = payload[distributions[0]] click.echo("{} {}".format("Release".rjust(7), title)) click.echo("------- ---------------") section = latest_distribution[section_name] names = sorted(section.keys()) for name in names: click.echo("{} {}".format(section[name].rjust(7), name))
[ "def", "show_distribution_section", "(", "config", ",", "title", ",", "section_name", ")", ":", "payload", "=", "requests", ".", "get", "(", "config", ".", "apps_url", ")", ".", "json", "(", ")", "distributions", "=", "sorted", "(", "payload", ".", "keys",...
Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes".
[ "Obtain", "distribution", "data", "and", "display", "latest", "distribution", "section", "i", ".", "e", ".", "demos", "or", "apps", "or", "themes", "." ]
7dac21907a2ac22a0efd06054ddea56f562efbaf
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/cli.py#L93-L106
train
46,995
pinax/pinax-cli
pinaxcli/cli.py
validate_django_compatible_with_python
def validate_django_compatible_with_python(): """ Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible. """ python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
python
def validate_django_compatible_with_python(): """ Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible. """ python_version = sys.version[:5] django_version = django.get_version() if sys.version_info == (2, 7) and django_version >= "2": click.BadArgumentUsage("Please install Django v1.11 for Python {}, or switch to Python >= v3.4".format(python_version))
[ "def", "validate_django_compatible_with_python", "(", ")", ":", "python_version", "=", "sys", ".", "version", "[", ":", "5", "]", "django_version", "=", "django", ".", "get_version", "(", ")", "if", "sys", ".", "version_info", "==", "(", "2", ",", "7", ")"...
Verify Django 1.11 is present if Python 2.7 is active Installation of pinax-cli requires the correct version of Django for the active Python version. If the developer subsequently changes the Python version the installed Django may no longer be compatible.
[ "Verify", "Django", "1", ".", "11", "is", "present", "if", "Python", "2", ".", "7", "is", "active" ]
7dac21907a2ac22a0efd06054ddea56f562efbaf
https://github.com/pinax/pinax-cli/blob/7dac21907a2ac22a0efd06054ddea56f562efbaf/pinaxcli/cli.py#L158-L169
train
46,996
bodylabs/lace
lace/lines.py
Lines.keep_vertices
def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of the kept edges. Otherwise return `self` for chaining. ''' if self.v is None: return initial_num_verts = self.v.shape[0] if self.e is not None: initial_num_edges = self.e.shape[0] e_indices_to_keep = self.all_edges_with_verts(indices_to_keep, as_boolean=True) self.v = self.v[indices_to_keep] if self.e is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) e_old_to_new = np.zeros(initial_num_edges, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.e = v_old_to_new[self.e[e_indices_to_keep]] e_old_to_new[e_indices_to_keep] = np.arange(self.e.shape[0], dtype=int) else: e_indices_to_keep = [] return np.nonzero(e_indices_to_keep)[0] if ret_kept_edges else self
python
def keep_vertices(self, indices_to_keep, ret_kept_edges=False): ''' Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of the kept edges. Otherwise return `self` for chaining. ''' if self.v is None: return initial_num_verts = self.v.shape[0] if self.e is not None: initial_num_edges = self.e.shape[0] e_indices_to_keep = self.all_edges_with_verts(indices_to_keep, as_boolean=True) self.v = self.v[indices_to_keep] if self.e is not None: v_old_to_new = np.zeros(initial_num_verts, dtype=int) e_old_to_new = np.zeros(initial_num_edges, dtype=int) v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int) self.e = v_old_to_new[self.e[e_indices_to_keep]] e_old_to_new[e_indices_to_keep] = np.arange(self.e.shape[0], dtype=int) else: e_indices_to_keep = [] return np.nonzero(e_indices_to_keep)[0] if ret_kept_edges else self
[ "def", "keep_vertices", "(", "self", ",", "indices_to_keep", ",", "ret_kept_edges", "=", "False", ")", ":", "if", "self", ".", "v", "is", "None", ":", "return", "initial_num_verts", "=", "self", ".", "v", ".", "shape", "[", "0", "]", "if", "self", ".",...
Keep the given vertices and discard the others, and any edges to which they may belong. If `ret_kept_edges` is `True`, return the original indices of the kept edges. Otherwise return `self` for chaining.
[ "Keep", "the", "given", "vertices", "and", "discard", "the", "others", "and", "any", "edges", "to", "which", "they", "may", "belong", "." ]
b68f4a60a4cac66c0607ffbae38ef9d07d37f459
https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/lines.py#L69-L99
train
46,997
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.lock
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
python
def lock(self, block=True): """ Lock connection from being used else where """ self._locked = True return self._lock.acquire(block)
[ "def", "lock", "(", "self", ",", "block", "=", "True", ")", ":", "self", ".", "_locked", "=", "True", "return", "self", ".", "_lock", ".", "acquire", "(", "block", ")" ]
Lock connection from being used else where
[ "Lock", "connection", "from", "being", "used", "else", "where" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L117-L122
train
46,998
nerdynick/PySQLPool
src/PySQLPool/connection.py
ConnectionManager.release
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
python
def release(self): """ Release the connection lock """ if self._locked is True: self._locked = False self._lock.release()
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "_locked", "is", "True", ":", "self", ".", "_locked", "=", "False", "self", ".", "_lock", ".", "release", "(", ")" ]
Release the connection lock
[ "Release", "the", "connection", "lock" ]
a561275fea091e2667b69ce376c507f541b56e7d
https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/connection.py#L124-L130
train
46,999